From eea839929ce43ce0f1a2d90306b8ddbafb77dd9b Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Sat, 26 Sep 2026 23:17:24 +0200 Subject: [PATCH 001/225] feat(create old backend): --- {backend => backend_old}/.gitignore | 0 {backend => backend_old}/captures/IP_in_IP.cap | Bin {backend => backend_old}/captures/README.md | 0 .../captures/path_MTU_discovery.cap | Bin {backend => backend_old}/captures/telnet.cap | Bin {backend => backend_old}/cmd/config.toml | 0 {backend => backend_old}/cmd/dev-config.toml | 0 {backend => backend_old}/cmd/main.go | 0 {backend => backend_old}/cmd/orchestrator.go | 0 {backend => backend_old}/cmd/setup_transport.go | 0 {backend => backend_old}/cmd/setup_vehicle.go | 0 {backend => backend_old}/go.mod | 0 {backend => backend_old}/go.sum | 0 {backend => backend_old}/internal/common/chan.go | 0 {backend => backend_old}/internal/common/errors.go | 0 {backend => backend_old}/internal/common/io.go | 0 {backend => backend_old}/internal/common/map.go | 0 .../internal/common/moving_average.go | 0 {backend => backend_old}/internal/common/net.go | 0 {backend => backend_old}/internal/common/numbers.go | 0 .../internal/common/ring_buf.go | 0 {backend => backend_old}/internal/common/set.go | 0 {backend => backend_old}/internal/common/slice.go | 0 {backend => backend_old}/internal/common/types.go | 0 {backend => backend_old}/internal/config/config.go | 0 .../internal/config/config_types.go | 0 {backend => backend_old}/internal/flags/flags.go | 0 .../internal/pod_data/measurement.go | 0 .../internal/pod_data/models.go | 0 .../internal/pod_data/pod_data.go | 0 .../internal/pod_data/sortable_packets.go | 0 {backend => backend_old}/internal/server/config.go | 0 .../internal/update_factory/models/update.go | 0 .../internal/update_factory/update_factory.go | 0 {backend => backend_old}/internal/utils/units.go | 0 {backend => backend_old}/internal/vehicle/config.go | 0 .../internal/vehicle/models/order_data.go | 0 .../internal/vehicle/packet_parser/config.go | 0 {backend => backend_old}/package-lock.json | 0 {backend => backend_old}/package.json | 0 {backend => backend_old}/pkg/abstraction/board.go | 0 {backend => backend_old}/pkg/abstraction/broker.go | 0 {backend => backend_old}/pkg/abstraction/logger.go | 0 {backend => backend_old}/pkg/abstraction/packet.go | 0 .../pkg/abstraction/transport.go | 0 {backend => backend_old}/pkg/adj/adj.go | 0 {backend => backend_old}/pkg/adj/boards.go | 0 {backend => backend_old}/pkg/adj/git.go | 0 {backend => backend_old}/pkg/adj/models.go | 0 {backend => backend_old}/pkg/adj/validator.go | 0 {backend => backend_old}/pkg/boards/errors.go | 0 {backend => backend_old}/pkg/boards/events.go | 0 {backend => backend_old}/pkg/broker/broker.go | 0 {backend => backend_old}/pkg/broker/errors.go | 0 .../pkg/broker/topics/connection/connection_test.go | 0 .../pkg/broker/topics/connection/push.go | 0 .../pkg/broker/topics/connection/update.go | 0 .../pkg/broker/topics/data/data_test.go | 0 .../pkg/broker/topics/data/push.go | 0 .../pkg/broker/topics/data/update.go | 0 .../pkg/broker/topics/errors.go | 0 .../pkg/broker/topics/logger/enable.go | 0 .../pkg/broker/topics/logger/logger_test.go | 0 .../pkg/broker/topics/message/message_test.go | 0 .../pkg/broker/topics/message/update.go | 0 .../pkg/broker/topics/order/order_test.go | 0 .../pkg/broker/topics/order/send.go | 0 .../pkg/broker/topics/order/state.go | 0 .../topics/tests_functions/tests_functions.go | 0 {backend => backend_old}/pkg/broker/topics/topic.go | 0 {backend => backend_old}/pkg/http/handlers.go | 0 {backend => backend_old}/pkg/http/mux.go | 0 {backend => backend_old}/pkg/http/server.go | 0 {backend => backend_old}/pkg/logger/.gitignore | 0 {backend => backend_old}/pkg/logger/base/logger.go | 0 .../pkg/logger/base/logger_test.go | 0 {backend => backend_old}/pkg/logger/data/.gitignore | 0 {backend => backend_old}/pkg/logger/data/logger.go | 0 .../pkg/logger/data/logger_test.go | 0 {backend => backend_old}/pkg/logger/errors.go | 0 {backend => backend_old}/pkg/logger/file/csv.go | 0 .../pkg/logger/file/csv_test.go | 0 {backend => backend_old}/pkg/logger/logger.go | 0 {backend => backend_old}/pkg/logger/logger_test.go | 0 {backend => backend_old}/pkg/logger/order/logger.go | 0 .../pkg/logger/order/logger_test.go | 0 .../pkg/logger/protection/logger.go | 0 {backend => backend_old}/pkg/logger/state/logger.go | 0 {backend => backend_old}/pkg/logger/time.go | 0 {backend => backend_old}/pkg/logger/time_test.go | 0 {backend => backend_old}/pkg/logger/trace/trace.go | 0 .../pkg/logger/validator/validator.go | 0 .../pkg/transport/constructor.go | 0 {backend => backend_old}/pkg/transport/errors.go | 0 {backend => backend_old}/pkg/transport/keepalive.go | 0 {backend => backend_old}/pkg/transport/messages.go | 0 .../pkg/transport/network/payload.go | 0 .../pkg/transport/network/sniffer/errors.go | 0 .../pkg/transport/network/tcp/client.go | 0 .../pkg/transport/network/tcp/config.go | 0 .../pkg/transport/network/tcp/conn.go | 0 .../pkg/transport/network/tcp/server.go | 0 .../pkg/transport/network/tcp/tcp_test.go | 0 .../pkg/transport/network/udp/server.go | 0 .../pkg/transport/notifications.go | 0 .../pkg/transport/packet/data/codec.go | 0 .../pkg/transport/packet/data/converter.go | 0 .../pkg/transport/packet/data/decoder.go | 0 .../pkg/transport/packet/data/descriptors.go | 0 .../pkg/transport/packet/data/encoder.go | 0 .../pkg/transport/packet/data/errors.go | 0 .../pkg/transport/packet/data/packet.go | 0 .../pkg/transport/packet/data/value.go | 0 .../pkg/transport/packet/order/codec.go | 0 .../pkg/transport/packet/order/decoder.go | 0 .../pkg/transport/packet/order/errors.go | 0 .../pkg/transport/packet/order/packet.go | 0 .../pkg/transport/packet/protection/decoder.go | 0 .../pkg/transport/packet/protection/errors.go | 0 .../pkg/transport/packet/protection/kind.go | 0 .../pkg/transport/packet/protection/packet.go | 0 .../pkg/transport/packet/state/decoder.go | 0 .../pkg/transport/packet/state/packet.go | 0 .../pkg/transport/presentation/decoder.go | 0 .../pkg/transport/presentation/decoder_test.go | 0 .../pkg/transport/presentation/encoder.go | 0 .../pkg/transport/presentation/encoder_test.go | 0 .../pkg/transport/presentation/errors.go | 0 .../pkg/transport/session/buffer.go | 0 {backend => backend_old}/pkg/transport/transport.go | 0 {backend => backend_old}/pkg/vehicle/constructor.go | 0 {backend => backend_old}/pkg/vehicle/errors.go | 0 .../pkg/vehicle/notification.go | 0 {backend => backend_old}/pkg/vehicle/vehicle.go | 0 {backend => backend_old}/pkg/websocket/client.go | 0 {backend => backend_old}/pkg/websocket/errors.go | 0 {backend => backend_old}/pkg/websocket/pool.go | 0 {backend => backend_old}/pkg/websocket/upgrader.go | 0 {backend => backend_old}/scripts/analyze_trace.py | 0 139 files changed, 0 insertions(+), 0 deletions(-) rename {backend => backend_old}/.gitignore (100%) rename {backend => backend_old}/captures/IP_in_IP.cap (100%) rename {backend => backend_old}/captures/README.md (100%) rename {backend => backend_old}/captures/path_MTU_discovery.cap (100%) rename {backend => backend_old}/captures/telnet.cap (100%) rename {backend => backend_old}/cmd/config.toml (100%) rename {backend => backend_old}/cmd/dev-config.toml (100%) rename {backend => backend_old}/cmd/main.go (100%) rename {backend => backend_old}/cmd/orchestrator.go (100%) rename {backend => backend_old}/cmd/setup_transport.go (100%) rename {backend => backend_old}/cmd/setup_vehicle.go (100%) rename {backend => backend_old}/go.mod (100%) rename {backend => backend_old}/go.sum (100%) rename {backend => backend_old}/internal/common/chan.go (100%) rename {backend => backend_old}/internal/common/errors.go (100%) rename {backend => backend_old}/internal/common/io.go (100%) rename {backend => backend_old}/internal/common/map.go (100%) rename {backend => backend_old}/internal/common/moving_average.go (100%) rename {backend => backend_old}/internal/common/net.go (100%) rename {backend => backend_old}/internal/common/numbers.go (100%) rename {backend => backend_old}/internal/common/ring_buf.go (100%) rename {backend => backend_old}/internal/common/set.go (100%) rename {backend => backend_old}/internal/common/slice.go (100%) rename {backend => backend_old}/internal/common/types.go (100%) rename {backend => backend_old}/internal/config/config.go (100%) rename {backend => backend_old}/internal/config/config_types.go (100%) rename {backend => backend_old}/internal/flags/flags.go (100%) rename {backend => backend_old}/internal/pod_data/measurement.go (100%) rename {backend => backend_old}/internal/pod_data/models.go (100%) rename {backend => backend_old}/internal/pod_data/pod_data.go (100%) rename {backend => backend_old}/internal/pod_data/sortable_packets.go (100%) rename {backend => backend_old}/internal/server/config.go (100%) rename {backend => backend_old}/internal/update_factory/models/update.go (100%) rename {backend => backend_old}/internal/update_factory/update_factory.go (100%) rename {backend => backend_old}/internal/utils/units.go (100%) rename {backend => backend_old}/internal/vehicle/config.go (100%) rename {backend => backend_old}/internal/vehicle/models/order_data.go (100%) rename {backend => backend_old}/internal/vehicle/packet_parser/config.go (100%) rename {backend => backend_old}/package-lock.json (100%) rename {backend => backend_old}/package.json (100%) rename {backend => backend_old}/pkg/abstraction/board.go (100%) rename {backend => backend_old}/pkg/abstraction/broker.go (100%) rename {backend => backend_old}/pkg/abstraction/logger.go (100%) rename {backend => backend_old}/pkg/abstraction/packet.go (100%) rename {backend => backend_old}/pkg/abstraction/transport.go (100%) rename {backend => backend_old}/pkg/adj/adj.go (100%) rename {backend => backend_old}/pkg/adj/boards.go (100%) rename {backend => backend_old}/pkg/adj/git.go (100%) rename {backend => backend_old}/pkg/adj/models.go (100%) rename {backend => backend_old}/pkg/adj/validator.go (100%) rename {backend => backend_old}/pkg/boards/errors.go (100%) rename {backend => backend_old}/pkg/boards/events.go (100%) rename {backend => backend_old}/pkg/broker/broker.go (100%) rename {backend => backend_old}/pkg/broker/errors.go (100%) rename {backend => backend_old}/pkg/broker/topics/connection/connection_test.go (100%) rename {backend => backend_old}/pkg/broker/topics/connection/push.go (100%) rename {backend => backend_old}/pkg/broker/topics/connection/update.go (100%) rename {backend => backend_old}/pkg/broker/topics/data/data_test.go (100%) rename {backend => backend_old}/pkg/broker/topics/data/push.go (100%) rename {backend => backend_old}/pkg/broker/topics/data/update.go (100%) rename {backend => backend_old}/pkg/broker/topics/errors.go (100%) rename {backend => backend_old}/pkg/broker/topics/logger/enable.go (100%) rename {backend => backend_old}/pkg/broker/topics/logger/logger_test.go (100%) rename {backend => backend_old}/pkg/broker/topics/message/message_test.go (100%) rename {backend => backend_old}/pkg/broker/topics/message/update.go (100%) rename {backend => backend_old}/pkg/broker/topics/order/order_test.go (100%) rename {backend => backend_old}/pkg/broker/topics/order/send.go (100%) rename {backend => backend_old}/pkg/broker/topics/order/state.go (100%) rename {backend => backend_old}/pkg/broker/topics/tests_functions/tests_functions.go (100%) rename {backend => backend_old}/pkg/broker/topics/topic.go (100%) rename {backend => backend_old}/pkg/http/handlers.go (100%) rename {backend => backend_old}/pkg/http/mux.go (100%) rename {backend => backend_old}/pkg/http/server.go (100%) rename {backend => backend_old}/pkg/logger/.gitignore (100%) rename {backend => backend_old}/pkg/logger/base/logger.go (100%) rename {backend => backend_old}/pkg/logger/base/logger_test.go (100%) rename {backend => backend_old}/pkg/logger/data/.gitignore (100%) rename {backend => backend_old}/pkg/logger/data/logger.go (100%) rename {backend => backend_old}/pkg/logger/data/logger_test.go (100%) rename {backend => backend_old}/pkg/logger/errors.go (100%) rename {backend => backend_old}/pkg/logger/file/csv.go (100%) rename {backend => backend_old}/pkg/logger/file/csv_test.go (100%) rename {backend => backend_old}/pkg/logger/logger.go (100%) rename {backend => backend_old}/pkg/logger/logger_test.go (100%) rename {backend => backend_old}/pkg/logger/order/logger.go (100%) rename {backend => backend_old}/pkg/logger/order/logger_test.go (100%) rename {backend => backend_old}/pkg/logger/protection/logger.go (100%) rename {backend => backend_old}/pkg/logger/state/logger.go (100%) rename {backend => backend_old}/pkg/logger/time.go (100%) rename {backend => backend_old}/pkg/logger/time_test.go (100%) rename {backend => backend_old}/pkg/logger/trace/trace.go (100%) rename {backend => backend_old}/pkg/logger/validator/validator.go (100%) rename {backend => backend_old}/pkg/transport/constructor.go (100%) rename {backend => backend_old}/pkg/transport/errors.go (100%) rename {backend => backend_old}/pkg/transport/keepalive.go (100%) rename {backend => backend_old}/pkg/transport/messages.go (100%) rename {backend => backend_old}/pkg/transport/network/payload.go (100%) rename {backend => backend_old}/pkg/transport/network/sniffer/errors.go (100%) rename {backend => backend_old}/pkg/transport/network/tcp/client.go (100%) rename {backend => backend_old}/pkg/transport/network/tcp/config.go (100%) rename {backend => backend_old}/pkg/transport/network/tcp/conn.go (100%) rename {backend => backend_old}/pkg/transport/network/tcp/server.go (100%) rename {backend => backend_old}/pkg/transport/network/tcp/tcp_test.go (100%) rename {backend => backend_old}/pkg/transport/network/udp/server.go (100%) rename {backend => backend_old}/pkg/transport/notifications.go (100%) rename {backend => backend_old}/pkg/transport/packet/data/codec.go (100%) rename {backend => backend_old}/pkg/transport/packet/data/converter.go (100%) rename {backend => backend_old}/pkg/transport/packet/data/decoder.go (100%) rename {backend => backend_old}/pkg/transport/packet/data/descriptors.go (100%) rename {backend => backend_old}/pkg/transport/packet/data/encoder.go (100%) rename {backend => backend_old}/pkg/transport/packet/data/errors.go (100%) rename {backend => backend_old}/pkg/transport/packet/data/packet.go (100%) rename {backend => backend_old}/pkg/transport/packet/data/value.go (100%) rename {backend => backend_old}/pkg/transport/packet/order/codec.go (100%) rename {backend => backend_old}/pkg/transport/packet/order/decoder.go (100%) rename {backend => backend_old}/pkg/transport/packet/order/errors.go (100%) rename {backend => backend_old}/pkg/transport/packet/order/packet.go (100%) rename {backend => backend_old}/pkg/transport/packet/protection/decoder.go (100%) rename {backend => backend_old}/pkg/transport/packet/protection/errors.go (100%) rename {backend => backend_old}/pkg/transport/packet/protection/kind.go (100%) rename {backend => backend_old}/pkg/transport/packet/protection/packet.go (100%) rename {backend => backend_old}/pkg/transport/packet/state/decoder.go (100%) rename {backend => backend_old}/pkg/transport/packet/state/packet.go (100%) rename {backend => backend_old}/pkg/transport/presentation/decoder.go (100%) rename {backend => backend_old}/pkg/transport/presentation/decoder_test.go (100%) rename {backend => backend_old}/pkg/transport/presentation/encoder.go (100%) rename {backend => backend_old}/pkg/transport/presentation/encoder_test.go (100%) rename {backend => backend_old}/pkg/transport/presentation/errors.go (100%) rename {backend => backend_old}/pkg/transport/session/buffer.go (100%) rename {backend => backend_old}/pkg/transport/transport.go (100%) rename {backend => backend_old}/pkg/vehicle/constructor.go (100%) rename {backend => backend_old}/pkg/vehicle/errors.go (100%) rename {backend => backend_old}/pkg/vehicle/notification.go (100%) rename {backend => backend_old}/pkg/vehicle/vehicle.go (100%) rename {backend => backend_old}/pkg/websocket/client.go (100%) rename {backend => backend_old}/pkg/websocket/errors.go (100%) rename {backend => backend_old}/pkg/websocket/pool.go (100%) rename {backend => backend_old}/pkg/websocket/upgrader.go (100%) rename {backend => backend_old}/scripts/analyze_trace.py (100%) diff --git a/backend/.gitignore b/backend_old/.gitignore similarity index 100% rename from backend/.gitignore rename to backend_old/.gitignore diff --git a/backend/captures/IP_in_IP.cap b/backend_old/captures/IP_in_IP.cap similarity index 100% rename from backend/captures/IP_in_IP.cap rename to backend_old/captures/IP_in_IP.cap diff --git a/backend/captures/README.md b/backend_old/captures/README.md similarity index 100% rename from backend/captures/README.md rename to backend_old/captures/README.md diff --git a/backend/captures/path_MTU_discovery.cap b/backend_old/captures/path_MTU_discovery.cap similarity index 100% rename from backend/captures/path_MTU_discovery.cap rename to backend_old/captures/path_MTU_discovery.cap diff --git a/backend/captures/telnet.cap b/backend_old/captures/telnet.cap similarity index 100% rename from backend/captures/telnet.cap rename to backend_old/captures/telnet.cap diff --git a/backend/cmd/config.toml b/backend_old/cmd/config.toml similarity index 100% rename from backend/cmd/config.toml rename to backend_old/cmd/config.toml diff --git a/backend/cmd/dev-config.toml b/backend_old/cmd/dev-config.toml similarity index 100% rename from backend/cmd/dev-config.toml rename to backend_old/cmd/dev-config.toml diff --git a/backend/cmd/main.go b/backend_old/cmd/main.go similarity index 100% rename from backend/cmd/main.go rename to backend_old/cmd/main.go diff --git a/backend/cmd/orchestrator.go b/backend_old/cmd/orchestrator.go similarity index 100% rename from backend/cmd/orchestrator.go rename to backend_old/cmd/orchestrator.go diff --git a/backend/cmd/setup_transport.go b/backend_old/cmd/setup_transport.go similarity index 100% rename from backend/cmd/setup_transport.go rename to backend_old/cmd/setup_transport.go diff --git a/backend/cmd/setup_vehicle.go b/backend_old/cmd/setup_vehicle.go similarity index 100% rename from backend/cmd/setup_vehicle.go rename to backend_old/cmd/setup_vehicle.go diff --git a/backend/go.mod b/backend_old/go.mod similarity index 100% rename from backend/go.mod rename to backend_old/go.mod diff --git a/backend/go.sum b/backend_old/go.sum similarity index 100% rename from backend/go.sum rename to backend_old/go.sum diff --git a/backend/internal/common/chan.go b/backend_old/internal/common/chan.go similarity index 100% rename from backend/internal/common/chan.go rename to backend_old/internal/common/chan.go diff --git a/backend/internal/common/errors.go b/backend_old/internal/common/errors.go similarity index 100% rename from backend/internal/common/errors.go rename to backend_old/internal/common/errors.go diff --git a/backend/internal/common/io.go b/backend_old/internal/common/io.go similarity index 100% rename from backend/internal/common/io.go rename to backend_old/internal/common/io.go diff --git a/backend/internal/common/map.go b/backend_old/internal/common/map.go similarity index 100% rename from backend/internal/common/map.go rename to backend_old/internal/common/map.go diff --git a/backend/internal/common/moving_average.go b/backend_old/internal/common/moving_average.go similarity index 100% rename from backend/internal/common/moving_average.go rename to backend_old/internal/common/moving_average.go diff --git a/backend/internal/common/net.go b/backend_old/internal/common/net.go similarity index 100% rename from backend/internal/common/net.go rename to backend_old/internal/common/net.go diff --git a/backend/internal/common/numbers.go b/backend_old/internal/common/numbers.go similarity index 100% rename from backend/internal/common/numbers.go rename to backend_old/internal/common/numbers.go diff --git a/backend/internal/common/ring_buf.go b/backend_old/internal/common/ring_buf.go similarity index 100% rename from backend/internal/common/ring_buf.go rename to backend_old/internal/common/ring_buf.go diff --git a/backend/internal/common/set.go b/backend_old/internal/common/set.go similarity index 100% rename from backend/internal/common/set.go rename to backend_old/internal/common/set.go diff --git a/backend/internal/common/slice.go b/backend_old/internal/common/slice.go similarity index 100% rename from backend/internal/common/slice.go rename to backend_old/internal/common/slice.go diff --git a/backend/internal/common/types.go b/backend_old/internal/common/types.go similarity index 100% rename from backend/internal/common/types.go rename to backend_old/internal/common/types.go diff --git a/backend/internal/config/config.go b/backend_old/internal/config/config.go similarity index 100% rename from backend/internal/config/config.go rename to backend_old/internal/config/config.go diff --git a/backend/internal/config/config_types.go b/backend_old/internal/config/config_types.go similarity index 100% rename from backend/internal/config/config_types.go rename to backend_old/internal/config/config_types.go diff --git a/backend/internal/flags/flags.go b/backend_old/internal/flags/flags.go similarity index 100% rename from backend/internal/flags/flags.go rename to backend_old/internal/flags/flags.go diff --git a/backend/internal/pod_data/measurement.go b/backend_old/internal/pod_data/measurement.go similarity index 100% rename from backend/internal/pod_data/measurement.go rename to backend_old/internal/pod_data/measurement.go diff --git a/backend/internal/pod_data/models.go b/backend_old/internal/pod_data/models.go similarity index 100% rename from backend/internal/pod_data/models.go rename to backend_old/internal/pod_data/models.go diff --git a/backend/internal/pod_data/pod_data.go b/backend_old/internal/pod_data/pod_data.go similarity index 100% rename from backend/internal/pod_data/pod_data.go rename to backend_old/internal/pod_data/pod_data.go diff --git a/backend/internal/pod_data/sortable_packets.go b/backend_old/internal/pod_data/sortable_packets.go similarity index 100% rename from backend/internal/pod_data/sortable_packets.go rename to backend_old/internal/pod_data/sortable_packets.go diff --git a/backend/internal/server/config.go b/backend_old/internal/server/config.go similarity index 100% rename from backend/internal/server/config.go rename to backend_old/internal/server/config.go diff --git a/backend/internal/update_factory/models/update.go b/backend_old/internal/update_factory/models/update.go similarity index 100% rename from backend/internal/update_factory/models/update.go rename to backend_old/internal/update_factory/models/update.go diff --git a/backend/internal/update_factory/update_factory.go b/backend_old/internal/update_factory/update_factory.go similarity index 100% rename from backend/internal/update_factory/update_factory.go rename to backend_old/internal/update_factory/update_factory.go diff --git a/backend/internal/utils/units.go b/backend_old/internal/utils/units.go similarity index 100% rename from backend/internal/utils/units.go rename to backend_old/internal/utils/units.go diff --git a/backend/internal/vehicle/config.go b/backend_old/internal/vehicle/config.go similarity index 100% rename from backend/internal/vehicle/config.go rename to backend_old/internal/vehicle/config.go diff --git a/backend/internal/vehicle/models/order_data.go b/backend_old/internal/vehicle/models/order_data.go similarity index 100% rename from backend/internal/vehicle/models/order_data.go rename to backend_old/internal/vehicle/models/order_data.go diff --git a/backend/internal/vehicle/packet_parser/config.go b/backend_old/internal/vehicle/packet_parser/config.go similarity index 100% rename from backend/internal/vehicle/packet_parser/config.go rename to backend_old/internal/vehicle/packet_parser/config.go diff --git a/backend/package-lock.json b/backend_old/package-lock.json similarity index 100% rename from backend/package-lock.json rename to backend_old/package-lock.json diff --git a/backend/package.json b/backend_old/package.json similarity index 100% rename from backend/package.json rename to backend_old/package.json diff --git a/backend/pkg/abstraction/board.go b/backend_old/pkg/abstraction/board.go similarity index 100% rename from backend/pkg/abstraction/board.go rename to backend_old/pkg/abstraction/board.go diff --git a/backend/pkg/abstraction/broker.go b/backend_old/pkg/abstraction/broker.go similarity index 100% rename from backend/pkg/abstraction/broker.go rename to backend_old/pkg/abstraction/broker.go diff --git a/backend/pkg/abstraction/logger.go b/backend_old/pkg/abstraction/logger.go similarity index 100% rename from backend/pkg/abstraction/logger.go rename to backend_old/pkg/abstraction/logger.go diff --git a/backend/pkg/abstraction/packet.go b/backend_old/pkg/abstraction/packet.go similarity index 100% rename from backend/pkg/abstraction/packet.go rename to backend_old/pkg/abstraction/packet.go diff --git a/backend/pkg/abstraction/transport.go b/backend_old/pkg/abstraction/transport.go similarity index 100% rename from backend/pkg/abstraction/transport.go rename to backend_old/pkg/abstraction/transport.go diff --git a/backend/pkg/adj/adj.go b/backend_old/pkg/adj/adj.go similarity index 100% rename from backend/pkg/adj/adj.go rename to backend_old/pkg/adj/adj.go diff --git a/backend/pkg/adj/boards.go b/backend_old/pkg/adj/boards.go similarity index 100% rename from backend/pkg/adj/boards.go rename to backend_old/pkg/adj/boards.go diff --git a/backend/pkg/adj/git.go b/backend_old/pkg/adj/git.go similarity index 100% rename from backend/pkg/adj/git.go rename to backend_old/pkg/adj/git.go diff --git a/backend/pkg/adj/models.go b/backend_old/pkg/adj/models.go similarity index 100% rename from backend/pkg/adj/models.go rename to backend_old/pkg/adj/models.go diff --git a/backend/pkg/adj/validator.go b/backend_old/pkg/adj/validator.go similarity index 100% rename from backend/pkg/adj/validator.go rename to backend_old/pkg/adj/validator.go diff --git a/backend/pkg/boards/errors.go b/backend_old/pkg/boards/errors.go similarity index 100% rename from backend/pkg/boards/errors.go rename to backend_old/pkg/boards/errors.go diff --git a/backend/pkg/boards/events.go b/backend_old/pkg/boards/events.go similarity index 100% rename from backend/pkg/boards/events.go rename to backend_old/pkg/boards/events.go diff --git a/backend/pkg/broker/broker.go b/backend_old/pkg/broker/broker.go similarity index 100% rename from backend/pkg/broker/broker.go rename to backend_old/pkg/broker/broker.go diff --git a/backend/pkg/broker/errors.go b/backend_old/pkg/broker/errors.go similarity index 100% rename from backend/pkg/broker/errors.go rename to backend_old/pkg/broker/errors.go diff --git a/backend/pkg/broker/topics/connection/connection_test.go b/backend_old/pkg/broker/topics/connection/connection_test.go similarity index 100% rename from backend/pkg/broker/topics/connection/connection_test.go rename to backend_old/pkg/broker/topics/connection/connection_test.go diff --git a/backend/pkg/broker/topics/connection/push.go b/backend_old/pkg/broker/topics/connection/push.go similarity index 100% rename from backend/pkg/broker/topics/connection/push.go rename to backend_old/pkg/broker/topics/connection/push.go diff --git a/backend/pkg/broker/topics/connection/update.go b/backend_old/pkg/broker/topics/connection/update.go similarity index 100% rename from backend/pkg/broker/topics/connection/update.go rename to backend_old/pkg/broker/topics/connection/update.go diff --git a/backend/pkg/broker/topics/data/data_test.go b/backend_old/pkg/broker/topics/data/data_test.go similarity index 100% rename from backend/pkg/broker/topics/data/data_test.go rename to backend_old/pkg/broker/topics/data/data_test.go diff --git a/backend/pkg/broker/topics/data/push.go b/backend_old/pkg/broker/topics/data/push.go similarity index 100% rename from backend/pkg/broker/topics/data/push.go rename to backend_old/pkg/broker/topics/data/push.go diff --git a/backend/pkg/broker/topics/data/update.go b/backend_old/pkg/broker/topics/data/update.go similarity index 100% rename from backend/pkg/broker/topics/data/update.go rename to backend_old/pkg/broker/topics/data/update.go diff --git a/backend/pkg/broker/topics/errors.go b/backend_old/pkg/broker/topics/errors.go similarity index 100% rename from backend/pkg/broker/topics/errors.go rename to backend_old/pkg/broker/topics/errors.go diff --git a/backend/pkg/broker/topics/logger/enable.go b/backend_old/pkg/broker/topics/logger/enable.go similarity index 100% rename from backend/pkg/broker/topics/logger/enable.go rename to backend_old/pkg/broker/topics/logger/enable.go diff --git a/backend/pkg/broker/topics/logger/logger_test.go b/backend_old/pkg/broker/topics/logger/logger_test.go similarity index 100% rename from backend/pkg/broker/topics/logger/logger_test.go rename to backend_old/pkg/broker/topics/logger/logger_test.go diff --git a/backend/pkg/broker/topics/message/message_test.go b/backend_old/pkg/broker/topics/message/message_test.go similarity index 100% rename from backend/pkg/broker/topics/message/message_test.go rename to backend_old/pkg/broker/topics/message/message_test.go diff --git a/backend/pkg/broker/topics/message/update.go b/backend_old/pkg/broker/topics/message/update.go similarity index 100% rename from backend/pkg/broker/topics/message/update.go rename to backend_old/pkg/broker/topics/message/update.go diff --git a/backend/pkg/broker/topics/order/order_test.go b/backend_old/pkg/broker/topics/order/order_test.go similarity index 100% rename from backend/pkg/broker/topics/order/order_test.go rename to backend_old/pkg/broker/topics/order/order_test.go diff --git a/backend/pkg/broker/topics/order/send.go b/backend_old/pkg/broker/topics/order/send.go similarity index 100% rename from backend/pkg/broker/topics/order/send.go rename to backend_old/pkg/broker/topics/order/send.go diff --git a/backend/pkg/broker/topics/order/state.go b/backend_old/pkg/broker/topics/order/state.go similarity index 100% rename from backend/pkg/broker/topics/order/state.go rename to backend_old/pkg/broker/topics/order/state.go diff --git a/backend/pkg/broker/topics/tests_functions/tests_functions.go b/backend_old/pkg/broker/topics/tests_functions/tests_functions.go similarity index 100% rename from backend/pkg/broker/topics/tests_functions/tests_functions.go rename to backend_old/pkg/broker/topics/tests_functions/tests_functions.go diff --git a/backend/pkg/broker/topics/topic.go b/backend_old/pkg/broker/topics/topic.go similarity index 100% rename from backend/pkg/broker/topics/topic.go rename to backend_old/pkg/broker/topics/topic.go diff --git a/backend/pkg/http/handlers.go b/backend_old/pkg/http/handlers.go similarity index 100% rename from backend/pkg/http/handlers.go rename to backend_old/pkg/http/handlers.go diff --git a/backend/pkg/http/mux.go b/backend_old/pkg/http/mux.go similarity index 100% rename from backend/pkg/http/mux.go rename to backend_old/pkg/http/mux.go diff --git a/backend/pkg/http/server.go b/backend_old/pkg/http/server.go similarity index 100% rename from backend/pkg/http/server.go rename to backend_old/pkg/http/server.go diff --git a/backend/pkg/logger/.gitignore b/backend_old/pkg/logger/.gitignore similarity index 100% rename from backend/pkg/logger/.gitignore rename to backend_old/pkg/logger/.gitignore diff --git a/backend/pkg/logger/base/logger.go b/backend_old/pkg/logger/base/logger.go similarity index 100% rename from backend/pkg/logger/base/logger.go rename to backend_old/pkg/logger/base/logger.go diff --git a/backend/pkg/logger/base/logger_test.go b/backend_old/pkg/logger/base/logger_test.go similarity index 100% rename from backend/pkg/logger/base/logger_test.go rename to backend_old/pkg/logger/base/logger_test.go diff --git a/backend/pkg/logger/data/.gitignore b/backend_old/pkg/logger/data/.gitignore similarity index 100% rename from backend/pkg/logger/data/.gitignore rename to backend_old/pkg/logger/data/.gitignore diff --git a/backend/pkg/logger/data/logger.go b/backend_old/pkg/logger/data/logger.go similarity index 100% rename from backend/pkg/logger/data/logger.go rename to backend_old/pkg/logger/data/logger.go diff --git a/backend/pkg/logger/data/logger_test.go b/backend_old/pkg/logger/data/logger_test.go similarity index 100% rename from backend/pkg/logger/data/logger_test.go rename to backend_old/pkg/logger/data/logger_test.go diff --git a/backend/pkg/logger/errors.go b/backend_old/pkg/logger/errors.go similarity index 100% rename from backend/pkg/logger/errors.go rename to backend_old/pkg/logger/errors.go diff --git a/backend/pkg/logger/file/csv.go b/backend_old/pkg/logger/file/csv.go similarity index 100% rename from backend/pkg/logger/file/csv.go rename to backend_old/pkg/logger/file/csv.go diff --git a/backend/pkg/logger/file/csv_test.go b/backend_old/pkg/logger/file/csv_test.go similarity index 100% rename from backend/pkg/logger/file/csv_test.go rename to backend_old/pkg/logger/file/csv_test.go diff --git a/backend/pkg/logger/logger.go b/backend_old/pkg/logger/logger.go similarity index 100% rename from backend/pkg/logger/logger.go rename to backend_old/pkg/logger/logger.go diff --git a/backend/pkg/logger/logger_test.go b/backend_old/pkg/logger/logger_test.go similarity index 100% rename from backend/pkg/logger/logger_test.go rename to backend_old/pkg/logger/logger_test.go diff --git a/backend/pkg/logger/order/logger.go b/backend_old/pkg/logger/order/logger.go similarity index 100% rename from backend/pkg/logger/order/logger.go rename to backend_old/pkg/logger/order/logger.go diff --git a/backend/pkg/logger/order/logger_test.go b/backend_old/pkg/logger/order/logger_test.go similarity index 100% rename from backend/pkg/logger/order/logger_test.go rename to backend_old/pkg/logger/order/logger_test.go diff --git a/backend/pkg/logger/protection/logger.go b/backend_old/pkg/logger/protection/logger.go similarity index 100% rename from backend/pkg/logger/protection/logger.go rename to backend_old/pkg/logger/protection/logger.go diff --git a/backend/pkg/logger/state/logger.go b/backend_old/pkg/logger/state/logger.go similarity index 100% rename from backend/pkg/logger/state/logger.go rename to backend_old/pkg/logger/state/logger.go diff --git a/backend/pkg/logger/time.go b/backend_old/pkg/logger/time.go similarity index 100% rename from backend/pkg/logger/time.go rename to backend_old/pkg/logger/time.go diff --git a/backend/pkg/logger/time_test.go b/backend_old/pkg/logger/time_test.go similarity index 100% rename from backend/pkg/logger/time_test.go rename to backend_old/pkg/logger/time_test.go diff --git a/backend/pkg/logger/trace/trace.go b/backend_old/pkg/logger/trace/trace.go similarity index 100% rename from backend/pkg/logger/trace/trace.go rename to backend_old/pkg/logger/trace/trace.go diff --git a/backend/pkg/logger/validator/validator.go b/backend_old/pkg/logger/validator/validator.go similarity index 100% rename from backend/pkg/logger/validator/validator.go rename to backend_old/pkg/logger/validator/validator.go diff --git a/backend/pkg/transport/constructor.go b/backend_old/pkg/transport/constructor.go similarity index 100% rename from backend/pkg/transport/constructor.go rename to backend_old/pkg/transport/constructor.go diff --git a/backend/pkg/transport/errors.go b/backend_old/pkg/transport/errors.go similarity index 100% rename from backend/pkg/transport/errors.go rename to backend_old/pkg/transport/errors.go diff --git a/backend/pkg/transport/keepalive.go b/backend_old/pkg/transport/keepalive.go similarity index 100% rename from backend/pkg/transport/keepalive.go rename to backend_old/pkg/transport/keepalive.go diff --git a/backend/pkg/transport/messages.go b/backend_old/pkg/transport/messages.go similarity index 100% rename from backend/pkg/transport/messages.go rename to backend_old/pkg/transport/messages.go diff --git a/backend/pkg/transport/network/payload.go b/backend_old/pkg/transport/network/payload.go similarity index 100% rename from backend/pkg/transport/network/payload.go rename to backend_old/pkg/transport/network/payload.go diff --git a/backend/pkg/transport/network/sniffer/errors.go b/backend_old/pkg/transport/network/sniffer/errors.go similarity index 100% rename from backend/pkg/transport/network/sniffer/errors.go rename to backend_old/pkg/transport/network/sniffer/errors.go diff --git a/backend/pkg/transport/network/tcp/client.go b/backend_old/pkg/transport/network/tcp/client.go similarity index 100% rename from backend/pkg/transport/network/tcp/client.go rename to backend_old/pkg/transport/network/tcp/client.go diff --git a/backend/pkg/transport/network/tcp/config.go b/backend_old/pkg/transport/network/tcp/config.go similarity index 100% rename from backend/pkg/transport/network/tcp/config.go rename to backend_old/pkg/transport/network/tcp/config.go diff --git a/backend/pkg/transport/network/tcp/conn.go b/backend_old/pkg/transport/network/tcp/conn.go similarity index 100% rename from backend/pkg/transport/network/tcp/conn.go rename to backend_old/pkg/transport/network/tcp/conn.go diff --git a/backend/pkg/transport/network/tcp/server.go b/backend_old/pkg/transport/network/tcp/server.go similarity index 100% rename from backend/pkg/transport/network/tcp/server.go rename to backend_old/pkg/transport/network/tcp/server.go diff --git a/backend/pkg/transport/network/tcp/tcp_test.go b/backend_old/pkg/transport/network/tcp/tcp_test.go similarity index 100% rename from backend/pkg/transport/network/tcp/tcp_test.go rename to backend_old/pkg/transport/network/tcp/tcp_test.go diff --git a/backend/pkg/transport/network/udp/server.go b/backend_old/pkg/transport/network/udp/server.go similarity index 100% rename from backend/pkg/transport/network/udp/server.go rename to backend_old/pkg/transport/network/udp/server.go diff --git a/backend/pkg/transport/notifications.go b/backend_old/pkg/transport/notifications.go similarity index 100% rename from backend/pkg/transport/notifications.go rename to backend_old/pkg/transport/notifications.go diff --git a/backend/pkg/transport/packet/data/codec.go b/backend_old/pkg/transport/packet/data/codec.go similarity index 100% rename from backend/pkg/transport/packet/data/codec.go rename to backend_old/pkg/transport/packet/data/codec.go diff --git a/backend/pkg/transport/packet/data/converter.go b/backend_old/pkg/transport/packet/data/converter.go similarity index 100% rename from backend/pkg/transport/packet/data/converter.go rename to backend_old/pkg/transport/packet/data/converter.go diff --git a/backend/pkg/transport/packet/data/decoder.go b/backend_old/pkg/transport/packet/data/decoder.go similarity index 100% rename from backend/pkg/transport/packet/data/decoder.go rename to backend_old/pkg/transport/packet/data/decoder.go diff --git a/backend/pkg/transport/packet/data/descriptors.go b/backend_old/pkg/transport/packet/data/descriptors.go similarity index 100% rename from backend/pkg/transport/packet/data/descriptors.go rename to backend_old/pkg/transport/packet/data/descriptors.go diff --git a/backend/pkg/transport/packet/data/encoder.go b/backend_old/pkg/transport/packet/data/encoder.go similarity index 100% rename from backend/pkg/transport/packet/data/encoder.go rename to backend_old/pkg/transport/packet/data/encoder.go diff --git a/backend/pkg/transport/packet/data/errors.go b/backend_old/pkg/transport/packet/data/errors.go similarity index 100% rename from backend/pkg/transport/packet/data/errors.go rename to backend_old/pkg/transport/packet/data/errors.go diff --git a/backend/pkg/transport/packet/data/packet.go b/backend_old/pkg/transport/packet/data/packet.go similarity index 100% rename from backend/pkg/transport/packet/data/packet.go rename to backend_old/pkg/transport/packet/data/packet.go diff --git a/backend/pkg/transport/packet/data/value.go b/backend_old/pkg/transport/packet/data/value.go similarity index 100% rename from backend/pkg/transport/packet/data/value.go rename to backend_old/pkg/transport/packet/data/value.go diff --git a/backend/pkg/transport/packet/order/codec.go b/backend_old/pkg/transport/packet/order/codec.go similarity index 100% rename from backend/pkg/transport/packet/order/codec.go rename to backend_old/pkg/transport/packet/order/codec.go diff --git a/backend/pkg/transport/packet/order/decoder.go b/backend_old/pkg/transport/packet/order/decoder.go similarity index 100% rename from backend/pkg/transport/packet/order/decoder.go rename to backend_old/pkg/transport/packet/order/decoder.go diff --git a/backend/pkg/transport/packet/order/errors.go b/backend_old/pkg/transport/packet/order/errors.go similarity index 100% rename from backend/pkg/transport/packet/order/errors.go rename to backend_old/pkg/transport/packet/order/errors.go diff --git a/backend/pkg/transport/packet/order/packet.go b/backend_old/pkg/transport/packet/order/packet.go similarity index 100% rename from backend/pkg/transport/packet/order/packet.go rename to backend_old/pkg/transport/packet/order/packet.go diff --git a/backend/pkg/transport/packet/protection/decoder.go b/backend_old/pkg/transport/packet/protection/decoder.go similarity index 100% rename from backend/pkg/transport/packet/protection/decoder.go rename to backend_old/pkg/transport/packet/protection/decoder.go diff --git a/backend/pkg/transport/packet/protection/errors.go b/backend_old/pkg/transport/packet/protection/errors.go similarity index 100% rename from backend/pkg/transport/packet/protection/errors.go rename to backend_old/pkg/transport/packet/protection/errors.go diff --git a/backend/pkg/transport/packet/protection/kind.go b/backend_old/pkg/transport/packet/protection/kind.go similarity index 100% rename from backend/pkg/transport/packet/protection/kind.go rename to backend_old/pkg/transport/packet/protection/kind.go diff --git a/backend/pkg/transport/packet/protection/packet.go b/backend_old/pkg/transport/packet/protection/packet.go similarity index 100% rename from backend/pkg/transport/packet/protection/packet.go rename to backend_old/pkg/transport/packet/protection/packet.go diff --git a/backend/pkg/transport/packet/state/decoder.go b/backend_old/pkg/transport/packet/state/decoder.go similarity index 100% rename from backend/pkg/transport/packet/state/decoder.go rename to backend_old/pkg/transport/packet/state/decoder.go diff --git a/backend/pkg/transport/packet/state/packet.go b/backend_old/pkg/transport/packet/state/packet.go similarity index 100% rename from backend/pkg/transport/packet/state/packet.go rename to backend_old/pkg/transport/packet/state/packet.go diff --git a/backend/pkg/transport/presentation/decoder.go b/backend_old/pkg/transport/presentation/decoder.go similarity index 100% rename from backend/pkg/transport/presentation/decoder.go rename to backend_old/pkg/transport/presentation/decoder.go diff --git a/backend/pkg/transport/presentation/decoder_test.go b/backend_old/pkg/transport/presentation/decoder_test.go similarity index 100% rename from backend/pkg/transport/presentation/decoder_test.go rename to backend_old/pkg/transport/presentation/decoder_test.go diff --git a/backend/pkg/transport/presentation/encoder.go b/backend_old/pkg/transport/presentation/encoder.go similarity index 100% rename from backend/pkg/transport/presentation/encoder.go rename to backend_old/pkg/transport/presentation/encoder.go diff --git a/backend/pkg/transport/presentation/encoder_test.go b/backend_old/pkg/transport/presentation/encoder_test.go similarity index 100% rename from backend/pkg/transport/presentation/encoder_test.go rename to backend_old/pkg/transport/presentation/encoder_test.go diff --git a/backend/pkg/transport/presentation/errors.go b/backend_old/pkg/transport/presentation/errors.go similarity index 100% rename from backend/pkg/transport/presentation/errors.go rename to backend_old/pkg/transport/presentation/errors.go diff --git a/backend/pkg/transport/session/buffer.go b/backend_old/pkg/transport/session/buffer.go similarity index 100% rename from backend/pkg/transport/session/buffer.go rename to backend_old/pkg/transport/session/buffer.go diff --git a/backend/pkg/transport/transport.go b/backend_old/pkg/transport/transport.go similarity index 100% rename from backend/pkg/transport/transport.go rename to backend_old/pkg/transport/transport.go diff --git a/backend/pkg/vehicle/constructor.go b/backend_old/pkg/vehicle/constructor.go similarity index 100% rename from backend/pkg/vehicle/constructor.go rename to backend_old/pkg/vehicle/constructor.go diff --git a/backend/pkg/vehicle/errors.go b/backend_old/pkg/vehicle/errors.go similarity index 100% rename from backend/pkg/vehicle/errors.go rename to backend_old/pkg/vehicle/errors.go diff --git a/backend/pkg/vehicle/notification.go b/backend_old/pkg/vehicle/notification.go similarity index 100% rename from backend/pkg/vehicle/notification.go rename to backend_old/pkg/vehicle/notification.go diff --git a/backend/pkg/vehicle/vehicle.go b/backend_old/pkg/vehicle/vehicle.go similarity index 100% rename from backend/pkg/vehicle/vehicle.go rename to backend_old/pkg/vehicle/vehicle.go diff --git a/backend/pkg/websocket/client.go b/backend_old/pkg/websocket/client.go similarity index 100% rename from backend/pkg/websocket/client.go rename to backend_old/pkg/websocket/client.go diff --git a/backend/pkg/websocket/errors.go b/backend_old/pkg/websocket/errors.go similarity index 100% rename from backend/pkg/websocket/errors.go rename to backend_old/pkg/websocket/errors.go diff --git a/backend/pkg/websocket/pool.go b/backend_old/pkg/websocket/pool.go similarity index 100% rename from backend/pkg/websocket/pool.go rename to backend_old/pkg/websocket/pool.go diff --git a/backend/pkg/websocket/upgrader.go b/backend_old/pkg/websocket/upgrader.go similarity index 100% rename from backend/pkg/websocket/upgrader.go rename to backend_old/pkg/websocket/upgrader.go diff --git a/backend/scripts/analyze_trace.py b/backend_old/scripts/analyze_trace.py similarity index 100% rename from backend/scripts/analyze_trace.py rename to backend_old/scripts/analyze_trace.py From 67f90152d6a1b02ae4e81a3b987b6505d8d43787 Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Tue, 29 Sep 2026 00:25:42 +0200 Subject: [PATCH 002/225] feat: basic setup --- backend/.gitignore | 7 + backend/Cargo.lock | 602 +++++++++++++++++++++++++ backend/Cargo.toml | 44 ++ backend/crates/core/Cargo.toml | 46 ++ backend/crates/core/README.md | 32 ++ backend/crates/core/src/hello_world.rs | 50 ++ backend/crates/core/src/lib.rs | 3 + backend/crates/station/Cargo.toml | 22 + backend/crates/station/README.md | 17 + backend/crates/station/src/main.rs | 13 + backend/package.json | 15 + backend/readme-demo.md | 42 ++ backend/rust-toolchain.toml | 3 + backend/rustfmt.toml | 3 + 14 files changed, 899 insertions(+) create mode 100644 backend/.gitignore create mode 100644 backend/Cargo.lock create mode 100644 backend/Cargo.toml create mode 100644 backend/crates/core/Cargo.toml create mode 100644 backend/crates/core/README.md create mode 100644 backend/crates/core/src/hello_world.rs create mode 100644 backend/crates/core/src/lib.rs create mode 100644 backend/crates/station/Cargo.toml create mode 100644 backend/crates/station/README.md create mode 100644 backend/crates/station/src/main.rs create mode 100644 backend/package.json create mode 100644 backend/readme-demo.md create mode 100644 backend/rust-toolchain.toml create mode 100644 backend/rustfmt.toml diff --git a/backend/.gitignore b/backend/.gitignore new file mode 100644 index 000000000..d51409096 --- /dev/null +++ b/backend/.gitignore @@ -0,0 +1,7 @@ +/target +/bin + +# Backend runtime output +/logger/ +*.log +*.csv diff --git a/backend/Cargo.lock b/backend/Cargo.lock new file mode 100644 index 000000000..94186abdf --- /dev/null +++ b/backend/Cargo.lock @@ -0,0 +1,602 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "crossbeam-channel" +version = "0.5.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "98b0cc327b5bc766e7fda9c9260cc0fa81b43a8e240440422dff70788e3f9ef1" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" + +[[package]] +name = "deranged" +version = "0.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c" +dependencies = [ + "powerfmt", +] + +[[package]] +name = "equivalent" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "lazy_static" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" + +[[package]] +name = "libc" +version = "0.2.189" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" + +[[package]] +name = "log" +version = "0.4.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" + +[[package]] +name = "matchers" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9" +dependencies = [ + "regex-automata", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "mio" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b18443e9c262bfe8fa82f51666e2642c53393f7e5c27b3e1aeab922cff5b9d8" +dependencies = [ + "libc", + "wasi", + "windows-sys", +] + +[[package]] +name = "nu-ansi-term" +version = "0.50.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" +dependencies = [ + "windows-sys", +] + +[[package]] +name = "num-conv" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "51d515d32fb182ee37cda2ccdcb92950d6a3c2893aa280e540671c2cd0f3b1d9" + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "powerfmt" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "regex-automata" +version = "0.4.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "serde_json" +version = "1.0.151" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_spanned" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6662b5879511e06e8999a8a235d848113e942c9124f211511b16466ee2995f26" +dependencies = [ + "serde_core", +] + +[[package]] +name = "sharded-slab" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6" +dependencies = [ + "lazy_static", +] + +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + +[[package]] +name = "smallvec" +version = "1.16.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9395f0f0eee849a9b707b2f06bb92a6a422090e2123bb2ef8e87a0e61892a8e" + +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys", +] + +[[package]] +name = "software-core" +version = "0.1.0" +dependencies = [ + "bytes", + "serde", + "thiserror", + "tokio", + "tracing", + "tracing-appender", + "tracing-subscriber", +] + +[[package]] +name = "station" +version = "0.1.0" +dependencies = [ + "serde", + "software-core", + "thiserror", + "tokio", + "toml", + "tracing", + "tracing-subscriber", +] + +[[package]] +name = "symlink" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7973cce6668464ea31f176d85b13c7ab3bba2cb3b77a2ed26abd7801688010a" + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8593e8e72159ed2257d083c7a454a85cbf854f37a0966d8d483aff8c8a3ebcee" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "thread_local" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ad99c4c6d32803332c548b1af0540b357b3f5fc0be8f6c6bfe8b2e6ae784070" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "time" +version = "0.3.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9e442fc33d7fdb45aa9bfeb312c095964abdf596f7567261062b2a7107aaabd" +dependencies = [ + "deranged", + "itoa", + "num-conv", + "powerfmt", + "serde_core", + "time-core", + "time-macros", +] + +[[package]] +name = "time-core" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b36ee98fd31ec7426d599183e8fe26932a8dc1fb76ddb6214d05493377d34ca" + +[[package]] +name = "time-macros" +version = "0.2.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "71e552d1249bf61ac2a52db88179fd0673def1e1ad8243a00d9ec9ed71fee3dd" +dependencies = [ + "num-conv", + "time-core", +] + +[[package]] +name = "tokio" +version = "1.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "202caea871b69668250d242070849eb495be178ed697a3e98aebce5bc81a0bed" +dependencies = [ + "libc", + "mio", + "pin-project-lite", + "signal-hook-registry", + "socket2", + "tokio-macros", + "windows-sys", +] + +[[package]] +name = "tokio-macros" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "toml" +version = "0.9.12+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf92845e79fc2e2def6a5d828f0801e29a2f8acc037becc5ab08595c7d5e9863" +dependencies = [ + "indexmap", + "serde_core", + "serde_spanned", + "toml_datetime", + "toml_parser", + "toml_writer", + "winnow 0.7.15", +] + +[[package]] +name = "toml_datetime" +version = "0.7.5+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92e1cfed4a3038bc5a127e35a2d360f145e1f4b971b551a2ba5fd7aedf7e1347" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_parser" +version = "1.1.3+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d38ac1cf9b95face32296c0a3ede1fdc270627c9d9c02a7274dd6d960dc4d56" +dependencies = [ + "winnow 1.0.4", +] + +[[package]] +name = "toml_writer" +version = "1.1.2+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d56353a2a665ad0f41a421187180aab746c8c325620617ad883a99a1cbe66d2" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-appender" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "050686193eb999b4bb3bc2acfa891a13da00f79734704c4b8b4ef1a10b368a3c" +dependencies = [ + "crossbeam-channel", + "symlink", + "thiserror", + "time", + "tracing-subscriber", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", + "valuable", +] + +[[package]] +name = "tracing-log" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3" +dependencies = [ + "log", + "once_cell", + "tracing-core", +] + +[[package]] +name = "tracing-serde" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "704b1aeb7be0d0a84fc9828cae51dab5970fee5088f83d1dd7ee6f6246fc6ff1" +dependencies = [ + "serde", + "tracing-core", +] + +[[package]] +name = "tracing-subscriber" +version = "0.3.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319" +dependencies = [ + "matchers", + "nu-ansi-term", + "once_cell", + "regex-automata", + "serde", + "serde_json", + "sharded-slab", + "smallvec", + "thread_local", + "tracing", + "tracing-core", + "tracing-log", + "tracing-serde", +] + +[[package]] +name = "unicode-ident" +version = "1.0.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954" + +[[package]] +name = "valuable" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "winnow" +version = "0.7.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945" + +[[package]] +name = "winnow" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81" + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/backend/Cargo.toml b/backend/Cargo.toml new file mode 100644 index 000000000..d9aeeb64e --- /dev/null +++ b/backend/Cargo.toml @@ -0,0 +1,44 @@ +[workspace] +resolver = "3" +members = ["crates/core", "crates/station"] +default-members = ["crates/station"] + +[workspace.package] +edition = "2024" +rust-version = "1.85" +license = "MIT" +authors = [ + "Hyperloop UPV Software Subsystem", + "Javier Ribal del Río", + "Gazi Halawani", + "Pau Minguet Micó" +] +repository = "https://github.com/Hyperloop-UPV/software" + +# Shared dependency versions. Members opt in with `dep.workspace = true`. +[workspace.dependencies] +software-core = { path = "crates/core" } + +bytes = "1" +serde = { version = "1", features = ["derive"] } +thiserror = "2" +tokio = { version = "1", features = ["rt-multi-thread", "macros", "net", "sync", "time", "signal"] } +toml = "0.9" +tracing = "0.1" +tracing-appender = "0.2" +tracing-subscriber = { version = "0.3", features = ["env-filter", "json"] } + +[workspace.lints.rust] +unsafe_code = "forbid" +missing_debug_implementations = "warn" + +[workspace.lints.clippy] +all = { level = "warn", priority = -1 } +unwrap_used = "warn" +expect_used = "warn" +panic = "warn" + +[profile.release] +lto = "thin" +codegen-units = 1 +panic = "abort" diff --git a/backend/crates/core/Cargo.toml b/backend/crates/core/Cargo.toml new file mode 100644 index 000000000..1b38a623e --- /dev/null +++ b/backend/crates/core/Cargo.toml @@ -0,0 +1,46 @@ +[package] +name = "software-core" +version = "0.1.0" +description = "Generic Hyperloop UPV building blocks: ADJ model, packet protocol and transport" +edition.workspace = true +rust-version.workspace = true +license.workspace = true +authors.workspace = true +repository.workspace = true + +[features] +default = [] +# TCP/UDP transport (pulls in tokio) +net = ["dep:tokio"] +# ADJ download through git (dependency added when the module is written) +git = [] +# Packet sniffing through pcap (dependency added when the module is written) +pcap = ["net"] +# CSV data logger (records, sessions, subloggers) +logger = [] +# Reusable tracing/diagnostics setup (console + non-blocking file + stderr layers) +trace = ["dep:tracing-subscriber", "dep:tracing-appender"] + +[dependencies] +bytes.workspace = true +serde.workspace = true +thiserror.workspace = true +tracing.workspace = true +tokio = { workspace = true, optional = true } +tracing-subscriber = { workspace = true, optional = true } +tracing-appender = { workspace = true, optional = true } + +# `workspace = true` can't be combined with extra lints in the same table, +# so the workspace list is repeated here with `missing_docs` added: this is +# the crate meant to be reused by other projects, so its public API must be +# documented. +[lints.rust] +unsafe_code = "forbid" +missing_debug_implementations = "warn" +missing_docs = "warn" + +[lints.clippy] +all = { level = "warn", priority = -1 } +unwrap_used = "warn" +expect_used = "warn" +panic = "warn" diff --git a/backend/crates/core/README.md b/backend/crates/core/README.md new file mode 100644 index 000000000..22ced735d --- /dev/null +++ b/backend/crates/core/README.md @@ -0,0 +1,32 @@ +# software-core + +Piezas genéricas y reutilizables de Hyperloop UPV: modelo de datos, protocolo de +paquetes, lectura del ADJ y transporte de red. No depende de nada propio del +backend (`station`), así que también sirve de base para otras herramientas +como un sniffer o un simulador. + +Ver [`../../ARCHITECTURE.md`](../../ARCHITECTURE.md) para el diseño completo. + +## Módulos + +- `model` — identificadores, paquetes, valores, medidas y unidades. Siempre disponible. +- `protocol` — traduce bytes a paquetes y paquetes a bytes. Siempre disponible. +- `adj` — lee el ADJ y construye los descriptores para `protocol`. +- `net` *(feature `net`)* — conexiones TCP y UDP. +- `logger` *(feature `logger`)* — registro de datos en CSV. +- `trace` *(feature `trace`)* — configuración de trazas de diagnóstico. + +## Features + +```toml +software-core = { path = "...", features = ["net", "adj"] } +``` + +Por defecto no se activa ninguna: quien use el crate paga solo por lo que +necesita. Ver la tabla completa en `ARCHITECTURE.md`, apartado 12. + +## Ejemplo + +```rust +// Pendiente: añadir cuando exista el primer decodificador público. +``` diff --git a/backend/crates/core/src/hello_world.rs b/backend/crates/core/src/hello_world.rs new file mode 100644 index 000000000..2c8b7da23 --- /dev/null +++ b/backend/crates/core/src/hello_world.rs @@ -0,0 +1,50 @@ +//! Demo de una API documentada con eventos y contexto de `tracing`. +//! +//! El ejecutable configura el subscriber; este módulo solo emite eventos. + +/// Construye un saludo para `name`, eliminando espacios exteriores. +/// +/// Si el nombre está vacío o solo contiene espacios, saluda a `World`. +/// Emite detalles a nivel `debug` y el saludo a nivel `info`, dentro de un +/// span que identifica al destinatario. +/// +/// # Ejemplo +/// +/// ``` +/// use software_core::hello_world::greet; +/// +/// assert_eq!(greet("Hyperloop"), "Hello, Hyperloop!"); +/// assert_eq!(greet(""), "Hello, World!"); +/// ``` +#[tracing::instrument(name = "hello_world", skip(name), fields(recipient = %name))] +pub fn greet(name: &str) -> String { + let trimmed = name.trim(); + let recipient = if trimmed.is_empty() { "World" } else { trimmed }; + + tracing::debug!(used_default = trimmed.is_empty(), "destinatario preparado"); + let greeting = format!("Hello, {recipient}!"); + tracing::info!(greeting = %greeting, "saludo generado"); + greeting +} + +#[cfg(test)] +mod tests { + use super::greet; + + #[test] + fn greets_named_recipient() { + assert_eq!(greet("Hyperloop"), "Hello, Hyperloop!"); + } + + #[test] + fn trims_whitespace_and_preserves_unicode() { + assert_eq!(greet(" Lucía 🚄 \n"), "Hello, Lucía 🚄!"); + } + + #[test] + fn defaults_to_world_for_empty_or_whitespace_names() { + for name in ["", " \t\n"] { + assert_eq!(greet(name), "Hello, World!"); + } + } +} diff --git a/backend/crates/core/src/lib.rs b/backend/crates/core/src/lib.rs new file mode 100644 index 000000000..a85bf01dd --- /dev/null +++ b/backend/crates/core/src/lib.rs @@ -0,0 +1,3 @@ +//! Componentes reutilizables de Hyperloop UPV. + +pub mod hello_world; diff --git a/backend/crates/station/Cargo.toml b/backend/crates/station/Cargo.toml new file mode 100644 index 000000000..20c403657 --- /dev/null +++ b/backend/crates/station/Cargo.toml @@ -0,0 +1,22 @@ +[package] +name = "station" +version = "0.1.0" +description = "Hyperloop UPV control station backend, built on software-core" +edition.workspace = true +rust-version.workspace = true +license.workspace = true +authors.workspace = true +repository.workspace = true + +[dependencies] +software-core = { workspace = true, features = ["net", "git"] } + +serde.workspace = true +thiserror.workspace = true +tokio.workspace = true +toml.workspace = true +tracing.workspace = true +tracing-subscriber.workspace = true + +[lints] +workspace = true diff --git a/backend/crates/station/README.md b/backend/crates/station/README.md new file mode 100644 index 000000000..00e8661df --- /dev/null +++ b/backend/crates/station/README.md @@ -0,0 +1,17 @@ +# station + +El backend de la Control Station de Hyperloop UPV: escucha a las placas del +pod, decodifica sus paquetes, los reenvía a los frontends y guarda un +registro en disco. Construido sobre [`software-core`](../core/README.md). + +Ver [`../../ARCHITECTURE.md`](../../ARCHITECTURE.md) para el diseño completo. + +## Arrancar + +```sh +cargo run -p station -- --config ./dev-config.toml +``` + +*(Pendiente: crear `dev-config.toml` y `config.toml`, portados de +`backend_old/cmd/`.)* + diff --git a/backend/crates/station/src/main.rs b/backend/crates/station/src/main.rs new file mode 100644 index 000000000..d872008d1 --- /dev/null +++ b/backend/crates/station/src/main.rs @@ -0,0 +1,13 @@ +//! Ejecutable mínimo para demostrar la integración con `software-core`. + +use tracing_subscriber::EnvFilter; + +fn main() { + let filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info")); + tracing_subscriber::fmt().with_env_filter(filter).init(); + + tracing::info!("iniciando demo de station"); + let name = std::env::args().nth(1).unwrap_or_else(|| "World".into()); + let _greeting = software_core::hello_world::greet(&name); + tracing::info!("demo finalizada"); +} diff --git a/backend/package.json b/backend/package.json new file mode 100644 index 000000000..cd65355be --- /dev/null +++ b/backend/package.json @@ -0,0 +1,15 @@ +{ + "name": "backend", + "version": "1.0.0", + "private": true, + "author": "Hyperloop UPV", + "license": "MIT", + "scripts": { + "dev": "cargo run -p station -- --config ./crates/station/dev-config.toml", + "dev:main": "cargo run -p station --release -- --config ./crates/station/config.toml", + "build": "cargo build -p station --release", + "build:ci": "cargo build --workspace --release", + "lint": "cargo clippy --workspace --all-targets -- -D warnings", + "fmt": "cargo fmt --all" + } +} diff --git a/backend/readme-demo.md b/backend/readme-demo.md new file mode 100644 index 000000000..875c83848 --- /dev/null +++ b/backend/readme-demo.md @@ -0,0 +1,42 @@ +# Demo: core → station + tracing + +Desde `software/backend`, con Rust 1.98.0 y Cargo instalados (la primera +ejecución descarga las dependencias): + +```sh +# Ejecutar: muestra el saludo y el ciclo de vida a nivel INFO. +cargo run -p station +cargo run -p station -- "Hyperloop UPV" + +# Mostrar también DEBUG del módulo, manteniendo INFO en station. +RUST_LOG=info,software_core::hello_world=debug cargo run -p station -- "Lucía" + +# Filtrar todos los eventos de esta demo (no emite errores). +RUST_LOG=error cargo run -p station + +# Tests unitarios y ejemplo de documentación ejecutable (doctest). +cargo test --workspace + +# Generar documentación HTML de la API. +cargo doc --workspace --no-deps + +# Comprobaciones de formato y lints. +cargo fmt --all -- --check +cargo clippy --workspace --all-targets -- -D warnings +``` + +Abre `target/doc/software_core/hello_world/index.html` para ver la API. + +- `crates/core/src/hello_world.rs`: `greet(&str) -> String`, con rustdoc, + un doctest y tres tests unitarios. Recorta espacios; un nombre vacío usa `World`. +- `crates/core/src/lib.rs`: exporta el módulo público. +- `crates/station/src/main.rs`: inicializa el subscriber una sola vez y llama a `greet`. +- `#[tracing::instrument]` crea el span `hello_world`; los eventos incluyen + el destinatario y campos estructurados como `greeting` o `used_default`. + `INFO` muestra el saludo; `DEBUG` permite inspeccionar la elección del destinatario. +- Core solo emite eventos: sin subscriber, devuelve igualmente el saludo. + Los tests comprueban ese resultado sin configurar logging global. + +Esta demo termina tras saludar; todavía no arranca servidores ni carga TOML. +Usa los comandos Cargo de arriba: los scripts `pnpm dev` están preparados para +la futura configuración del backend, que esta demo no interpreta. diff --git a/backend/rust-toolchain.toml b/backend/rust-toolchain.toml new file mode 100644 index 000000000..aa20bc990 --- /dev/null +++ b/backend/rust-toolchain.toml @@ -0,0 +1,3 @@ +[toolchain] +channel = "1.98.0" +components = ["rustfmt", "clippy"] diff --git a/backend/rustfmt.toml b/backend/rustfmt.toml new file mode 100644 index 000000000..4937083a4 --- /dev/null +++ b/backend/rustfmt.toml @@ -0,0 +1,3 @@ +edition = "2024" +max_width = 100 +use_field_init_shorthand = true From dbb1c286d64e8716f0fa3d6020c2e42f3c1d17f7 Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Tue, 29 Sep 2026 01:24:12 +0200 Subject: [PATCH 003/225] wip: new abstraction --- backend/crates/core/src/model/id.rs | 32 ++++ backend/crates/core/src/model/measurement.rs | 162 +++++++++++++++++++ backend/crates/core/src/model/mod.rs | 21 +++ backend/crates/core/src/model/value.rs | 35 ++++ 4 files changed, 250 insertions(+) create mode 100644 backend/crates/core/src/model/id.rs create mode 100644 backend/crates/core/src/model/measurement.rs create mode 100644 backend/crates/core/src/model/mod.rs create mode 100644 backend/crates/core/src/model/value.rs diff --git a/backend/crates/core/src/model/id.rs b/backend/crates/core/src/model/id.rs new file mode 100644 index 000000000..de799e506 --- /dev/null +++ b/backend/crates/core/src/model/id.rs @@ -0,0 +1,32 @@ +//! Domain identifiers. +//! +//! Defined as their own types (wrapping a `u16`) instead of using a plain +//! `u16`, so the compiler won't let an [`AdjId`] be confused with a +//! [`BoardId`] by mistake, even though both are just numbers underneath. + +/// Unique identifier of a packet, order or protection, defined by the ADJ. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub struct AdjId(pub u16); + +/// Unique identifier of a board, defined by the ADJ. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub struct BoardId(pub u16); + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn two_packet_ids_with_the_same_number_are_equal() { + assert_eq!(AdjId(1000), AdjId(1000)); + } + + #[test] + fn packet_id_and_board_id_cannot_be_compared_to_each_other() { + // This wouldn't compile if you tried it: AdjId(1) == BoardId(1) + // That's the whole point of this file: the compiler protects us. + let packet = AdjId(1); + let board = BoardId(1); + assert_eq!(packet.0, board.0); // only the inner numbers can be compared + } +} diff --git a/backend/crates/core/src/model/measurement.rs b/backend/crates/core/src/model/measurement.rs new file mode 100644 index 000000000..5ba0fe16e --- /dev/null +++ b/backend/crates/core/src/model/measurement.rs @@ -0,0 +1,162 @@ +//! Measurement descriptions. +//! +//! A [`Measurement`] describes a single field of a packet, as defined by +//! the ADJ: whether it holds a number, a boolean, or the variant of an +//! enum, and, for numeric measurements, its wire type and its safe and +//! warning ranges. This is a *description*, not a decoded value — see +//! [`super::Value`] for the value itself, once decoded. + +use crate::model::AdjId; + +/// The wire type of a numeric measurement: how many bytes it takes on the +/// wire and whether it is signed. +/// +/// This only matters while decoding. Once a number is decoded it is always +/// stored as a [`super::Value::Number`], regardless of its original wire +/// type. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum NumericKind { + /// Unsigned 8-bit integer. + U8, + /// Unsigned 16-bit integer. + U16, + /// Unsigned 32-bit integer. + U32, + /// Unsigned 64-bit integer. + U64, + /// Signed 8-bit integer. + I8, + /// Signed 16-bit integer. + I16, + /// Signed 32-bit integer. + I32, + /// Signed 64-bit integer. + I64, + /// 32-bit floating point number. + F32, + /// 64-bit floating point number. + F64, +} + +/// An inclusive range with an optional lower and upper bound. +/// +/// Either bound can be missing, meaning that side of the range is +/// unconstrained. For example, `Range { min: Some(0.0), max: None }` means +/// "any value of 0.0 or above". +#[derive(Debug, Clone, Copy, PartialEq, Default)] +pub struct Range { + /// The lower bound, if any. + pub min: Option, + /// The upper bound, if any. + pub max: Option, +} + +/// What kind of data a measurement holds, and the details specific to that +/// kind. +#[derive(Debug, Clone, PartialEq)] +pub enum MeasurementKind { + /// A numeric measurement. + Numeric { + /// How the value is encoded on the wire. + wire_type: NumericKind, + }, + /// A boolean measurement. + Boolean, + /// A measurement whose value is one of a fixed set of named variants. + Enum { + /// The variants this measurement can take, in ADJ order. + options: Vec, + }, +} + +/// The description of a single field of a packet, as defined by the ADJ. +#[derive(Debug, Clone, PartialEq)] +pub struct Measurement { + /// The measurement's ADJid, e.g. `3000`. + pub id: AdjId, + /// The alias used to identify it + pub alias: String, + /// The human-readable name shown to the user. + pub name: String, + + /// The units of the measurement to be shown at tefronend + pub displa_units: String, + + /// What kind of data this measurement holds. + pub kind: MeasurementKind, +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_default_range_has_no_bounds() { + let range = Range::default(); + assert_eq!(range.min, None); + assert_eq!(range.max, None); + } + + #[test] + fn two_measurements_with_the_same_data_are_equal() { + let a = Measurement { + alias: "arming".to_string(), + name: "Arming".to_string(), + kind: MeasurementKind::Boolean, + }; + let b = a.clone(); + assert_eq!(a, b); + } + + #[test] + fn numeric_measurements_carry_their_wire_type_and_ranges() { + let measurement = Measurement { + alias: "voltage".to_string(), + name: "Voltage".to_string(), + kind: MeasurementKind::Numeric { + wire_type: NumericKind::F32, + safe_range: Range { + min: Some(0.0), + max: Some(48.0), + }, + warning_range: Range { + min: Some(-5.0), + max: Some(53.0), + }, + }, + }; + + let MeasurementKind::Numeric { + wire_type, + safe_range, + .. + } = measurement.kind + else { + unreachable!("measurement was just constructed as Numeric above"); + }; + + assert_eq!(wire_type, NumericKind::F32); + assert_eq!(safe_range.max, Some(48.0)); + } + + #[test] + fn enum_measurements_list_their_options_in_adj_order() { + let measurement = Measurement { + id: "state".to_string(), + name: "State".to_string(), + kind: MeasurementKind::Enum { + options: vec![ + "Idle".to_string(), + "Operational".to_string(), + "Fault".to_string(), + ], + }, + }; + + let MeasurementKind::Enum { options } = measurement.kind else { + unreachable!("measurement was just constructed as Enum above"); + }; + + assert_eq!(options, vec!["Idle", "Operational", "Fault"]); + } +} diff --git a/backend/crates/core/src/model/mod.rs b/backend/crates/core/src/model/mod.rs new file mode 100644 index 000000000..50312d878 --- /dev/null +++ b/backend/crates/core/src/model/mod.rs @@ -0,0 +1,21 @@ +//! Basic domain types: identifiers, packets, values, measurements and +//! units. No I/O and no networking here, just data and the operations +//! performed on it. +//! +//! # Upcoming modules (not written yet) +//! +//! - `value` — [`Value`] and unit conversion (pod ⇄ display). +//! - `measurement` — the description of a measurement (its type, its ranges). +//! - `packet` — [`Packet`] and its variants: data, order, state order, protection. +//! - `board` — `PodData`, `Board`: a whole board with its packets. +//! +//! Add each one here with `mod name;` + `pub use name::...;` as you write +//! them, the same way it's done below with `id`. + +mod id; +mod measurement; +mod value; + +pub use id::{AdjId, BoardId}; +pub use measurement::{Measurement, MeasurementKind, NumericKind, Range}; +pub use value::Value; diff --git a/backend/crates/core/src/model/value.rs b/backend/crates/core/src/model/value.rs new file mode 100644 index 000000000..5dcd7e62d --- /dev/null +++ b/backend/crates/core/src/model/value.rs @@ -0,0 +1,35 @@ +//! Decoded values. +//! +//! [`Value`] is how the backend represents a piece of data once it has been +//! decoded, regardless of what it looked like on the wire. Even though the +//! ADJ defines several numeric wire types (`uint8`, `float32`...), once a +//! number is decoded it is always stored as an `f64`: what matters from +//! here on is the number itself, not how many bytes it took on the wire. +//! The wire type only matters while decoding, and lives in `NumericKind` +//! instead. + +/// A single decoded value, of whichever shape the measurement defines. +#[derive(Debug, Clone, PartialEq)] +pub enum Value { + /// A numeric measurement, regardless of its original wire type. + Number(f64), + /// A boolean measurement. + Bool(bool), + /// The selected variant of an enum measurement, e.g. `"Operational"`. + Enum(String), +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn two_numbers_with_the_same_value_are_equal() { + assert_eq!(Value::Number(1.5), Value::Number(1.5)); + } + + #[test] + fn different_variants_are_never_equal_even_with_similar_data() { + assert_ne!(Value::Bool(true), Value::Enum("true".to_string())); + } +} From c7715162d5e891e5276707389c73099960bda90b Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Tue, 29 Sep 2026 09:08:04 +0200 Subject: [PATCH 004/225] wip: meadurement and protections --- backend/crates/core/src/model/measurement.rs | 78 +------------------- backend/crates/core/src/model/protections.rs | 0 2 files changed, 3 insertions(+), 75 deletions(-) create mode 100644 backend/crates/core/src/model/protections.rs diff --git a/backend/crates/core/src/model/measurement.rs b/backend/crates/core/src/model/measurement.rs index 5ba0fe16e..8a8176356 100644 --- a/backend/crates/core/src/model/measurement.rs +++ b/backend/crates/core/src/model/measurement.rs @@ -80,83 +80,11 @@ pub struct Measurement { pub name: String, /// The units of the measurement to be shown at tefronend - pub displa_units: String, + pub display_units: String, /// What kind of data this measurement holds. pub kind: MeasurementKind, -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn a_default_range_has_no_bounds() { - let range = Range::default(); - assert_eq!(range.min, None); - assert_eq!(range.max, None); - } - - #[test] - fn two_measurements_with_the_same_data_are_equal() { - let a = Measurement { - alias: "arming".to_string(), - name: "Arming".to_string(), - kind: MeasurementKind::Boolean, - }; - let b = a.clone(); - assert_eq!(a, b); - } - - #[test] - fn numeric_measurements_carry_their_wire_type_and_ranges() { - let measurement = Measurement { - alias: "voltage".to_string(), - name: "Voltage".to_string(), - kind: MeasurementKind::Numeric { - wire_type: NumericKind::F32, - safe_range: Range { - min: Some(0.0), - max: Some(48.0), - }, - warning_range: Range { - min: Some(-5.0), - max: Some(53.0), - }, - }, - }; - - let MeasurementKind::Numeric { - wire_type, - safe_range, - .. - } = measurement.kind - else { - unreachable!("measurement was just constructed as Numeric above"); - }; - - assert_eq!(wire_type, NumericKind::F32); - assert_eq!(safe_range.max, Some(48.0)); - } - - #[test] - fn enum_measurements_list_their_options_in_adj_order() { - let measurement = Measurement { - id: "state".to_string(), - name: "State".to_string(), - kind: MeasurementKind::Enum { - options: vec![ - "Idle".to_string(), - "Operational".to_string(), - "Fault".to_string(), - ], - }, - }; - - let MeasurementKind::Enum { options } = measurement.kind else { - unreachable!("measurement was just constructed as Enum above"); - }; - assert_eq!(options, vec!["Idle", "Operational", "Fault"]); - } + /// The protectionst that are checked for this messurement. + pub protections: Protections, } diff --git a/backend/crates/core/src/model/protections.rs b/backend/crates/core/src/model/protections.rs new file mode 100644 index 000000000..e69de29bb From c558a1b8dd72f70bfe6c0a3864766a912b917163 Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Wed, 30 Sep 2026 17:22:56 +0200 Subject: [PATCH 005/225] feat(backend): complete core::model with protections, packets and boards MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Implements the ADJv3 domain types for software-core: - measurement: add numeric id + alias (per ADJv3 §2), display_units, and a protections list; drop the now-superseded safe/warning ranges - protections: ProtectionKind (Above/Below/Equal/NotEqual/Range), Severity, Protection — data-carrying variants instead of a flat value array + range flag, so mismatched bound counts can't compile - packet: Packet and its variants (Data, Order, Protection, Message), ShortTimestamp with the sub-second field, MessageLevel — protections and messages are now unrelated wire formats, so state orders and the old message-as-protection-kind are gone - board: PacketKind, PacketDef, Board, PodData - fix 9 broken rustdoc intra-doc links, restore missing tests on measurement.rs, remove dead code, run cargo fmt DataPacket/OrderPacket values are positional (Vec, matched by index against PacketDef.measurements), not tagged per-value with an id. Open questions for a follow-up: whether to drop the now-unused Range type, and the exact shape of core::adj (raw ADJ JSON -> these types). --- backend/crates/core/src/lib.rs | 4 + .../src/model/Comunicaciones_Reunion01-2.pdf | Bin 0 -> 670255 bytes backend/crates/core/src/model/board.rs | 99 ++++++++ backend/crates/core/src/model/id.rs | 4 + backend/crates/core/src/model/measurement.rs | 82 ++++++- backend/crates/core/src/model/mod.rs | 30 ++- backend/crates/core/src/model/packet.rs | 230 ++++++++++++++++++ backend/crates/core/src/model/protections.rs | 171 +++++++++++++ backend/readme-demo.md | 1 - 9 files changed, 603 insertions(+), 18 deletions(-) create mode 100644 backend/crates/core/src/model/Comunicaciones_Reunion01-2.pdf create mode 100644 backend/crates/core/src/model/board.rs create mode 100644 backend/crates/core/src/model/packet.rs diff --git a/backend/crates/core/src/lib.rs b/backend/crates/core/src/lib.rs index a85bf01dd..287b512a1 100644 --- a/backend/crates/core/src/lib.rs +++ b/backend/crates/core/src/lib.rs @@ -1,3 +1,7 @@ //! Componentes reutilizables de Hyperloop UPV. pub mod hello_world; + +/// Basic domain types: identifiers, values, measurements, protections, +/// packets and boards. +pub mod model; diff --git a/backend/crates/core/src/model/Comunicaciones_Reunion01-2.pdf b/backend/crates/core/src/model/Comunicaciones_Reunion01-2.pdf new file mode 100644 index 0000000000000000000000000000000000000000..a1d7f34bc65782fda6a3122b31bb61327bc85839 GIT binary patch literal 670255 zcmeEP2|$e77yqWFT{{Ua(;_?BBQhx}FJzA_Nl{eVR1~I#vegvty|RYvTS#`2kiG1c zC1jUfW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3%(AbEqLU2C=&@Vvd- zxi^E>L;51luZN)%hW-u95hkM>zZ!8AI^3+%3jO&!S5Yj)>PGa+o7|;K$QT75+O*=c zJ&QK7HuMH8j&1dXuN1vW^TG}A!MrQT|AR$cX&e>)j0Ll=`V)@QHc}}!R_C) z^OSs#JM)ycMsL@CZ%5^8otlZBVwGY{$_Jz!K^^1?OL@IhE7ARk8b{wmEpkR!Av%xl zZwpB!MQpF{7(jLf&l6yRO)e94HAi*U6mWvKkE)^%j?yojzFfZku)f@WxlK>e`?H{; za8EBeheI)ptfmrdtytb+DSpE$+3phSj?aa-qhKUz-yOjtsTf(r(xRBfT62>N-&#cE zuOK9iCoRjIv=}fEYVsjx{CbwA&)XPqF=~T4&O^kKc{Qsn^^rMY(Pt{OgEe9#KieYj zeM5>u+u!BT5Wffq<7|tfy!;f!wgi{%nB$0*ePLri{HWUKAj}wZI`%~b9lzg z7n_2pf*H@c1oY(^Se$y{A$m){Nd<=By zE|TeO!cyfQ8kV1D#vV*(CM4l_TsxwVWsG&G>l1y#f4sLhpyn0s_wM(0O7N5^f+wPi z$a7OQ6en?gQByS*E}t=xXC-dRa9HjYeE^pz{h$A04^MM, +} + +/// A single board of the vehicle, as defined by the ADJ. +#[derive(Debug, Clone, PartialEq)] +pub struct Board { + /// The board's unique id. + pub id: BoardId, + /// The board's name, e.g. `"BCU"`. + pub name: String, + /// The packets this board can send or receive. + pub packets: Vec, +} + +/// The whole vehicle, as described by the ADJ: every board and every +/// packet each one can send or receive. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct PodData { + /// Every board of the vehicle. + pub boards: Vec, +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::model::MeasurementKind; + + fn sample_measurement() -> Measurement { + Measurement { + id: AdjId(3000), + alias: "temperature_1".to_string(), + name: "Temperature 1".to_string(), + display_units: "ºC".to_string(), + kind: MeasurementKind::Boolean, + protections: vec![], + } + } + + #[test] + fn an_empty_pod_data_has_no_boards() { + let pod_data = PodData::default(); + assert!(pod_data.boards.is_empty()); + } + + #[test] + fn a_board_groups_its_packets_and_their_measurements() { + let board = Board { + id: BoardId(1), + name: "BCU".to_string(), + packets: vec![PacketDef { + id: AdjId(1000), + name: "bcu_data".to_string(), + kind: PacketKind::Data, + measurements: vec![sample_measurement()], + }], + }; + + assert_eq!(board.packets.len(), 1); + assert_eq!(board.packets[0].measurements.len(), 1); + assert_eq!(board.packets[0].kind, PacketKind::Data); + } +} diff --git a/backend/crates/core/src/model/id.rs b/backend/crates/core/src/model/id.rs index de799e506..14fc8232b 100644 --- a/backend/crates/core/src/model/id.rs +++ b/backend/crates/core/src/model/id.rs @@ -5,6 +5,10 @@ //! [`BoardId`] by mistake, even though both are just numbers underneath. /// Unique identifier of a packet, order or protection, defined by the ADJ. +/// Ranges +/// - `[0, 511]` | `[0x0000, 0x01FF]` for special range +/// - `[512, 8191]` | `[0x0200, 0x1FFF]` for packets, orders and measurements +/// - `[8192, 65535]` | `[0x2000, 0xFFFF]` for protections: each protection is associated with a measurement, so the low 13 bits of the compound id are the measurement id, and the high 3 bits are the protection's position for that measurement (1-7; 0 is reserved for a normal, non-protection id) #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub struct AdjId(pub u16); diff --git a/backend/crates/core/src/model/measurement.rs b/backend/crates/core/src/model/measurement.rs index 8a8176356..198bed4ec 100644 --- a/backend/crates/core/src/model/measurement.rs +++ b/backend/crates/core/src/model/measurement.rs @@ -6,6 +6,7 @@ //! warning ranges. This is a *description*, not a decoded value — see //! [`super::Value`] for the value itself, once decoded. +use super::protections::Protection; use crate::model::AdjId; /// The wire type of a numeric measurement: how many bytes it takes on the @@ -72,19 +73,90 @@ pub enum MeasurementKind { /// The description of a single field of a packet, as defined by the ADJ. #[derive(Debug, Clone, PartialEq)] pub struct Measurement { - /// The measurement's ADJid, e.g. `3000`. + /// The measurement's numeric ADJ id, e.g. `3000`. pub id: AdjId, - /// The alias used to identify it + + /// The legacy textual identifier, used by code generation. pub alias: String, + /// The human-readable name shown to the user. pub name: String, - /// The units of the measurement to be shown at tefronend + /// The name of the unit to display at the frontend, e.g. `"ºC"`. pub display_units: String, /// What kind of data this measurement holds. pub kind: MeasurementKind, - /// The protectionst that are checked for this messurement. - pub protections: Protections, + /// The protections that are checked for this measurement, in ADJ + /// order. The ADJ limits this list to 7 entries per measurement, but + /// that limit is enforced by the ADJ validator, not by this type. + pub protections: Vec, +} + +#[cfg(test)] +mod tests { + use super::*; + + fn base(kind: MeasurementKind) -> Measurement { + Measurement { + id: AdjId(3000), + alias: "temperature_1".to_string(), + name: "Temperature 1".to_string(), + display_units: "ºC".to_string(), + kind, + protections: vec![], + } + } + + #[test] + fn a_numeric_measurement_carries_its_wire_type() { + let measurement = base(MeasurementKind::Numeric { + wire_type: NumericKind::F32, + }); + + let MeasurementKind::Numeric { wire_type } = measurement.kind else { + unreachable!("measurement was just constructed as Numeric above"); + }; + + assert_eq!(wire_type, NumericKind::F32); + } + + #[test] + fn an_enum_measurement_lists_its_options_in_adj_order() { + let measurement = base(MeasurementKind::Enum { + options: vec![ + "Idle".to_string(), + "Operational".to_string(), + "Fault".to_string(), + ], + }); + + let MeasurementKind::Enum { options } = measurement.kind else { + unreachable!("measurement was just constructed as Enum above"); + }; + + assert_eq!(options, vec!["Idle", "Operational", "Fault"]); + } + + #[test] + fn two_measurements_with_the_same_data_are_equal() { + let a = base(MeasurementKind::Boolean); + let b = a.clone(); + assert_eq!(a, b); + } + + #[test] + fn measurements_with_different_protections_are_not_equal() { + let a = base(MeasurementKind::Boolean); + let mut b = a.clone(); + b.protections.push(Protection { + id: AdjId(1), + kind: crate::model::ProtectionKind::Above { limit: 100.0 }, + severity: crate::model::Severity::Fault, + time: std::time::Duration::ZERO, + }); + + assert_ne!(a, b); + } } diff --git a/backend/crates/core/src/model/mod.rs b/backend/crates/core/src/model/mod.rs index 50312d878..fec13b632 100644 --- a/backend/crates/core/src/model/mod.rs +++ b/backend/crates/core/src/model/mod.rs @@ -1,21 +1,27 @@ -//! Basic domain types: identifiers, packets, values, measurements and -//! units. No I/O and no networking here, just data and the operations -//! performed on it. +//! Basic domain types: identifiers, packets, values, measurements, +//! protections and boards. No I/O and no networking here, just data and +//! the operations performed on it. //! -//! # Upcoming modules (not written yet) -//! -//! - `value` — [`Value`] and unit conversion (pod ⇄ display). -//! - `measurement` — the description of a measurement (its type, its ranges). -//! - `packet` — [`Packet`] and its variants: data, order, state order, protection. -//! - `board` — `PodData`, `Board`: a whole board with its packets. -//! -//! Add each one here with `mod name;` + `pub use name::...;` as you write -//! them, the same way it's done below with `id`. +//! - `id` — `AdjId`, `BoardId`. +//! - `value` — `Value`, the result of decoding a measurement. +//! - `measurement` — `Measurement`: what a field of a packet looks like. +//! - `protections` — `Protection`: bounds declared for a measurement. +//! - `packet` — `Packet` and its variants: data, order, +//! protection packet, message. +//! - `board` — `PodData`, `Board`, `PacketDef`: the whole vehicle. +mod board; mod id; mod measurement; +mod packet; +mod protections; mod value; +pub use board::{Board, PacketDef, PacketKind, PodData}; pub use id::{AdjId, BoardId}; pub use measurement::{Measurement, MeasurementKind, NumericKind, Range}; +pub use packet::{ + DataPacket, MessageLevel, MessagePacket, OrderPacket, Packet, ProtectionPacket, ShortTimestamp, +}; +pub use protections::{Protection, ProtectionKind, Severity}; pub use value::Value; diff --git a/backend/crates/core/src/model/packet.rs b/backend/crates/core/src/model/packet.rs new file mode 100644 index 000000000..61a3bd797 --- /dev/null +++ b/backend/crates/core/src/model/packet.rs @@ -0,0 +1,230 @@ +//! Wire packets. +//! +//! A [`Packet`] is a single message actually sent or received over the +//! wire, once decoded. This is the *instance* — as opposed to +//! [`super::Measurement`] and [`super::Protection`], which describe what a +//! packet or a protection *can* look like, or [`super::PacketDef`], which +//! describes a whole packet. + +use super::{AdjId, Value}; + +/// A short timestamp carrying only the time of day: hour, minute, second +/// and a sub-second fraction, each one byte. +/// +/// Used by [`ProtectionPacket`] and [`MessagePacket`]. Unlike a full +/// calendar timestamp, this only records *when today* something happened; +/// the date is assumed to be the day the packet was received. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub struct ShortTimestamp { + /// The hour, 0–23. + pub hour: u8, + /// The minute, 0–59. + pub minute: u8, + /// The second, 0–59. + pub second: u8, + /// The sub-second fraction, as the raw byte on the wire. + /// + /// This byte was labeled `resv` ("reserved for alignment") at first, + /// but it is in fact used for sub-second resolution. Its exact unit + /// (e.g. milliseconds, or 1/256ths of a second) hasn't been confirmed + /// yet, so it is kept as a raw `u8` here instead of converted to + /// something like a `Duration` — convert it once the unit is settled. + pub subsecond: u8, +} + +/// A data packet: the decoded values of the measurements a board just +/// sent. +/// +/// The wire protocol is positional: values are not individually tagged +/// with their measurement's id, just written back to back in the order +/// their [`super::Measurement`]s appear in this packet's +/// [`super::PacketDef::measurements`]. `values[i]` is the decoded value of +/// `measurements[i]` in that definition — matching them up by position is +/// `protocol`'s job, this type just holds the result in that same order. +#[derive(Debug, Clone, PartialEq)] +pub struct DataPacket { + /// Which packet definition this is an instance of. + pub id: AdjId, + /// The decoded value of each measurement in the packet, positional — + /// see the struct-level docs above. + pub values: Vec, +} + +/// An order sent from the backend to a board. +/// +/// Positional, the same way [`DataPacket::values`] is: see its docs. +#[derive(Debug, Clone, PartialEq)] +pub struct OrderPacket { + /// Which order definition this is an instance of. + pub id: AdjId, + /// The value to set for each field of the order, positional. + pub fields: Vec, +} + +/// A protection packet: sent by a board when one of its declared +/// [`super::Protection`]s triggers. +/// +/// `measurement` and `protection` together are the two halves of the +/// compound wire id — decoding that split is `protocol`'s job, this type +/// just holds the result. +#[derive(Debug, Clone, PartialEq)] +pub struct ProtectionPacket { + /// The measurement this protection watches. + pub measurement: AdjId, + /// Which of that measurement's protections triggered — see + /// [`super::Protection::id`]. + pub protection: AdjId, + /// When it triggered. + pub timestamp: ShortTimestamp, + /// The value that triggered it, decoded with the same wire type as the + /// watched measurement. + pub value: Value, +} + +/// How severe a message is (reusing `general_info.json`'s `message_ids`). +/// +/// Unlike [`super::Severity`], which only distinguishes fault from warning +/// for protections, a message has two extra levels: `messages` and +/// `protections` are unrelated wire formats as of ADJv3, so this is a +/// separate type on purpose, not a reuse of [`super::Severity`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum MessageLevel { + /// Stops the vehicle automatically. + Fault, + /// Flags something unexpected, without stopping the vehicle. + Warning, + /// Informational, no action implied. + Info, + /// An unrecoverable firmware error. + Panic, +} + +/// A free-text message sent by a board. +#[derive(Debug, Clone, PartialEq)] +pub struct MessagePacket { + /// How severe the message is. + pub level: MessageLevel, + /// When it was sent. + pub timestamp: ShortTimestamp, + /// Where it came from, e.g. a source file path. + pub origin: String, + /// The message's contents. + pub message: String, +} + +/// Any packet actually sent or received over the wire, once decoded. +#[derive(Debug, Clone, PartialEq)] +pub enum Packet { + /// A set of measurements sent by a board. + Data(DataPacket), + /// An order sent to a board. + Order(OrderPacket), + /// A protection that triggered. + Protection(ProtectionPacket), + /// A free-text message sent by a board. + Message(MessagePacket), +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn two_timestamps_with_the_same_time_of_day_are_equal() { + let a = ShortTimestamp { + hour: 10, + minute: 30, + second: 0, + subsecond: 0, + }; + let b = ShortTimestamp { + hour: 10, + minute: 30, + second: 0, + subsecond: 0, + }; + assert_eq!(a, b); + } + + #[test] + fn two_timestamps_that_only_differ_in_subsecond_are_not_equal() { + let a = ShortTimestamp { + hour: 10, + minute: 30, + second: 0, + subsecond: 0, + }; + let b = ShortTimestamp { + hour: 10, + minute: 30, + second: 0, + subsecond: 128, + }; + assert_ne!(a, b); + } + + #[test] + fn a_protection_packet_carries_its_measurement_and_its_own_position_separately() { + let packet = ProtectionPacket { + measurement: AdjId(3000), + protection: AdjId(1), + timestamp: ShortTimestamp { + hour: 12, + minute: 0, + second: 5, + subsecond: 0, + }, + value: Value::Number(53.2), + }; + + assert_eq!(packet.measurement, AdjId(3000)); + assert_eq!(packet.protection, AdjId(1)); + } + + #[test] + fn message_level_has_four_distinct_values() { + let levels = [ + MessageLevel::Fault, + MessageLevel::Warning, + MessageLevel::Info, + MessageLevel::Panic, + ]; + + for (i, a) in levels.iter().enumerate() { + for (j, b) in levels.iter().enumerate() { + assert_eq!(a == b, i == j); + } + } + } + + #[test] + fn data_packet_values_are_positional_not_tagged_with_an_id() { + // values[0] is whatever measurements[0] is in this packet's + // PacketDef — there is no id stored alongside each value here. + let packet = DataPacket { + id: AdjId(1000), + values: vec![Value::Number(53.2), Value::Bool(true)], + }; + + assert_eq!(packet.values[0], Value::Number(53.2)); + assert_eq!(packet.values[1], Value::Bool(true)); + } + + #[test] + fn packet_wraps_each_kind_without_mixing_them_up() { + let data = Packet::Data(DataPacket { + id: AdjId(1000), + values: vec![], + }); + let order = Packet::Order(OrderPacket { + id: AdjId(2000), + fields: vec![], + }); + + assert_ne!(data, order); + match data { + Packet::Data(_) => {} + _ => unreachable!("this is a Packet::Data"), + } + } +} diff --git a/backend/crates/core/src/model/protections.rs b/backend/crates/core/src/model/protections.rs index e69de29bb..3159c107c 100644 --- a/backend/crates/core/src/model/protections.rs +++ b/backend/crates/core/src/model/protections.rs @@ -0,0 +1,171 @@ +//! Protection declarations. +//! +//! A [`Protection`] is a bound checked against a measurement's decoded +//! value, as declared for that measurement in the ADJ (see +//! `_measurements.json`, `protections` array). This describes the +//! *declaration*: what to watch for and how +//! severe it is. It is not the packet actually received over the wire when +//! a protection triggers; that belongs with the rest of the wire packets, +//! once `packet` exists. +//! +//! In ADJv2, a protection was just a `message` with a specific kind. +//! ADJv3 splits them into two unrelated wire formats, so from here on +//! `Protection` and a future `Message` type are not related at all. + +use crate::model::AdjId; +use std::time::Duration; + +/// What a protection checks, and the bound(s) it needs. +/// +/// Modeled as data-carrying variants instead of a flat `value: Vec` +/// plus a `range: bool` flag (as the ADJ JSON represents it), so a +/// protection with the wrong number of bounds for its kind — e.g. an +/// `Above` with two values, or a `Range` with only one — cannot be +/// represented at all. +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum ProtectionKind { + /// Triggers when the value goes above `limit`. + Above { + /// The upper limit. + limit: f64, + }, + /// Triggers when the value goes below `limit`. + Below { + /// The lower limit. + limit: f64, + }, + /// Triggers when the value equals `target`. + Equal { + /// The value that must not occur. + target: f64, + }, + /// Triggers when the value is different from `target`. + NotEqual { + /// The value that is expected. + target: f64, + }, + /// Triggers when the value leaves the `[min, max]` interval. + /// + /// Unlike [`super::Range`], both bounds are mandatory here: the ADJ + /// always provides exactly two values for a `Range` protection, so + /// there is no "open-ended" case to represent. + Range { + /// The lower bound of the interval. + min: f64, + /// The upper bound of the interval. + max: f64, + }, +} + +/// How severe a triggered protection is. +/// +/// Only two values, unlike a message's severity: a protection is either a +/// [`Severity::Fault`], which stops the vehicle, or a [`Severity::Warning`], +/// which does not. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum Severity { + /// Stops the vehicle automatically. + Fault, + /// Flags the value as unexpected, without stopping the vehicle. + Warning, +} + +/// A single protection watching a measurement, as declared in the ADJ. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct Protection { + /// This protection's position within its measurement's `protections` + /// list, encoded as an [`AdjId`] in the 1–7 range. + /// + /// This is *not* an independently assigned id from the global ADJ id + /// space (`[0, 8191]`): a protection is only ever + /// addressed relative to the measurement that owns it. On the wire, + /// this position becomes the 3-bit `pos` field that, combined with the + /// owning measurement's 13-bit id, forms the compound id — that + /// combination is `protocol`'s job, not this type's. + pub id: AdjId, + /// What this protection checks and its bound(s). + pub kind: ProtectionKind, + /// How severe it is once triggered. + pub severity: Severity, + /// How long the value must stay out of bounds before this protection + /// triggers. `Duration::ZERO` (the ADJ's default) means it triggers + /// immediately. + pub time: Duration, +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_range_protection_always_carries_both_bounds() { + let protection = Protection { + id: AdjId(1), + kind: ProtectionKind::Range { + min: 0.0, + max: 48.0, + }, + severity: Severity::Fault, + time: Duration::ZERO, + }; + + let ProtectionKind::Range { min, max } = protection.kind else { + unreachable!("protection was just constructed as Range above"); + }; + + assert_eq!(min, 0.0); + assert_eq!(max, 48.0); + } + + #[test] + fn two_protections_with_the_same_data_are_equal() { + let a = Protection { + id: AdjId(2), + kind: ProtectionKind::Above { limit: 100.0 }, + severity: Severity::Warning, + time: Duration::from_millis(500), + }; + let b = a; + assert_eq!(a, b); + } + + #[test] + fn zero_time_means_it_triggers_immediately() { + let protection = Protection { + id: AdjId(3), + kind: ProtectionKind::Equal { target: 0.0 }, + severity: Severity::Fault, + time: Duration::ZERO, + }; + + assert_eq!(protection.time, Duration::ZERO); + } + + #[test] + fn a_protections_id_is_its_position_not_a_global_id() { + // Two different measurements can each have a protection at + // position 1 — they are unrelated protections that happen to + // share the same "slot" id, disambiguated by their measurement. + let first_measurement_protection = Protection { + id: AdjId(1), + kind: ProtectionKind::Below { limit: -10.0 }, + severity: Severity::Warning, + time: Duration::ZERO, + }; + let second_measurement_protection = Protection { + id: AdjId(1), + kind: ProtectionKind::Above { limit: 90.0 }, + severity: Severity::Fault, + time: Duration::ZERO, + }; + + assert_eq!( + first_measurement_protection.id, + second_measurement_protection.id + ); + assert_ne!( + first_measurement_protection.kind, + second_measurement_protection.kind + ); + } +} diff --git a/backend/readme-demo.md b/backend/readme-demo.md index 875c83848..050e911ac 100644 --- a/backend/readme-demo.md +++ b/backend/readme-demo.md @@ -28,7 +28,6 @@ cargo clippy --workspace --all-targets -- -D warnings Abre `target/doc/software_core/hello_world/index.html` para ver la API. - `crates/core/src/hello_world.rs`: `greet(&str) -> String`, con rustdoc, - un doctest y tres tests unitarios. Recorta espacios; un nombre vacío usa `World`. - `crates/core/src/lib.rs`: exporta el módulo público. - `crates/station/src/main.rs`: inicializa el subscriber una sola vez y llama a `greet`. - `#[tracing::instrument]` crea el span `hello_world`; los eventos incluyen From db41226217539238ca0ab4f5ad05007ebbbed5e4 Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Wed, 30 Sep 2026 17:42:20 +0200 Subject: [PATCH 006/225] fix: delete docs --- .../src/model/Comunicaciones_Reunion01-2.pdf | Bin 670255 -> 0 bytes 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 backend/crates/core/src/model/Comunicaciones_Reunion01-2.pdf diff --git a/backend/crates/core/src/model/Comunicaciones_Reunion01-2.pdf b/backend/crates/core/src/model/Comunicaciones_Reunion01-2.pdf deleted file mode 100644 index a1d7f34bc65782fda6a3122b31bb61327bc85839..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 670255 zcmeEP2|$e77yqWFT{{Ua(;_?BBQhx}FJzA_Nl{eVR1~I#vegvty|RYvTS#`2kiG1c zC1jUfWc{D}eKXU{e0Qel;s1E%`+NUp=G^a`bAR{TbI(2Bz4vSE=GePc+t!`c8=tv+ zZq!*Z-a0h> zct-!%A01jw>8^gS?d7kw^=dsc%I(d}z3Y#;+}<*3>7bsg zhJX3;_I7EU+l3F;Gxob~%PkIzD|vCWe~;)Prz?7B_b8g#^6mD-=}*f?k1@47*mNgT zx25~R17CJ_QkgWXXl(FkHJ|IRK1`{)=h7#8;6!ffjLbuJaqA{%z1sF+=?aT(JkFq#h=j`l*mZb~RvYIxIZF}miSHZbhSBIc_zDu|hg5GFc zwK*F+(XY>u<4xN5#9mxh`Pp{y#3}nP@4u9K=6^42APh^R7O6_eXl;*gLb=)gNs=x{3dkK>;gm zY|GR8OuM;UcX`S5?K&2L$^E*iZ>aB(>9wiYZvX8;feq(dPYgV5Rq0{XFFMQb&YSVp zZFl?Vzt&$^bz+16?t;*lCD-~IpAO2de`W8&yA2whVDze|w_#M2SKJ>Ba$9M4_WJW- z)}S{_L!4W#KRf-N_2!19UZ&wio11RR7!}@W^$OF4vy1keJ3PukDX)dihTGR{^4jY; zE*`eTZ1IA>9_;s<_xJU73sf}LJZ<*j(J`HcelaC^vy*+j`cE5jwtPig>v@Cfj%si^ zeR<3)df}^Lv>AOd7aOE9B{1o&yRB! z*`9u2yZq1S1mhLGZtdKy{JPw4$K)H9M+U_WNMGH*&CtNv{aUL!y-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BB z=gFP)6M_o1Qo_85cTaX)_gLn-mWZ;Kl~rVcBXvE)^q%q`>(B|148<93e}JC{FN6#W zoyn!?1$O-_UC6(QD)Ij7@r(b6F6e0htpTj^&Q?HQfZ^-m3=Up)fH8no)6V}jJn^ct z>b?%M12|vX>#&B4izk4C=PgK~@ixoa<+b+~s(R~5y&{G9Ik;qGq@<)|q&da;xn$V5 z`1obm*!a1``T6*zq}aqo{yUIYPyesr1~13IzmI?>(O4Pm4skk&$ickWMp(a#;uozQ@4D~*pjEoX<&4(kTHd%Qfhqv$Nfp> z{)5o|tx)Iw6)NSYDC$qta!i$IS}-3%(AbEqLU2C=&@Vvd- zxi^E>L;51luZN)%hW-u95hkM>zZ!8AI^3+%3jO&!S5Yj)>PGa+o7|;K$QT75+O*=c zJ&QK7HuMH8j&1dXuN1vW^TG}A!MrQT|AR$cX&e>)j0Ll=`V)@QHc}}!R_C) z^OSs#JM)ycMsL@CZ%5^8otlZBVwGY{$_Jz!K^^1?OL@IhE7ARk8b{wmEpkR!Av%xl zZwpB!MQpF{7(jLf&l6yRO)e94HAi*U6mWvKkE)^%j?yojzFfZku)f@WxlK>e`?H{; za8EBeheI)ptfmrdtytb+DSpE$+3phSj?aa-qhKUz-yOjtsTf(r(xRBfT62>N-&#cE zuOK9iCoRjIv=}fEYVsjx{CbwA&)XPqF=~T4&O^kKc{Qsn^^rMY(Pt{OgEe9#KieYj zeM5>u+u!BT5Wffq<7|tfy!;f!wgi{%nB$0*ePLri{HWUKAj}wZI`%~b9lzg z7n_2pf*H@c1oY(^Se$y{A$m){Nd<=By zE|TeO!cyfQ8kV1D#vV*(CM4l_TsxwVWsG&G>l1y#f4sLhpyn0s_wM(0O7N5^f+wPi z$a7OQ6en?gQByS*E}t=xXC-dRa9HjYeE^pz{h$A04^MM Date: Wed, 30 Sep 2026 17:49:09 +0200 Subject: [PATCH 007/225] feat: include mac adress --- backend/crates/core/src/model/board.rs | 10 ++++++++- backend/crates/core/src/model/id.rs | 29 ++++++++++++++++++++++++++ backend/crates/core/src/model/mod.rs | 4 ++-- 3 files changed, 40 insertions(+), 3 deletions(-) diff --git a/backend/crates/core/src/model/board.rs b/backend/crates/core/src/model/board.rs index 6eda926db..ceb25b0e0 100644 --- a/backend/crates/core/src/model/board.rs +++ b/backend/crates/core/src/model/board.rs @@ -10,7 +10,8 @@ //! left out rather than guessed — add them once the packet-level JSON //! shape is settled. -use super::{AdjId, BoardId, Measurement}; +use super::{AdjId, BoardId, MacAddress, Measurement}; +use std::net::IpAddr; /// What kind of packet a [`PacketDef`] declares. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] @@ -45,6 +46,10 @@ pub struct Board { pub id: BoardId, /// The board's name, e.g. `"BCU"`. pub name: String, + /// The board's IP address, used to open its TCP/UDP connections. + pub ip: IpAddr, + /// The board's MAC address (ADJv3 spec, section 5). + pub mac: MacAddress, /// The packets this board can send or receive. pub packets: Vec, } @@ -84,6 +89,8 @@ mod tests { let board = Board { id: BoardId(1), name: "BCU".to_string(), + ip: IpAddr::from([192, 168, 0, 10]), + mac: MacAddress([0x00, 0x11, 0x22, 0x33, 0x44, 0x55]), packets: vec![PacketDef { id: AdjId(1000), name: "bcu_data".to_string(), @@ -95,5 +102,6 @@ mod tests { assert_eq!(board.packets.len(), 1); assert_eq!(board.packets[0].measurements.len(), 1); assert_eq!(board.packets[0].kind, PacketKind::Data); + assert_eq!(board.mac.to_string(), "00:11:22:33:44:55"); } } diff --git a/backend/crates/core/src/model/id.rs b/backend/crates/core/src/model/id.rs index 14fc8232b..878532e06 100644 --- a/backend/crates/core/src/model/id.rs +++ b/backend/crates/core/src/model/id.rs @@ -16,6 +16,29 @@ pub struct AdjId(pub u16); #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub struct BoardId(pub u16); +/// A board's physical MAC address, as 6 raw bytes. +/// +/// Kept as a fixed-size byte array instead of a `String` on purpose: a +/// malformed or miswritten address (the ADJv3 meeting notes mention a real +/// `67:67:67:67:67:67` that caused hours of debugging) should not be able +/// to reach this type at all. Parsing the usual `"aa:bb:cc:dd:ee:ff"` text +/// form is `adj`'s job, not this type's. +#[derive(Clone, Copy, PartialEq, Eq, Hash)] +pub struct MacAddress(pub [u8; 6]); + +impl std::fmt::Debug for MacAddress { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "MacAddress({self})") + } +} + +impl std::fmt::Display for MacAddress { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let [a, b, c, d, e, g] = self.0; + write!(f, "{a:02x}:{b:02x}:{c:02x}:{d:02x}:{e:02x}:{g:02x}") + } +} + #[cfg(test)] mod tests { use super::*; @@ -25,6 +48,12 @@ mod tests { assert_eq!(AdjId(1000), AdjId(1000)); } + #[test] + fn a_mac_address_displays_as_colon_separated_lowercase_hex() { + let mac = MacAddress([0xaa, 0xbb, 0xcc, 0x0d, 0x0e, 0xff]); + assert_eq!(mac.to_string(), "aa:bb:cc:0d:0e:ff"); + } + #[test] fn packet_id_and_board_id_cannot_be_compared_to_each_other() { // This wouldn't compile if you tried it: AdjId(1) == BoardId(1) diff --git a/backend/crates/core/src/model/mod.rs b/backend/crates/core/src/model/mod.rs index fec13b632..2ca135984 100644 --- a/backend/crates/core/src/model/mod.rs +++ b/backend/crates/core/src/model/mod.rs @@ -2,7 +2,7 @@ //! protections and boards. No I/O and no networking here, just data and //! the operations performed on it. //! -//! - `id` — `AdjId`, `BoardId`. +//! - `id` — `AdjId`, `BoardId`, `MacAddress`. //! - `value` — `Value`, the result of decoding a measurement. //! - `measurement` — `Measurement`: what a field of a packet looks like. //! - `protections` — `Protection`: bounds declared for a measurement. @@ -18,7 +18,7 @@ mod protections; mod value; pub use board::{Board, PacketDef, PacketKind, PodData}; -pub use id::{AdjId, BoardId}; +pub use id::{AdjId, BoardId, MacAddress}; pub use measurement::{Measurement, MeasurementKind, NumericKind, Range}; pub use packet::{ DataPacket, MessageLevel, MessagePacket, OrderPacket, Packet, ProtectionPacket, ShortTimestamp, From 24e78b7c72bbe3b2feac3ffe740d11c512c6a034 Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Wed, 30 Sep 2026 23:40:33 +0200 Subject: [PATCH 008/225] fix(model): rename mod.rs to model.rs --- backend/crates/core/src/{model/mod.rs => model.rs} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename backend/crates/core/src/{model/mod.rs => model.rs} (100%) diff --git a/backend/crates/core/src/model/mod.rs b/backend/crates/core/src/model.rs similarity index 100% rename from backend/crates/core/src/model/mod.rs rename to backend/crates/core/src/model.rs From e0989102cea537e0be513929b6ffdb73b587651c Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Fri, 2 Oct 2026 11:01:10 +0200 Subject: [PATCH 009/225] feat(ntp): implementation of the NTP server and its addition as a feature --- backend/crates/core/Cargo.toml | 7 +- backend/crates/core/src/lib.rs | 4 ++ backend/crates/core/src/ntp.rs | 122 +++++++++++++++++++++++++++++++++ 3 files changed, 131 insertions(+), 2 deletions(-) create mode 100644 backend/crates/core/src/ntp.rs diff --git a/backend/crates/core/Cargo.toml b/backend/crates/core/Cargo.toml index 1b38a623e..087f62a60 100644 --- a/backend/crates/core/Cargo.toml +++ b/backend/crates/core/Cargo.toml @@ -10,6 +10,8 @@ repository.workspace = true [features] default = [] +# NTP server +ntp = ["dep:tokio", "dep:ntp_usg-server", "dep:tracing-subscriber"] # TCP/UDP transport (pulls in tokio) net = ["dep:tokio"] # ADJ download through git (dependency added when the module is written) @@ -26,9 +28,10 @@ bytes.workspace = true serde.workspace = true thiserror.workspace = true tracing.workspace = true -tokio = { workspace = true, optional = true } -tracing-subscriber = { workspace = true, optional = true } +tokio = { workspace = true, optional = true, features = ["macros", "rt-multi-thread"] } +tracing-subscriber = { workspace = true, optional = true , features = ["env-filter", "fmt"]} tracing-appender = { workspace = true, optional = true } +ntp_usg-server = { version = "5.0.0", optional = true, features = ["ipv4", "tokio"] } # `workspace = true` can't be combined with extra lints in the same table, # so the workspace list is repeated here with `missing_docs` added: this is diff --git a/backend/crates/core/src/lib.rs b/backend/crates/core/src/lib.rs index a85bf01dd..8deef0cc3 100644 --- a/backend/crates/core/src/lib.rs +++ b/backend/crates/core/src/lib.rs @@ -1,3 +1,7 @@ //! Componentes reutilizables de Hyperloop UPV. pub mod hello_world; + +/// NTP server +#[cfg(feature = "ntp")] +pub mod ntp; diff --git a/backend/crates/core/src/ntp.rs b/backend/crates/core/src/ntp.rs new file mode 100644 index 000000000..3a7dea8d4 --- /dev/null +++ b/backend/crates/core/src/ntp.rs @@ -0,0 +1,122 @@ +use ntp_server::{protocol::Stratum, server::NtpServer}; +use std::{ + io, + net::{Ipv4Addr, SocketAddrV4}, +}; +use tracing::{debug, info, instrument}; + +/// Starts the NTP server +/// Arguments: +/// - `interface`: (Optional) Interface which is suposed to listen. Default interface is `0.0.0.0`. +/// - `port`: (Optional) Specific port for the server to listen. Default port is `8123`. +#[instrument(level = "info")] +pub async fn start_ntp_server(interface: Option, port: Option) -> io::Result<()> { + let server = build_ntp_server(interface, port).await?; + debug!("Starting NTP server loop"); + // Any internal log of server.run() will be wrapped within this function Span + server.run().await +} + +async fn build_ntp_server(interface: Option, port: Option) -> io::Result { + let interface = interface.unwrap_or(Ipv4Addr::UNSPECIFIED); // Same as Ipv4Addr::new(0,0,0,0); + + let port = port.unwrap_or(8123); + + let socket_addr_v4 = SocketAddrV4::new(interface, port); + + // % -> use structured variables + debug!(%socket_addr_v4, "Building NTP server"); + + let server = NtpServer::builder() + .listen(socket_addr_v4.to_string()) + // Stratum indicates the server's distance from the source of the reference clock. + // This server syncronizes from a stratum 1 source, and advertises stratum 2 to its clients. + .stratum(Stratum(2)) + .build() + .await?; + + info!(%socket_addr_v4, "NTP server built successfully"); + + Ok(server) +} + +#[cfg(test)] +mod test { + + use super::*; + use ntp_server::protocol::{ + ConstPackedSizeBytes, FromBytes, Mode, Packet, TimestampFormat, ToBytes, Version, + }; + use std::time::Duration; + use tokio::net::UdpSocket; + use tracing_subscriber; + + // Inicializes the subscriber for tests + fn init_tracing_for_tests() { + let _ = tracing_subscriber::fmt() + .with_env_filter("debug") + .with_test_writer() // Ensures that the logs get showed by cargo test + .try_init(); // Avoids the test failure if there is another test in parallel + } + + #[tokio::test] + async fn ntp_server_responds_to_client_request() { + init_tracing_for_tests(); + + let server = build_ntp_server(Some(Ipv4Addr::LOCALHOST), Some(0)) + .await + .expect("NTP server should bind to an ephemeral local port"); + let server_addr = server + .local_addr() + .expect("NTP server should expose its bound address"); + let server_task = tokio::spawn(server.run()); + + let socket = UdpSocket::bind((Ipv4Addr::LOCALHOST, 0)) + .await + .expect("NTP client socket should bind to an ephemeral local port"); + let request = Packet { + transmit_timestamp: TimestampFormat { + seconds: 0xE0000000, + fraction: 0x12345678, + }, + ..Packet::default() + }; + let mut request_bytes = [0; Packet::PACKED_SIZE_BYTES]; + request + .to_bytes(&mut request_bytes) + .expect("NTP client request should serialize"); + socket + .send_to(&request_bytes, server_addr) + .await + .expect("NTP client request should be sent"); + + let mut response_bytes = [0; 2048]; + let (response_len, source_addr) = tokio::time::timeout( + Duration::from_secs(2), + socket.recv_from(&mut response_bytes), + ) + .await + .expect("NTP server should respond before timeout") + .expect("NTP response should be received"); + + assert_eq!(source_addr, server_addr); + assert_eq!(response_len, Packet::PACKED_SIZE_BYTES); + + let (response, bytes_read) = Packet::from_bytes(&response_bytes[..response_len]) + .expect("server response should be a valid NTP packet"); + assert_eq!(bytes_read, Packet::PACKED_SIZE_BYTES); + assert_eq!(response.mode, Mode::Server); + assert_eq!(response.version, Version::V4); + assert_eq!(response.stratum, Stratum(2)); + assert_eq!(response.origin_timestamp, request.transmit_timestamp); + assert_ne!(response.transmit_timestamp, TimestampFormat::default()); + + server_task.abort(); + assert!( + server_task + .await + .expect_err("server task should be aborted") + .is_cancelled() + ); + } +} From 3f8179a76a678ded63057bc5ed1fdf079cfd5575 Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Fri, 2 Oct 2026 11:01:56 +0200 Subject: [PATCH 010/225] update: update rust version from 1.85 to 1.98 --- backend/Cargo.lock | 54 ++++++++++++++++++++++++++++++++++------------ backend/Cargo.toml | 4 ++-- 2 files changed, 42 insertions(+), 16 deletions(-) diff --git a/backend/Cargo.lock b/backend/Cargo.lock index 94186abdf..69d6e2bfb 100644 --- a/backend/Cargo.lock +++ b/backend/Cargo.lock @@ -11,6 +11,12 @@ dependencies = [ "memchr", ] +[[package]] +name = "byteorder" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" + [[package]] name = "bytes" version = "1.12.1" @@ -43,9 +49,6 @@ name = "deranged" version = "0.5.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c" -dependencies = [ - "powerfmt", -] [[package]] name = "equivalent" @@ -87,9 +90,9 @@ checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" [[package]] name = "lazy_static" -version = "1.5.0" +version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" +checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" [[package]] name = "libc" @@ -129,6 +132,27 @@ dependencies = [ "windows-sys", ] +[[package]] +name = "ntp_usg-proto" +version = "5.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "31316ff46fc87e03a95e55b93525a27feecfd86fab094ca887a773395f13f50a" +dependencies = [ + "byteorder", + "log", +] + +[[package]] +name = "ntp_usg-server" +version = "5.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0002bd55912864af88a46077abd71db2c4cda88887b46b19c31e1e9a1f289e4e" +dependencies = [ + "ntp_usg-proto", + "tokio", + "tracing", +] + [[package]] name = "nu-ansi-term" version = "0.50.3" @@ -140,9 +164,9 @@ dependencies = [ [[package]] name = "num-conv" -version = "0.1.0" +version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "51d515d32fb182ee37cda2ccdcb92950d6a3c2893aa280e540671c2cd0f3b1d9" +checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" [[package]] name = "once_cell" @@ -289,6 +313,7 @@ name = "software-core" version = "0.1.0" dependencies = [ "bytes", + "ntp_usg-server", "serde", "thiserror", "tokio", @@ -369,12 +394,11 @@ dependencies = [ [[package]] name = "time" -version = "0.3.45" +version = "0.3.55" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f9e442fc33d7fdb45aa9bfeb312c095964abdf596f7567261062b2a7107aaabd" +checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134" dependencies = [ "deranged", - "itoa", "num-conv", "powerfmt", "serde_core", @@ -384,15 +408,15 @@ dependencies = [ [[package]] name = "time-core" -version = "0.1.7" +version = "0.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b36ee98fd31ec7426d599183e8fe26932a8dc1fb76ddb6214d05493377d34ca" +checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" [[package]] name = "time-macros" -version = "0.2.25" +version = "0.2.32" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "71e552d1249bf61ac2a52db88179fd0673def1e1ad8243a00d9ec9ed71fee3dd" +checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85" dependencies = [ "num-conv", "time-core", @@ -404,6 +428,7 @@ version = "1.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "202caea871b69668250d242070849eb495be178ed697a3e98aebce5bc81a0bed" dependencies = [ + "bytes", "libc", "mio", "pin-project-lite", @@ -469,6 +494,7 @@ version = "0.1.44" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" dependencies = [ + "log", "pin-project-lite", "tracing-attributes", "tracing-core", diff --git a/backend/Cargo.toml b/backend/Cargo.toml index d9aeeb64e..a1161a8d8 100644 --- a/backend/Cargo.toml +++ b/backend/Cargo.toml @@ -5,7 +5,7 @@ default-members = ["crates/station"] [workspace.package] edition = "2024" -rust-version = "1.85" +rust-version = "1.98" license = "MIT" authors = [ "Hyperloop UPV Software Subsystem", @@ -26,7 +26,7 @@ tokio = { version = "1", features = ["rt-multi-thread", "macros", "net", "sync", toml = "0.9" tracing = "0.1" tracing-appender = "0.2" -tracing-subscriber = { version = "0.3", features = ["env-filter", "json"] } +tracing-subscriber = { version = "0.3", features = ["env-filter", "fmt", "json"] } [workspace.lints.rust] unsafe_code = "forbid" From 37aa08a23b2127ef41fc0d768446bc0b87a16f82 Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Sat, 3 Oct 2026 11:50:29 +0200 Subject: [PATCH 011/225] fix: requests from PR, create port const, comment test, and changes in start_ntp_server function --- backend/crates/core/src/ntp.rs | 62 +++++++++++++++++++++++++++++----- 1 file changed, 53 insertions(+), 9 deletions(-) diff --git a/backend/crates/core/src/ntp.rs b/backend/crates/core/src/ntp.rs index 3a7dea8d4..aeab276c9 100644 --- a/backend/crates/core/src/ntp.rs +++ b/backend/crates/core/src/ntp.rs @@ -5,14 +5,39 @@ use std::{ }; use tracing::{debug, info, instrument}; +const NTP_DEFAULT_PORT: u16 = 8123; + +/// Represents the address used to start the NTP server. +/// It can be defined as an IPv4 interface + port or as a full socket address. +#[derive(Debug)] +pub enum NtpAddress { + /// Uses the interface and port separately. + Interface { + /// IPv4 interface to bind to. If `None`, the default interface (`0.0.0.0`) is used. + interface: Option, + /// Port to listen on. If `None`, the default NTP port (`8123`) is used. + port: Option, + }, + /// Uses a complete IPv4 socket address. + Socket(Option) +} + /// Starts the NTP server /// Arguments: -/// - `interface`: (Optional) Interface which is suposed to listen. Default interface is `0.0.0.0`. -/// - `port`: (Optional) Specific port for the server to listen. Default port is `8123`. +/// - `address`: The target address configuration used to bind the server. #[instrument(level = "info")] -pub async fn start_ntp_server(interface: Option, port: Option) -> io::Result<()> { +pub async fn start_ntp_server(address: NtpAddress) -> io::Result<()> { + + let (interface, port) = match address { + NtpAddress::Interface {interface, port} => (interface, port), + NtpAddress::Socket(Some(socket)) => { + (Some(*socket.ip()), Some(socket.port())) + }, + NtpAddress::Socket(None) => (None, None) + }; + let server = build_ntp_server(interface, port).await?; - debug!("Starting NTP server loop"); + info!("Starting NTP server loop"); // Any internal log of server.run() will be wrapped within this function Span server.run().await } @@ -20,7 +45,7 @@ pub async fn start_ntp_server(interface: Option, port: Option) -> async fn build_ntp_server(interface: Option, port: Option) -> io::Result { let interface = interface.unwrap_or(Ipv4Addr::UNSPECIFIED); // Same as Ipv4Addr::new(0,0,0,0); - let port = port.unwrap_or(8123); + let port = port.unwrap_or(NTP_DEFAULT_PORT); let socket_addr_v4 = SocketAddrV4::new(interface, port); @@ -30,7 +55,7 @@ async fn build_ntp_server(interface: Option, port: Option) -> io: let server = NtpServer::builder() .listen(socket_addr_v4.to_string()) // Stratum indicates the server's distance from the source of the reference clock. - // This server syncronizes from a stratum 1 source, and advertises stratum 2 to its clients. + // This server synchronizes from a stratum 1 source, and advertises stratum 2 to its clients. .stratum(Stratum(2)) .build() .await?; @@ -51,45 +76,60 @@ mod test { use tokio::net::UdpSocket; use tracing_subscriber; - // Inicializes the subscriber for tests + // Initializes the subscriber for tests fn init_tracing_for_tests() { let _ = tracing_subscriber::fmt() .with_env_filter("debug") - .with_test_writer() // Ensures that the logs get showed by cargo test + .with_test_writer() // Ensures that the logs are shown by cargo test .try_init(); // Avoids the test failure if there is another test in parallel } #[tokio::test] + // Verifies if the NTP server responds correctly to a client request async fn ntp_server_responds_to_client_request() { init_tracing_for_tests(); + // Create the NTP server let server = build_ntp_server(Some(Ipv4Addr::LOCALHOST), Some(0)) .await .expect("NTP server should bind to an ephemeral local port"); + + // Get the address assigned by the OS let server_addr = server .local_addr() .expect("NTP server should expose its bound address"); + + // Start the server on a thread let server_task = tokio::spawn(server.run()); + // Bind a UDP socket to send NTP requests let socket = UdpSocket::bind((Ipv4Addr::LOCALHOST, 0)) .await .expect("NTP client socket should bind to an ephemeral local port"); + + // Build NTP request packet for testing requests let request = Packet { transmit_timestamp: TimestampFormat { + // Test data, just to verify the server responds correctly seconds: 0xE0000000, fraction: 0x12345678, }, - ..Packet::default() + ..Packet::default() // Fills the rest of the packet with the default values }; + + // Serialize the request into a fixed-size byte array. let mut request_bytes = [0; Packet::PACKED_SIZE_BYTES]; request .to_bytes(&mut request_bytes) .expect("NTP client request should serialize"); + + // Send the request socket .send_to(&request_bytes, server_addr) .await .expect("NTP client request should be sent"); + // Waiting for the server to respond let mut response_bytes = [0; 2048]; let (response_len, source_addr) = tokio::time::timeout( Duration::from_secs(2), @@ -99,9 +139,12 @@ mod test { .expect("NTP server should respond before timeout") .expect("NTP response should be received"); + // Response should come from the same server address assert_eq!(source_addr, server_addr); + // Response should have the same packet length assert_eq!(response_len, Packet::PACKED_SIZE_BYTES); + // Deserialize response and validate contents let (response, bytes_read) = Packet::from_bytes(&response_bytes[..response_len]) .expect("server response should be a valid NTP packet"); assert_eq!(bytes_read, Packet::PACKED_SIZE_BYTES); @@ -111,6 +154,7 @@ mod test { assert_eq!(response.origin_timestamp, request.transmit_timestamp); assert_ne!(response.transmit_timestamp, TimestampFormat::default()); + // Stop the server task and verify that it was cancelled. server_task.abort(); assert!( server_task From c48c98605c0d0aa3aa41fabd02d708b874f4cd49 Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Sat, 3 Oct 2026 12:48:40 +0200 Subject: [PATCH 012/225] fix: delete NtpAddress and use two functions --- backend/crates/core/src/ntp.rs | 45 +++++++++++++++------------------- 1 file changed, 20 insertions(+), 25 deletions(-) diff --git a/backend/crates/core/src/ntp.rs b/backend/crates/core/src/ntp.rs index aeab276c9..1f94d620a 100644 --- a/backend/crates/core/src/ntp.rs +++ b/backend/crates/core/src/ntp.rs @@ -7,35 +7,30 @@ use tracing::{debug, info, instrument}; const NTP_DEFAULT_PORT: u16 = 8123; -/// Represents the address used to start the NTP server. -/// It can be defined as an IPv4 interface + port or as a full socket address. -#[derive(Debug)] -pub enum NtpAddress { - /// Uses the interface and port separately. - Interface { - /// IPv4 interface to bind to. If `None`, the default interface (`0.0.0.0`) is used. - interface: Option, - /// Port to listen on. If `None`, the default NTP port (`8123`) is used. - port: Option, - }, - /// Uses a complete IPv4 socket address. - Socket(Option) +/// Starts the NTP server with an interface and a port. +/// +/// Arguments: +/// - `interface`: IPv4 interface to bind to. If `None`, the default interface (`0.0.0.0`) is used. +/// - `port`: Port to listen on. If `None`, the default NTP port (`8123`) is used. +pub async fn start_ntp(interface: Option, port: Option) -> io::Result<()> { + start_ntp_server(interface, port).await } -/// Starts the NTP server +/// Starts the NTP server with a socket. +/// /// Arguments: -/// - `address`: The target address configuration used to bind the server. -#[instrument(level = "info")] -pub async fn start_ntp_server(address: NtpAddress) -> io::Result<()> { - - let (interface, port) = match address { - NtpAddress::Interface {interface, port} => (interface, port), - NtpAddress::Socket(Some(socket)) => { - (Some(*socket.ip()), Some(socket.port())) - }, - NtpAddress::Socket(None) => (None, None) +/// - `socket`: Complete IPv4 socket address. If `None` the default `SocketAddrV4` is used (`0.0.0.0:8123`). +pub async fn start_ntp_with_socket(socket: Option) -> io::Result<()> { + let (interface, port) = match socket { + Some(socket) => (Some(*socket.ip()), Some(socket.port())), + None => (None, None) }; + start_ntp_server(interface, port).await +} + +#[instrument(level = "info")] +async fn start_ntp_server(interface: Option, port: Option) -> io::Result<()> { let server = build_ntp_server(interface, port).await?; info!("Starting NTP server loop"); // Any internal log of server.run() will be wrapped within this function Span @@ -106,7 +101,7 @@ mod test { let socket = UdpSocket::bind((Ipv4Addr::LOCALHOST, 0)) .await .expect("NTP client socket should bind to an ephemeral local port"); - + // Build NTP request packet for testing requests let request = Packet { transmit_timestamp: TimestampFormat { From 6b3429115145c338658ae4479dbe733b3868232a Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Sat, 3 Oct 2026 12:53:35 +0200 Subject: [PATCH 013/225] feat: add tracing to new functions --- backend/crates/core/src/ntp.rs | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/backend/crates/core/src/ntp.rs b/backend/crates/core/src/ntp.rs index 1f94d620a..83b3487cf 100644 --- a/backend/crates/core/src/ntp.rs +++ b/backend/crates/core/src/ntp.rs @@ -8,22 +8,24 @@ use tracing::{debug, info, instrument}; const NTP_DEFAULT_PORT: u16 = 8123; /// Starts the NTP server with an interface and a port. -/// +/// /// Arguments: /// - `interface`: IPv4 interface to bind to. If `None`, the default interface (`0.0.0.0`) is used. /// - `port`: Port to listen on. If `None`, the default NTP port (`8123`) is used. +#[instrument(level = "info")] pub async fn start_ntp(interface: Option, port: Option) -> io::Result<()> { start_ntp_server(interface, port).await } /// Starts the NTP server with a socket. -/// +/// /// Arguments: /// - `socket`: Complete IPv4 socket address. If `None` the default `SocketAddrV4` is used (`0.0.0.0:8123`). +#[instrument(level = "info")] pub async fn start_ntp_with_socket(socket: Option) -> io::Result<()> { let (interface, port) = match socket { Some(socket) => (Some(*socket.ip()), Some(socket.port())), - None => (None, None) + None => (None, None), }; start_ntp_server(interface, port).await From e01eadb5195ab92db699c9aa885df03c3c8600cb Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Sat, 3 Oct 2026 13:06:02 +0200 Subject: [PATCH 014/225] fix: change function name, and explain NTP packet values --- backend/crates/core/src/ntp.rs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/backend/crates/core/src/ntp.rs b/backend/crates/core/src/ntp.rs index 83b3487cf..5cf85b712 100644 --- a/backend/crates/core/src/ntp.rs +++ b/backend/crates/core/src/ntp.rs @@ -13,8 +13,8 @@ const NTP_DEFAULT_PORT: u16 = 8123; /// - `interface`: IPv4 interface to bind to. If `None`, the default interface (`0.0.0.0`) is used. /// - `port`: Port to listen on. If `None`, the default NTP port (`8123`) is used. #[instrument(level = "info")] -pub async fn start_ntp(interface: Option, port: Option) -> io::Result<()> { - start_ntp_server(interface, port).await +pub async fn start_ntp_server(interface: Option, port: Option) -> io::Result<()> { + run_ntp_server(interface, port).await } /// Starts the NTP server with a socket. @@ -22,17 +22,17 @@ pub async fn start_ntp(interface: Option, port: Option) -> io::Re /// Arguments: /// - `socket`: Complete IPv4 socket address. If `None` the default `SocketAddrV4` is used (`0.0.0.0:8123`). #[instrument(level = "info")] -pub async fn start_ntp_with_socket(socket: Option) -> io::Result<()> { +pub async fn start_ntp_server_with_socket(socket: Option) -> io::Result<()> { let (interface, port) = match socket { Some(socket) => (Some(*socket.ip()), Some(socket.port())), None => (None, None), }; - start_ntp_server(interface, port).await + run_ntp_server(interface, port).await } #[instrument(level = "info")] -async fn start_ntp_server(interface: Option, port: Option) -> io::Result<()> { +async fn run_ntp_server(interface: Option, port: Option) -> io::Result<()> { let server = build_ntp_server(interface, port).await?; info!("Starting NTP server loop"); // Any internal log of server.run() will be wrapped within this function Span @@ -107,7 +107,7 @@ mod test { // Build NTP request packet for testing requests let request = Packet { transmit_timestamp: TimestampFormat { - // Test data, just to verify the server responds correctly + // Random data for test purpose only, just to verify the server responds correctly seconds: 0xE0000000, fraction: 0x12345678, }, From 2c15a65bb95098f534a62eb1c4dc8dc591c77ff9 Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Tue, 6 Oct 2026 20:08:31 +0200 Subject: [PATCH 015/225] feat: adj --- backend/crates/core/src/adj.rs | 34 + .../core/src/adj/Comunicaciones_Reunion01.qmd | 356 ++++++ backend/crates/core/src/adj/error.rs | 145 +++ backend/crates/core/src/adj/info.rs | 37 + backend/crates/core/src/adj/raw.rs | 12 + backend/crates/core/src/adj/raw/loader.rs | 281 +++++ backend/crates/core/src/adj/raw/types.rs | 470 +++++++ .../crates/core/src/adj/test/adj/README.md | 291 +++++ .../crates/core/src/adj/test/adj/boards.json | 6 + .../src/adj/test/adj/boards/BLCU/BLCU.json | 12 + .../adj/boards/BLCU/BLCU_measurements.json | 34 + .../src/adj/test/adj/boards/BLCU/orders.json | 15 + .../src/adj/test/adj/boards/BLCU/packets.json | 28 + .../src/adj/test/adj/boards/BLCU/sockets.json | 14 + .../src/adj/test/adj/boards/HVBMS/HVBMS.json | 15 + .../adj/boards/HVBMS/HVBMS_measurements.json | 1102 +++++++++++++++++ .../src/adj/test/adj/boards/HVBMS/orders.json | 32 + .../adj/test/adj/boards/HVBMS/packets.json | 218 ++++ .../adj/test/adj/boards/HVBMS/sockets.json | 13 + .../core/src/adj/test/adj/boards/LCU/LCU.json | 15 + .../test/adj/boards/LCU/LCU_measurements.json | 752 +++++++++++ .../src/adj/test/adj/boards/LCU/orders.json | 142 +++ .../src/adj/test/adj/boards/LCU/packets.json | 163 +++ .../src/adj/test/adj/boards/LCU/sockets.json | 13 + .../core/src/adj/test/adj/boards/PCU/PCU.json | 15 + .../test/adj/boards/PCU/PCU_measurements.json | 304 +++++ .../src/adj/test/adj/boards/PCU/orders.json | 53 + .../src/adj/test/adj/boards/PCU/packets.json | 91 ++ .../src/adj/test/adj/boards/PCU/sockets.json | 13 + .../core/src/adj/test/adj/boards/VCU/VCU.json | 16 + .../test/adj/boards/VCU/VCU_measurements.json | 95 ++ .../src/adj/test/adj/boards/VCU/orders.json | 87 ++ .../src/adj/test/adj/boards/VCU/packets.json | 62 + .../src/adj/test/adj/boards/VCU/sockets.json | 13 + .../core/src/adj/test/adj/general_info.json | 61 + backend/crates/core/src/lib.rs | 5 + backend/crates/station/src/main.rs | 12 + 37 files changed, 5027 insertions(+) create mode 100644 backend/crates/core/src/adj.rs create mode 100644 backend/crates/core/src/adj/Comunicaciones_Reunion01.qmd create mode 100644 backend/crates/core/src/adj/error.rs create mode 100644 backend/crates/core/src/adj/info.rs create mode 100644 backend/crates/core/src/adj/raw.rs create mode 100644 backend/crates/core/src/adj/raw/loader.rs create mode 100644 backend/crates/core/src/adj/raw/types.rs create mode 100644 backend/crates/core/src/adj/test/adj/README.md create mode 100644 backend/crates/core/src/adj/test/adj/boards.json create mode 100644 backend/crates/core/src/adj/test/adj/boards/BLCU/BLCU.json create mode 100644 backend/crates/core/src/adj/test/adj/boards/BLCU/BLCU_measurements.json create mode 100644 backend/crates/core/src/adj/test/adj/boards/BLCU/orders.json create mode 100644 backend/crates/core/src/adj/test/adj/boards/BLCU/packets.json create mode 100644 backend/crates/core/src/adj/test/adj/boards/BLCU/sockets.json create mode 100644 backend/crates/core/src/adj/test/adj/boards/HVBMS/HVBMS.json create mode 100644 backend/crates/core/src/adj/test/adj/boards/HVBMS/HVBMS_measurements.json create mode 100644 backend/crates/core/src/adj/test/adj/boards/HVBMS/orders.json create mode 100644 backend/crates/core/src/adj/test/adj/boards/HVBMS/packets.json create mode 100644 backend/crates/core/src/adj/test/adj/boards/HVBMS/sockets.json create mode 100644 backend/crates/core/src/adj/test/adj/boards/LCU/LCU.json create mode 100644 backend/crates/core/src/adj/test/adj/boards/LCU/LCU_measurements.json create mode 100644 backend/crates/core/src/adj/test/adj/boards/LCU/orders.json create mode 100644 backend/crates/core/src/adj/test/adj/boards/LCU/packets.json create mode 100644 backend/crates/core/src/adj/test/adj/boards/LCU/sockets.json create mode 100644 backend/crates/core/src/adj/test/adj/boards/PCU/PCU.json create mode 100644 backend/crates/core/src/adj/test/adj/boards/PCU/PCU_measurements.json create mode 100644 backend/crates/core/src/adj/test/adj/boards/PCU/orders.json create mode 100644 backend/crates/core/src/adj/test/adj/boards/PCU/packets.json create mode 100644 backend/crates/core/src/adj/test/adj/boards/PCU/sockets.json create mode 100644 backend/crates/core/src/adj/test/adj/boards/VCU/VCU.json create mode 100644 backend/crates/core/src/adj/test/adj/boards/VCU/VCU_measurements.json create mode 100644 backend/crates/core/src/adj/test/adj/boards/VCU/orders.json create mode 100644 backend/crates/core/src/adj/test/adj/boards/VCU/packets.json create mode 100644 backend/crates/core/src/adj/test/adj/boards/VCU/sockets.json create mode 100644 backend/crates/core/src/adj/test/adj/general_info.json diff --git a/backend/crates/core/src/adj.rs b/backend/crates/core/src/adj.rs new file mode 100644 index 000000000..3053f76b9 --- /dev/null +++ b/backend/crates/core/src/adj.rs @@ -0,0 +1,34 @@ +//! Parses an ADJ (Architecture Description JSON) directory into +//! [`crate::model::PodData`], plus backend-session metadata not modeled as +//! vehicle data ([`crate::adj::AdjInfo`]). +//! +//! Loading (not downloading — see `core::git` for that, a sibling module +//! this one is a client of) is not specific to `station`: a sniffer, a +//! simulator, or any other tool that reads an ADJ needs exactly the same +//! parsing. Scope for this iteration: no `sockets.json`, no +//! `period`/`period_type`/`socket` packet fields (matches +//! [`crate::model::PacketDef`]'s own omission), and no schema validation +//! (`adj::validate` is a separate, deliberately out-of-scope concern for +//! now) — this module only surfaces structural errors it cannot avoid, +//! e.g. a packet referencing a measurement alias that doesn't exist. + +mod error; +mod info; +pub mod raw; + +pub use error::{LoadError, MeasurementError, ProtectionError}; +pub use info::{AdjInfo, ProtectionTypeInfo}; +pub use raw::load_from_dir; + +use crate::model::PodData; + +/// The result of loading an ADJ: the vehicle's data (as [`crate::model`] +/// describes it) plus backend-session metadata. Built by +/// [`raw::load_from_dir`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct Adj { + /// Every board and packet defined by the ADJ. + pub pod_data: PodData, + /// Backend-session metadata from `general_info.json`. + pub info: AdjInfo, +} diff --git a/backend/crates/core/src/adj/Comunicaciones_Reunion01.qmd b/backend/crates/core/src/adj/Comunicaciones_Reunion01.qmd new file mode 100644 index 000000000..fe6540072 --- /dev/null +++ b/backend/crates/core/src/adj/Comunicaciones_Reunion01.qmd @@ -0,0 +1,356 @@ +--- +title: "ADJv3" +subtitle: Acta de la 1ª Reunión de comunicaciones +author: "Javier Ribal del Río" +date: 2026/09/16 +department: "ALL" # "SW" o "FW" +attendees: + - Javier Ribal del Río (SW-FW) (1ª y 2ª) + - Jorge Canut (FW) (1ª) + - Víctor López (FW) (1ª y 2ª) + - Aleksandr Globa (FW) (1ª y 2ª) + - Pau Minguet (SW) (2ª) + - Gazi Halawali (SW) (2ª) + - Pablo Pertusa (FW) (2ª) + - Boris Mladenov (2ª) + - Javier Lara (2ª) +--- + +## Contextualización + +El presente documento tiene como objetivo servir como especificación técnica para la implementación del `ADJv3`, partiendo de la base del `ADJv2` definido en el `README.md` del repositorio. El cambio más significativo se corresponde con la separación en forma y concepto de los `messages` y las `protections`. En el pasado, un `message` se correspondía con la información que enviaban las placas al vehículo, y las `protections` eran una implementación de los `messages`; es decir, una `protection` era un `message` con un tipo determinado. Asimismo, el documento también se corresponde con el acta de la primera reunión de comunicaciones. Debido a su larga duración, esta reunión se dividió en dos convocatorias (1ª y 2ª), celebradas los días 10 y 16 de septiembre de 2026, de ahí que el documento recoja las dos fechas y que la asistencia se indique por convocatoria. + +En el Drive del equipo hay unas diapositivas de la reunión que quizá arrojen algo de luz sobre el contenido de este texto. + +\newpage + +## Modificación de la estructura de los `measurements` y modificación de los `id` de los `packets/orders` + +Con el objetivo de dar soporte a las `protections` para cada `measurement`, el campo `id` pasa a ser un identificador único numérico común entre `packets` y `orders`. El rango de este identificador común es $[0, 8.191] = [0, 2^{13} - 1]$ ^[Podríamos definirlo como un `int13`]. Sin embargo, los `id` comprendidos en $[0, 511]$ se corresponden con los *ID* especiales: no asignados a `packets`, `orders` ni `protections`, o reservados para otros fines. + +Sin embargo, no podemos prescindir del `id` textual previamente definido, puesto que es empleado por la generación de código y no puede ser sustituido por el `id` numérico ^[Esto se debe a que actualmente la generación de código utiliza el `id` del `measurement` para generar su variable asociada]. Por ello, definimos un nuevo campo denominado `alias` que se corresponde con el antiguo campo `id` ^[Esta decisión de mantener un campo legado maximiza la compatibilidad con la `logging-view`]. Además, el campo `alias` se corresponde con el identificador para los archivos tipo `packets` y `orders`. + + + +## Incorporación de las `protections` al ADJ + +Las `protections` se desvinculan de la implementación de los `messages`, por lo que es necesario definir una nueva estructura para el paquete a enviar. + +### Estructura del paquete + +El paquete de una `protection` tiene longitud casi fija: una cabecera de 64 bits (`id` más +`timestamp`, con relleno de alineación) seguida del valor que ha disparado la protección, +cuyo tamaño depende del tipo del `measurement` vigilado. + +```{mermaid} +%%| label: fig-estructura-proteccion +%%| fig-cap: "Estructura del paquete de una protección. Las casillas van numeradas por su offset en bits. El campo `value` ocupa el mismo tamaño que el `measurement` asociado (de 8 a 64 bits); aquí se dibuja con 64." +%%| fig-width: 5.2 +%%| fig-pos: 'H' +%%{init: {"packet": {"bitWidth": 15, "rowHeight": 34, "bitsPerRow": 32, "showBits": true}}}%% +packet-beta +0-15: "id" +16-23: "hora" +24-31: "min" +32-39: "seg" +40-47: "subseg" +48-63: "resv" +64-127: "value" +``` + +- `id` (bits 0–15): identificador numérico de la protección. +- `timestamp` (bits 16–47): instante en que salta la protección, con `hora`, `min`, `seg` y + `subseg` en 8 bits cada uno. +- `resv` (bits 48–63): 2 bytes reservados, únicamente para alinear `value` a un offset + múltiplo de 8 bytes. +- `value` (bits 64 en adelante): valor que ha excedido el umbral. Ocupa exactamente el mismo + tamaño que el `measurement` que vigila la protección (de 8 a 64 bits según su `type`), de + modo que el receptor lo decodifica con el mismo codificador que ese `measurement`. + + +### Tipos de `protection` definidos en `general_info.json` + +Los tipos de `protection` que pueden saltar se declaran en `general_info.json`, en un objeto +`protectionTypes` que asocia el nombre de cada protección a su definición: + +``` +{ + "protectionTypes": { + "": { + "range": booleano?, + "text": "", + "textTime": "?" + } + } +} +``` + +- `range`: booleano opcional, `false` por defecto. Indica cuántos límites tiene la + protección: `false` para las de un solo valor (`Above`, `Below`, `Equal`…) y `true` para + las de intervalo (`Range`), en cuyo caso los dos límites se escriben con notación de + intervalo, p. ej. `[233, 333]`. +- `text`: plantilla del mensaje que se muestr aen la control station. Los `{}` se + sustituyen por los límites definidos para la protección (un único valor, o el intervalo + `[min, max]` si `range` es `true`) y el `%`, por el valor que los ha excedido. +- `textTime`: plantilla alternativa para las protecciones de acumulación temporal + (`time_accumulation`), que saltan cuando el valor se mantiene fuera de rango durante un + intervalo dado. Se usa en lugar de `text` y el `%` se sustituye por ese tiempo máximo, no + por el valor. + + +#### Ejemplos de tipos de `protection` + +- `Above` +- `Below` +- `Equal` +- `NotEqual` ^[La protección se encuentra definida en la `ST-LIB`, por el momento no se nos ha ocurrido su propósito] +- `Range` + +### Definición de `protections` en los `measurements` + +Cada `measurement` de `_measurements.json` incorpora los cambios anteriores (el `id` +pasa a ser numérico, de rango $[0, 8.191]$, y el identificador textual antiguo se conserva +en `alias`) y, además, una lista opcional `protections` con las protecciones que vigilan esa +medida: + +``` +{ + "id": número, + "alias": "", + "name": "", + "type": "", + "podUnits": "?", + "displayUnits": "?", + "enumValues": [""]?, + "protections": [ + { + "type": "", + "value": [número] | [número, número], + "fault": booleano?, + "time": "?" + } + ]? +} +``` + +`protections` *array* limitado a 7 protecciones. + +- `type`: uno de los tipos declarados en `protectionTypes` (`Above`, `Below`, `Equal`, + `NotEqual`, `Range`). +- `value`: lista con el o los límites de la protección. Un elemento para las de un solo + valor y dos, `[min, max]`, para `Range`. +- `fault`: booleano opcional, `true` por defecto. Fija la severidad con la que se emite la + protección: `true` la envía como *fault* y `false` como *warning*. +- `time`: opcional, solo para las protecciones de acumulación temporal. Cadena con valor y + unidad (`"500ms"`, `"3s"`…) que indica cuánto tiempo debe mantenerse la medida fuera de + rango antes de que la protección salte, por defecto `0`. + +### Id de las protecciones + +\begin{quote} +\fbox{\parbox{0.92\linewidth}{\raggedright +\textbf{¿Qué es \textit{bit-packing}?}\\[4pt] +Es la técnica de meter varios campos independientes dentro de un mismo entero, cada uno +ocupando solo los bits que necesita, en vez de reservarle un byte o un campo propio. Aquí +el \texttt{uint16} del \texttt{id} empaqueta dos campos: \texttt{pos} (3 bits) e +\texttt{id\_measurement} (13 bits). Se construye desplazando y combinando con operadores a +nivel de bit --- \texttt{(pos << 13) | id\_measurement} --- y se deshace igual, en el otro +sentido: \texttt{pos = id >> 13} e \texttt{id\_measurement = id \& 0x1FFF}. La ventaja es +que no se desperdicia ni un bit; el coste es que, si un consumidor no sabe que el campo va +empaquetado, lo interpreta mal sin que nada se lo avise. +}} +\end{quote} + +Esta codificación no es exclusiva del paquete de la `protection`: como `packets`, `orders` y +`protections` comparten el mismo campo `id` de 16 bits, se aplica al `id` de **cualquier** +paquete del protocolo. Al recibir un `id`, lo primero que se mira son sus 3 bits altos +(`pos`): si valen `000`, el resto son los 13 bits del `id` normal de un `packet`, `order` o +`measurement`; si no, indican qué `protection` (`1`–`7`) del `measurement` de esos 13 bits +ha saltado: + +$$\texttt{id} = (\texttt{pos} \ll 13) \mathbin{|} \texttt{id\_measurement}$$ + +```{mermaid} +%%| label: fig-id-protection +%%| fig-cap: "Id de 16 bits compartido por packets, orders y protections: 3 bits de posición (000 = id normal) + 13 bits del id de measurement/packet/order." +%%| fig-width: 4.6 +%%| fig-pos: 'H' +%%{init: {"packet": {"bitWidth": 22, "rowHeight": 34, "bitsPerRow": 16, "showBits": true}}}%% +packet-beta +0-12: "id measurement" +13-15: "pos" +``` + +| `pos` | Significado | +|:-----:|-------------------------------------------------| +| `000` | `id` normal: `packet`, `order` o `measurement` | +| `001` | `protections[0]` | +| `010` | `protections[1]` | +| `011` | `protections[2]` | +| `100` | `protections[3]` | +| `101` | `protections[4]` | +| `110` | `protections[5]` | +| `111` | `protections[6]` | + +Con `pos` de `1` a `7` caben exactamente las 7 `protections` por `measurement` fijadas +antes; `pos = 0` deja el `id` libre para su uso normal. Como el resto del protocolo, este +`id` compuesto viaja como un único `uint16` en *little-endian* ^[`pos` no ocupa un byte +aparte: son los 3 bits más altos de ese mismo `uint16`, así que quedan repartidos en el +byte alto junto con los 5 bits más significativos de `id_measurement`.]. + + +\newpage + + +## Refactor de los `messages` + +### Estructura del `message` + +```{mermaid} +%%| label: fig-estructura-message +%%| fig-cap: "Estructura del nuevo message. origin (máx. 48 bytes) y message (máx. 320 bytes) son cadenas terminadas en 0, de longitud variable; aquí se dibujan truncadas a 4 bytes." +%%| fig-width: 5.2 +%%| fig-pos: 'H' +%%{init: {"packet": {"bitWidth": 40, "rowHeight": 34, "bitsPerRow": 10, "showBits": true}}}%% +packet-beta +0-1: "id" +2-2: "hora" +3-3: "min" +4-4: "seg" +5-5: "subseg" +6-9: "origin (txt 0)" +10-13: "message (txt 0)" +``` + +- `id` (2 bytes): tipo de mensaje (`uint16`). Reutiliza `message_ids` de `general_info.json` + (ver más abajo): `10` = `fault`, `11` = `warning`, `12` = `info` y, como tipo nuevo, + `13` = `panic`^[Ya estaba definido en la `ST-LIB` y era enmascarado como un mensaje de `fault`, ahora queda incluido en el `ADJ`]. +- `timestamp` (4 bytes): el mismo formato que en las `protections` — `hora`, `min`, `seg` y + `subseg` en un byte cada uno. +- `origin` (hasta 48 bytes, cadena terminada en `0`): de dónde sale el mensaje. Actualmente + es la ruta absoluta del fichero de origen ^[Sería mejor que fuese la ruta relativa desde + la raíz del repositorio de la placa, no la ruta absoluta del sistema en el que se + compiló.]. +- `message` (hasta 320 bytes, cadena terminada en `0`): contenido del mensaje. + +`origin` y `message` llevan tamaño máximo pero longitud variable: al llegar al byte `0` se +entiende que la cadena ha terminado. + +#### Implementación en `general_info.json` + +Reutilizamos los `message_ids` definidos en `general_info.json`, que por el momento estaban +en desuso: + +``` +{ + "message_ids": { + "fault": 10, + "warning": 11, + "info": 12, + "panic": 13 + } +} +``` + +## Adición de la MAC a la información propia de cada placa + +En vista de lo acontecido en la EHW en H11^[Hubo MAC *curiosas* como `67:67:67:67:67:67` que causaban problemas y horas de *debugging*], se va a añadir un campo `mac` que se corresponde con la `MAC` de cada placa con el objetivo de que se use en la generación de código y sea validado por el `adj-validator`. + + +## Gestión de tiempos y `SNTP` + +Se comenta la posibilidad de realizar un *POC* para mirar la viabilidad de utilizar el protocolo `SNTP` para sincronizar reloj de las placas y el backend. Boris comenta que ya estaba implementado pero que no funcionaba. + +Se ocuparán Víctor y Javier Ribal. Mirar el `README` de `SNTP` en la `ST-LIB`. + + +## Módulo `units` + +Se abandona la implementación del `ADJv2`, se desimplementa `podUnits` y su contraparte en `general_info.json`. Se debate sobre la utilidad del módulo y su practicidad. + +Se acuerda implementarlo añadiendo a cada `measurement` un factor para cada operación. + +## Asignar `id` especiales para la `BLCU` + +Se reserva el rango $[20, 29]$ para los paquetes/órdenes asociados a la `BLCU`. + +## Verificación del `ADJ` *hash* + +Se reserva el `id` 2 para la comparación de commits. + +En caso de que estemos utilizando la `VCU` como `master`, durante la conexión `TCP` compararán el *hash* del `ADJ`; si coinciden todos, se pasará al `backend` (si no, se pasará `hash = 0x00...`). + +En la comparación en el `backend`, si coinciden todos, estará bien; si no, y únicamente si está marcada una nueva opción del `backend`, *Different ADJ hash Fault*, se irá a `fault`; si no, simplemente imprimiremos un `warning`. + + +### Formato + +```{mermaid} +%%| label: fig-formato-hash-adj +%%| fig-cap: "Formato del paquete de verificación del hash del `ADJ`: `id` fijo a `2` (uint16) seguido del `commit` (uint64) del `ADJ` vigente." +%%| fig-width: 5.2 +%%| fig-pos: 'H' +%%{init: {"packet": {"bitWidth": 15, "rowHeight": 34, "bitsPerRow": 32, "showBits": true}}}%% +packet-beta +0-15: "id (=2)" +16-79: "commit" +``` + +- `id` (16 bits): fijo a `2`, identifica este paquete como la comparación de *hash* del `ADJ`. +- `commit` (64 bits): *hash* del commit del `ADJ` que está usando la placa o el `backend`. + + + +## *Custom Keep-alive* + +Mantenemos el estilo: será el `backend` quien envíe el *keep-alive* y nos iremos a `fault` si no se recibe el `ack`. `FW` hará lo propio en las placas. + +Posibilidad de añadir un botón para desactivar el *keep-alive* del `backend`. + +## Propuesta de incorporación del `array` + +Autor: *Víctor López* + +Añadimos un atributo opcional a los measurements 'arrayLength'. + +Este atributo define la longitud de array para el measurement, si el measurement tiene protecciones, se comprobará la protección por cada elemento del array. + +Si se necesita envíar una alerta de que la protección ha detectado un fallo en un elemento del array, se envía en el campo `reserved` del mensaje de la protección el índice del array que ha fallado (empezando por el índice 0). + +Se vería así el paquete de protección entonces: + +```{mermaid} +%%| label: fig-proteccion-array +%%| fig-cap: "Estructura del paquete de una protección sobre un measurement de tipo array. El campo `resv` pasa a contener el índice del elemento que ha fallado (empezando por 0). El campo `value` ocupa el mismo tamaño que el elemento del array; aquí se dibuja con 64 bits." +%%| fig-width: 5.2 +%%| fig-pos: 'H' +%%{init: {"packet": {"bitWidth": 15, "rowHeight": 34, "bitsPerRow": 32, "showBits": true}}}%% +packet-beta +0-15: "id" +16-23: "hora" +24-31: "min" +32-39: "seg" +40-47: "subseg" +48-63: "índice" +64-127: "value" +``` + +```{mermaid} +%%| label: fig-packet-array +%%| fig-cap: "Estructura de un paquete para un measurement que es un array de `uint16` (aquí, con 3 elementos): el `id` seguido de los elementos consecutivos." +%%| fig-width: 5.2 +%%| fig-pos: 'H' +%%{init: {"packet": {"bitWidth": 15, "rowHeight": 34, "bitsPerRow": 32, "showBits": true}}}%% +packet-beta +0-15: "id" +16-31: "value[0]" +32-47: "value[1]" +48-63: "value[2]" +``` + +## Otros apuntes de la reunión + +Por la parte de FW, Víctor y Jorge Canut se muestran conformes con la implementación del refactor en la `ST-LIB`. Por otra parte, Javier Ribal comenta que al rehacerse el `backend` desde cero no ve ningún impedimiento en aplicar estos cambios. + +Primera reunión de Aleksandr Globa y Pablo Pertusa que se incorporan al subsistema de Firmware. + diff --git a/backend/crates/core/src/adj/error.rs b/backend/crates/core/src/adj/error.rs new file mode 100644 index 000000000..c080b036d --- /dev/null +++ b/backend/crates/core/src/adj/error.rs @@ -0,0 +1,145 @@ +//! Errors produced while loading an ADJ. +//! +//! Layered on purpose: [`LoadError`] is the only public error type here — +//! the one a composition root's own aggregate error would `#[from]`-chain +//! into — while [`MeasurementError`] and [`ProtectionError`] stay +//! crate-private. Nothing outside this crate needs to match past +//! `LoadError` into them; `.source()` still returns `&dyn Error` for +//! logging regardless of the concrete type's visibility. + +use std::net::AddrParseError; +use std::path::PathBuf; + +/// An error produced while loading an ADJ directory into an [`crate::adj::Adj`]. +#[derive(Debug, thiserror::Error)] +pub enum LoadError { + /// Couldn't read a file. + #[error("couldn't read {path:?}")] + ReadFile { + /// The file that couldn't be read. + path: PathBuf, + /// The underlying I/O error. + #[source] + source: std::io::Error, + }, + + /// A file's contents weren't valid JSON for the shape expected there. + #[error("couldn't parse {path:?} as JSON")] + ParseJson { + /// The file that failed to parse. + path: PathBuf, + /// The underlying JSON error. + #[source] + source: serde_json::Error, + }, + + /// A board's `board_ip` isn't a valid IP address. + #[error("board {board:?}: invalid IP address {raw:?}")] + InvalidIp { + /// The board whose IP address is invalid. + board: String, + /// The text that failed to parse. + raw: String, + /// The underlying parse error. + #[source] + source: AddrParseError, + }, + + /// A board's `mac` isn't a valid MAC address. + #[error("board {board:?}: invalid MAC address {raw:?}")] + InvalidMac { + /// The board whose MAC address is invalid. + board: String, + /// The text that failed to parse. + raw: String, + }, + + /// A board has no `mac` field at all. + #[error("board {board:?}: missing MAC address")] + MissingMac { + /// The board missing its MAC address. + board: String, + }, + + /// A packet or order declares a `type` other than `"data"` or `"order"`. + #[error("board {board:?}, packet {name:?}: unknown packet type {type_name:?}")] + UnknownPacketType { + /// The board the packet belongs to. + board: String, + /// The packet's name. + name: String, + /// The unrecognized type string. + type_name: String, + }, + + /// A packet or order references a measurement alias that doesn't exist + /// among that board's own measurements. + #[error("board {board:?}, packet {name:?}: unknown measurement alias {alias:?}")] + UnknownAlias { + /// The board the packet belongs to. + board: String, + /// The packet's name. + name: String, + /// The alias that couldn't be resolved. + alias: String, + }, + + /// A measurement couldn't be converted into [`crate::model::Measurement`]. + #[error("board {board:?}, measurement {alias:?}: {source}")] + Measurement { + /// The board the measurement belongs to. + board: String, + /// The measurement's alias. + alias: String, + /// The underlying conversion error. + #[source] + source: MeasurementError, + }, +} + +/// An error converting a raw measurement into [`crate::model::Measurement`]. +#[derive(Debug, thiserror::Error)] +pub enum MeasurementError { + /// The measurement's `type` isn't a recognized wire type, `"bool"` or + /// `"enum"`. + #[error("unknown measurement type {0:?}")] + UnknownType(String), + + /// The measurement's `type` is `"enum"` but no `enumValues` were given. + #[error("type is \"enum\" but no enumValues were given")] + MissingEnumValues, + + /// One of the measurement's declared protections failed to convert. + #[error("protection #{index}: {source}")] + Protection { + /// The protection's 1-based position within the measurement's list. + index: usize, + /// The underlying conversion error. + #[source] + source: ProtectionError, + }, +} + +/// An error converting a raw protection into [`crate::model::Protection`]. +#[derive(Debug, thiserror::Error)] +pub enum ProtectionError { + /// The protection's `type` isn't one of the five known kinds. + #[error("unknown protection type {0:?}")] + UnknownType(String), + + /// The protection's `value` array doesn't have the number of bounds its + /// `type` requires. + #[error("type {kind:?} needs {expected} bound(s), got {got}")] + WrongBoundCount { + /// The protection's type string. + kind: String, + /// How many bounds that type requires. + expected: u8, + /// How many bounds were actually given. + got: usize, + }, + + /// The protection's `time` string couldn't be parsed as a duration. + #[error("couldn't parse time {0:?}")] + InvalidTime(String), +} diff --git a/backend/crates/core/src/adj/info.rs b/backend/crates/core/src/adj/info.rs new file mode 100644 index 000000000..02d9870b9 --- /dev/null +++ b/backend/crates/core/src/adj/info.rs @@ -0,0 +1,37 @@ +//! Backend-session metadata from `general_info.json`. +//! +//! This is not vehicle data — that's [`crate::model::PodData`] — but what +//! *this backend session* needs beyond the vehicle: known ports and +//! addresses, message-id conventions, and how to display a triggered +//! protection. + +use std::collections::HashMap; + +/// A protection type's display text, as declared in `general_info.json`'s +/// `protectionTypes`. +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct ProtectionTypeInfo { + /// Whether this protection type takes an interval (`[min, max]`) + /// instead of a single bound. + pub is_range: bool, + /// The message template shown at the control station; `{}` stands for + /// the protection's bound(s), `%` for the value that triggered it. + pub text: String, + /// The alternative template for time-accumulation protections, if one + /// was declared. + pub text_time: Option, +} + +/// Backend-session metadata parsed from `general_info.json`. +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct AdjInfo { + /// Known port numbers, by name (e.g. `"TCP_SERVER"` -> `50500`). + pub ports: HashMap, + /// Known addresses, by name (e.g. `"backend"` -> `"192.168.0.9"`), kept + /// as text: nothing in this crate needs them parsed as an `IpAddr` yet. + pub addresses: HashMap, + /// Known message ids, by name (e.g. `"fault"` -> `2`). + pub message_ids: HashMap, + /// Declared protection types, by name (e.g. `"Range"`). + pub protection_types: HashMap, +} diff --git a/backend/crates/core/src/adj/raw.rs b/backend/crates/core/src/adj/raw.rs new file mode 100644 index 000000000..7347e48af --- /dev/null +++ b/backend/crates/core/src/adj/raw.rs @@ -0,0 +1,12 @@ +//! Raw ADJ JSON shapes and the directory-walking loader. +//! +//! Kept together as their own submodule — unlike `error`/`info` — because +//! this whole module is the one piece of `adj` meant to be reused as-is by +//! a future non-`station` product (a sniffer, a simulator...). The +//! individual `RawX` shapes stay private; what's reusable is the +//! [`load_from_dir`] entry point, not picking apart its internals. + +mod loader; +mod types; + +pub use loader::load_from_dir; diff --git a/backend/crates/core/src/adj/raw/loader.rs b/backend/crates/core/src/adj/raw/loader.rs new file mode 100644 index 000000000..aec8a9934 --- /dev/null +++ b/backend/crates/core/src/adj/raw/loader.rs @@ -0,0 +1,281 @@ +//! Walks an ADJ directory and builds an [`crate::adj::Adj`] from it. + +use super::types::{RawBoard, RawGeneralInfo, RawMeasurement, RawPacket}; +use crate::adj::error::LoadError; +use crate::adj::{Adj, AdjInfo}; +use crate::model::{ + AdjId, Board, BoardId, MacAddress, Measurement, PacketDef, PacketKind, PodData, +}; +use serde::de::DeserializeOwned; +use std::collections::HashMap; +use std::fs; +use std::net::IpAddr; +use std::path::Path; + +/// Loads an ADJ directory rooted at `path` (containing `general_info.json` +/// and `boards.json`) into an [`Adj`]. +/// +/// Boards are read in alphabetical order by name — not `boards.json`'s own +/// unordered map order — so [`PodData::boards`] is deterministic. A board +/// present on disk but absent from `boards.json` is never read; that isn't +/// an error. +pub fn load_from_dir(path: &Path) -> Result { + let general_info: RawGeneralInfo = read_json(&path.join("general_info.json"))?; + let board_paths: HashMap = read_json(&path.join("boards.json"))?; + + let mut entries: Vec<(&String, &String)> = board_paths.iter().collect(); + entries.sort_by_key(|(name, _)| *name); + + let mut boards = Vec::with_capacity(entries.len()); + for (name, rel_path) in entries { + boards.push(load_board(path, name, rel_path)?); + } + + Ok(Adj { + pod_data: PodData { boards }, + info: AdjInfo::from(general_info), + }) +} + +fn read_json(path: &Path) -> Result { + let text = fs::read_to_string(path).map_err(|source| LoadError::ReadFile { + path: path.to_path_buf(), + source, + })?; + serde_json::from_str(&text).map_err(|source| LoadError::ParseJson { + path: path.to_path_buf(), + source, + }) +} + +fn load_board(root: &Path, name: &str, rel_path: &str) -> Result { + let board_file = root.join(rel_path); + let raw_board: RawBoard = read_json(&board_file)?; + let board_dir = board_file + .parent() + .map(Path::to_path_buf) + .unwrap_or_else(|| root.to_path_buf()); + + let mut measurements: HashMap = HashMap::new(); + for measurements_path in &raw_board.measurements { + let raws: Vec = read_json(&board_dir.join(measurements_path))?; + for raw in raws { + let alias = raw.alias.clone(); + let measurement = + Measurement::try_from(raw).map_err(|source| LoadError::Measurement { + board: name.to_string(), + alias: alias.clone(), + source, + })?; + measurements.insert(alias, measurement); + } + } + + let mut packets = Vec::new(); + for packets_path in &raw_board.packets { + let raws: Vec = read_json(&board_dir.join(packets_path))?; + for raw in raws { + packets.push(build_packet_def(name, raw, &measurements)?); + } + } + + let ip: IpAddr = raw_board + .board_ip + .parse() + .map_err(|source| LoadError::InvalidIp { + board: name.to_string(), + raw: raw_board.board_ip.clone(), + source, + })?; + + let mac_text = raw_board.mac.ok_or_else(|| LoadError::MissingMac { + board: name.to_string(), + })?; + let mac = parse_mac(&mac_text).ok_or_else(|| LoadError::InvalidMac { + board: name.to_string(), + raw: mac_text.clone(), + })?; + + Ok(Board { + id: BoardId(raw_board.board_id), + name: name.to_string(), + ip, + mac, + packets, + }) +} + +fn build_packet_def( + board: &str, + raw: RawPacket, + measurements: &HashMap, +) -> Result { + let kind = match raw.kind.as_str() { + "data" => PacketKind::Data, + "order" => PacketKind::Order, + other => { + return Err(LoadError::UnknownPacketType { + board: board.to_string(), + name: raw.name.clone(), + type_name: other.to_string(), + }); + } + }; + + let mut packet_measurements = Vec::with_capacity(raw.variables.len()); + for alias in &raw.variables { + let measurement = + measurements + .get(alias) + .cloned() + .ok_or_else(|| LoadError::UnknownAlias { + board: board.to_string(), + name: raw.name.clone(), + alias: alias.clone(), + })?; + packet_measurements.push(measurement); + } + + Ok(PacketDef { + id: AdjId(raw.id), + name: raw.name, + kind, + measurements: packet_measurements, + }) +} + +/// Parses a MAC address text form, e.g. `"aa:bb:cc:dd:ee:ff"` or the +/// unpadded `"0:0:0:0:0:0"` real ADJ fixtures actually use — each octet is +/// 1 or 2 hex digits. `None` on anything else. +fn parse_mac(raw: &str) -> Option { + let parts: Vec<&str> = raw.split(':').collect(); + if parts.len() != 6 { + return None; + } + + let mut octets = [0u8; 6]; + for (octet, part) in octets.iter_mut().zip(parts) { + if part.is_empty() || part.len() > 2 { + return None; + } + *octet = u8::from_str_radix(part, 16).ok()?; + } + Some(MacAddress(octets)) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::adj::ProtectionTypeInfo; + use crate::model::{PacketKind, ProtectionKind, Severity}; + use std::path::Path; + use std::time::Duration; + + fn must_load(path: &Path) -> Adj { + let Ok(adj) = load_from_dir(path) else { + unreachable!("fixture directory should load cleanly"); + }; + adj + } + + #[test] + fn mac_address_accepts_padded_and_unpadded_octets() { + assert_eq!( + parse_mac("aa:bb:cc:dd:ee:ff"), + Some(MacAddress([0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff])) + ); + assert_eq!(parse_mac("0:0:0:0:0:0"), Some(MacAddress([0; 6]))); + } + + #[test] + fn mac_address_rejects_malformed_text() { + assert_eq!(parse_mac("aa:bb:cc:dd:ee"), None); + assert_eq!(parse_mac("aa:bb:cc:dd:ee:ff:00"), None); + assert_eq!(parse_mac("aaa:bb:cc:dd:ee:ff"), None); + assert_eq!(parse_mac("zz:bb:cc:dd:ee:ff"), None); + } + + #[test] + fn build_packet_def_rejects_unknown_packet_type() { + let raw = RawPacket { + id: 1, + kind: "status".to_string(), + name: "Status".to_string(), + variables: vec![], + }; + assert!(matches!( + build_packet_def("VCU", raw, &HashMap::new()), + Err(LoadError::UnknownPacketType { .. }) + )); + } + + #[test] + fn build_packet_def_rejects_unknown_alias() { + let raw = RawPacket { + id: 1, + kind: "data".to_string(), + name: "Status".to_string(), + variables: vec!["missing".to_string()], + }; + assert!(matches!( + build_packet_def("VCU", raw, &HashMap::new()), + Err(LoadError::UnknownAlias { .. }) + )); + } + + #[test] + fn loads_the_sample_adj_fixture() { + let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("src/adj/test/adj"); + let adj = must_load(&path); + + let board_names: Vec<&str> = adj + .pod_data + .boards + .iter() + .map(|b| b.name.as_str()) + .collect(); + assert_eq!(board_names, vec!["HVBMS", "LCU", "PCU", "VCU"]); + + let Some(vcu) = adj.pod_data.boards.iter().find(|b| b.name == "VCU") else { + unreachable!("VCU should be among the loaded boards"); + }; + assert_eq!(vcu.id, BoardId(3)); + assert_eq!(vcu.ip, IpAddr::from([192, 168, 1, 3])); + assert_eq!(vcu.mac, MacAddress([0; 6])); + assert_eq!(vcu.packets.len(), 18); + assert_eq!(vcu.packets[0].kind, PacketKind::Order); + assert_eq!(vcu.packets[0].id, AdjId(600)); + assert_eq!(vcu.packets[13].kind, PacketKind::Data); + assert_eq!(vcu.packets[13].id, AdjId(625)); + + let Some(pcu) = adj.pod_data.boards.iter().find(|b| b.name == "PCU") else { + unreachable!("PCU should be among the loaded boards"); + }; + let Some(protected) = pcu + .packets + .iter() + .flat_map(|p| &p.measurements) + .find(|m| !m.protections.is_empty()) + else { + unreachable!("PCU should have a measurement with a protection"); + }; + assert_eq!(protected.protections.len(), 1); + let protection = &protected.protections[0]; + assert_eq!(protection.kind, ProtectionKind::Equal { target: 1.0 }); + assert_eq!(protection.severity, Severity::Fault); + assert_eq!(protection.time, Duration::ZERO); + assert_eq!(protection.id, AdjId(1)); + + assert_eq!(adj.info.ports["TCP_SERVER"], 50500); + assert_eq!(adj.info.addresses["backend"], "192.168.0.9"); + assert_eq!(adj.info.message_ids["fault"], 2); + assert_eq!( + adj.info.protection_types["Range"], + ProtectionTypeInfo { + is_range: true, + text: "Value out of range {} (measured: %)".to_string(), + text_time: None, + } + ); + } +} diff --git a/backend/crates/core/src/adj/raw/types.rs b/backend/crates/core/src/adj/raw/types.rs new file mode 100644 index 000000000..6baa15dd2 --- /dev/null +++ b/backend/crates/core/src/adj/raw/types.rs @@ -0,0 +1,470 @@ +//! Raw ADJ JSON shapes and their conversion into `model` types. +//! +//! These shapes mirror the JSON exactly — including the fields this crate +//! intentionally doesn't model yet (`sockets`, `period`, `period_type`, +//! `socket`, `units`, `podUnits`), which are simply absent from these +//! structs and therefore ignored by serde, not rejected. + +use crate::adj::error::{MeasurementError, ProtectionError}; +use crate::adj::info::{AdjInfo, ProtectionTypeInfo}; +use crate::model::{ + AdjId, Measurement, MeasurementKind, NumericKind, Protection, ProtectionKind, Severity, +}; +use serde::Deserialize; +use std::collections::HashMap; +use std::time::Duration; + +#[derive(Debug, Clone, PartialEq, Deserialize)] +pub(crate) struct RawGeneralInfo { + pub(crate) ports: HashMap, + pub(crate) addresses: HashMap, + #[serde(rename = "protectionTypes", default)] + pub(crate) protection_types: HashMap, + pub(crate) message_ids: HashMap, +} + +#[derive(Debug, Clone, PartialEq, Deserialize)] +pub(crate) struct RawProtectionType { + #[serde(default)] + pub(crate) range: bool, + pub(crate) text: String, + #[serde(default, rename = "textTime")] + pub(crate) text_time: Option, +} + +#[derive(Debug, Clone, PartialEq, Deserialize)] +pub(crate) struct RawBoard { + pub(crate) board_id: u16, + #[serde(default)] + pub(crate) mac: Option, + pub(crate) board_ip: String, + #[serde(default)] + pub(crate) measurements: Vec, + #[serde(default)] + pub(crate) packets: Vec, +} + +#[derive(Debug, Clone, PartialEq, Deserialize)] +pub(crate) struct RawMeasurement { + pub(crate) id: u16, + pub(crate) alias: String, + pub(crate) name: String, + #[serde(rename = "type")] + pub(crate) kind: String, + #[serde(default, rename = "displayUnits")] + pub(crate) display_units: String, + #[serde(default, rename = "enumValues")] + pub(crate) enum_values: Vec, + #[serde(default)] + pub(crate) protections: Vec, +} + +#[derive(Debug, Clone, PartialEq, Deserialize)] +pub(crate) struct RawProtection { + #[serde(rename = "type")] + pub(crate) kind: String, + pub(crate) value: Vec, + #[serde(default = "default_fault")] + pub(crate) fault: bool, + #[serde(default)] + pub(crate) time: Option, +} + +fn default_fault() -> bool { + true +} + +#[derive(Debug, Clone, PartialEq, Deserialize)] +pub(crate) struct RawPacket { + pub(crate) id: u16, + #[serde(rename = "type")] + pub(crate) kind: String, + pub(crate) name: String, + #[serde(default)] + pub(crate) variables: Vec, +} + +impl From for AdjInfo { + fn from(raw: RawGeneralInfo) -> Self { + AdjInfo { + ports: raw.ports, + addresses: raw.addresses, + message_ids: raw.message_ids, + protection_types: raw + .protection_types + .into_iter() + .map(|(name, kind)| { + ( + name, + ProtectionTypeInfo { + is_range: kind.range, + text: kind.text, + text_time: kind.text_time, + }, + ) + }) + .collect(), + } + } +} + +impl TryFrom for Measurement { + type Error = MeasurementError; + + fn try_from(raw: RawMeasurement) -> Result { + let kind = parse_measurement_kind(&raw.kind, raw.enum_values)?; + + let mut protections = Vec::with_capacity(raw.protections.len()); + for (zero_based, raw_protection) in raw.protections.into_iter().enumerate() { + let position = (zero_based + 1) as u16; + let protection = + Protection::try_from((raw_protection, position)).map_err(|source| { + MeasurementError::Protection { + index: position as usize, + source, + } + })?; + protections.push(protection); + } + + Ok(Measurement { + id: AdjId(raw.id), + alias: raw.alias, + name: raw.name, + display_units: raw.display_units, + kind, + protections, + }) + } +} + +impl TryFrom<(RawProtection, u16)> for Protection { + type Error = ProtectionError; + + fn try_from((raw, position): (RawProtection, u16)) -> Result { + let kind = parse_protection_kind(&raw.kind, &raw.value)?; + let time = match &raw.time { + Some(text) => parse_duration(text)?, + None => Duration::ZERO, + }; + + Ok(Protection { + id: AdjId(position), + kind, + severity: if raw.fault { + Severity::Fault + } else { + Severity::Warning + }, + time, + }) + } +} + +fn parse_measurement_kind( + kind: &str, + enum_values: Vec, +) -> Result { + let numeric = |wire_type| MeasurementKind::Numeric { wire_type }; + + match kind { + "uint8" => Ok(numeric(NumericKind::U8)), + "uint16" => Ok(numeric(NumericKind::U16)), + "uint32" => Ok(numeric(NumericKind::U32)), + "uint64" => Ok(numeric(NumericKind::U64)), + "int8" => Ok(numeric(NumericKind::I8)), + "int16" => Ok(numeric(NumericKind::I16)), + "int32" => Ok(numeric(NumericKind::I32)), + "int64" => Ok(numeric(NumericKind::I64)), + "float32" => Ok(numeric(NumericKind::F32)), + "float64" => Ok(numeric(NumericKind::F64)), + "bool" => Ok(MeasurementKind::Boolean), + "enum" if !enum_values.is_empty() => Ok(MeasurementKind::Enum { + options: enum_values, + }), + "enum" => Err(MeasurementError::MissingEnumValues), + other => Err(MeasurementError::UnknownType(other.to_string())), + } +} + +fn parse_protection_kind(kind: &str, value: &[f64]) -> Result { + fn one(kind: &str, value: &[f64]) -> Result { + match value { + [bound] => Ok(*bound), + other => Err(ProtectionError::WrongBoundCount { + kind: kind.to_string(), + expected: 1, + got: other.len(), + }), + } + } + + fn two(kind: &str, value: &[f64]) -> Result<(f64, f64), ProtectionError> { + match value { + [min, max] => Ok((*min, *max)), + other => Err(ProtectionError::WrongBoundCount { + kind: kind.to_string(), + expected: 2, + got: other.len(), + }), + } + } + + match kind { + "Above" => Ok(ProtectionKind::Above { + limit: one(kind, value)?, + }), + "Below" => Ok(ProtectionKind::Below { + limit: one(kind, value)?, + }), + "Equal" => Ok(ProtectionKind::Equal { + target: one(kind, value)?, + }), + "NotEqual" => Ok(ProtectionKind::NotEqual { + target: one(kind, value)?, + }), + "Range" => { + let (min, max) = two(kind, value)?; + Ok(ProtectionKind::Range { min, max }) + } + other => Err(ProtectionError::UnknownType(other.to_string())), + } +} + +/// Parses a duration string like `"500ms"`, `"3s"` or `"10us"`. +/// +/// Rejects non-finite or negative numbers explicitly before handing them to +/// [`Duration::from_secs_f64`], which panics on either — this reads +/// externally-authored ADJ text, so a malformed `"time"` (e.g. `"-5ms"`) +/// must become an error, not a panic. +fn parse_duration(text: &str) -> Result { + let Some(split_at) = text.find(|c: char| c.is_ascii_alphabetic()) else { + return Err(ProtectionError::InvalidTime(text.to_string())); + }; + let (number, unit) = text.split_at(split_at); + + let value: f64 = number + .parse() + .map_err(|_| ProtectionError::InvalidTime(text.to_string()))?; + + if !value.is_finite() || value < 0.0 { + return Err(ProtectionError::InvalidTime(text.to_string())); + } + + let seconds = match unit { + "s" => value, + "ms" => value / 1_000.0, + "us" => value / 1_000_000.0, + _ => return Err(ProtectionError::InvalidTime(text.to_string())), + }; + + Ok(Duration::from_secs_f64(seconds)) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn raw_protection( + kind: &str, + value: Vec, + fault: bool, + time: Option<&str>, + ) -> RawProtection { + RawProtection { + kind: kind.to_string(), + value, + fault, + time: time.map(str::to_string), + } + } + + fn must_build_protection(raw: RawProtection, position: u16) -> Protection { + let Ok(protection) = Protection::try_from((raw, position)) else { + unreachable!("valid protection should convert cleanly"); + }; + protection + } + + #[test] + fn numeric_measurement_types_map_to_their_numeric_kind() { + let cases = [ + ("uint8", NumericKind::U8), + ("uint16", NumericKind::U16), + ("uint32", NumericKind::U32), + ("uint64", NumericKind::U64), + ("int8", NumericKind::I8), + ("int16", NumericKind::I16), + ("int32", NumericKind::I32), + ("int64", NumericKind::I64), + ("float32", NumericKind::F32), + ("float64", NumericKind::F64), + ]; + + for (type_name, expected) in cases { + assert!(matches!( + parse_measurement_kind(type_name, vec![]), + Ok(MeasurementKind::Numeric { wire_type }) if wire_type == expected + )); + } + } + + #[test] + fn bool_type_maps_to_boolean() { + assert!(matches!( + parse_measurement_kind("bool", vec![]), + Ok(MeasurementKind::Boolean) + )); + } + + #[test] + fn enum_type_with_values_keeps_their_order() { + let options = vec!["Idle".to_string(), "Fault".to_string()]; + assert!(matches!( + parse_measurement_kind("enum", options.clone()), + Ok(MeasurementKind::Enum { options: got }) if got == options + )); + } + + #[test] + fn enum_type_without_values_is_an_error() { + assert!(matches!( + parse_measurement_kind("enum", vec![]), + Err(MeasurementError::MissingEnumValues) + )); + } + + #[test] + fn unknown_measurement_type_is_an_error() { + assert!(matches!( + parse_measurement_kind("potato", vec![]), + Err(MeasurementError::UnknownType(t)) if t == "potato" + )); + } + + #[test] + fn one_bound_protection_kinds_take_a_single_value() { + assert!(matches!( + parse_protection_kind("Above", &[1.0]), + Ok(ProtectionKind::Above { limit }) if limit == 1.0 + )); + assert!(matches!( + parse_protection_kind("Below", &[2.0]), + Ok(ProtectionKind::Below { limit }) if limit == 2.0 + )); + assert!(matches!( + parse_protection_kind("Equal", &[3.0]), + Ok(ProtectionKind::Equal { target }) if target == 3.0 + )); + assert!(matches!( + parse_protection_kind("NotEqual", &[4.0]), + Ok(ProtectionKind::NotEqual { target }) if target == 4.0 + )); + } + + #[test] + fn range_protection_takes_two_values() { + assert!(matches!( + parse_protection_kind("Range", &[0.0, 48.0]), + Ok(ProtectionKind::Range { min, max }) if min == 0.0 && max == 48.0 + )); + } + + #[test] + fn wrong_bound_count_is_an_error() { + assert!(matches!( + parse_protection_kind("Above", &[1.0, 2.0]), + Err(ProtectionError::WrongBoundCount { + expected: 1, + got: 2, + .. + }) + )); + assert!(matches!( + parse_protection_kind("Range", &[1.0]), + Err(ProtectionError::WrongBoundCount { + expected: 2, + got: 1, + .. + }) + )); + } + + #[test] + fn unknown_protection_type_is_an_error() { + assert!(matches!( + parse_protection_kind("Potato", &[1.0]), + Err(ProtectionError::UnknownType(t)) if t == "Potato" + )); + } + + #[test] + fn fault_flag_selects_severity_default_true() { + let protection = must_build_protection(raw_protection("Equal", vec![1.0], true, None), 1); + assert_eq!(protection.severity, Severity::Fault); + + let protection = must_build_protection(raw_protection("Equal", vec![1.0], false, None), 1); + assert_eq!(protection.severity, Severity::Warning); + } + + #[test] + fn protection_id_is_its_position_not_a_global_id() { + let protection = must_build_protection(raw_protection("Equal", vec![1.0], true, None), 3); + assert_eq!(protection.id, AdjId(3)); + } + + #[test] + fn missing_time_defaults_to_zero() { + let protection = must_build_protection(raw_protection("Equal", vec![1.0], true, None), 1); + assert_eq!(protection.time, Duration::ZERO); + } + + #[test] + fn duration_strings_parse_with_their_unit() { + assert!(matches!(parse_duration("500ms"), Ok(d) if d == Duration::from_millis(500))); + assert!(matches!(parse_duration("3s"), Ok(d) if d == Duration::from_secs(3))); + assert!(matches!(parse_duration("10us"), Ok(d) if d == Duration::from_micros(10))); + } + + #[test] + fn invalid_duration_strings_are_rejected() { + assert!(matches!( + parse_duration("banana"), + Err(ProtectionError::InvalidTime(_)) + )); + assert!(matches!( + parse_duration("-5ms"), + Err(ProtectionError::InvalidTime(_)) + )); + assert!(matches!( + parse_duration("5"), + Err(ProtectionError::InvalidTime(_)) + )); + } + + #[test] + fn general_info_converts_into_adj_info() { + let mut protection_types = HashMap::new(); + protection_types.insert( + "Range".to_string(), + RawProtectionType { + range: true, + text: "Value out of range {} (measured: %)".to_string(), + text_time: None, + }, + ); + let raw = RawGeneralInfo { + ports: HashMap::from([("TCP_SERVER".to_string(), 50500u16)]), + addresses: HashMap::from([("backend".to_string(), "192.168.0.9".to_string())]), + protection_types, + message_ids: HashMap::from([("fault".to_string(), 2u16)]), + }; + + let info = AdjInfo::from(raw); + + assert_eq!(info.ports["TCP_SERVER"], 50500); + assert_eq!(info.addresses["backend"], "192.168.0.9"); + assert_eq!(info.message_ids["fault"], 2); + assert!(info.protection_types["Range"].is_range); + } +} diff --git a/backend/crates/core/src/adj/test/adj/README.md b/backend/crates/core/src/adj/test/adj/README.md new file mode 100644 index 000000000..453182930 --- /dev/null +++ b/backend/crates/core/src/adj/test/adj/README.md @@ -0,0 +1,291 @@ +# ADJ v2 Specification + +This document defines the ADJ v2 configuration format used by the Hyperloop Control Station. The configuration is organized as a distributed collection of JSON files that define boards, measurements, packets, and general system information. + +## File Structure + +The ADJ configuration is organized in the following directory structure: + +``` +adj/ +├── general_info.json # System-wide configuration +├── boards.json # Board list and path mappings +└── boards/ # Board-specific configurations + └── {board_name}/ + ├── {board_name}.json # Main board configuration + ├── {board_name}_measurements.json # Board measurements + ├── packets.json # Data packets + ├── orders.json # Order packets + └── sockets.json # Board sockets +``` + +## Data Types + +### General Info (`general_info.json`) + +System-wide configuration including ports, addresses, units, and message IDs. + +```json +{ + "ports": { + "string": "number" + }, + "addresses": { + "string": "string" + }, + "units": { + "string": "string" + }, + "message_ids": { + "string": "number" + } +} +``` + +**Example:** +```json +{ + "ports": { + "main": 8080, + "data": 8081 + }, + "addresses": { + "primary": "192.168.1.100", + "secondary": "192.168.1.101" + }, + "units": { + "pressure": "PSI", + "temperature": "°C", + "voltage": "V" + }, + "message_ids": { + "status": 1, + "data": 2 + } +} +``` + +### Board List (`boards.json`) + +Mapping of board names to their configuration file paths. + +```json +{ + "string": "string" +} +``` + +**Example:** +```json +{ + "brake_board": "boards/brake_board/brake_board.json", + "sensor_board": "boards/sensor_board/sensor_board.json" +} +``` + +### Board Configuration (`{board_name}.json`) + +Main board configuration including ID, IP address, and references to measurements, packets and sockets files. + +```json +{ + "board_id": "number", + "board_ip": "string", + "measurements": ["string"], + "packets": ["string"], + "sockets": ["string"] +} +``` + +**Field Descriptions:** +- `board_id`: Unique 32-bit unsigned integer identifier for the board +- `board_ip`: IP address string for network communication +- `measurements`: Array of measurement file paths relative to board directory +- `packets`: Array of packet file paths relative to board directory + +**Example:** +```json +{ + "board_id": 1001, + "board_ip": "192.168.1.10", + "measurements": ["brake_board_measurements.json"], + "packets": ["packets.json", "orders.json"], + "sockets":["sockets.json"] +} +``` + +### Measurements (`{board_name}_measurements.json`) + +Array of measurement definitions for data collection and monitoring. + +```json +[ + { + "id": "string", + "name": "string", + "type": "string", + "podUnits": "string?", + "displayUnits": "string?", + "enumValues": ["string"]?, + "safeRange": "[number, number]?", + "warningRange": "[number, number]?" + } +] +``` + +**Field Descriptions:** +- `id`: Unique string identifier for the measurement +- `name`: Human-readable display name +- `type`: Data type - one of: `uint8`, `uint16`, `uint32`, `uint64`, `int8`, `int16`, `int32`, `int64`, `float32`, `float64` +- `podUnits`: Optional pod-side units (references `general_info.units`) +- `displayUnits`: Optional display units (references `general_info.units`) +- `enumValues`: Optional array of enumeration values for discrete measurements +- `safeRange`: Optional two-element array `[min, max]` defining safe operating range +- `warningRange`: Optional two-element array `[min, max]` defining warning thresholds + +**Example:** +```json +[ + { + "id": "brake_pressure", + "name": "Brake Pressure", + "type": "float32", + "podUnits": "PSI", + "displayUnits": "PSI", + "safeRange": [0.0, 100.0], + "warningRange": [80.0, 95.0] + }, + { + "id": "brake_status", + "name": "Brake Status", + "type": "uint8", + "enumValues": ["released", "engaged", "error"] + } +] +``` + +### Packets (`packets.json`, `orders.json`) + +Array of packet definitions for network communication. Packets are separated by type: +- `packets.json`: Data packets for telemetry and status +- `orders.json`: Command packets for control operations + +```json +[ + { + "id": "number?", + "type": "string", + "name": "string", + "variables": ["string"], + "period_type": "us/ms?", + "period": "number?", + "socket": "string?" + } +] +``` + +**Field Descriptions:** +- `id`: Optional 32-bit unsigned integer packet identifier +- `type`: Packet type string (e.g., "data", "order", "status") +- `name`: Human-readable packet name +- `variables`: Array of variable names/measurement IDs included in this packet +- `period_type`: Optional string specifying the type of measurement for period, either microseconds +or milliseconds +- `period`: Optional number specifying the transmission period in milliseconds or microseconds for periodic packets. Can be an integer or floating-point value +- `socket`: Optinal string that should match the name of the socket you want to transmit this packet trhough + +**Example:** +```json +[ + { + "id": 2001, + "type": "data", + "name": "Brake Telemetry", + "variables": ["brake_pressure", "brake_status", "brake_temperature"], + "period_type":"ms", + "period": 16.67, + "socket": "control_station_udp" + }, + { + "type": "order", + "name": "Brake Command", + "variables": ["brake_command", "target_pressure"] + } +] +``` + +### Sockets (`sockets.json`) + +Array of socket definitions for network communication. + +```json +{ + "type": "string", + "name": "string", + "port": "number?", + "local_port":"number?", + "remote_ip": "string?", + "remote_port":"number?" + +} +``` + +**Field Descriptions:** +- `type`: Socket type string(e.g., "ServerSocket","DatagramSocket","Socket") +- `name`: Socket name +- `port`: Optional number that describes the port number used for a ServerSocket or a DatagramSocket +- `local_port`: Optional number that describes the local port number used for a Socket +- `remote_ip`: Optional string that describes the remote ip you want to connect to in a DatagramSocket or Socket +- `remote_port`: Optional number that describes the remote port number used for a Socket + +**Example:** +```json +[ + { + "type": "ServerSocket", + "name": "control_station_tcp", + "port": 50500 + }, + + { + "type": "DatagramSocket", + "name": "control_station_udp", + "remote_ip":"192.168.0.9", + "port": 50400 + }, + + { + "type": "Socket", + "name": "pcu_tcp", + "local_port": 50501, + "remote_ip": "192.168.1.5", + "remote_port": 50500 + } +] +``` + +## Configuration Rules + +1. **Naming Convention**: Board directories and main configuration files must use the same name as the board key in `boards.json` + +2. **File References**: All file paths in board configurations are relative to the board's directory + +3. **Measurement References**: Packet `variables` arrays should reference measurement `id` values defined in the board's measurements files + +4. **Unit References**: Measurement `podUnits` and `displayUnits` should reference keys defined in `general_info.units` + +5. **ID Uniqueness**: Board IDs must be unique across all boards. Packet IDs should be unique within their type category. + +6. **Socket Naming**: The sockets referenced inside the packet definitions must use exact names as defined in `socket.json`. + +## Validation Notes + +- All numeric fields use standard JSON number format +- Optional fields may be omitted entirely or set to `null` +- Empty arrays are permitted for measurements and packets +- File paths use forward slashes (`/`) regardless of operating system +- IP addresses must be valid IPv4 format strings + +## Backward Compatibility + +This specification maintains compatibility with existing ADJ v1 configurations while supporting the new distributed file structure introduced in v2. The system can automatically migrate v1 configurations to the v2 format. diff --git a/backend/crates/core/src/adj/test/adj/boards.json b/backend/crates/core/src/adj/test/adj/boards.json new file mode 100644 index 000000000..9de2c650a --- /dev/null +++ b/backend/crates/core/src/adj/test/adj/boards.json @@ -0,0 +1,6 @@ +{ + "VCU": "boards/VCU/VCU.json", + "LCU": "boards/LCU/LCU.json", + "PCU": "boards/PCU/PCU.json", + "HVBMS": "boards/HVBMS/HVBMS.json" +} diff --git a/backend/crates/core/src/adj/test/adj/boards/BLCU/BLCU.json b/backend/crates/core/src/adj/test/adj/boards/BLCU/BLCU.json new file mode 100644 index 000000000..2c98964c1 --- /dev/null +++ b/backend/crates/core/src/adj/test/adj/boards/BLCU/BLCU.json @@ -0,0 +1,12 @@ +{ + "board_id": 27, + "board_ip": "192.168.0.27", + "measurements": ["BLCU_measurements.json"], + "packets": [ + "packets.json", + "orders.json" + ], + "sockets": [ + "sockets.json" + ] +} diff --git a/backend/crates/core/src/adj/test/adj/boards/BLCU/BLCU_measurements.json b/backend/crates/core/src/adj/test/adj/boards/BLCU/BLCU_measurements.json new file mode 100644 index 000000000..f44182d73 --- /dev/null +++ b/backend/crates/core/src/adj/test/adj/boards/BLCU/BLCU_measurements.json @@ -0,0 +1,34 @@ +[ + { + "id": "target", + "name": "target", + "type": "enum", + "enumValues": [ + "VCU", + "HVBMS", + "LVBMS", + "PCU", + "LCU" + ] + }, + { + "id": "general_state_machine", + "name": "General State Machine", + "type": "enum", + "enumValues": [ + "Connecting", + "Operational", + "Fault" + ] + }, + { + "id": "operational_state_machine", + "name": "Operational state machine", + "type": "enum", + "enumValues": [ + "Idle", + "Flashing" + ] + } + +] diff --git a/backend/crates/core/src/adj/test/adj/boards/BLCU/orders.json b/backend/crates/core/src/adj/test/adj/boards/BLCU/orders.json new file mode 100644 index 000000000..1a7167d60 --- /dev/null +++ b/backend/crates/core/src/adj/test/adj/boards/BLCU/orders.json @@ -0,0 +1,15 @@ +[ + { + "id": 701, + "type": "order", + "name": "Reset All" + }, + { + "id":700, + "type": "order", + "name":"Write Program", + "variables":[ + "target" + ] + } +] diff --git a/backend/crates/core/src/adj/test/adj/boards/BLCU/packets.json b/backend/crates/core/src/adj/test/adj/boards/BLCU/packets.json new file mode 100644 index 000000000..4674afdc2 --- /dev/null +++ b/backend/crates/core/src/adj/test/adj/boards/BLCU/packets.json @@ -0,0 +1,28 @@ +[ + { + "id":3, + "type": "packet", + "name":"ack" + }, + { + "id":4, + "type": "packet", + "name":"nack" + }, + + { + "id": 1, + "type": "packet", + "name": "state_machine_state", + "variables": + [ + "general_state_machine", + "operational_state_machine" + ], + "period_type": "ms", + "period": 16.67, + "socket": "control_station_udp" + + } + +] diff --git a/backend/crates/core/src/adj/test/adj/boards/BLCU/sockets.json b/backend/crates/core/src/adj/test/adj/boards/BLCU/sockets.json new file mode 100644 index 000000000..173e674e2 --- /dev/null +++ b/backend/crates/core/src/adj/test/adj/boards/BLCU/sockets.json @@ -0,0 +1,14 @@ +[ + { + "type": "ServerSocket", + "name": "control_station_tcp", + "port": 50500 + }, + + { + "type": "DatagramSocket", + "name": "control_station_udp", + "remote_ip":"backend", + "port": 50420 + } +] diff --git a/backend/crates/core/src/adj/test/adj/boards/HVBMS/HVBMS.json b/backend/crates/core/src/adj/test/adj/boards/HVBMS/HVBMS.json new file mode 100644 index 000000000..0022eb5ec --- /dev/null +++ b/backend/crates/core/src/adj/test/adj/boards/HVBMS/HVBMS.json @@ -0,0 +1,15 @@ +{ + "board_id": 7, + "mac": "0:0:0:0:0:0", + "board_ip": "192.168.1.7", + "measurements": [ + "HVBMS_measurements.json" + ], + "packets": [ + "packets.json", + "orders.json" + ], + "sockets": [ + "sockets.json" + ] +} \ No newline at end of file diff --git a/backend/crates/core/src/adj/test/adj/boards/HVBMS/HVBMS_measurements.json b/backend/crates/core/src/adj/test/adj/boards/HVBMS/HVBMS_measurements.json new file mode 100644 index 000000000..d31af6972 --- /dev/null +++ b/backend/crates/core/src/adj/test/adj/boards/HVBMS/HVBMS_measurements.json @@ -0,0 +1,1102 @@ +[ + { + "id": 2005, + "alias": "battery1_cell1", + "name": "Battery 1 Cell 1", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2006, + "alias": "battery1_cell2", + "name": "Battery 1 Cell 2", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2007, + "alias": "battery1_cell3", + "name": "Battery 1 Cell 3", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2008, + "alias": "battery1_cell4", + "name": "Battery 1 Cell 4", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2009, + "alias": "battery1_cell5", + "name": "Battery 1 Cell 5", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2010, + "alias": "battery1_cell6", + "name": "Battery 1 Cell 6", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2011, + "alias": "battery1_cell7", + "name": "Battery 1 Cell 7", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2012, + "alias": "battery1_cell8", + "name": "Battery 1 Cell 8", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2013, + "alias": "battery1_cell9", + "name": "Battery 1 Cell 9", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2014, + "alias": "battery1_cell10", + "name": "Battery 1 Cell 10", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2015, + "alias": "battery1_cell11", + "name": "Battery 1 Cell 11", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2016, + "alias": "battery1_cell12", + "name": "Battery 1 Cell 12", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2017, + "alias": "battery1_total_voltage", + "name": "Battery 1 Voltage", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2018, + "alias": "battery1_temp1", + "name": "Battery 1 Temperature 1", + "type": "float32", + "displayUnits": "ºC" + }, + { + "id": 2019, + "alias": "battery1_temp2", + "name": "Battery 1 Temperature 2", + "type": "float32", + "displayUnits": "ºC" + }, + { + "id": 2020, + "alias": "battery1_temp3", + "name": "Battery 1 Temperature 3", + "type": "float32", + "displayUnits": "ºC" + }, + { + "id": 2021, + "alias": "battery1_temp4", + "name": "Battery 1 Temperature 4", + "type": "float32", + "displayUnits": "ºC" + }, + { + "id": 2022, + "alias": "battery2_cell1", + "name": "Battery 2 Cell 1", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2023, + "alias": "battery2_cell2", + "name": "Battery 2 Cell 2", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2024, + "alias": "battery2_cell3", + "name": "Battery 2 Cell 3", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2025, + "alias": "battery2_cell4", + "name": "Battery 2 Cell 4", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2026, + "alias": "battery2_cell5", + "name": "Battery 2 Cell 5", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2027, + "alias": "battery2_cell6", + "name": "Battery 2 Cell 6", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2028, + "alias": "battery2_cell7", + "name": "Battery 2 Cell 7", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2029, + "alias": "battery2_cell8", + "name": "Battery 2 Cell 8", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2030, + "alias": "battery2_cell9", + "name": "Battery 2 Cell 9", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2031, + "alias": "battery2_cell10", + "name": "Battery 2 Cell 10", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2032, + "alias": "battery2_cell11", + "name": "Battery 2 Cell 11", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2033, + "alias": "battery2_cell12", + "name": "Battery 2 Cell 12", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2034, + "alias": "battery2_total_voltage", + "name": "Battery 2 Voltage", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2035, + "alias": "battery2_temp1", + "name": "Battery 2 Temperature 1", + "type": "float32", + "displayUnits": "ºC" + }, + { + "id": 2036, + "alias": "battery2_temp2", + "name": "Battery 2 Temperature 2", + "type": "float32", + "displayUnits": "ºC" + }, + { + "id": 2037, + "alias": "battery2_temp3", + "name": "Battery 2 Temperature 3", + "type": "float32", + "displayUnits": "ºC" + }, + { + "id": 2038, + "alias": "battery2_temp4", + "name": "Battery 2 Temperature 4", + "type": "float32", + "displayUnits": "ºC" + }, + { + "id": 2039, + "alias": "battery3_cell1", + "name": "Battery 3 Cell 1", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2040, + "alias": "battery3_cell2", + "name": "Battery 3 Cell 2", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2041, + "alias": "battery3_cell3", + "name": "Battery 3 Cell 3", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2042, + "alias": "battery3_cell4", + "name": "Battery 3 Cell 4", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2043, + "alias": "battery3_cell5", + "name": "Battery 3 Cell 5", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2044, + "alias": "battery3_cell6", + "name": "Battery 3 Cell 6", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2045, + "alias": "battery3_cell7", + "name": "Battery 3 Cell 7", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2046, + "alias": "battery3_cell8", + "name": "Battery 3 Cell 8", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2047, + "alias": "battery3_cell9", + "name": "Battery 3 Cell 9", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2048, + "alias": "battery3_cell10", + "name": "Battery 3 Cell 10", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2049, + "alias": "battery3_cell11", + "name": "Battery 3 Cell 11", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2050, + "alias": "battery3_cell12", + "name": "Battery 3 Cell 12", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2051, + "alias": "battery3_total_voltage", + "name": "Battery 3 Voltage", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2052, + "alias": "battery3_temp1", + "name": "Battery 3 Temperature 1", + "type": "float32", + "displayUnits": "ºC" + }, + { + "id": 2053, + "alias": "battery3_temp2", + "name": "Battery 3 Temperature 2", + "type": "float32", + "displayUnits": "ºC" + }, + { + "id": 2054, + "alias": "battery3_temp3", + "name": "Battery 3 Temperature 3", + "type": "float32", + "displayUnits": "ºC" + }, + { + "id": 2055, + "alias": "battery3_temp4", + "name": "Battery 3 Temperature 4", + "type": "float32", + "displayUnits": "ºC" + }, + { + "id": 2056, + "alias": "battery4_cell1", + "name": "Battery 4 Cell 1", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2057, + "alias": "battery4_cell2", + "name": "Battery 4 Cell 2", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2058, + "alias": "battery4_cell3", + "name": "Battery 4 Cell 3", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2059, + "alias": "battery4_cell4", + "name": "Battery 4 Cell 4", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2060, + "alias": "battery4_cell5", + "name": "Battery 4 Cell 5", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2061, + "alias": "battery4_cell6", + "name": "Battery 4 Cell 6", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2062, + "alias": "battery4_cell7", + "name": "Battery 4 Cell 7", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2063, + "alias": "battery4_cell8", + "name": "Battery 4 Cell 8", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2064, + "alias": "battery4_cell9", + "name": "Battery 4 Cell 9", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2065, + "alias": "battery4_cell10", + "name": "Battery 4 Cell 10", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2066, + "alias": "battery4_cell11", + "name": "Battery 4 Cell 11", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2067, + "alias": "battery4_cell12", + "name": "Battery 4 Cell 12", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2068, + "alias": "battery4_total_voltage", + "name": "Battery 4 Voltage", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2069, + "alias": "battery4_temp1", + "name": "Battery 4 Temperature 1", + "type": "float32", + "displayUnits": "ºC" + }, + { + "id": 2070, + "alias": "battery4_temp2", + "name": "Battery 4 Temperature 2", + "type": "float32", + "displayUnits": "ºC" + }, + { + "id": 2071, + "alias": "battery4_temp3", + "name": "Battery 4 Temperature 3", + "type": "float32", + "displayUnits": "ºC" + }, + { + "id": 2072, + "alias": "battery4_temp4", + "name": "Battery 4 Temperature 4", + "type": "float32", + "displayUnits": "ºC" + }, + { + "id": 2073, + "alias": "battery5_cell1", + "name": "Battery 5 Cell 1", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2074, + "alias": "battery5_cell2", + "name": "Battery 5 Cell 2", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2075, + "alias": "battery5_cell3", + "name": "Battery 5 Cell 3", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2076, + "alias": "battery5_cell4", + "name": "Battery 5 Cell 4", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2077, + "alias": "battery5_cell5", + "name": "Battery 5 Cell 5", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2078, + "alias": "battery5_cell6", + "name": "Battery 5 Cell 6", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2079, + "alias": "battery5_cell7", + "name": "Battery 5 Cell 7", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2080, + "alias": "battery5_cell8", + "name": "Battery 5 Cell 8", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2081, + "alias": "battery5_cell9", + "name": "Battery 5 Cell 9", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2082, + "alias": "battery5_cell10", + "name": "Battery 5 Cell 10", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2083, + "alias": "battery5_cell11", + "name": "Battery 5 Cell 11", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2084, + "alias": "battery5_cell12", + "name": "Battery 5 Cell 12", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2085, + "alias": "battery5_total_voltage", + "name": "Battery 5 Voltage", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2086, + "alias": "battery5_temp1", + "name": "Battery 5 Temperature 1", + "type": "float32", + "displayUnits": "ºC" + }, + { + "id": 2087, + "alias": "battery5_temp2", + "name": "Battery 5 Temperature 2", + "type": "float32", + "displayUnits": "ºC" + }, + { + "id": 2088, + "alias": "battery5_temp3", + "name": "Battery 5 Temperature 3", + "type": "float32", + "displayUnits": "ºC" + }, + { + "id": 2089, + "alias": "battery5_temp4", + "name": "Battery 5 Temperature 4", + "type": "float32", + "displayUnits": "ºC" + }, + { + "id": 2090, + "alias": "battery6_cell1", + "name": "Battery 6 Cell 1", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2091, + "alias": "battery6_cell2", + "name": "Battery 6 Cell 2", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2092, + "alias": "battery6_cell3", + "name": "Battery 6 Cell 3", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2093, + "alias": "battery6_cell4", + "name": "Battery 6 Cell 4", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2094, + "alias": "battery6_cell5", + "name": "Battery 6 Cell 5", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2095, + "alias": "battery6_cell6", + "name": "Battery 6 Cell 6", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2096, + "alias": "battery6_cell7", + "name": "Battery 6 Cell 7", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2097, + "alias": "battery6_cell8", + "name": "Battery 6 Cell 8", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2098, + "alias": "battery6_cell9", + "name": "Battery 6 Cell 9", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2099, + "alias": "battery6_cell10", + "name": "Battery 6 Cell 10", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2100, + "alias": "battery6_cell11", + "name": "Battery 6 Cell 11", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2101, + "alias": "battery6_cell12", + "name": "Battery 6 Cell 12", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2102, + "alias": "battery6_total_voltage", + "name": "Battery 6 Voltage", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2103, + "alias": "battery6_temp1", + "name": "Battery 6 Temperature 1", + "type": "float32", + "displayUnits": "ºC" + }, + { + "id": 2104, + "alias": "battery6_temp2", + "name": "Battery 6 Temperature 2", + "type": "float32", + "displayUnits": "ºC" + }, + { + "id": 2105, + "alias": "battery6_temp3", + "name": "Battery 6 Temperature 3", + "type": "float32", + "displayUnits": "ºC" + }, + { + "id": 2106, + "alias": "battery6_temp4", + "name": "Battery 6 Temperature 4", + "type": "float32", + "displayUnits": "ºC" + }, + { + "id": 2107, + "alias": "battery7_cell1", + "name": "Battery 7 Cell 1", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2108, + "alias": "battery7_cell2", + "name": "Battery 7 Cell 2", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2109, + "alias": "battery7_cell3", + "name": "Battery 7 Cell 3", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2110, + "alias": "battery7_cell4", + "name": "Battery 7 Cell 4", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2111, + "alias": "battery7_cell5", + "name": "Battery 7 Cell 5", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2112, + "alias": "battery7_cell6", + "name": "Battery 7 Cell 6", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2113, + "alias": "battery7_cell7", + "name": "Battery 7 Cell 7", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2114, + "alias": "battery7_cell8", + "name": "Battery 7 Cell 8", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2115, + "alias": "battery7_cell9", + "name": "Battery 7 Cell 9", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2116, + "alias": "battery7_cell10", + "name": "Battery 7 Cell 10", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2117, + "alias": "battery7_cell11", + "name": "Battery 7 Cell 11", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2118, + "alias": "battery7_cell12", + "name": "Battery 7 Cell 12", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2119, + "alias": "battery7_total_voltage", + "name": "Battery 7 Voltage", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2120, + "alias": "battery7_temp1", + "name": "Battery 7 Temperature 1", + "type": "float32", + "displayUnits": "ºC" + }, + { + "id": 2121, + "alias": "battery7_temp2", + "name": "Battery 7 Temperature 2", + "type": "float32", + "displayUnits": "ºC" + }, + { + "id": 2122, + "alias": "battery7_temp3", + "name": "Battery 7 Temperature 3", + "type": "float32", + "displayUnits": "ºC" + }, + { + "id": 2123, + "alias": "battery7_temp4", + "name": "Battery 7 Temperature 4", + "type": "float32", + "displayUnits": "ºC" + }, + { + "id": 2124, + "alias": "battery8_cell1", + "name": "Battery 8 Cell 1", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2125, + "alias": "battery8_cell2", + "name": "Battery 8 Cell 2", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2126, + "alias": "battery8_cell3", + "name": "Battery 8 Cell 3", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2127, + "alias": "battery8_cell4", + "name": "Battery 8 Cell 4", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2128, + "alias": "battery8_cell5", + "name": "Battery 8 Cell 5", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2129, + "alias": "battery8_cell6", + "name": "Battery 8 Cell 6", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2130, + "alias": "battery8_cell7", + "name": "Battery 8 Cell 7", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2131, + "alias": "battery8_cell8", + "name": "Battery 8 Cell 8", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2132, + "alias": "battery8_cell9", + "name": "Battery 8 Cell 9", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2133, + "alias": "battery8_cell10", + "name": "Battery 8 Cell 10", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2134, + "alias": "battery8_cell11", + "name": "Battery 8 Cell 11", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2135, + "alias": "battery8_cell12", + "name": "Battery 8 Cell 12", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2136, + "alias": "battery8_total_voltage", + "name": "Battery 8 Voltage", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2137, + "alias": "battery8_temp1", + "name": "Battery 8 Temperature 1", + "type": "float32", + "displayUnits": "ºC" + }, + { + "id": 2138, + "alias": "battery8_temp2", + "name": "Battery 8 Temperature 2", + "type": "float32", + "displayUnits": "ºC" + }, + { + "id": 2139, + "alias": "battery8_temp3", + "name": "Battery 8 Temperature 3", + "type": "float32", + "displayUnits": "ºC" + }, + { + "id": 2140, + "alias": "battery8_temp4", + "name": "Battery 8 Temperature 4", + "type": "float32", + "displayUnits": "ºC" + }, + { + "id": 2141, + "alias": "batteries_voltage_reading", + "name": "Batteries Voltage", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2142, + "alias": "voltage_reading", + "name": "Voltage Sensor", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2143, + "alias": "current_reading", + "name": "Current Sensor", + "type": "float32", + "displayUnits": "A" + }, + { + "id": 2144, + "alias": "sdc_status", + "name": "SDC Status", + "type": "enum", + "enumValues": [ + "ENGAGED", + "DISENGAGED" + ] + }, + { + "id": 2145, + "alias": "voltage_min", + "name": "Minimum Cell Voltage", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2146, + "alias": "voltage_max", + "name": "Maximum Cell Voltage", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 2147, + "alias": "temp_min", + "name": "Minimum Temperature", + "type": "float32", + "displayUnits": "ºC" + }, + { + "id": 2148, + "alias": "temp_max", + "name": "Maximum Temperature", + "type": "float32", + "displayUnits": "ºC" + }, + { + "id": 2149, + "alias": "imd_status", + "name": "IMD Status", + "type": "enum", + "enumValues": [ + "SHORTCIRCUIT", + "NORMAL", + "UNDERVOLTAGE", + "FAST_EVAL", + "EQUIPMENT_FAULT", + "GROUNDING_FAULT" + ] + }, + { + "id": 2150, + "alias": "imd_resistance", + "name": "IMD Resistance", + "type": "float32", + "displayUnits": "MOhm" + }, + { + "id": 2151, + "alias": "imd_is_ok", + "name": "IMD OK", + "type": "bool" + }, + { + "id": 2152, + "alias": "imd_duty", + "name": "IMD Duty", + "type": "float32" + }, + { + "id": 2153, + "alias": "imd_freq", + "name": "IMD Frequency", + "type": "float32" + }, + { + "id": 2154, + "alias": "contactor_precharge", + "name": "Contactor Precharge", + "type": "bool" + }, + { + "id": 2155, + "alias": "contactor_discharge", + "name": "Contactor Discharge", + "type": "bool" + }, + { + "id": 2156, + "alias": "contactor_high", + "name": "Contactor High", + "type": "bool" + }, + { + "id": 2157, + "alias": "contactor_low", + "name": "Contactor Low", + "type": "bool" + }, + { + "id": 2158, + "alias": "contactor_common_high", + "name": "Contactor Common High", + "type": "bool" + }, + { + "id": 2159, + "alias": "soc", + "name": "SOC", + "type": "float32" + }, + { + "id": 2160, + "alias": "sm_status", + "name": "State Machine Status", + "type": "enum", + "enumValues": [ + "Connecting", + "Idle", + "Ready To Precharge", + "Precharging", + "Energized", + "FAULT" + ] + } +] \ No newline at end of file diff --git a/backend/crates/core/src/adj/test/adj/boards/HVBMS/orders.json b/backend/crates/core/src/adj/test/adj/boards/HVBMS/orders.json new file mode 100644 index 000000000..fe54b536a --- /dev/null +++ b/backend/crates/core/src/adj/test/adj/boards/HVBMS/orders.json @@ -0,0 +1,32 @@ +[ + { + "type": "order", + "name": "FAULT", + "variables": [], + "id": 2000 + }, + { + "type": "order", + "name": "Open Contactors", + "variables": [], + "id": 2001 + }, + { + "type": "order", + "name": "Cell Balance", + "variables": [], + "id": 2002 + }, + { + "type": "order", + "name": "Start Precharge", + "variables": [], + "id": 2003 + }, + { + "type": "order", + "name": "Check Faults", + "variables": [], + "id": 2004 + } +] \ No newline at end of file diff --git a/backend/crates/core/src/adj/test/adj/boards/HVBMS/packets.json b/backend/crates/core/src/adj/test/adj/boards/HVBMS/packets.json new file mode 100644 index 000000000..01a841af3 --- /dev/null +++ b/backend/crates/core/src/adj/test/adj/boards/HVBMS/packets.json @@ -0,0 +1,218 @@ +[ + { + "type": "data", + "name": "High Voltage System", + "variables": [ + "voltage_min", + "voltage_max", + "temp_min", + "temp_max", + "current_reading", + "voltage_reading", + "batteries_voltage_reading", + "sm_status" + ], + "id": 2161, + "period": 10, + "period_type": "ms", + "socket": "control_station_udp" + }, + { + "type": "data", + "name": "SOC", + "variables": [ + "soc" + ], + "id": 2162, + "period": 50, + "period_type": "ms", + "socket": "control_station_udp" + }, + { + "type": "data", + "name": "SDC", + "variables": [ + "sdc_status" + ], + "id": 2163, + "period": 50, + "period_type": "ms", + "socket": "control_station_udp" + }, + { + "type": "data", + "name": "High Voltage Batteries", + "variables": [ + "battery1_cell1", + "battery1_cell2", + "battery1_cell3", + "battery1_cell4", + "battery1_cell5", + "battery1_cell6", + "battery1_cell7", + "battery1_cell8", + "battery1_cell9", + "battery1_cell10", + "battery1_cell11", + "battery1_cell12", + "battery1_total_voltage", + "battery1_temp1", + "battery1_temp2", + "battery1_temp3", + "battery1_temp4", + "battery2_cell1", + "battery2_cell2", + "battery2_cell3", + "battery2_cell4", + "battery2_cell5", + "battery2_cell6", + "battery2_cell7", + "battery2_cell8", + "battery2_cell9", + "battery2_cell10", + "battery2_cell11", + "battery2_cell12", + "battery2_total_voltage", + "battery2_temp1", + "battery2_temp2", + "battery2_temp3", + "battery2_temp4", + "battery3_cell1", + "battery3_cell2", + "battery3_cell3", + "battery3_cell4", + "battery3_cell5", + "battery3_cell6", + "battery3_cell7", + "battery3_cell8", + "battery3_cell9", + "battery3_cell10", + "battery3_cell11", + "battery3_cell12", + "battery3_total_voltage", + "battery3_temp1", + "battery3_temp2", + "battery3_temp3", + "battery3_temp4", + "battery4_cell1", + "battery4_cell2", + "battery4_cell3", + "battery4_cell4", + "battery4_cell5", + "battery4_cell6", + "battery4_cell7", + "battery4_cell8", + "battery4_cell9", + "battery4_cell10", + "battery4_cell11", + "battery4_cell12", + "battery4_total_voltage", + "battery4_temp1", + "battery4_temp2", + "battery4_temp3", + "battery4_temp4", + "battery5_cell1", + "battery5_cell2", + "battery5_cell3", + "battery5_cell4", + "battery5_cell5", + "battery5_cell6", + "battery5_cell7", + "battery5_cell8", + "battery5_cell9", + "battery5_cell10", + "battery5_cell11", + "battery5_cell12", + "battery5_total_voltage", + "battery5_temp1", + "battery5_temp2", + "battery5_temp3", + "battery5_temp4", + "battery6_cell1", + "battery6_cell2", + "battery6_cell3", + "battery6_cell4", + "battery6_cell5", + "battery6_cell6", + "battery6_cell7", + "battery6_cell8", + "battery6_cell9", + "battery6_cell10", + "battery6_cell11", + "battery6_cell12", + "battery6_total_voltage", + "battery6_temp1", + "battery6_temp2", + "battery6_temp3", + "battery6_temp4", + "battery7_cell1", + "battery7_cell2", + "battery7_cell3", + "battery7_cell4", + "battery7_cell5", + "battery7_cell6", + "battery7_cell7", + "battery7_cell8", + "battery7_cell9", + "battery7_cell10", + "battery7_cell11", + "battery7_cell12", + "battery7_total_voltage", + "battery7_temp1", + "battery7_temp2", + "battery7_temp3", + "battery7_temp4", + "battery8_cell1", + "battery8_cell2", + "battery8_cell3", + "battery8_cell4", + "battery8_cell5", + "battery8_cell6", + "battery8_cell7", + "battery8_cell8", + "battery8_cell9", + "battery8_cell10", + "battery8_cell11", + "battery8_cell12", + "battery8_total_voltage", + "battery8_temp1", + "battery8_temp2", + "battery8_temp3", + "battery8_temp4" + ], + "id": 2164, + "period": 50, + "period_type": "ms", + "socket": "control_station_udp" + }, + { + "type": "data", + "name": "IMD", + "variables": [ + "imd_status", + "imd_resistance", + "imd_is_ok", + "imd_duty", + "imd_freq" + ], + "id": 2165, + "period": 50, + "period_type": "ms", + "socket": "control_station_udp" + }, + { + "type": "data", + "name": "Contactor Status", + "variables": [ + "contactor_discharge", + "contactor_precharge", + "contactor_low", + "contactor_high", + "contactor_common_high" + ], + "id": 2166, + "period": 50, + "period_type": "ms", + "socket": "control_station_udp" + } +] \ No newline at end of file diff --git a/backend/crates/core/src/adj/test/adj/boards/HVBMS/sockets.json b/backend/crates/core/src/adj/test/adj/boards/HVBMS/sockets.json new file mode 100644 index 000000000..6c6e6b86f --- /dev/null +++ b/backend/crates/core/src/adj/test/adj/boards/HVBMS/sockets.json @@ -0,0 +1,13 @@ +[ + { + "type": "ServerSocket", + "name": "control_station_tcp", + "port": 50500 + }, + { + "type": "DatagramSocket", + "name": "control_station_udp", + "remote_ip": "192.168.0.9", + "port": 50400 + } +] diff --git a/backend/crates/core/src/adj/test/adj/boards/LCU/LCU.json b/backend/crates/core/src/adj/test/adj/boards/LCU/LCU.json new file mode 100644 index 000000000..2617f5ce6 --- /dev/null +++ b/backend/crates/core/src/adj/test/adj/boards/LCU/LCU.json @@ -0,0 +1,15 @@ +{ + "board_id": 4, + "mac": "0:0:0:0:0:0", + "board_ip": "192.168.1.4", + "measurements": [ + "LCU_measurements.json" + ], + "packets": [ + "packets.json", + "orders.json" + ], + "sockets": [ + "sockets.json" + ] +} diff --git a/backend/crates/core/src/adj/test/adj/boards/LCU/LCU_measurements.json b/backend/crates/core/src/adj/test/adj/boards/LCU/LCU_measurements.json new file mode 100644 index 000000000..6e1ca1ec5 --- /dev/null +++ b/backend/crates/core/src/adj/test/adj/boards/LCU/LCU_measurements.json @@ -0,0 +1,752 @@ +[ + { + "id": 819, + "alias": "master_state_machine", + "name": "Master SM", + "type": "enum", + "enumValues": [ + "Connecting", + "Idle", + "Levitating", + "Current Control", + "Debug", + "Fault" + ] + }, + { + "id": 820, + "alias": "slave_state_machine", + "name": "Slave SM", + "type": "enum", + "enumValues": [ + "SPI Connecting", + "Idle", + "Levitating", + "Current Control", + "Debug", + "Fault" + ] + }, + { + "id": 821, + "alias": "desired_current", + "name": "Desired Current", + "type": "float32", + "displayUnits": "A" + }, + { + "id": 822, + "alias": "fixed_vbat", + "name": "Fixed VBAT", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 823, + "alias": "desired_distance", + "name": "Desired Distance", + "type": "float32", + "displayUnits": "mm" + }, + { + "id": 824, + "alias": "lpu_id", + "name": "LPU ID", + "type": "uint32" + }, + { + "id": 825, + "alias": "fixed_pwm_duty_cycle", + "name": "Fixed PWM Duty Cycle", + "type": "float32", + "displayUnits": "%" + }, + { + "id": 826, + "alias": "pwm_duty_cycle_1", + "name": "Duty Cycle 1", + "type": "float32", + "displayUnits": "%" + }, + { + "id": 827, + "alias": "pwm_duty_cycle_2", + "name": "Duty Cycle 2", + "type": "float32", + "displayUnits": "%" + }, + { + "id": 828, + "alias": "pwm_duty_cycle_3", + "name": "Duty Cycle 3", + "type": "float32", + "displayUnits": "%" + }, + { + "id": 829, + "alias": "pwm_duty_cycle_4", + "name": "Duty Cycle 4", + "type": "float32", + "displayUnits": "%" + }, + { + "id": 830, + "alias": "pwm_duty_cycle_5", + "name": "Duty Cycle 5", + "type": "float32", + "displayUnits": "%" + }, + { + "id": 831, + "alias": "pwm_duty_cycle_6", + "name": "Duty Cycle 6", + "type": "float32", + "displayUnits": "%" + }, + { + "id": 832, + "alias": "pwm_duty_cycle_7", + "name": "Duty Cycle 7", + "type": "float32", + "displayUnits": "%" + }, + { + "id": 833, + "alias": "pwm_duty_cycle_8", + "name": "Duty Cycle 8", + "type": "float32", + "displayUnits": "%" + }, + { + "id": 834, + "alias": "pwm_duty_cycle_9", + "name": "Duty Cycle 9", + "type": "float32", + "displayUnits": "%" + }, + { + "id": 835, + "alias": "pwm_duty_cycle_10", + "name": "Duty Cycle 10", + "type": "float32", + "displayUnits": "%" + }, + { + "id": 836, + "alias": "coil_current_1", + "name": "Coil Current 1", + "type": "float32", + "displayUnits": "A" + }, + { + "id": 837, + "alias": "coil_current_2", + "name": "Coil Current 2", + "type": "float32", + "displayUnits": "A" + }, + { + "id": 838, + "alias": "coil_current_3", + "name": "Coil Current 3", + "type": "float32", + "displayUnits": "A" + }, + { + "id": 839, + "alias": "coil_current_4", + "name": "Coil Current 4", + "type": "float32", + "displayUnits": "A" + }, + { + "id": 840, + "alias": "coil_current_5", + "name": "Coil Current 5", + "type": "float32", + "displayUnits": "A" + }, + { + "id": 841, + "alias": "coil_current_6", + "name": "Coil Current 6", + "type": "float32", + "displayUnits": "A" + }, + { + "id": 842, + "alias": "coil_current_7", + "name": "Coil Current 7", + "type": "float32", + "displayUnits": "A" + }, + { + "id": 843, + "alias": "coil_current_8", + "name": "Coil Current 8", + "type": "float32", + "displayUnits": "A" + }, + { + "id": 844, + "alias": "coil_current_9", + "name": "Coil Current 9", + "type": "float32", + "displayUnits": "A" + }, + { + "id": 845, + "alias": "coil_current_10", + "name": "Coil Current 10", + "type": "float32", + "displayUnits": "A" + }, + { + "id": 846, + "alias": "airgap_1", + "name": "Airgap 1", + "type": "float32", + "displayUnits": "mm" + }, + { + "id": 847, + "alias": "airgap_2", + "name": "Airgap 2", + "type": "float32", + "displayUnits": "mm" + }, + { + "id": 848, + "alias": "airgap_3", + "name": "Airgap 3", + "type": "float32", + "displayUnits": "mm" + }, + { + "id": 849, + "alias": "airgap_4", + "name": "Airgap 4", + "type": "float32", + "displayUnits": "mm" + }, + { + "id": 850, + "alias": "airgap_5", + "name": "Airgap 5", + "type": "float32", + "displayUnits": "mm" + }, + { + "id": 851, + "alias": "airgap_6", + "name": "Airgap 6", + "type": "float32", + "displayUnits": "mm" + }, + { + "id": 852, + "alias": "airgap_7", + "name": "Airgap 7", + "type": "float32", + "displayUnits": "mm" + }, + { + "id": 853, + "alias": "airgap_8", + "name": "Airgap 8", + "type": "float32", + "displayUnits": "mm" + }, + { + "id": 854, + "alias": "cinema_current", + "name": "Cinema Current", + "type": "float32" + }, + { + "id": 855, + "alias": "ctrl_voltage_1", + "name": "Control Voltage 1", + "type": "float32" + }, + { + "id": 856, + "alias": "ctrl_voltage_2", + "name": "Control Voltage 2", + "type": "float32" + }, + { + "id": 857, + "alias": "ctrl_voltage_3", + "name": "Control Voltage 3", + "type": "float32" + }, + { + "id": 858, + "alias": "ctrl_voltage_4", + "name": "Control Voltage 4", + "type": "float32" + }, + { + "id": 859, + "alias": "ctrl_voltage_5", + "name": "Control Voltage 5", + "type": "float32" + }, + { + "id": 860, + "alias": "ctrl_voltage_6", + "name": "Control Voltage 6", + "type": "float32" + }, + { + "id": 861, + "alias": "ctrl_voltage_7", + "name": "Control Voltage 7", + "type": "float32" + }, + { + "id": 862, + "alias": "ctrl_voltage_8", + "name": "Control Voltage 8", + "type": "float32" + }, + { + "id": 863, + "alias": "ctrl_voltage_9", + "name": "Control Voltage 9", + "type": "float32" + }, + { + "id": 864, + "alias": "ctrl_voltage_10", + "name": "Control Voltage 10", + "type": "float32" + }, + { + "id": 865, + "alias": "ctrl_gap_local_1", + "name": "Control Gap Local 1", + "type": "float32" + }, + { + "id": 866, + "alias": "ctrl_gap_local_2", + "name": "Control Gap Local 2", + "type": "float32" + }, + { + "id": 867, + "alias": "ctrl_gap_local_3", + "name": "Control Gap Local 3", + "type": "float32" + }, + { + "id": 868, + "alias": "ctrl_gap_local_4", + "name": "Control Gap Local 4", + "type": "float32" + }, + { + "id": 869, + "alias": "ctrl_state_1", + "name": "Control State 1", + "type": "float32" + }, + { + "id": 870, + "alias": "ctrl_state_2", + "name": "Control State 2", + "type": "float32" + }, + { + "id": 871, + "alias": "ctrl_state_3", + "name": "Control State 3", + "type": "float32" + }, + { + "id": 872, + "alias": "ctrl_state_4", + "name": "Control State 4", + "type": "float32" + }, + { + "id": 873, + "alias": "ctrl_state_5", + "name": "Control State 5", + "type": "float32" + }, + { + "id": 874, + "alias": "ctrl_current_ref_1", + "name": "Control Current Ref 1", + "type": "float32" + }, + { + "id": 875, + "alias": "ctrl_current_ref_2", + "name": "Control Current Ref 2", + "type": "float32" + }, + { + "id": 876, + "alias": "ctrl_current_ref_3", + "name": "Control Current Ref 3", + "type": "float32" + }, + { + "id": 877, + "alias": "ctrl_current_ref_4", + "name": "Control Current Ref 4", + "type": "float32" + }, + { + "id": 878, + "alias": "ctrl_current_ref_5", + "name": "Control Current Ref 5", + "type": "float32" + }, + { + "id": 879, + "alias": "ctrl_current_ref_6", + "name": "Control Current Ref 6", + "type": "float32" + }, + { + "id": 880, + "alias": "ctrl_current_ref_7", + "name": "Control Current Ref 7", + "type": "float32" + }, + { + "id": 881, + "alias": "ctrl_current_ref_8", + "name": "Control Current Ref 8", + "type": "float32" + }, + { + "id": 882, + "alias": "ctrl_current_ref_9", + "name": "Control Current Ref 9", + "type": "float32" + }, + { + "id": 883, + "alias": "ctrl_current_ref_10", + "name": "Control Current Ref 10", + "type": "float32" + }, + { + "id": 884, + "alias": "ctrl_fe_1", + "name": "Control Fe 1", + "type": "float32" + }, + { + "id": 885, + "alias": "ctrl_fe_2", + "name": "Control Fe 2", + "type": "float32" + }, + { + "id": 886, + "alias": "ctrl_fe_3", + "name": "Control Fe 3", + "type": "float32" + }, + { + "id": 887, + "alias": "ctrl_fa_1", + "name": "Control Fa 1", + "type": "float32" + }, + { + "id": 888, + "alias": "ctrl_fa_2", + "name": "Control Fa 2", + "type": "float32" + }, + { + "id": 889, + "alias": "ctrl_fa_3", + "name": "Control Fa 3", + "type": "float32" + }, + { + "id": 890, + "alias": "ctrl_fa_4", + "name": "Control Fa 4", + "type": "float32" + }, + { + "id": 891, + "alias": "ctrl_ef_1", + "name": "Control Ef 1", + "type": "float32" + }, + { + "id": 892, + "alias": "ctrl_ef_2", + "name": "Control Ef 2", + "type": "float32" + }, + { + "id": 893, + "alias": "ctrl_ef_3", + "name": "Control Ef 3", + "type": "float32" + }, + { + "id": 894, + "alias": "ctrl_p_1", + "name": "Control P 1", + "type": "float32" + }, + { + "id": 895, + "alias": "ctrl_p_2", + "name": "Control P 2", + "type": "float32" + }, + { + "id": 896, + "alias": "ctrl_p_3", + "name": "Control P 3", + "type": "float32" + }, + { + "id": 897, + "alias": "ctrl_r_1", + "name": "Control R 1", + "type": "float32" + }, + { + "id": 898, + "alias": "ctrl_r_2", + "name": "Control R 2", + "type": "float32" + }, + { + "id": 899, + "alias": "ctrl_r_3", + "name": "Control R 3", + "type": "float32" + }, + { + "id": 900, + "alias": "ctrl_zz_1", + "name": "Control Zz 1", + "type": "float32" + }, + { + "id": 901, + "alias": "ctrl_zz_2", + "name": "Control Zz 2", + "type": "float32" + }, + { + "id": 902, + "alias": "ctrl_zz_3", + "name": "Control Zz 3", + "type": "float32" + }, + { + "id": 903, + "alias": "ctrl_fe_l_1", + "name": "Control Fe L 1", + "type": "float32" + }, + { + "id": 904, + "alias": "ctrl_fe_l_2", + "name": "Control Fe L 2", + "type": "float32" + }, + { + "id": 905, + "alias": "ctrl_fe_l_3", + "name": "Control Fe L 3", + "type": "float32" + }, + { + "id": 906, + "alias": "ctrl_referencia", + "name": "Control Referencia", + "type": "float32" + }, + { + "id": 907, + "alias": "ctrl_i_hems_out_1", + "name": "Control I HEMS Out 1", + "type": "float32" + }, + { + "id": 908, + "alias": "ctrl_i_hems_out_2", + "name": "Control I HEMS Out 2", + "type": "float32" + }, + { + "id": 909, + "alias": "ctrl_i_hems_out_3", + "name": "Control I HEMS Out 3", + "type": "float32" + }, + { + "id": 910, + "alias": "ctrl_i_hems_out_4", + "name": "Control I HEMS Out 4", + "type": "float32" + }, + { + "id": 911, + "alias": "ctrl_a_1", + "name": "Control A 1", + "type": "float32" + }, + { + "id": 912, + "alias": "ctrl_a_2", + "name": "Control A 2", + "type": "float32" + }, + { + "id": 913, + "alias": "ctrl_a_3", + "name": "Control A 3", + "type": "float32" + }, + { + "id": 914, + "alias": "ctrl_a_4", + "name": "Control A 4", + "type": "float32" + }, + { + "id": 915, + "alias": "ctrl_a_5", + "name": "Control A 5", + "type": "float32" + }, + { + "id": 916, + "alias": "ctrl_a_6", + "name": "Control A 6", + "type": "float32" + }, + { + "id": 917, + "alias": "ctrl_a_7", + "name": "Control A 7", + "type": "float32" + }, + { + "id": 918, + "alias": "ctrl_a_8", + "name": "Control A 8", + "type": "float32" + }, + { + "id": 919, + "alias": "ctrl_ak_1", + "name": "Control Ak 1", + "type": "float32" + }, + { + "id": 920, + "alias": "ctrl_ak_2", + "name": "Control Ak 2", + "type": "float32" + }, + { + "id": 921, + "alias": "ctrl_ak_3", + "name": "Control Ak 3", + "type": "float32" + }, + { + "id": 922, + "alias": "ctrl_ak_4", + "name": "Control Ak 4", + "type": "float32" + }, + { + "id": 923, + "alias": "ctrl_bk_1", + "name": "Control Bk 1", + "type": "float32" + }, + { + "id": 924, + "alias": "ctrl_bk_2", + "name": "Control Bk 2", + "type": "float32" + }, + { + "id": 925, + "alias": "ctrl_bk_3", + "name": "Control Bk 3", + "type": "float32" + }, + { + "id": 926, + "alias": "ctrl_pi_hems_1", + "name": "Control PI HEMS 1", + "type": "float32" + }, + { + "id": 927, + "alias": "ctrl_pi_hems_2", + "name": "Control PI HEMS 2", + "type": "float32" + }, + { + "id": 928, + "alias": "ctrl_pi_hems_3", + "name": "Control PI HEMS 3", + "type": "float32" + }, + { + "id": 929, + "alias": "ctrl_pi_hems_4", + "name": "Control PI HEMS 4", + "type": "float32" + }, + { + "id": 930, + "alias": "ctrl_pi_ems_1", + "name": "Control PI EMS 1", + "type": "float32" + }, + { + "id": 931, + "alias": "ctrl_pi_ems_2", + "name": "Control PI EMS 2", + "type": "float32" + }, + { + "id": 932, + "alias": "ctrl_pi_ems_3", + "name": "Control PI EMS 3", + "type": "float32" + }, + { + "id": 933, + "alias": "ctrl_pi_ems_4", + "name": "Control PI EMS 4", + "type": "float32" + }, + { + "id": 934, + "alias": "ctrl_pi_ems_5", + "name": "Control PI EMS 5", + "type": "float32" + }, + { + "id": 935, + "alias": "ctrl_pi_ems_6", + "name": "Control PI EMS 6", + "type": "float32" + } +] \ No newline at end of file diff --git a/backend/crates/core/src/adj/test/adj/boards/LCU/orders.json b/backend/crates/core/src/adj/test/adj/boards/LCU/orders.json new file mode 100644 index 000000000..ad42d50c9 --- /dev/null +++ b/backend/crates/core/src/adj/test/adj/boards/LCU/orders.json @@ -0,0 +1,142 @@ +[ + { + "type": "order", + "name": "FAULT", + "variables": [], + "id": 800 + }, + { + "type": "order", + "name": "Stop", + "variables": [], + "id": 801 + }, + { + "type": "order", + "name": "Set Fixed VBAT", + "variables": [ + "fixed_vbat" + ], + "id": 802 + }, + { + "type": "order", + "name": "Unset Fixed VBAT", + "variables": [], + "id": 803 + }, + { + "type": "order", + "name": "Levitate", + "variables": [ + "desired_distance" + ], + "id": 804 + }, + { + "type": "order", + "name": "Levitate Ramp", + "variables": [ + "desired_distance" + ], + "id": 805 + }, + { + "type": "order", + "name": "Set Desired Distance", + "variables": [ + "desired_distance" + ], + "id": 806 + }, + { + "type": "order", + "name": "Set Desired Distance Ramp", + "variables": [ + "desired_distance" + ], + "id": 807 + }, + { + "type": "order", + "name": "Stop Ramp", + "variables": [], + "id": 808 + }, + { + "type": "order", + "name": "Current Control", + "variables": [ + "lpu_id", + "desired_current" + ], + "id": 809 + }, + { + "type": "order", + "name": "All Current Control", + "variables": [ + "desired_current" + ], + "id": 810 + }, + { + "type": "order", + "name": "Stop Current Control", + "variables": [ + "lpu_id" + ], + "id": 811 + }, + { + "type": "order", + "name": "PWM", + "variables": [ + "lpu_id", + "fixed_pwm_duty_cycle" + ], + "id": 812 + }, + { + "type": "order", + "name": "All PWM", + "variables": [ + "fixed_pwm_duty_cycle" + ], + "id": 813 + }, + { + "type": "order", + "name": "Stop PWM", + "variables": [ + "lpu_id" + ], + "id": 814 + }, + { + "type": "order", + "name": "Reset All", + "variables": [], + "id": 815 + }, + { + "type": "order", + "name": "Reset Slave", + "variables": [], + "id": 816 + }, + { + "type": "order", + "name": "Cinema", + "variables": [ + "cinema_current" + ], + "id": 817 + }, + { + "type": "order", + "name": "Stop Cinema", + "variables": [], + "id": 818 + } +] diff --git a/backend/crates/core/src/adj/test/adj/boards/LCU/packets.json b/backend/crates/core/src/adj/test/adj/boards/LCU/packets.json new file mode 100644 index 000000000..6cfaf8900 --- /dev/null +++ b/backend/crates/core/src/adj/test/adj/boards/LCU/packets.json @@ -0,0 +1,163 @@ +[ + { + "id": 936, + "type": "data", + "name": "LPU PWM Duties", + "variables": [ + "pwm_duty_cycle_1", + "pwm_duty_cycle_2", + "pwm_duty_cycle_3", + "pwm_duty_cycle_4", + "pwm_duty_cycle_5", + "pwm_duty_cycle_6", + "pwm_duty_cycle_7", + "pwm_duty_cycle_8", + "pwm_duty_cycle_9", + "pwm_duty_cycle_10" + ], + "period_type": "ms", + "period": 10.0, + "socket": "control_station_udp" + }, + { + "id": 937, + "type": "data", + "name": "LPU Coil Currents", + "variables": [ + "coil_current_1", + "coil_current_2", + "coil_current_3", + "coil_current_4", + "coil_current_5", + "coil_current_6", + "coil_current_7", + "coil_current_8", + "coil_current_9", + "coil_current_10" + ], + "period_type": "ms", + "period": 10.0, + "socket": "control_station_udp" + }, + { + "id": 938, + "type": "data", + "name": "Airgaps", + "variables": [ + "airgap_1", + "airgap_2", + "airgap_3", + "airgap_4", + "airgap_5", + "airgap_6", + "airgap_7", + "airgap_8" + ], + "period_type": "ms", + "period": 10.0, + "socket": "control_station_udp" + }, + { + "id": 939, + "type": "data", + "name": "State Machine", + "variables": [ + "master_state_machine", + "slave_state_machine" + ], + "period_type": "ms", + "period": 10.0, + "socket": "control_station_udp" + }, + { + "id": 940, + "type": "data", + "name": "General State", + "variables": [ + "ctrl_voltage_1", + "ctrl_voltage_2", + "ctrl_voltage_3", + "ctrl_voltage_4", + "ctrl_voltage_5", + "ctrl_voltage_6", + "ctrl_voltage_7", + "ctrl_voltage_8", + "ctrl_voltage_9", + "ctrl_voltage_10", + "ctrl_gap_local_1", + "ctrl_gap_local_2", + "ctrl_gap_local_3", + "ctrl_gap_local_4", + "ctrl_state_1", + "ctrl_state_2", + "ctrl_state_3", + "ctrl_state_4", + "ctrl_state_5", + "ctrl_current_ref_1", + "ctrl_current_ref_2", + "ctrl_current_ref_3", + "ctrl_current_ref_4", + "ctrl_current_ref_5", + "ctrl_current_ref_6", + "ctrl_current_ref_7", + "ctrl_current_ref_8", + "ctrl_current_ref_9", + "ctrl_current_ref_10", + "ctrl_fe_1", + "ctrl_fe_2", + "ctrl_fe_3", + "ctrl_fa_1", + "ctrl_fa_2", + "ctrl_fa_3", + "ctrl_fa_4", + "ctrl_ef_1", + "ctrl_ef_2", + "ctrl_ef_3", + "ctrl_p_1", + "ctrl_p_2", + "ctrl_p_3", + "ctrl_r_1", + "ctrl_r_2", + "ctrl_r_3", + "ctrl_zz_1", + "ctrl_zz_2", + "ctrl_zz_3", + "ctrl_fe_l_1", + "ctrl_fe_l_2", + "ctrl_fe_l_3", + "ctrl_referencia", + "ctrl_i_hems_out_1", + "ctrl_i_hems_out_2", + "ctrl_i_hems_out_3", + "ctrl_i_hems_out_4", + "ctrl_a_1", + "ctrl_a_2", + "ctrl_a_3", + "ctrl_a_4", + "ctrl_a_5", + "ctrl_a_6", + "ctrl_a_7", + "ctrl_a_8", + "ctrl_ak_1", + "ctrl_ak_2", + "ctrl_ak_3", + "ctrl_ak_4", + "ctrl_bk_1", + "ctrl_bk_2", + "ctrl_bk_3", + "ctrl_pi_hems_1", + "ctrl_pi_hems_2", + "ctrl_pi_hems_3", + "ctrl_pi_hems_4", + "ctrl_pi_ems_1", + "ctrl_pi_ems_2", + "ctrl_pi_ems_3", + "ctrl_pi_ems_4", + "ctrl_pi_ems_5", + "ctrl_pi_ems_6" + ], + "period_type": "ms", + "period": 10.0, + "socket": "control_station_udp" + } +] \ No newline at end of file diff --git a/backend/crates/core/src/adj/test/adj/boards/LCU/sockets.json b/backend/crates/core/src/adj/test/adj/boards/LCU/sockets.json new file mode 100644 index 000000000..6c6e6b86f --- /dev/null +++ b/backend/crates/core/src/adj/test/adj/boards/LCU/sockets.json @@ -0,0 +1,13 @@ +[ + { + "type": "ServerSocket", + "name": "control_station_tcp", + "port": 50500 + }, + { + "type": "DatagramSocket", + "name": "control_station_udp", + "remote_ip": "192.168.0.9", + "port": 50400 + } +] diff --git a/backend/crates/core/src/adj/test/adj/boards/PCU/PCU.json b/backend/crates/core/src/adj/test/adj/boards/PCU/PCU.json new file mode 100644 index 000000000..ffacc86ef --- /dev/null +++ b/backend/crates/core/src/adj/test/adj/boards/PCU/PCU.json @@ -0,0 +1,15 @@ +{ + "board_id": 5, + "mac": "0:0:0:0:0:0", + "board_ip": "192.168.1.5", + "measurements": [ + "PCU_measurements.json" + ], + "packets": [ + "packets.json", + "orders.json" + ], + "sockets": [ + "sockets.json" + ] +} \ No newline at end of file diff --git a/backend/crates/core/src/adj/test/adj/boards/PCU/PCU_measurements.json b/backend/crates/core/src/adj/test/adj/boards/PCU/PCU_measurements.json new file mode 100644 index 000000000..cd68d8b95 --- /dev/null +++ b/backend/crates/core/src/adj/test/adj/boards/PCU/PCU_measurements.json @@ -0,0 +1,304 @@ +[ + { + "id": 559, + "alias": "frequency", + "name": "Frequency Commutation hz", + "type": "uint32", + "displayUnits": "Hz" + }, + { + "id": 560, + "alias": "modulation_frequency", + "name": "Modulation Frequency", + "type": "float32", + "displayUnits": "Hz" + }, + { + "id": 561, + "alias": "duty_u", + "name": "Duty U", + "type": "float32", + "displayUnits": "%" + }, + { + "id": 562, + "alias": "duty_v", + "name": "Duty V", + "type": "float32", + "displayUnits": "%" + }, + { + "id": 563, + "alias": "duty_w", + "name": "Duty W", + "type": "float32", + "displayUnits": "%" + }, + { + "id": 564, + "alias": "voltage_battery_a", + "name": "Voltage Battery A", + "type": "float32" + }, + { + "id": 565, + "alias": "voltage_battery_b", + "name": "Voltage Battery B", + "type": "float32" + }, + { + "id": 566, + "alias": "v_ref", + "name": "Reference Voltage", + "type": "float32" + }, + { + "id": 567, + "alias": "frequency_to_send_svpwm", + "name": "Frequency Modulation hz", + "type": "float32", + "displayUnits": "Hz" + }, + { + "id": 568, + "alias": "frequency_to_send_pwm", + "name": "Frequency Commutation hz", + "type": "float32", + "displayUnits": "Hz" + }, + { + "id": 569, + "alias": "current_sensor_u_a", + "name": "Current Sensor U Connector A", + "type": "float32", + "displayUnits": "A" + }, + { + "id": 570, + "alias": "current_sensor_u_b", + "name": "Current Sensor U Connector B", + "type": "float32", + "displayUnits": "A" + }, + { + "id": 571, + "alias": "current_sensor_v_a", + "name": "Current Sensor V Connector A", + "type": "float32", + "displayUnits": "A" + }, + { + "id": 572, + "alias": "current_sensor_v_b", + "name": "Current Sensor V Connector B", + "type": "float32", + "displayUnits": "A" + }, + { + "id": 573, + "alias": "current_sensor_w_a", + "name": "Current Sensor W Connector A", + "type": "float32", + "displayUnits": "A" + }, + { + "id": 574, + "alias": "current_sensor_w_b", + "name": "Current Sensor W Connector B", + "type": "float32", + "displayUnits": "A" + }, + { + "id": 575, + "alias": "state", + "name": "State", + "type": "enum", + "enumValues": [ + "Connecting", + "Idle", + "Accelerating", + "Fault" + ] + }, + { + "id": 576, + "alias": "current_ref", + "name": "Current Ref", + "type": "float32", + "displayUnits": "A" + }, + { + "id": 577, + "alias": "freq_to_send_svpwm", + "name": "Frequency Modulation hz", + "type": "float32", + "displayUnits": "Hz" + }, + { + "id": 578, + "alias": "freq_to_send_pwm", + "name": "Frequency Commutation hz", + "type": "float32", + "displayUnits": "Hz" + }, + { + "id": 579, + "alias": "current_Peak", + "name": "Max Current Peak", + "type": "float32", + "displayUnits": "A" + }, + { + "id": 580, + "alias": "error_pi", + "name": "Actual Current Error", + "type": "float32", + "displayUnits": "A" + }, + { + "id": 581, + "alias": "vf_control", + "name": "Variable frecuency control", + "type": "bool" + }, + { + "id": 582, + "alias": "slip_motor", + "name": "Slip Motor", + "type": "float32", + "displayUnits": "%" + }, + { + "id": 583, + "alias": "imu_speed_km_h", + "name": "Speed IMU", + "type": "float64", + "displayUnits": "km/h" + }, + { + "id": 584, + "alias": "imu_position_m", + "name": "IMU Position", + "type": "float32", + "displayUnits": "m" + }, + { + "id": 585, + "alias": "target_voltage", + "name": "Target Voltage", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 586, + "alias": "vmax", + "name": "Max Voltage", + "type": "float32", + "displayUnits": "V" + }, + { + "id": 587, + "alias": "speed_ref", + "name": "Reference Speed", + "type": "float32", + "displayUnits": "km/h" + }, + { + "id": 588, + "alias": "svpwm_time", + "name": "SVPWM Time", + "type": "float32", + "displayUnits": "s" + }, + { + "id": 589, + "alias": "target_speed", + "name": "Target Speed KM/H", + "type": "float32", + "displayUnits": "km/h" + }, + { + "id": 590, + "alias": "speed_error", + "name": "Speed Error", + "type": "float64", + "displayUnits": "km/h" + }, + { + "id": 591, + "alias": "actual_current_ref", + "name": "Control Current ref", + "type": "float32", + "displayUnits": "A" + }, + { + "id": 592, + "alias": "imod", + "name": "Modulation Index", + "type": "float32" + }, + { + "id": 593, + "alias": "gd_fault_a", + "name": "GateDriver A Fault", + "type": "bool", + "displayUnits": "", + "protections": [ + { + "type": "Equal", + "value": [ + 1 + ], + "fault": true + } + ] + }, + { + "id": 594, + "alias": "gd_fault_b", + "name": "GateDriver B Fault", + "type": "bool", + "displayUnits": "", + "protections": [ + { + "type": "Equal", + "value": [ + 1 + ], + "fault": true + } + ] + }, + { + "id": 595, + "alias": "gd_ready_a", + "name": "GateDriver A Ready", + "type": "bool", + "displayUnits": "", + "protections": [ + { + "type": "Equal", + "value": [ + 1 + ], + "fault": true + } + ] + }, + { + "id": 596, + "alias": "gd_ready_b", + "name": "GateDriver B Ready", + "type": "bool", + "displayUnits": "", + "protections": [ + { + "type": "Equal", + "value": [ + 1 + ], + "fault": true + } + ] + } +] \ No newline at end of file diff --git a/backend/crates/core/src/adj/test/adj/boards/PCU/orders.json b/backend/crates/core/src/adj/test/adj/boards/PCU/orders.json new file mode 100644 index 000000000..180437e93 --- /dev/null +++ b/backend/crates/core/src/adj/test/adj/boards/PCU/orders.json @@ -0,0 +1,53 @@ +[ + { + "type": "order", + "name": "FAULT", + "variables": [], + "id": 512 + }, + { + "type": "order", + "name": "Start SVPWM", + "variables": [ + "frequency_to_send_svpwm", + "frequency_to_send_pwm", + "v_ref", + "vmax" + ], + "id": 513 + }, + { + "type": "order", + "name": "Stop Motor", + "variables": [], + "id": 514 + }, + { + "type": "order", + "name": "Send Reference Current", + "variables": [ + "freq_to_send_svpwm", + "freq_to_send_pwm", + "current_ref", + "vmax", + "vf_control" + ], + "id": 515 + }, + { + "type": "order", + "name": "Zeroing", + "variables": [], + "id": 516 + }, + { + "type": "order", + "name": "Send Reference Speed", + "variables": [ + "speed_ref", + "freq_to_send_pwm", + "vmax" + ], + "id": 517 + } +] \ No newline at end of file diff --git a/backend/crates/core/src/adj/test/adj/boards/PCU/packets.json b/backend/crates/core/src/adj/test/adj/boards/PCU/packets.json new file mode 100644 index 000000000..64a4254e3 --- /dev/null +++ b/backend/crates/core/src/adj/test/adj/boards/PCU/packets.json @@ -0,0 +1,91 @@ +[ + { + "type": "data", + "name": "PWM", + "variables": [ + "frequency", + "modulation_frequency", + "duty_u", + "duty_v", + "duty_w" + ], + "id": 550, + "period_type": "ms", + "period": 16.67, + "socket": "control_station_udp" + }, + { + "type": "data", + "name": "Batteries Voltage", + "variables": [ + "voltage_battery_a", + "voltage_battery_b" + ], + "id": 551, + "period_type": "ms", + "period": 16.67, + "socket": "control_station_udp" + }, + { + "type": "data", + "name": "Current Sensors", + "variables": [ + "current_sensor_u_a", + "current_sensor_v_a", + "current_sensor_w_a", + "current_sensor_u_b", + "current_sensor_v_b", + "current_sensor_w_b", + "current_Peak", + "error_pi", + "target_voltage", + "svpwm_time", + "imod" + ], + "id": 552, + "period_type": "ms", + "period": 16.67, + "socket": "control_station_udp" + }, + { + "type": "data", + "name": "State Machine States", + "variables": [ + "state" + ], + "id": 553, + "period_type": "ms", + "period": 16.67, + "socket": "control_station_udp" + }, + { + "type": "data", + "name": "Speed Data", + "variables": [ + "target_speed", + "speed_error", + "actual_current_ref", + "slip_motor", + "imu_speed_km_h", + "imu_position_m" + ], + "id": 555, + "period_type": "ms", + "period": 16.67, + "socket": "control_station_udp" + }, + { + "type": "data", + "name": "Gate Driver Reporting", + "variables": [ + "gd_fault_a", + "gd_fault_b", + "gd_ready_a", + "gd_ready_b" + ], + "id": 558, + "period_type": "ms", + "period": 16.67, + "socket": "control_station_udp" + } +] \ No newline at end of file diff --git a/backend/crates/core/src/adj/test/adj/boards/PCU/sockets.json b/backend/crates/core/src/adj/test/adj/boards/PCU/sockets.json new file mode 100644 index 000000000..6c6e6b86f --- /dev/null +++ b/backend/crates/core/src/adj/test/adj/boards/PCU/sockets.json @@ -0,0 +1,13 @@ +[ + { + "type": "ServerSocket", + "name": "control_station_tcp", + "port": 50500 + }, + { + "type": "DatagramSocket", + "name": "control_station_udp", + "remote_ip": "192.168.0.9", + "port": 50400 + } +] diff --git a/backend/crates/core/src/adj/test/adj/boards/VCU/VCU.json b/backend/crates/core/src/adj/test/adj/boards/VCU/VCU.json new file mode 100644 index 000000000..7203dedeb --- /dev/null +++ b/backend/crates/core/src/adj/test/adj/boards/VCU/VCU.json @@ -0,0 +1,16 @@ +{ + "board_id": 3, + "mac": "0:0:0:0:0:0", + "board_ip": "192.168.1.3", + "measurements": [ + "VCU_measurements.json" + ], + "packets": [ + "orders.json", + "packets.json" + ], + "sockets":[ + "sockets.json" + ] + +} \ No newline at end of file diff --git a/backend/crates/core/src/adj/test/adj/boards/VCU/VCU_measurements.json b/backend/crates/core/src/adj/test/adj/boards/VCU/VCU_measurements.json new file mode 100644 index 000000000..d80dbeea9 --- /dev/null +++ b/backend/crates/core/src/adj/test/adj/boards/VCU/VCU_measurements.json @@ -0,0 +1,95 @@ +[ + { + "id": 613, + "alias": "state", + "name": "State", + "type": "enum", + "enumValues": [ + "Idle", + "Connected", + "Maintenance", + "Precharging", + "HVActive", + "Ready", + "Propulsion", + "Static Levitation", + "Dynamic Levitation", + "Fault" + ] + }, + { + "id": 614, + "alias": "sdc_closed", + "name": "SDC Closed", + "type": "bool" + }, + { + "id": 615, + "alias": "high_pressure", + "name": "High Pressure", + "type": "float32", + "displayUnits": "bar" + }, + { + "id": 616, + "alias": "low_pressure", + "name": "Low Pressure", + "type": "float32", + "displayUnits": "bar" + }, + { + "id": 617, + "alias": "pressure_regulator_feedback", + "name": "Pressure Regulator Feedback", + "type": "float32", + "displayUnits": "bar" + }, + { + "id": 618, + "alias": "brakes_status", + "name": "Brakes Status", + "type": "enum", + "enumValues": [ + "BRAKED", + "UNBRAKED" + ] + }, + { + "id": 619, + "alias": "electrovalve_enabled", + "name": "Electrovalve Enabled", + "type": "bool" + }, + { + "id": 620, + "alias": "hvbms_connected", + "name": "HVBMS Connected", + "type": "bool" + }, + { + "id": 621, + "alias": "pcu_connected", + "name": "PCU Connected", + "type": "bool" + }, + { + "id": 622, + "alias": "lcu_connected", + "name": "LCU Connected", + "type": "bool" + }, + { + "id": 623, + "alias": "propulsion_current_reference", + "name": "Propulsion Current Reference", + "type": "float32", + "displayUnits": "A" + }, + { + "id": 624, + "alias": "levitation_target_height", + "name": "Levitation Target Height", + "type": "float32", + "displayUnits": "mm" + } +] diff --git a/backend/crates/core/src/adj/test/adj/boards/VCU/orders.json b/backend/crates/core/src/adj/test/adj/boards/VCU/orders.json new file mode 100644 index 000000000..338eb3cc8 --- /dev/null +++ b/backend/crates/core/src/adj/test/adj/boards/VCU/orders.json @@ -0,0 +1,87 @@ +[ + { + "id": 600, + "name": "FAULT", + "type": "order", + "variables": [] + }, + { + "id": 601, + "name": "Stop", + "type": "order", + "variables": [] + }, + { + "id": 602, + "name": "Maintenance", + "type": "order", + "variables": [] + }, + { + "id": 603, + "name": "Precharge", + "type": "order", + "variables": [] + }, + { + "id": 604, + "name": "Open Contactors", + "type": "order", + "variables": [] + }, + { + "id": 605, + "name": "Unbrake", + "type": "order", + "variables": [] + }, + { + "id": 606, + "name": "Brake", + "type": "order", + "variables": [] + }, + { + "id": 607, + "name": "Static Levitation", + "type": "order", + "variables": [] + }, + { + "id": 608, + "name": "Propulsion", + "type": "order", + "variables": [] + }, + { + "id": 609, + "name": "Dynamic Levitation", + "type": "order", + "variables": [] + }, + { + "id": 610, + "name": "Propulsion Parameterized", + "type": "order", + "variables": [ + "propulsion_current_reference" + ] + }, + { + "id": 611, + "name": "Static Levitation Parameterized", + "type": "order", + "variables": [ + "levitation_target_height" + ] + }, + { + "id": 612, + "name": "Dynamic Levitation Parameterized", + "type": "order", + "variables": [ + "propulsion_current_reference", + "levitation_target_height" + ] + } +] diff --git a/backend/crates/core/src/adj/test/adj/boards/VCU/packets.json b/backend/crates/core/src/adj/test/adj/boards/VCU/packets.json new file mode 100644 index 000000000..c270f8762 --- /dev/null +++ b/backend/crates/core/src/adj/test/adj/boards/VCU/packets.json @@ -0,0 +1,62 @@ +[ + { + "type": "data", + "name": "VCU State", + "variables": [ + "state" + ], + "id": 625, + "period_type": "ms", + "period": 10, + "socket": "control_station_udp" + }, + { + "type": "data", + "name": "Pressures", + "variables": [ + "high_pressure", + "low_pressure", + "pressure_regulator_feedback" + ], + "id": 626, + "period_type": "ms", + "period": 10, + "socket": "control_station_udp" + }, + { + "type": "data", + "name": "Brake Status", + "variables": [ + "brakes_status" + ], + "id": 627, + "period_type": "ms", + "period": 10, + "socket": "control_station_udp" + }, + { + "type": "data", + "name": "Outputs", + "variables": [ + "electrovalve_enabled" + ], + "id": 628, + "period_type": "ms", + "period": 10, + "socket": "control_station_udp" + }, + { + "type": "data", + "name": "Safety", + "variables": [ + "sdc_closed", + "hvbms_connected", + "pcu_connected", + "lcu_connected" + ], + "id": 629, + "period_type": "ms", + "period": 10, + "socket": "control_station_udp" + } +] diff --git a/backend/crates/core/src/adj/test/adj/boards/VCU/sockets.json b/backend/crates/core/src/adj/test/adj/boards/VCU/sockets.json new file mode 100644 index 000000000..20af9231b --- /dev/null +++ b/backend/crates/core/src/adj/test/adj/boards/VCU/sockets.json @@ -0,0 +1,13 @@ +[ + { + "type": "ServerSocket", + "name": "control_station_tcp", + "port": 50500 + }, + { + "type": "DatagramSocket", + "name": "control_station_udp", + "remote_ip":"192.168.0.9", + "port": 50400 + } +] diff --git a/backend/crates/core/src/adj/test/adj/general_info.json b/backend/crates/core/src/adj/test/adj/general_info.json new file mode 100644 index 000000000..c0dfc21ba --- /dev/null +++ b/backend/crates/core/src/adj/test/adj/general_info.json @@ -0,0 +1,61 @@ +{ + "ports": { + "TCP_CLIENT": 50401, + "TCP_SERVER": 50500, + "UDP": 50400, + "SNTP": 123, + "TFTP": 69, + "BLCU_UDP": 50420, + "BLCU_TCP_CLIENT": 50421 + }, + "addresses": { + "backend": "192.168.0.9", + "hypervisor": "192.168.0.13" + }, + "protectionTypes": { + "Equal": { + "range": false, + "text": "Value is equal to {} (measured: %)" + }, + "Range": { + "range": true, + "text": "Value out of range {} (measured: %)" + }, + "Below": { + "range": false, + "text": "Value below {} (measured: %)" + } + }, + "units": { + "m/ss": "*1", + "Hz": "*1", + "MOhm": "*1000000", + "ºC": "+273.15", + "deg": "/57.2957", + "km/h": "*3.6", + "ns": "*1", + "m/s": "*1", + "rad": "*1", + "A": "*1", + "%": "/100", + "m": "*1", + "mrad": "/1000", + "KOhm": "*1000", + "V": "*1", + "mV": "/1000", + "Ohm": "*1", + "mm": "/1000", + "G": "*9.8", + "bar": "*1", + "s": "*1" + }, + "message_ids": { + "state_space": 7, + "fault": 2, + "info": 1, + "blcu_ack": 4, + "remove_state_order": 6, + "add_state_order": 5, + "warning": 3 + } +} diff --git a/backend/crates/core/src/lib.rs b/backend/crates/core/src/lib.rs index 287b512a1..e1eda88f6 100644 --- a/backend/crates/core/src/lib.rs +++ b/backend/crates/core/src/lib.rs @@ -5,3 +5,8 @@ pub mod hello_world; /// Basic domain types: identifiers, values, measurements, protections, /// packets and boards. pub mod model; + +/// Parses an ADJ (Architecture Description JSON) directory into +/// [`model::PodData`], plus backend-session metadata not modeled as +/// vehicle data. See [`adj::load_from_dir`]. +pub mod adj; diff --git a/backend/crates/station/src/main.rs b/backend/crates/station/src/main.rs index d872008d1..27767e13f 100644 --- a/backend/crates/station/src/main.rs +++ b/backend/crates/station/src/main.rs @@ -9,5 +9,17 @@ fn main() { tracing::info!("iniciando demo de station"); let name = std::env::args().nth(1).unwrap_or_else(|| "World".into()); let _greeting = software_core::hello_world::greet(&name); + + let adj_path = + std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../core/src/adj/test/adj"); + let adj = match software_core::adj::load_from_dir(&adj_path) { + Ok(adj) => adj, + Err(err) => { + tracing::error!(%err, "no se pudo cargar el ADJ de prueba"); + std::process::exit(1); + } + }; + tracing::info!(boards = adj.pod_data.boards.len(), "adj de prueba cargado"); + tracing::info!("demo finalizada"); } From 1e427d94fff370f15125f843199103991f4276c6 Mon Sep 17 00:00:00 2001 From: Gazi Al Saad Halawani Date: Tue, 6 Oct 2026 21:35:07 +0200 Subject: [PATCH 016/225] Feat(backend): Implementation of protection IDs and TooManyProtections error. --- backend/crates/core/src/adj/error.rs | 5 +++++ backend/crates/core/src/adj/raw/loader.rs | 16 ++++++++++++++++ backend/crates/core/src/adj/raw/types.rs | 5 +++++ 3 files changed, 26 insertions(+) diff --git a/backend/crates/core/src/adj/error.rs b/backend/crates/core/src/adj/error.rs index c080b036d..73d7174dd 100644 --- a/backend/crates/core/src/adj/error.rs +++ b/backend/crates/core/src/adj/error.rs @@ -100,6 +100,11 @@ pub enum LoadError { /// An error converting a raw measurement into [`crate::model::Measurement`]. #[derive(Debug, thiserror::Error)] pub enum MeasurementError { + + /// The measurement has more than 7 protections + #[error("measurement has {count} protections, maximum allowed is 7")] + TooManyProtections {count: usize}, + /// The measurement's `type` isn't a recognized wire type, `"bool"` or /// `"enum"`. #[error("unknown measurement type {0:?}")] diff --git a/backend/crates/core/src/adj/raw/loader.rs b/backend/crates/core/src/adj/raw/loader.rs index aec8a9934..cfa8b345e 100644 --- a/backend/crates/core/src/adj/raw/loader.rs +++ b/backend/crates/core/src/adj/raw/loader.rs @@ -57,6 +57,8 @@ fn load_board(root: &Path, name: &str, rel_path: &str) -> Result = HashMap::new(); + let mut protection_packets: Vec = Vec::new(); + for measurements_path in &raw_board.measurements { let raws: Vec = read_json(&board_dir.join(measurements_path))?; for raw in raws { @@ -67,6 +69,18 @@ fn load_board(root: &Path, name: &str, rel_path: &str) -> Result Result for Measurement { type Error = MeasurementError; fn try_from(raw: RawMeasurement) -> Result { + + if raw.protections.len() > 7 { + return Err(MeasurementError::TooManyProtections{count: raw.protections.len()}); + } + let kind = parse_measurement_kind(&raw.kind, raw.enum_values)?; let mut protections = Vec::with_capacity(raw.protections.len()); From 6cf3497c6260ab7c59caffa7ac663e590468853b Mon Sep 17 00:00:00 2001 From: Gazi Al Saad Halawani Date: Tue, 6 Oct 2026 21:50:51 +0200 Subject: [PATCH 017/225] Feat(backend): Implemented ADJ tests. --- backend/crates/core/src/adj/raw/loader.rs | 3 +++ backend/crates/core/src/adj/raw/types.rs | 23 +++++++++++++++++++++++ 2 files changed, 26 insertions(+) diff --git a/backend/crates/core/src/adj/raw/loader.rs b/backend/crates/core/src/adj/raw/loader.rs index cfa8b345e..0cf05aa66 100644 --- a/backend/crates/core/src/adj/raw/loader.rs +++ b/backend/crates/core/src/adj/raw/loader.rs @@ -293,5 +293,8 @@ mod tests { text_time: None, } ); + + let protection_packet = pcu.packets.iter().find(|p| p.name.contains("_protection_")).unwrap(); + assert_eq!(protection_packet.id, AdjId(protected.id.0 + 1)); } } diff --git a/backend/crates/core/src/adj/raw/types.rs b/backend/crates/core/src/adj/raw/types.rs index d3dfb4acc..8188608a9 100644 --- a/backend/crates/core/src/adj/raw/types.rs +++ b/backend/crates/core/src/adj/raw/types.rs @@ -472,4 +472,27 @@ mod tests { assert_eq!(info.message_ids["fault"], 2); assert!(info.protection_types["Range"].is_range); } + + #[test] + fn measurement_with_too_many_protections() { + let mut raw = RawMeasurement{ + id: 100, + alias: "too_many".to_string(), + name: "Too Many Protections".to_string(), + kind: "float32".to_string(), + display_units: "V".to_string(), + enum_values: vec![], + protections: vec![], + }; + + for _ in 0..8{ + raw.protections.push(raw_protection("Equal", vec![1.0], true, None)); + } + + assert!(matches!( + Measurement::try_from(raw), + Err(MeasurementError::TooManyProtections{count:8}) + )) + } + } From fa9f338f9b3f87ef0bcd2f36ac7d00567692d454 Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Wed, 7 Oct 2026 14:16:51 +0200 Subject: [PATCH 018/225] fix: change rust version and add gix --- backend/Cargo.lock | 3102 ++++++++++++++++++++++++++++++-- backend/Cargo.toml | 2 +- backend/crates/core/Cargo.toml | 1 + 3 files changed, 2999 insertions(+), 106 deletions(-) diff --git a/backend/Cargo.lock b/backend/Cargo.lock index 94186abdf..0a8ad6631 100644 --- a/backend/Cargo.lock +++ b/backend/Cargo.lock @@ -11,191 +11,2524 @@ dependencies = [ "memchr", ] +[[package]] +name = "allocator-api2" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" + +[[package]] +name = "arc-swap" +version = "1.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c049c0be4daef0b145cb3555416b3b8ef5b7888a38aea1a3a155801fe7b0810b" +dependencies = [ + "rustversion", +] + +[[package]] +name = "arrayvec" +version = "0.7.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56" + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "aws-lc-rs" +version = "1.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b281d307588d634de920874890732659e2e7672f72b5e10e81badc1a8a83621e" +dependencies = [ + "aws-lc-sys", + "zeroize", +] + +[[package]] +name = "aws-lc-sys" +version = "0.45.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9bff6c3b54fad79a2e60b8102caf565819711497c1f5f092f49508e2f5c31b27" +dependencies = [ + "cc", + "cmake", + "dunce", + "fs_extra", + "pkg-config", +] + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + +[[package]] +name = "bitflags" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "bstr" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6bb31b46c14244e20ee9984b11bf5c992b91fb6939fea616e3512c8baecdbe5f" +dependencies = [ + "memchr", + "regex-automata", + "serde_core", +] + +[[package]] +name = "bumpalo" +version = "3.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" + +[[package]] +name = "byteorder" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" + [[package]] name = "bytes" version = "1.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + +[[package]] +name = "bytesize" +version = "2.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7354288c522e7e980fafd2075d63d1285794c3a6a16cdd492f189ea406e5f18b" + +[[package]] +name = "cc" +version = "1.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f74872d07caf508b30a21f6836e7d7016a2eaf7d9ff4f48deaa58cd8a0407630" +dependencies = [ + "find-msvc-tools", + "jobserver", + "libc", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "cfg_aliases" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" + +[[package]] +name = "chacha20" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "rand_core", +] + +[[package]] +name = "clru" +version = "0.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "197fd99cb113a8d5d9b6376f3aa817f32c1078f2343b714fff7d2ca44fdf67d5" +dependencies = [ + "hashbrown 0.16.1", +] + +[[package]] +name = "cmake" +version = "0.1.58" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0f78a02292a74a88ac736019ab962ece0bc380e3f977bf72e376c5d78ff0678" +dependencies = [ + "cc", +] + +[[package]] +name = "combine" +version = "4.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfc320937d09e6de266b31b9afb480f197d7a861be86be7cb2ea7e5d1bfffc5e" +dependencies = [ + "bytes", + "memchr", +] + +[[package]] +name = "core-foundation" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "core_detect" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48" + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +dependencies = [ + "libc", +] + +[[package]] +name = "crc32fast" +version = "1.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "01a7799fd6b852db0e61728dde9a204c423b44d689dbd432522543614b490e78" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "crossbeam-channel" +version = "0.5.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "98b0cc327b5bc766e7fda9c9260cc0fa81b43a8e240440422dff70788e3f9ef1" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-deque" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "622f3fc73690be383c7214310406f28a90e6edeadc3cea882f9d71e495b9711a" +dependencies = [ + "crossbeam-epoch", + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-epoch" +version = "0.9.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc74980687109a3b14c72fd458107bf0baa1da1a1a805e178d15501ba9b86d9d" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "dashmap" +version = "6.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6361d5c062261c78a176addb82d4c821ae42bed6089de0e12603cd25de2059c" +dependencies = [ + "cfg-if", + "crossbeam-utils", + "hashbrown 0.14.5", + "lock_api", + "once_cell", + "parking_lot_core", +] + +[[package]] +name = "defmt" +version = "0.3.100" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0963443817029b2024136fc4dd07a5107eb8f977eaf18fcd1fdeb11306b64ad" +dependencies = [ + "defmt 1.1.1", +] + +[[package]] +name = "defmt" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e2953bfe4f93bbd20cc71198842756f77d161884c99ebbabc41d80231ded88d1" +dependencies = [ + "bitflags 1.3.2", + "defmt-macros", +] + +[[package]] +name = "defmt-macros" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bad9c72e7ca2137e0dc3813245a0d282fd6daad32fd800af018306a9169b5fe8" +dependencies = [ + "defmt-parser", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "defmt-parser" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10d60334b3b2e7c9d91ef8150abfb6fa4c1c39ebbcf4a81c2e346aad939fee3e" +dependencies = [ + "thiserror", +] + +[[package]] +name = "deranged" +version = "0.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c" + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", +] + +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "dunce" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" + +[[package]] +name = "encoding_rs" +version = "0.8.42" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e985e0451871ad22fb8d2b6b076e2028a502a0d3950998c2c5c0a4f9b5d9679" +dependencies = [ + "cfg-if", + "core_detect", + "multiversion_no_op", + "rustversion", + "scopeguard", + "simdutf8", +] + +[[package]] +name = "equivalent" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "faster-hex" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "04839bdf9d8c10f66806fad16b852fc72aab80873aebc3cb69d85b4fa41543ed" +dependencies = [ + "autocfg", + "defmt 0.3.100", + "heapless", + "serde", +] + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "filetime" +version = "0.2.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c287a33c7f0a620c38e641e7f60827713987b3c0f26e8ddc9462cc69cf75759" +dependencies = [ + "cfg-if", + "libc", +] + +[[package]] +name = "find-msvc-tools" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aedcfb3409746eddb02b9e19ebda1c3394f759a152e48ee875a0844d1b955484" + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "fs_extra" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", + "futures-sink", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-io" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" + +[[package]] +name = "futures-sink" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-core", + "futures-io", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "slab", +] + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "wasi", + "wasm-bindgen", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "r-efi", + "rand_core", + "wasm-bindgen", +] + +[[package]] +name = "gix" +version = "0.87.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fdefc1465d8631807deaf504dacdeff628b978de515653b47976ca7c28ab2a7a" +dependencies = [ + "gix-actor", + "gix-archive", + "gix-attributes", + "gix-blame", + "gix-command", + "gix-commitgraph", + "gix-config", + "gix-credentials", + "gix-date", + "gix-diff", + "gix-dir", + "gix-discover", + "gix-error", + "gix-features", + "gix-filter", + "gix-fs", + "gix-glob", + "gix-hash", + "gix-hashtable", + "gix-ignore", + "gix-index", + "gix-lock", + "gix-mailmap", + "gix-merge", + "gix-negotiate", + "gix-note", + "gix-object", + "gix-odb", + "gix-pack", + "gix-path", + "gix-pathspec", + "gix-prompt", + "gix-protocol", + "gix-quote", + "gix-ref", + "gix-refspec", + "gix-revision", + "gix-revwalk", + "gix-sec", + "gix-shallow", + "gix-status", + "gix-submodule", + "gix-tempfile", + "gix-trace", + "gix-transport", + "gix-traverse", + "gix-url", + "gix-utils", + "gix-validate", + "gix-worktree", + "gix-worktree-state", + "gix-worktree-stream", + "gix-zlib", + "nonempty", + "parking_lot", + "regex", + "signal-hook", + "smallvec", + "thiserror", +] + +[[package]] +name = "gix-actor" +version = "0.42.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e37efa99929ac62f980fb1a7dcd09dea85b3aa6ead6ba0498362add3f4e698de" +dependencies = [ + "bstr", + "gix-date", + "gix-error", +] + +[[package]] +name = "gix-archive" +version = "0.36.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c4ef97efd3920d3525104c5f253dec94dc935f953a50055954939177aed2cdd" +dependencies = [ + "bstr", + "gix-date", + "gix-error", + "gix-object", + "gix-worktree-stream", +] + +[[package]] +name = "gix-attributes" +version = "0.35.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76b83782ac69ae28921a6e8fbcf2e24069613f1518030b97ae622b079abffa54" +dependencies = [ + "bstr", + "gix-features", + "gix-glob", + "gix-path", + "gix-quote", + "gix-trace", + "smallvec", + "thiserror", + "unicode-bom", +] + +[[package]] +name = "gix-bitmap" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f17013c7ef5cb95ebb4bf4978201e6a8a42ffea9d666fd5388f1b7e742307d80" +dependencies = [ + "gix-error", +] + +[[package]] +name = "gix-blame" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "54fe27f8037c58cb4b6d60fe0aacf7ee2c998633cedf4e989351c07d9a3a575d" +dependencies = [ + "gix-commitgraph", + "gix-date", + "gix-diff", + "gix-error", + "gix-hash", + "gix-object", + "gix-revwalk", + "gix-trace", + "gix-traverse", + "gix-worktree", + "smallvec", + "thiserror", +] + +[[package]] +name = "gix-chunk" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00e32f938b3745ac93d73bc7490b6a15a661b2fc81973bfe90e275cc53c908e1" +dependencies = [ + "gix-error", +] + +[[package]] +name = "gix-command" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa00adbd2c77f584cfe41f348772d2f131af1fa519a7f6b98638f1144ead96a4" +dependencies = [ + "bstr", + "gix-path", + "gix-quote", + "gix-trace", +] + +[[package]] +name = "gix-commitgraph" +version = "0.39.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b93c9fb1f5be01bba54a7a3b7455d359efc68555539c75ef74b8021bb6db497" +dependencies = [ + "bstr", + "gix-chunk", + "gix-error", + "gix-hash", + "memmap2", + "nonempty", +] + +[[package]] +name = "gix-config" +version = "0.60.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f973c28c0a4871a7926fc90c8377d4458fd6cbb19692f56582b4d2022313ae90" +dependencies = [ + "bstr", + "gix-config-value", + "gix-features", + "gix-glob", + "gix-path", + "gix-ref", + "gix-sec", + "gix-utils", + "smallvec", + "thiserror", + "unicode-bom", +] + +[[package]] +name = "gix-config-value" +version = "0.19.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f6af5321bfd3711a279d6b244d58532ba1cfabf9eb6374791f19929d8970082" +dependencies = [ + "bitflags 2.13.2", + "bstr", + "gix-path", + "libc", + "thiserror", +] + +[[package]] +name = "gix-credentials" +version = "0.40.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16c11822054fd4b80a1ab722b703f2e7c691b20484d898374289b742c1f49e50" +dependencies = [ + "bstr", + "gix-command", + "gix-config-value", + "gix-date", + "gix-path", + "gix-prompt", + "gix-quote", + "gix-sec", + "gix-trace", + "gix-url", + "thiserror", +] + +[[package]] +name = "gix-date" +version = "0.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e63d9aa18f29facd571c8953e66224ee0075b9e16622024794555ed4acceea85" +dependencies = [ + "bstr", + "gix-error", + "itoa", + "jiff", +] + +[[package]] +name = "gix-diff" +version = "0.67.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b1689ff5ddeee4acfb2a43e875a1072a76d208624b15a9065c938b39cb0da2a" +dependencies = [ + "bstr", + "gix-attributes", + "gix-command", + "gix-filter", + "gix-fs", + "gix-hash", + "gix-imara-diff", + "gix-index", + "gix-object", + "gix-path", + "gix-pathspec", + "gix-tempfile", + "gix-trace", + "gix-traverse", + "gix-worktree", + "thiserror", +] + +[[package]] +name = "gix-dir" +version = "0.29.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8342d5eb0ea054ed6ef807e628e38f06dd51eceeec9529767d8b23e33eff9c09" +dependencies = [ + "bstr", + "gix-discover", + "gix-fs", + "gix-ignore", + "gix-index", + "gix-object", + "gix-path", + "gix-pathspec", + "gix-trace", + "gix-utils", + "gix-worktree", + "thiserror", +] + +[[package]] +name = "gix-discover" +version = "0.55.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec32a30ec2934735599c2545f30067e80bd255fd3454b52a5d59bc02b52874a3" +dependencies = [ + "bstr", + "dunce", + "gix-fs", + "gix-path", + "gix-ref", + "gix-sec", + "thiserror", +] + +[[package]] +name = "gix-error" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a1ba536602db507119eb5f3cdf80bef3ca5a5ec0dfc6e9c7f46dc70ade7c112" +dependencies = [ + "bstr", +] + +[[package]] +name = "gix-features" +version = "0.49.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39c0e59d9d253dcccc38c3a46b91bfb9b46bd63eed54fe1a719e12194884d52a" +dependencies = [ + "bytes", + "bytesize", + "crc32fast", + "crossbeam-channel", + "gix-path", + "gix-trace", + "gix-utils", + "libc", + "once_cell", + "parking_lot", + "prodash", + "walkdir", +] + +[[package]] +name = "gix-filter" +version = "0.34.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c30b28d957e2e6f1e1bbfbfd26b8e0bb0aab68d8a5e730fb4fd3049943575e3" +dependencies = [ + "bstr", + "encoding_rs", + "gix-attributes", + "gix-command", + "gix-hash", + "gix-object", + "gix-packetline", + "gix-path", + "gix-quote", + "gix-trace", + "gix-utils", + "smallvec", + "thiserror", +] + +[[package]] +name = "gix-fs" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebcfa9fd253f25350a3b21b3dd74034a446098e373c6123d4cee3519894f12ef" +dependencies = [ + "bstr", + "gix-features", + "gix-path", + "gix-utils", + "thiserror", +] + +[[package]] +name = "gix-glob" +version = "0.27.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b417cf515fd8c91468b578071f76d6cba716f8a1eccd853906bff4908b2c1413" +dependencies = [ + "bitflags 2.13.2", + "bstr", + "gix-features", + "gix-path", +] + +[[package]] +name = "gix-hash" +version = "0.26.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "380b9c423a54f0821064b954b5a5ab25c660812f6a91da03c3f1cb4b10762aa5" +dependencies = [ + "faster-hex", + "gix-features", + "sha1-checked", + "thiserror", +] + +[[package]] +name = "gix-hashtable" +version = "0.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78fccd6fea3bcf0b39c076bae60ae49b08daaf538b950202101a981f9d3c01d3" +dependencies = [ + "gix-hash", + "hashbrown 0.17.1", + "parking_lot", +] + +[[package]] +name = "gix-ignore" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65859a2f7de5e159d4344a5486ebf53b6bac22d5ec6afa836e47c10ae88a7f0f" +dependencies = [ + "bstr", + "gix-glob", + "gix-path", + "gix-trace", + "unicode-bom", +] + +[[package]] +name = "gix-imara-diff" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c91d8cffac8849493a82233811bd02b2b183b8cf39bf704de0fa0841b737595" +dependencies = [ + "bstr", + "hashbrown 0.17.1", +] + +[[package]] +name = "gix-index" +version = "0.55.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "632e16cb48b0e88a747e106924cb2765194105d8070a7a961b0d080ed806c632" +dependencies = [ + "bitflags 2.13.2", + "bstr", + "filetime", + "fnv", + "gix-bitmap", + "gix-features", + "gix-fs", + "gix-hash", + "gix-lock", + "gix-object", + "gix-traverse", + "gix-utils", + "gix-validate", + "hashbrown 0.17.1", + "itoa", + "libc", + "memmap2", + "rustix", + "smallvec", + "thiserror", +] + +[[package]] +name = "gix-lock" +version = "24.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4c69157820343bf1c6e4b88b9808e920900de02e18aaf5862b30ada43814848" +dependencies = [ + "gix-tempfile", + "gix-utils", + "thiserror", +] + +[[package]] +name = "gix-macros" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3836b4b051393464a753c5a08fe19c7ce0d8b77574a92bd558972941d4553cb" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "gix-mailmap" +version = "0.34.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a1c6ca2f9481e5e98b3600b859bc595d46cdf3b600709d5f91b8c118ae452a1" +dependencies = [ + "bstr", + "gix-actor", + "gix-date", + "gix-error", +] + +[[package]] +name = "gix-merge" +version = "0.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72fad4279c940a0fa460ffdf3a3c0e48b7ca5ccb2b08f51a02b22ffcd1efb900" +dependencies = [ + "bstr", + "gix-command", + "gix-diff", + "gix-filter", + "gix-fs", + "gix-hash", + "gix-imara-diff", + "gix-index", + "gix-object", + "gix-path", + "gix-quote", + "gix-revision", + "gix-revwalk", + "gix-tempfile", + "gix-trace", + "gix-worktree", + "nonempty", + "thiserror", +] + +[[package]] +name = "gix-negotiate" +version = "0.35.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91068ecee956121d663635b873ae87ad9c5d3f2d6788facfd12829140b39c897" +dependencies = [ + "bitflags 2.13.2", + "gix-commitgraph", + "gix-date", + "gix-hash", + "gix-object", + "gix-revwalk", +] + +[[package]] +name = "gix-note" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9af6bbdb3f3c62b4920407c479af1cc0beb27fd75a762782d48baed53d330958" +dependencies = [ + "gix-error", + "gix-hash", + "gix-hashtable", + "gix-object", +] + +[[package]] +name = "gix-object" +version = "0.64.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56fef799ca40cdeab4de5a3e74a696d8fa9b9c6264592646bf022e026f13ce2c" +dependencies = [ + "bstr", + "gix-actor", + "gix-command", + "gix-date", + "gix-features", + "gix-hash", + "gix-hashtable", + "gix-tempfile", + "gix-utils", + "gix-validate", + "itoa", + "smallvec", + "thiserror", +] + +[[package]] +name = "gix-odb" +version = "0.84.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf45d195b71cb6363886e7b466821bf4dffd7aba1b6b814ff75488e0061d72a7" +dependencies = [ + "arc-swap", + "gix-features", + "gix-fs", + "gix-hash", + "gix-hashtable", + "gix-object", + "gix-pack", + "gix-path", + "gix-quote", + "gix-zlib", + "memmap2", + "parking_lot", + "tempfile", + "thiserror", +] + +[[package]] +name = "gix-pack" +version = "0.74.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d199d515cbdcf05f531f3859be9771fc12acac7b7fe0f5b581b2c1ab1c3a61e" +dependencies = [ + "clru", + "crossbeam-deque", + "gix-chunk", + "gix-error", + "gix-features", + "gix-hash", + "gix-hashtable", + "gix-object", + "gix-path", + "gix-tempfile", + "gix-zlib", + "memmap2", + "parking_lot", + "smallvec", + "thiserror", + "uluru", +] + +[[package]] +name = "gix-packetline" +version = "0.22.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "792bd92bea390087e6223b18d4d023decc36467de31e6b066b69b94beea1b9e2" +dependencies = [ + "bstr", + "faster-hex", + "gix-trace", + "thiserror", +] + +[[package]] +name = "gix-path" +version = "0.12.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38fc6f029ea67de83cbcbd33fd98c05a48360d2932b39d9fdacbc6eae802d475" +dependencies = [ + "bstr", + "gix-trace", + "gix-validate", + "thiserror", +] + +[[package]] +name = "gix-pathspec" +version = "0.20.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c92e44c63ba53bb55aa88ee48847664beae9446417621582fb14dfc69b2f8c72" +dependencies = [ + "bitflags 2.13.2", + "bstr", + "gix-attributes", + "gix-config-value", + "gix-glob", + "gix-path", + "thiserror", +] + +[[package]] +name = "gix-prompt" +version = "0.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "802256e13ecb2133ba5f9e6acbaa6b08bac027b1c5929f85f6adbb56ba3a4f28" +dependencies = [ + "gix-command", + "gix-config-value", + "parking_lot", + "rustix", + "thiserror", +] + +[[package]] +name = "gix-protocol" +version = "0.65.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68878c37ae168b474c762d70adc8a8e0f9323ed0d80444a672e2eb561fa16691" +dependencies = [ + "bstr", + "gix-credentials", + "gix-date", + "gix-features", + "gix-hash", + "gix-lock", + "gix-macros", + "gix-negotiate", + "gix-object", + "gix-ref", + "gix-refspec", + "gix-revwalk", + "gix-shallow", + "gix-trace", + "gix-transport", + "gix-utils", + "nonempty", + "thiserror", +] + +[[package]] +name = "gix-quote" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f74795eb76eab8313063849f9cbd2bbcdc6e4692f71c1d7d0244ab11cd777329" +dependencies = [ + "bstr", + "gix-error", + "gix-utils", +] + +[[package]] +name = "gix-ref" +version = "0.67.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8328387e7ab354e1dc3afb63e6b4d1866f82d7ce035222bc9d5baaf36bc88020" +dependencies = [ + "gix-actor", + "gix-features", + "gix-fs", + "gix-hash", + "gix-lock", + "gix-object", + "gix-path", + "gix-tempfile", + "gix-utils", + "gix-validate", + "memmap2", + "thiserror", +] + +[[package]] +name = "gix-refspec" +version = "0.45.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7de280d46e8fd9e4d3e7e2ab4276b965e377ba68b2b9a8fce56371015e8bb059" +dependencies = [ + "bstr", + "gix-hash", + "gix-validate", + "smallvec", + "thiserror", +] + +[[package]] +name = "gix-revision" +version = "0.49.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4577b864c3e134697e91564553e43230c2e401bb1bcc51cfa998edca21c95078" +dependencies = [ + "bitflags 2.13.2", + "bstr", + "gix-commitgraph", + "gix-date", + "gix-error", + "gix-hash", + "gix-hashtable", + "gix-object", + "gix-revwalk", + "gix-trace", + "nonempty", +] + +[[package]] +name = "gix-revwalk" +version = "0.35.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "248823eefe405e2c0754b74f6f43ab6faab68670cdbf2d6e114cb0471f766450" +dependencies = [ + "gix-commitgraph", + "gix-date", + "gix-error", + "gix-hash", + "gix-hashtable", + "gix-object", + "smallvec", + "thiserror", +] + +[[package]] +name = "gix-sec" +version = "0.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af4fe6c152c1d50aea36f299825702cd37e303307832fec1d0fdd5844e47ce2f" +dependencies = [ + "bitflags 2.13.2", + "gix-path", + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "gix-shallow" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ecc9f4b40537043e4bbd7d3d1760e74fb8e7b07a546166b558acaa73ad97f4a" +dependencies = [ + "bstr", + "gix-hash", + "gix-lock", + "nonempty", + "thiserror", +] + +[[package]] +name = "gix-status" +version = "0.34.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1401d871c01d82add5a9f654439b00722d0c632b332cd2cb63193f94327c8458" +dependencies = [ + "bstr", + "filetime", + "gix-diff", + "gix-dir", + "gix-features", + "gix-filter", + "gix-fs", + "gix-hash", + "gix-index", + "gix-object", + "gix-path", + "gix-pathspec", + "gix-worktree", + "hashbrown 0.16.1", + "portable-atomic", + "thiserror", + "windows-sys 0.61.2", +] + +[[package]] +name = "gix-submodule" +version = "0.34.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da85564d6725c483b8d95d7b31d1db0b78c29e462a2b481949e2f18e1ed55a6a" +dependencies = [ + "bstr", + "gix-config", + "gix-path", + "gix-pathspec", + "gix-refspec", + "gix-url", + "thiserror", +] + +[[package]] +name = "gix-tempfile" +version = "24.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b675b920bd5a61d17ad542772f03ec34c60feb8ff683e1560c03ae967363731e" +dependencies = [ + "dashmap", + "gix-fs", + "libc", + "parking_lot", + "signal-hook", + "signal-hook-registry", + "tempfile", +] + +[[package]] +name = "gix-trace" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be3eb81d9dc914335923e50d52829c551feefd6a72d176c4130c546b67a60814" + +[[package]] +name = "gix-transport" +version = "0.59.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b3f41a64939953ff49117df4eb91334d299abc59ff57a90fb2193d8ffa5886f1" +dependencies = [ + "base64 0.22.1", + "bstr", + "gix-command", + "gix-credentials", + "gix-features", + "gix-packetline", + "gix-path", + "gix-quote", + "gix-sec", + "gix-url", + "parking_lot", + "reqwest", + "thiserror", +] + +[[package]] +name = "gix-traverse" +version = "0.61.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9af3503668739f4de5dba57fe15cfd9adc443b08bcbbf195e5de16b648872245" +dependencies = [ + "bitflags 2.13.2", + "gix-commitgraph", + "gix-date", + "gix-hash", + "gix-hashtable", + "gix-object", + "gix-revwalk", + "smallvec", + "thiserror", +] + +[[package]] +name = "gix-url" +version = "0.38.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5bda80ccb4bc81fb9fb07a975916eb0c7a889bcbcb0c8a239c3f82a9cc2abdda" +dependencies = [ + "bstr", + "gix-path", + "gix-utils", + "percent-encoding", + "thiserror", +] + +[[package]] +name = "gix-utils" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0da1c46491b49458a446cc76f0085860f8164c2290742e0aa8c653ce67240a97" +dependencies = [ + "bstr", + "fastrand", + "getrandom 0.4.3", + "unicode-normalization", +] + +[[package]] +name = "gix-validate" +version = "0.11.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4dae8780f63ed8a803b8bdabbd7aa5f5c5d74592c8b50eed875c1bb4f6545a6a" +dependencies = [ + "bstr", +] + +[[package]] +name = "gix-worktree" +version = "0.56.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ed36b627476e2072c129900a17c977a38052b5497e27308159bc881fbf4eecf" +dependencies = [ + "bstr", + "gix-attributes", + "gix-features", + "gix-fs", + "gix-glob", + "gix-hash", + "gix-ignore", + "gix-index", + "gix-object", + "gix-path", + "gix-validate", +] + +[[package]] +name = "gix-worktree-state" +version = "0.34.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c14faa5b9527823c656a033e841dde11ca5b774f1bca7a9cdc23db677e55d56" +dependencies = [ + "bstr", + "gix-features", + "gix-filter", + "gix-fs", + "gix-index", + "gix-object", + "gix-path", + "gix-worktree", + "io-close", + "thiserror", +] + +[[package]] +name = "gix-worktree-stream" +version = "0.36.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "de5ec0ccbab39c9994656ea031ded8ffd90b370a3cc8e360fbe3c4ebe7c64964" +dependencies = [ + "gix-attributes", + "gix-error", + "gix-features", + "gix-filter", + "gix-fs", + "gix-hash", + "gix-object", + "gix-path", + "gix-traverse", + "parking_lot", +] + +[[package]] +name = "gix-zlib" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e8813f5579b3075ff9c90f7c59cd2b62b4ebb639361f0911648b22d7446cc7c" +dependencies = [ + "thiserror", + "zlib-rs", +] + +[[package]] +name = "h2" +version = "0.4.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d29020232d6aa3fb1daca64c1127cf662cf97f254ae16c18c05b8ab635fc118" +dependencies = [ + "atomic-waker", + "bytes", + "fnv", + "futures-core", + "futures-sink", + "http", + "indexmap", + "slab", + "tokio", + "tokio-util", + "tracing", +] + +[[package]] +name = "hash32" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d60b12902ba28e2730cd37e95b8c9223af2808df9e902d4df49588d1470606" +dependencies = [ + "byteorder", +] + +[[package]] +name = "hashbrown" +version = "0.14.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" + +[[package]] +name = "hashbrown" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" +dependencies = [ + "allocator-api2", + "equivalent", + "foldhash", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" +dependencies = [ + "allocator-api2", + "equivalent", + "foldhash", +] + +[[package]] +name = "heapless" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bfb9eb618601c89945a70e254898da93b13be0388091d42117462b265bb3fad" +dependencies = [ + "hash32", + "stable_deref_trait", +] + +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "human_format" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eaec953f16e5bcf6b8a3cb3aa959b17e5577dbd2693e94554c462c08be22624b" + +[[package]] +name = "hyper" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c3e324da4c95177d6291d4c8730197c0d1822f8a9766814a4a44fa5ab797c9c" +dependencies = [ + "atomic-waker", + "bytes", + "futures-channel", + "futures-core", + "h2", + "http", + "http-body", + "httparse", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", + "want", +] + +[[package]] +name = "hyper-rustls" +version = "0.27.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfa8e654703247911e29c23fbeaa261834bd9bb74efba2f9acddc37bfb127f53" +dependencies = [ + "http", + "hyper", + "hyper-util", + "rustls", + "tokio", + "tokio-rustls", + "tower-service", +] + +[[package]] +name = "hyper-util" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" +dependencies = [ + "base64 0.23.1", + "bytes", + "futures-channel", + "futures-util", + "http", + "http-body", + "httparse", + "hyper", + "ipnet", + "libc", + "percent-encoding", + "pin-project-lite", + "socket2", + "tokio", + "tower-service", + "tracing", +] + +[[package]] +name = "icu_collections" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa68d21081c4a05d5a901a1c62add574c77048b6a1c67be3b50ce0b60d4ca513" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d56e28588da92eee5c3201a6eff33fabdd49b62269c8938d4ff050ce4d900deb" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12f9cf5f235641ed274641dd81c3f28d870e276763d0797aeeab72317b1c646f" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1563da1ed3e0b3bf3d74c9b85917ac9c56464d2f57242270c09c9e752f8021a0" + +[[package]] +name = "icu_properties" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e7ca276ad3145661a65914e6daf131ca5120cd3dcee8f8f3214b8875184a148" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e590f038c1464a96894fd6d10127e90a8be4509f56ff7ecef851b15cee0b7caa" + +[[package]] +name = "icu_provider" +version = "2.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d27bbb9d3abbefac45d55f647c9de1d44aafcd1186eb91879afef17c396c3e73" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown 0.17.1", +] + +[[package]] +name = "io-close" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9cadcf447f06744f8ce713d2d6239bb5bde2c357a452397a9ed90c625da390bc" +dependencies = [ + "libc", + "winapi", +] + +[[package]] +name = "ipnet" +version = "2.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "jiff" +version = "0.2.38" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2b005715dcbeb0089a3c0dab99f2ff1cc3b2525323552703d648585d342a383" +dependencies = [ + "defmt 1.1.1", + "jiff-core", + "jiff-static", + "jiff-tzdb-platform", + "log", + "portable-atomic", + "portable-atomic-util", + "serde_core", + "windows-link", +] + +[[package]] +name = "jiff-core" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e52fe76043ccecc9005d2305ebaadf7d7fc0cc89ca6baa10a94d6bc68c7128c" +dependencies = [ + "defmt 1.1.1", + "log", +] + +[[package]] +name = "jiff-static" +version = "0.2.38" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2cc9817253cf7c7ee4684451bd327e88d6f3658014e54a29198625590650695c" +dependencies = [ + "jiff-core", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "jiff-tzdb" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa8377070c6bae868759445e5a77f66d84f0b72f3a054bfb00e6d038b8282da7" + +[[package]] +name = "jiff-tzdb-platform" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "875a5a69ac2bab1a891711cf5eccbec1ce0341ea805560dcd90b7a2e925132e8" +dependencies = [ + "jiff-tzdb", +] + +[[package]] +name = "jni" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498" +dependencies = [ + "cfg-if", + "combine", + "jni-macros", + "jni-sys", + "log", + "simd_cesu8", + "thiserror", + "walkdir", + "windows-link", +] + +[[package]] +name = "jni-macros" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a00109accc170f0bdb141fed3e393c565b6f5e072365c3bd58f5b062591560a3" +dependencies = [ + "proc-macro2", + "quote", + "rustc_version", + "simd_cesu8", + "syn 2.0.119", +] + +[[package]] +name = "jni-sys" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2" +dependencies = [ + "jni-sys-macros", +] + +[[package]] +name = "jni-sys-macros" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264" +dependencies = [ + "quote", + "syn 2.0.119", +] + +[[package]] +name = "jobserver" +version = "0.1.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3" +dependencies = [ + "getrandom 0.4.3", + "libc", +] + +[[package]] +name = "js-sys" +version = "0.3.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7883d941dae510fb2d978fc3fe018c71c9e2892fd38854de3e8b92c2e5ad9cc5" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "lazy_static" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" + +[[package]] +name = "libc" +version = "0.2.190" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce5d3ddc6d3fa000eb1536d85e147bfe31aacaba692ed6a876f95cb7c855be78" + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" + +[[package]] +name = "lru-slab" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4050469837a6ff301cd14c1f8f24f88549e6d548f24f64e2148eb0f72cebc51f" + +[[package]] +name = "matchers" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9" +dependencies = [ + "regex-automata", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "memmap2" +version = "0.9.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1219ed1b7f229ee7104d281dd01d6802fe28bb6e95d292942c4daacdeb798c0" +dependencies = [ + "libc", +] + +[[package]] +name = "mime" +version = "0.3.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" + +[[package]] +name = "mio" +version = "1.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee" +dependencies = [ + "libc", + "wasi", + "windows-sys 0.61.2", +] + +[[package]] +name = "multiversion_no_op" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "743fb55ba31b18fb1ecef6bdc9aa2743314978ac084044301a7eee33fb99a20d" + +[[package]] +name = "nonempty" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9737e026353e5cd0736f98eddae28665118eb6f6600902a7f50db585621fecb6" + +[[package]] +name = "nu-ansi-term" +version = "0.50.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "num-conv" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "openssl-probe" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe" + +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "smallvec", + "windows-link", +] + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "pkg-config" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" [[package]] -name = "cfg-if" -version = "1.0.5" +name = "portable-atomic" +version = "1.15.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" +checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" [[package]] -name = "crossbeam-channel" -version = "0.5.17" +name = "portable-atomic-util" +version = "0.2.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "98b0cc327b5bc766e7fda9c9260cc0fa81b43a8e240440422dff70788e3f9ef1" +checksum = "10ab3eb7f3becc3a1cbc4f2c6f20267996cfc1a6467a873763411b136a122715" dependencies = [ - "crossbeam-utils", + "portable-atomic", ] [[package]] -name = "crossbeam-utils" -version = "0.8.23" +name = "potential_utf" +version = "0.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "zerovec", +] [[package]] -name = "deranged" -version = "0.5.8" +name = "powerfmt" +version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c" +checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958" + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" dependencies = [ - "powerfmt", + "unicode-ident", ] [[package]] -name = "equivalent" -version = "1.0.2" +name = "prodash" +version = "31.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" +checksum = "cf52d87428247c5aa3760ac8e7d8b13ec7b3579b955a8c3f311668b6860acba5" +dependencies = [ + "bytesize", + "human_format", + "parking_lot", +] [[package]] -name = "errno" -version = "0.3.14" +name = "quinn" +version = "0.11.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +checksum = "4051e23e9185c255a7e33ef59cdbca87a22d359052eecd22fc6b901fb37d9d11" dependencies = [ - "libc", - "windows-sys", + "bytes", + "cfg_aliases", + "pin-project-lite", + "quinn-proto", + "quinn-udp", + "rustc-hash", + "rustls", + "socket2", + "thiserror", + "tokio", + "tracing", + "web-time", ] [[package]] -name = "hashbrown" -version = "0.17.1" +name = "quinn-proto" +version = "0.11.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" +checksum = "0e750cca55fe4f0439a15d0bb529da9651e79993e8e72c61a899a36d462befbe" +dependencies = [ + "aws-lc-rs", + "bytes", + "getrandom 0.4.3", + "lru-slab", + "rand", + "rand_pcg", + "ring", + "rustc-hash", + "rustls", + "rustls-pki-types", + "slab", + "thiserror", + "tinyvec", + "tracing", + "web-time", +] [[package]] -name = "indexmap" -version = "2.14.2" +name = "quinn-udp" +version = "0.5.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +checksum = "af66907df18639dcf4db56ca65490cabc4b27a97dbadd96f2926cca73298f016" dependencies = [ - "equivalent", - "hashbrown", + "cfg_aliases", + "libc", + "once_cell", + "socket2", + "tracing", + "windows-sys 0.61.2", ] [[package]] -name = "itoa" -version = "1.0.18" +name = "quote" +version = "1.0.47" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] [[package]] -name = "lazy_static" -version = "1.5.0" +name = "r-efi" +version = "6.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" [[package]] -name = "libc" -version = "0.2.189" +name = "rand" +version = "0.10.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" +checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af" +dependencies = [ + "chacha20", + "getrandom 0.4.3", + "rand_core", +] [[package]] -name = "log" -version = "0.4.34" +name = "rand_core" +version = "0.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" [[package]] -name = "matchers" -version = "0.2.0" +name = "rand_pcg" +version = "0.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9" +checksum = "caa0f4137e1c0a72f4c651489402276c8e8e1cf081f3b0ba156d2cbeef09e86a" +dependencies = [ + "rand_core", +] + +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags 2.13.2", +] + +[[package]] +name = "regex" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d" dependencies = [ + "aho-corasick", + "memchr", "regex-automata", + "regex-syntax", ] [[package]] -name = "memchr" -version = "2.8.3" +name = "regex-automata" +version = "0.4.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] [[package]] -name = "mio" -version = "1.2.3" +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + +[[package]] +name = "reqwest" +version = "0.13.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16a1cfa75cc186dd73d5818e510e042e40927bccc9c236b061cea97e1eb08029" +dependencies = [ + "base64 0.23.1", + "bytes", + "encoding_rs", + "futures-channel", + "futures-core", + "futures-util", + "h2", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-rustls", + "hyper-util", + "js-sys", + "log", + "mime", + "percent-encoding", + "pin-project-lite", + "quinn", + "rustls", + "rustls-pki-types", + "rustls-platform-verifier", + "sync_wrapper", + "tokio", + "tokio-rustls", + "tower", + "tower-http", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[package]] +name = "ring" +version = "0.17.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4b18443e9c262bfe8fa82f51666e2642c53393f7e5c27b3e1aeab922cff5b9d8" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", "libc", - "wasi", - "windows-sys", + "untrusted", + "windows-sys 0.52.0", ] [[package]] -name = "nu-ansi-term" -version = "0.50.3" +name = "rustc-hash" +version = "2.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" +checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" + +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" dependencies = [ - "windows-sys", + "semver", ] [[package]] -name = "num-conv" -version = "0.1.0" +name = "rustix" +version = "1.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "51d515d32fb182ee37cda2ccdcb92950d6a3c2893aa280e540671c2cd0f3b1d9" +checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d" +dependencies = [ + "bitflags 2.13.2", + "errno", + "libc", + "linux-raw-sys", + "windows-sys 0.61.2", +] [[package]] -name = "once_cell" -version = "1.21.4" +name = "rustls" +version = "0.23.45" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" +checksum = "0d41d731c7d2f962d1ccc364cec258de3c0e93b38c2fb3ba97ac74513048d634" +dependencies = [ + "aws-lc-rs", + "once_cell", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] [[package]] -name = "pin-project-lite" -version = "0.2.17" +name = "rustls-native-certs" +version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" +checksum = "dab5152771c58876a2146916e53e35057e1a4dfa2b9df0f0305b07f611fdea4d" +dependencies = [ + "openssl-probe", + "rustls-pki-types", + "schannel", + "security-framework", +] [[package]] -name = "powerfmt" +name = "rustls-pki-types" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" +dependencies = [ + "web-time", + "zeroize", +] + +[[package]] +name = "rustls-platform-verifier" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1167586491e2b18b8bfbb293e8180ec17c201c4f076d7cb3070ca964e7598f98" +dependencies = [ + "core-foundation", + "core-foundation-sys", + "jni", + "log", + "once_cell", + "rustls", + "rustls-native-certs", + "rustls-platform-verifier-android", + "rustls-webpki", + "security-framework", + "security-framework-sys", + "webpki-root-certs", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls-platform-verifier-android" version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" +checksum = "eec689c0bc40ff2458a5977b6619cb718087084a18e02a131c599b62d05e1a5f" [[package]] -name = "proc-macro2" -version = "1.0.107" +name = "rustls-webpki" +version = "0.103.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2" dependencies = [ - "unicode-ident", + "aws-lc-rs", + "ring", + "rustls-pki-types", + "untrusted", ] [[package]] -name = "quote" -version = "1.0.47" +name = "rustversion" +version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" dependencies = [ - "proc-macro2", + "winapi-util", ] [[package]] -name = "regex-automata" -version = "0.4.18" +name = "schannel" +version = "0.1.29" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +checksum = "91c1b7e4904c873ef0710c1f407dde2e6287de2bebc1bbbf7d430bb7cbffd939" dependencies = [ - "aho-corasick", - "memchr", - "regex-syntax", + "windows-sys 0.61.2", ] [[package]] -name = "regex-syntax" -version = "0.8.11" +name = "scopeguard" +version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "security-framework" +version = "3.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" +dependencies = [ + "bitflags 2.13.2", + "core-foundation", + "core-foundation-sys", + "libc", + "security-framework-sys", +] + +[[package]] +name = "security-framework-sys" +version = "2.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" [[package]] name = "serde" @@ -249,6 +2582,27 @@ dependencies = [ "serde_core", ] +[[package]] +name = "sha1" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "digest", +] + +[[package]] +name = "sha1-checked" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "89f599ac0c323ebb1c6082821a54962b839832b03984598375bff3975b804423" +dependencies = [ + "digest", + "sha1", +] + [[package]] name = "sharded-slab" version = "0.1.7" @@ -258,6 +2612,22 @@ dependencies = [ "lazy_static", ] +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "signal-hook" +version = "0.4.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b29ffa27d3d59a049bb328258de100f8012848d1b08d444e08bbc02ac468435e" +dependencies = [ + "libc", + "signal-hook-registry", +] + [[package]] name = "signal-hook-registry" version = "1.4.8" @@ -268,6 +2638,28 @@ dependencies = [ "libc", ] +[[package]] +name = "simd_cesu8" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11031e251abf8611c80f460e19dbdeb54a66db918e49c65a7065b46ac7aec520" +dependencies = [ + "rustc_version", + "simdutf8", +] + +[[package]] +name = "simdutf8" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + [[package]] name = "smallvec" version = "1.16.2" @@ -281,7 +2673,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" dependencies = [ "libc", - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -289,6 +2681,7 @@ name = "software-core" version = "0.1.0" dependencies = [ "bytes", + "gix", "serde", "thiserror", "tokio", @@ -297,6 +2690,12 @@ dependencies = [ "tracing-subscriber", ] +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + [[package]] name = "station" version = "0.1.0" @@ -310,6 +2709,12 @@ dependencies = [ "tracing-subscriber", ] +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + [[package]] name = "symlink" version = "0.1.0" @@ -320,22 +2725,55 @@ checksum = "a7973cce6668464ea31f176d85b13c7ab3bba2cb3b77a2ed26abd7801688010a" name = "syn" version = "2.0.119" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8593e8e72159ed2257d083c7a454a85cbf854f37a0966d8d483aff8c8a3ebcee" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" +dependencies = [ + "futures-core", +] + +[[package]] +name = "synstructure" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" dependencies = [ "proc-macro2", "quote", - "unicode-ident", + "syn 3.0.6", ] [[package]] -name = "syn" -version = "3.0.6" +name = "tempfile" +version = "3.27.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8593e8e72159ed2257d083c7a454a85cbf854f37a0966d8d483aff8c8a3ebcee" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" dependencies = [ - "proc-macro2", - "quote", - "unicode-ident", + "fastrand", + "getrandom 0.4.3", + "once_cell", + "rustix", + "windows-sys 0.61.2", ] [[package]] @@ -369,12 +2807,11 @@ dependencies = [ [[package]] name = "time" -version = "0.3.45" +version = "0.3.55" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f9e442fc33d7fdb45aa9bfeb312c095964abdf596f7567261062b2a7107aaabd" +checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134" dependencies = [ "deranged", - "itoa", "num-conv", "powerfmt", "serde_core", @@ -384,33 +2821,50 @@ dependencies = [ [[package]] name = "time-core" -version = "0.1.7" +version = "0.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b36ee98fd31ec7426d599183e8fe26932a8dc1fb76ddb6214d05493377d34ca" +checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" [[package]] name = "time-macros" -version = "0.2.25" +version = "0.2.32" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "71e552d1249bf61ac2a52db88179fd0673def1e1ad8243a00d9ec9ed71fee3dd" +checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85" dependencies = [ "num-conv", "time-core", ] +[[package]] +name = "tinystr" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1e27c91459209c2986af3dcf603a5a74a4368754ce37414f59acc971167f643" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tinyvec" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" + [[package]] name = "tokio" -version = "1.53.1" +version = "1.53.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "202caea871b69668250d242070849eb495be178ed697a3e98aebce5bc81a0bed" +checksum = "e95f91fcc7a621e8b030f6aa23c71fe9838ae2fb4d8118b75602a328f5144044" dependencies = [ + "bytes", "libc", "mio", "pin-project-lite", "signal-hook-registry", "socket2", "tokio-macros", - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -424,6 +2878,30 @@ dependencies = [ "syn 3.0.6", ] +[[package]] +name = "tokio-rustls" +version = "0.26.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9cc2678c2cdd569ef8215e2afd7954ada2ae20b4fdd2c5fe6139a3b02d105db" +dependencies = [ + "rustls", + "tokio", +] + +[[package]] +name = "tokio-util" +version = "0.7.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "494815d09bf52b5548659851081238f0ca39ff638363907596da739561c62c52" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "libc", + "pin-project-lite", + "tokio", +] + [[package]] name = "toml" version = "0.9.12+spec-1.1.0" @@ -463,6 +2941,51 @@ version = "1.1.2+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7d56353a2a665ad0f41a421187180aab746c8c325620617ad883a99a1cbe66d2" +[[package]] +name = "tower" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper", + "tokio", + "tower-layer", + "tower-service", +] + +[[package]] +name = "tower-http" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" +dependencies = [ + "bitflags 2.13.2", + "bytes", + "futures-util", + "http", + "http-body", + "pin-project-lite", + "tower", + "tower-layer", + "tower-service", + "url", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + [[package]] name = "tracing" version = "0.1.44" @@ -550,30 +3073,240 @@ dependencies = [ "tracing-serde", ] +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "uluru" +version = "3.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7c8a2469e56e6e5095c82ccd3afb98dad95f7af7929aab6d8ba8d6e0f73657da" +dependencies = [ + "arrayvec", +] + +[[package]] +name = "unicode-bom" +version = "2.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7eec5d1121208364f6793f7d2e222bf75a915c19557537745b195b253dd64217" + [[package]] name = "unicode-ident" version = "1.0.26" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954" +[[package]] +name = "unicode-normalization" +version = "0.1.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5fd4f6878c9cb28d874b009da9e8d183b5abc80117c40bbd187a1fde336be6e8" +dependencies = [ + "tinyvec", +] + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "utf8_iter" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" + [[package]] name = "valuable" version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "walkdir" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" +dependencies = [ + "same-file", + "winapi-util", +] + +[[package]] +name = "want" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec4cdd0dd910afe868b7ef477227d8d538b46b3075031afee8a9f2acb0a2ed0b" +dependencies = [ + "try-lock", +] + [[package]] name = "wasi" version = "0.11.1+wasi-snapshot-preview1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" +[[package]] +name = "wasm-bindgen" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9bb54f33acc68fd454578d9820b0bde1a1a3d17aa17bb7b6595806d02886d409" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.79" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3cbab34de2d982e9b48e18d216d04c4a6f641066ff19ffb699980f591ee3610e" +dependencies = [ + "js-sys", + "tokio", + "wasm-bindgen", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e29d0c35b16e224a7eeb5cd2d25e3e1968fbd65604117b44d3b789d00ee8535" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f501a8bc3719dba86ef8ae4728879c08001bea749eb1333ac5b91e040e2a6b7" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.6", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23f0c9c52aa7cd7d77769a4cfe2a9adb1b331f489a41d912ce14513d5ab995c6" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "web-sys" +version = "0.3.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88261b9deccee56594c11a3460c462c41f58d148598fe70ad77070126a68aba4" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "web-time" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "webpki-root-certs" +version = "1.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b96554aa2acc8ccdb7e1c9a58a7a68dd5d13bccc69cd124cb09406db612a1c9b" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + +[[package]] +name = "winapi-util" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + [[package]] name = "windows-link" version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + [[package]] name = "windows-sys" version = "0.61.2" @@ -583,6 +3316,70 @@ dependencies = [ "windows-link", ] +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + [[package]] name = "winnow" version = "0.7.15" @@ -595,6 +3392,101 @@ version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81" +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + +[[package]] +name = "yoke" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", + "synstructure", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", + "synstructure", +] + +[[package]] +name = "zeroize" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb0464e17806c1d976d5cba29399c7f08e516e279e2ba493f63123b5fca67dd8" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34df6fc39dbd26ddc9c10e6a2984476e13acce22e64e4487636ef494369225da" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "zlib-rs" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112" + [[package]] name = "zmij" version = "1.0.23" diff --git a/backend/Cargo.toml b/backend/Cargo.toml index d9aeeb64e..bc5d0e4cd 100644 --- a/backend/Cargo.toml +++ b/backend/Cargo.toml @@ -5,7 +5,7 @@ default-members = ["crates/station"] [workspace.package] edition = "2024" -rust-version = "1.85" +rust-version = "1.98" license = "MIT" authors = [ "Hyperloop UPV Software Subsystem", diff --git a/backend/crates/core/Cargo.toml b/backend/crates/core/Cargo.toml index 1b38a623e..878c62e3c 100644 --- a/backend/crates/core/Cargo.toml +++ b/backend/crates/core/Cargo.toml @@ -29,6 +29,7 @@ tracing.workspace = true tokio = { workspace = true, optional = true } tracing-subscriber = { workspace = true, optional = true } tracing-appender = { workspace = true, optional = true } +gix = { version = "0.87.1", features = ["blocking-http-transport-reqwest-rust-tls"] } # `workspace = true` can't be combined with extra lints in the same table, # so the workspace list is repeated here with `missing_docs` added: this is From 253672787952e922f3cff66444686877f0949504 Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Wed, 7 Oct 2026 14:43:45 +0200 Subject: [PATCH 019/225] feat: NTP readme --- backend/crates/core/src/ntp/README.md | 31 +++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 backend/crates/core/src/ntp/README.md diff --git a/backend/crates/core/src/ntp/README.md b/backend/crates/core/src/ntp/README.md new file mode 100644 index 000000000..8fcaf15fa --- /dev/null +++ b/backend/crates/core/src/ntp/README.md @@ -0,0 +1,31 @@ +# NTP module + +NTP (**Network Time Protocol**) is a protocol used to synchronize clocks between devices over a network. In this project, it is used to synchronize the boards in the pod. + +There are two related concepts worth mentioning: + +- **SNTP (Simple Network Time Protocol):** a simplified subset of NTP intended for simpler synchronization scenarios, such as clients using a single time server. +- **NTS (Network Time Security):** an extension to NTP that adds authentication and cryptographic security to time synchronization. + +The boards in this project use **SNTP**. However, this module implements an **NTP server**, since NTP and SNTP use compatible protocol messages and are interoperable. An SNTP client can therefore communicate with this NTP server as defined by RFC 5905. + +## Implementation + +The server is implemented using the [`ntp_usg-server`](https://crates.io/crates/ntp_usg-server) crate with the **Tokio** runtime. + +The crate handles the NTP protocol logic, including request parsing and response generation, while this module is responsible for configuring and starting the server. + +The server interface and port can be configured when starting it. By default, the server listens on: + +- Interface: `0.0.0.0` +- Port: `8123` + +The standard NTP port is `123`, but this project uses `8123` as its default port. + +## Documentation + +The module documentation can be generated and opened with: + +```bash +cargo doc --open -p software-core -F ntp +``` \ No newline at end of file From e48d73b9321ea42cfbedfb04a97f327b9b28dcd3 Mon Sep 17 00:00:00 2001 From: Gazi Al Saad Halawani Date: Thu, 8 Oct 2026 22:20:45 +0200 Subject: [PATCH 020/225] Feat(backend): Added Protection PacketKind. Made load_board public so it can be used in new tests. Added comments and changed implementation of protection ID asignation and bit mapping. Created two tests as requested (review this as Gemini was used) --- backend/crates/core/src/adj/raw/loader.rs | 10 ++-- backend/crates/core/src/adj/raw/types.rs | 64 +++++++++++++++++++++++ backend/crates/core/src/model/board.rs | 2 + 3 files changed, 73 insertions(+), 3 deletions(-) diff --git a/backend/crates/core/src/adj/raw/loader.rs b/backend/crates/core/src/adj/raw/loader.rs index 0cf05aa66..688f731d8 100644 --- a/backend/crates/core/src/adj/raw/loader.rs +++ b/backend/crates/core/src/adj/raw/loader.rs @@ -48,7 +48,7 @@ fn read_json(path: &Path) -> Result { }) } -fn load_board(root: &Path, name: &str, rel_path: &str) -> Result { +pub fn load_board(root: &Path, name: &str, rel_path: &str) -> Result { let board_file = root.join(rel_path); let raw_board: RawBoard = read_json(&board_file)?; let board_dir = board_file @@ -71,12 +71,16 @@ fn load_board(root: &Path, name: &str, rel_path: &str) -> Result Result { #[cfg(test)] mod tests { + use crate::adj::raw::loader::load_board; + use crate::model::PacketKind; use super::*; fn raw_protection( @@ -495,4 +497,66 @@ mod tests { )) } + #[test] + fn protection_id_generation_matches_specification() { + // Base measurement ID = 512 (Binary: 00000 0100 0000 0000) + let measurement_id: u16 = 512; + + // Test for the first protection index (idx = 0 -> pos = 1) + let idx_0: usize = 0; + let pos_1 = idx_0 as u16 + 1; + let id_0 = (pos_1 << 13) | measurement_id; + + // Expected binary pattern: [pos=001][measurement_id=0000001000000] + // 0b001_0000001000000 = 8704 + assert_eq!(id_0, 8704, "First protection packet ID must pack pos=1 into the high bits"); + + // Test for the seventh protection index (idx = 6 -> pos = 7) + let idx_6: usize = 6; + let pos_7 = idx_6 as u16 + 1; + let id_6 = (pos_7 << 13) | measurement_id; + + // Expected binary pattern: [pos=111][measurement_id=0000001000000] + // 0b111_0000001000000 = 57856 + assert_eq!(id_6, 57856, "Seventh protection packet ID must pack pos=7 into the high bits"); + } + + #[test] + fn board_incorporates_synthetic_protection_packets() { + // Arrange: Create a temporary environment or setup standard board mocks + let temp_dir = std::env::temp_dir(); + let board_name = "H12_Test_Board"; + let rel_path = "test_board.json"; + + // Ensure you create valid mock JSON configuration files in temp_dir representing: + // 1. `test_board.json` (containing 1 measurement path and 1 packet path) + // 2. A measurement file containing 1 measurement (ID: 100) with exactly 2 protections. + // 3. A packet file containing 0 standard packets to cleanly isolate the test. + + // Act + let result = load_board(&temp_dir, board_name, rel_path); + + // Assert + assert!(result.is_ok(), "Board loading failed: {:?}", result.err()); + let board = result.unwrap(); + + // Since we provided 0 standard packets and 2 protections, + // the total synthetic packets injected into the board must equal 2. + let protection_packets: Vec<_> = board.packets + .iter() + .filter(|p| p.kind == PacketKind::Protection) + .collect(); + + assert_eq!(protection_packets.len(), 2, "Board should contain exactly 2 protection packets"); + + // Verify the bit-packed properties of the injected synthetic packets + // For protection index 0 (pos = 1): (1 << 13) | 100 = 8192 | 100 = 8292 + assert_eq!(protection_packets[0].id, AdjId(8292)); + assert_eq!(protection_packets[0].name, format!("{}_mock_alias_protection_1", board_name)); + + // For protection index 1 (pos = 2): (2 << 13) | 100 = 16384 | 100 = 16484 + assert_eq!(protection_packets[1].id, AdjId(16484)); + assert_eq!(protection_packets[1].name, format!("{}_mock_alias_protection_2", board_name)); + } + } diff --git a/backend/crates/core/src/model/board.rs b/backend/crates/core/src/model/board.rs index ceb25b0e0..f5d2ad025 100644 --- a/backend/crates/core/src/model/board.rs +++ b/backend/crates/core/src/model/board.rs @@ -18,6 +18,8 @@ use std::net::IpAddr; pub enum PacketKind { /// Measurements sent by a board. Data, + /// Measurement with a protection. + Protection, /// An order sent to a board. Order, } From 2c69cd61d3a348eefe14b5a4cd62319b6b4c0137 Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Thu, 8 Oct 2026 23:51:58 +0200 Subject: [PATCH 021/225] fix(backend, model): add missing type message --- backend/crates/core/src/model/board.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/backend/crates/core/src/model/board.rs b/backend/crates/core/src/model/board.rs index f5d2ad025..1dd36927b 100644 --- a/backend/crates/core/src/model/board.rs +++ b/backend/crates/core/src/model/board.rs @@ -18,10 +18,12 @@ use std::net::IpAddr; pub enum PacketKind { /// Measurements sent by a board. Data, - /// Measurement with a protection. + /// Protection associated with a measurement. Protection, /// An order sent to a board. Order, + /// A message sent by a board. + Message, } /// The declaration of a single packet a board can send or receive, as From 3b7275e538293c72551d647114b37eb1a82a89d9 Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Thu, 8 Oct 2026 23:52:23 +0200 Subject: [PATCH 022/225] docs(backend, adj): correction to docs --- backend/crates/core/src/adj.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/backend/crates/core/src/adj.rs b/backend/crates/core/src/adj.rs index 3053f76b9..3966e677d 100644 --- a/backend/crates/core/src/adj.rs +++ b/backend/crates/core/src/adj.rs @@ -2,8 +2,7 @@ //! [`crate::model::PodData`], plus backend-session metadata not modeled as //! vehicle data ([`crate::adj::AdjInfo`]). //! -//! Loading (not downloading — see `core::git` for that, a sibling module -//! this one is a client of) is not specific to `station`: a sniffer, a +//! Loading (and if `git` feature is enabled also downloading) is not specific to `station`: a sniffer, a //! simulator, or any other tool that reads an ADJ needs exactly the same //! parsing. Scope for this iteration: no `sockets.json`, no //! `period`/`period_type`/`socket` packet fields (matches From fc40b4f0dc38c2280f5f9c8de821535d572746a6 Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Fri, 9 Oct 2026 01:11:57 +0200 Subject: [PATCH 023/225] feat: use serde --- backend/Cargo.toml | 1 + backend/crates/core/Cargo.toml | 1 + 2 files changed, 2 insertions(+) diff --git a/backend/Cargo.toml b/backend/Cargo.toml index d9aeeb64e..41c26b843 100644 --- a/backend/Cargo.toml +++ b/backend/Cargo.toml @@ -21,6 +21,7 @@ software-core = { path = "crates/core" } bytes = "1" serde = { version = "1", features = ["derive"] } +serde_json = "1" thiserror = "2" tokio = { version = "1", features = ["rt-multi-thread", "macros", "net", "sync", "time", "signal"] } toml = "0.9" diff --git a/backend/crates/core/Cargo.toml b/backend/crates/core/Cargo.toml index 1b38a623e..553b6996d 100644 --- a/backend/crates/core/Cargo.toml +++ b/backend/crates/core/Cargo.toml @@ -24,6 +24,7 @@ trace = ["dep:tracing-subscriber", "dep:tracing-appender"] [dependencies] bytes.workspace = true serde.workspace = true +serde_json.workspace = true thiserror.workspace = true tracing.workspace = true tokio = { workspace = true, optional = true } From d4524adea8edcd1c6df3a8a3d09db14f0077ff37 Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Fri, 9 Oct 2026 01:12:46 +0200 Subject: [PATCH 024/225] feat(backend, adj):include board id inside ach packet --- backend/crates/core/src/model/board.rs | 42 ++++++++++++++++++-------- 1 file changed, 30 insertions(+), 12 deletions(-) diff --git a/backend/crates/core/src/model/board.rs b/backend/crates/core/src/model/board.rs index 1dd36927b..00f0cce18 100644 --- a/backend/crates/core/src/model/board.rs +++ b/backend/crates/core/src/model/board.rs @@ -11,6 +11,7 @@ //! shape is settled. use super::{AdjId, BoardId, MacAddress, Measurement}; +use std::collections::HashMap; use std::net::IpAddr; /// What kind of packet a [`PacketDef`] declares. @@ -35,6 +36,12 @@ pub enum PacketKind { pub struct PacketDef { /// The packet's numeric ADJ id. pub id: AdjId, + /// The board this packet belongs to. A `PacketDef` is always reached + /// through its owning [`Board`] already, but carrying the id here too + /// means anything holding just a `&PacketDef` (e.g. a lookup table + /// indexed by [`AdjId`]) knows which board it is without a second, + /// separate index back to it. + pub board: BoardId, /// The human-readable name shown to the user. pub name: String, /// Whether this is data or an order. @@ -54,16 +61,20 @@ pub struct Board { pub ip: IpAddr, /// The board's MAC address (ADJv3 spec, section 5). pub mac: MacAddress, - /// The packets this board can send or receive. - pub packets: Vec, + /// The packets this board can send or receive, keyed by id — same + /// reasoning as [`PodData::boards`], the ADJ gives this list no + /// meaningful order either. + pub packets: HashMap, } /// The whole vehicle, as described by the ADJ: every board and every /// packet each one can send or receive. #[derive(Debug, Clone, PartialEq, Default)] pub struct PodData { - /// Every board of the vehicle. - pub boards: Vec, + /// Every board of the vehicle, keyed by its id — the ADJ doesn't give + /// boards any meaningful order, so iterating this in some particular + /// sequence is never something to rely on. + pub boards: HashMap, } #[cfg(test)] @@ -95,17 +106,24 @@ mod tests { name: "BCU".to_string(), ip: IpAddr::from([192, 168, 0, 10]), mac: MacAddress([0x00, 0x11, 0x22, 0x33, 0x44, 0x55]), - packets: vec![PacketDef { - id: AdjId(1000), - name: "bcu_data".to_string(), - kind: PacketKind::Data, - measurements: vec![sample_measurement()], - }], + packets: HashMap::from([( + AdjId(1000), + PacketDef { + id: AdjId(1000), + board: BoardId(1), + name: "bcu_data".to_string(), + kind: PacketKind::Data, + measurements: vec![sample_measurement()], + }, + )]), }; assert_eq!(board.packets.len(), 1); - assert_eq!(board.packets[0].measurements.len(), 1); - assert_eq!(board.packets[0].kind, PacketKind::Data); + let Some(packet) = board.packets.get(&AdjId(1000)) else { + unreachable!("the packet we just inserted should be there"); + }; + assert_eq!(packet.measurements.len(), 1); + assert_eq!(packet.kind, PacketKind::Data); assert_eq!(board.mac.to_string(), "00:11:22:33:44:55"); } } From cdf63977ecc00d7136303bf838e02df8c8874ee7 Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Fri, 9 Oct 2026 01:13:09 +0200 Subject: [PATCH 025/225] docs(backend, adj): update docs --- backend/crates/core/src/adj/error.rs | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/backend/crates/core/src/adj/error.rs b/backend/crates/core/src/adj/error.rs index 73d7174dd..6e173fce1 100644 --- a/backend/crates/core/src/adj/error.rs +++ b/backend/crates/core/src/adj/error.rs @@ -61,7 +61,7 @@ pub enum LoadError { board: String, }, - /// A packet or order declares a `type` other than `"data"` or `"order"`. + /// A packet or order declares a `type` other than `"data", `"order"`, `"message"` or `"protection"`. #[error("board {board:?}, packet {name:?}: unknown packet type {type_name:?}")] UnknownPacketType { /// The board the packet belongs to. @@ -100,10 +100,12 @@ pub enum LoadError { /// An error converting a raw measurement into [`crate::model::Measurement`]. #[derive(Debug, thiserror::Error)] pub enum MeasurementError { - - /// The measurement has more than 7 protections + /// The measurement has more than 7 protections. #[error("measurement has {count} protections, maximum allowed is 7")] - TooManyProtections {count: usize}, + TooManyProtections { + /// How many protections were declared. + count: usize, + }, /// The measurement's `type` isn't a recognized wire type, `"bool"` or /// `"enum"`. From 719c108a0fd9229e4deaefeac8972653b75190f9 Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Fri, 9 Oct 2026 01:14:03 +0200 Subject: [PATCH 026/225] feat: adj final version --- backend/Cargo.lock | 1 + backend/crates/core/src/adj/raw/loader.rs | 89 ++++++++------ backend/crates/core/src/adj/raw/types.rs | 134 +++++++++++++--------- 3 files changed, 129 insertions(+), 95 deletions(-) diff --git a/backend/Cargo.lock b/backend/Cargo.lock index 94186abdf..f911ba9d8 100644 --- a/backend/Cargo.lock +++ b/backend/Cargo.lock @@ -290,6 +290,7 @@ version = "0.1.0" dependencies = [ "bytes", "serde", + "serde_json", "thiserror", "tokio", "tracing", diff --git a/backend/crates/core/src/adj/raw/loader.rs b/backend/crates/core/src/adj/raw/loader.rs index 688f731d8..4e18f30de 100644 --- a/backend/crates/core/src/adj/raw/loader.rs +++ b/backend/crates/core/src/adj/raw/loader.rs @@ -15,20 +15,16 @@ use std::path::Path; /// Loads an ADJ directory rooted at `path` (containing `general_info.json` /// and `boards.json`) into an [`Adj`]. /// -/// Boards are read in alphabetical order by name — not `boards.json`'s own -/// unordered map order — so [`PodData::boards`] is deterministic. A board -/// present on disk but absent from `boards.json` is never read; that isn't -/// an error. +/// A board present on disk but absent from `boards.json` is never read; +/// that isn't an error. pub fn load_from_dir(path: &Path) -> Result { let general_info: RawGeneralInfo = read_json(&path.join("general_info.json"))?; let board_paths: HashMap = read_json(&path.join("boards.json"))?; - let mut entries: Vec<(&String, &String)> = board_paths.iter().collect(); - entries.sort_by_key(|(name, _)| *name); - - let mut boards = Vec::with_capacity(entries.len()); - for (name, rel_path) in entries { - boards.push(load_board(path, name, rel_path)?); + let mut boards = HashMap::new(); + for (name, rel_path) in &board_paths { + let board = load_board(path, name, rel_path)?; + boards.insert(board.id, board); } Ok(Adj { @@ -37,6 +33,8 @@ pub fn load_from_dir(path: &Path) -> Result { }) } +/// Reads a JSON file at `path` and deserializes it into `T`, returning a +/// [`LoadError`] on failure. fn read_json(path: &Path) -> Result { let text = fs::read_to_string(path).map_err(|source| LoadError::ReadFile { path: path.to_path_buf(), @@ -48,16 +46,18 @@ fn read_json(path: &Path) -> Result { }) } -pub fn load_board(root: &Path, name: &str, rel_path: &str) -> Result { +pub(crate) fn load_board(root: &Path, name: &str, rel_path: &str) -> Result { + // Read the board's JSON, then its measurements and packets, and build a `Board` from it let board_file = root.join(rel_path); let raw_board: RawBoard = read_json(&board_file)?; + let board_id = BoardId(raw_board.board_id); let board_dir = board_file .parent() .map(Path::to_path_buf) .unwrap_or_else(|| root.to_path_buf()); let mut measurements: HashMap = HashMap::new(); - let mut protection_packets: Vec = Vec::new(); + let mut packets: HashMap = HashMap::new(); for measurements_path in &raw_board.measurements { let raws: Vec = read_json(&board_dir.join(measurements_path))?; @@ -70,35 +70,32 @@ pub fn load_board(root: &Path, name: &str, rel_path: &str) -> Result = read_json(&board_dir.join(packets_path))?; for raw in raws { - packets.push(build_packet_def(name, raw, &measurements)?); + let packet = build_packet_def(name, board_id, raw, &measurements)?; + packets.insert(packet.id, packet); } } - packets.extend(protection_packets); - let ip: IpAddr = raw_board .board_ip .parse() @@ -117,7 +114,7 @@ pub fn load_board(root: &Path, name: &str, rel_path: &str) -> Result Result, ) -> Result { let kind = match raw.kind.as_str() { "data" => PacketKind::Data, "order" => PacketKind::Order, + "protection" => PacketKind::Protection, + "message" => PacketKind::Message, other => { return Err(LoadError::UnknownPacketType { board: board.to_string(), @@ -158,6 +158,7 @@ fn build_packet_def( Ok(PacketDef { id: AdjId(raw.id), + board: board_id, name: raw.name, kind, measurements: packet_measurements, @@ -224,7 +225,7 @@ mod tests { variables: vec![], }; assert!(matches!( - build_packet_def("VCU", raw, &HashMap::new()), + build_packet_def("VCU", BoardId(3), raw, &HashMap::new()), Err(LoadError::UnknownPacketType { .. }) )); } @@ -238,7 +239,7 @@ mod tests { variables: vec!["missing".to_string()], }; assert!(matches!( - build_packet_def("VCU", raw, &HashMap::new()), + build_packet_def("VCU", BoardId(3), raw, &HashMap::new()), Err(LoadError::UnknownAlias { .. }) )); } @@ -248,32 +249,39 @@ mod tests { let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("src/adj/test/adj"); let adj = must_load(&path); - let board_names: Vec<&str> = adj + // `HashMap` iteration order is unspecified, so sort before comparing. + let mut board_names: Vec<&str> = adj .pod_data .boards - .iter() + .values() .map(|b| b.name.as_str()) .collect(); + board_names.sort(); assert_eq!(board_names, vec!["HVBMS", "LCU", "PCU", "VCU"]); - let Some(vcu) = adj.pod_data.boards.iter().find(|b| b.name == "VCU") else { + let Some(vcu) = adj.pod_data.boards.get(&BoardId(3)) else { unreachable!("VCU should be among the loaded boards"); }; assert_eq!(vcu.id, BoardId(3)); assert_eq!(vcu.ip, IpAddr::from([192, 168, 1, 3])); assert_eq!(vcu.mac, MacAddress([0; 6])); assert_eq!(vcu.packets.len(), 18); - assert_eq!(vcu.packets[0].kind, PacketKind::Order); - assert_eq!(vcu.packets[0].id, AdjId(600)); - assert_eq!(vcu.packets[13].kind, PacketKind::Data); - assert_eq!(vcu.packets[13].id, AdjId(625)); + let Some(order) = vcu.packets.get(&AdjId(600)) else { + unreachable!("VCU should have order 600"); + }; + assert_eq!(order.kind, PacketKind::Order); + assert_eq!(order.board, BoardId(3)); + let Some(data) = vcu.packets.get(&AdjId(625)) else { + unreachable!("VCU should have data packet 625"); + }; + assert_eq!(data.kind, PacketKind::Data); - let Some(pcu) = adj.pod_data.boards.iter().find(|b| b.name == "PCU") else { + let Some(pcu) = adj.pod_data.boards.get(&BoardId(5)) else { unreachable!("PCU should be among the loaded boards"); }; let Some(protected) = pcu .packets - .iter() + .values() .flat_map(|p| &p.measurements) .find(|m| !m.protections.is_empty()) else { @@ -298,7 +306,12 @@ mod tests { } ); - let protection_packet = pcu.packets.iter().find(|p| p.name.contains("_protection_")).unwrap(); - assert_eq!(protection_packet.id, AdjId(protected.id.0 + 1)); + // `protected` has exactly one protection (asserted above), at position 1, + // so its compound wire id is `(1 << 13) | protected.id.0`. + let Some(protection_packet) = pcu.packets.get(&AdjId((1u16 << 13) | protected.id.0)) else { + unreachable!("PCU should have a synthetic protection packet"); + }; + assert_eq!(protection_packet.kind, PacketKind::Protection); + assert_eq!(protection_packet.board, pcu.id); } } diff --git a/backend/crates/core/src/adj/raw/types.rs b/backend/crates/core/src/adj/raw/types.rs index ea785820e..dd95d21f9 100644 --- a/backend/crates/core/src/adj/raw/types.rs +++ b/backend/crates/core/src/adj/raw/types.rs @@ -112,9 +112,10 @@ impl TryFrom for Measurement { type Error = MeasurementError; fn try_from(raw: RawMeasurement) -> Result { - if raw.protections.len() > 7 { - return Err(MeasurementError::TooManyProtections{count: raw.protections.len()}); + return Err(MeasurementError::TooManyProtections { + count: raw.protections.len(), + }); } let kind = parse_measurement_kind(&raw.kind, raw.enum_values)?; @@ -268,9 +269,9 @@ fn parse_duration(text: &str) -> Result { #[cfg(test)] mod tests { + use super::*; use crate::adj::raw::loader::load_board; use crate::model::PacketKind; - use super::*; fn raw_protection( kind: &str, @@ -477,7 +478,7 @@ mod tests { #[test] fn measurement_with_too_many_protections() { - let mut raw = RawMeasurement{ + let mut raw = RawMeasurement { id: 100, alias: "too_many".to_string(), name: "Too Many Protections".to_string(), @@ -487,76 +488,95 @@ mod tests { protections: vec![], }; - for _ in 0..8{ - raw.protections.push(raw_protection("Equal", vec![1.0], true, None)); + for _ in 0..8 { + raw.protections + .push(raw_protection("Equal", vec![1.0], true, None)); } assert!(matches!( Measurement::try_from(raw), - Err(MeasurementError::TooManyProtections{count:8}) + Err(MeasurementError::TooManyProtections { count: 8 }) )) } - #[test] - fn protection_id_generation_matches_specification() { - // Base measurement ID = 512 (Binary: 00000 0100 0000 0000) - let measurement_id: u16 = 512; - - // Test for the first protection index (idx = 0 -> pos = 1) - let idx_0: usize = 0; - let pos_1 = idx_0 as u16 + 1; - let id_0 = (pos_1 << 13) | measurement_id; - - // Expected binary pattern: [pos=001][measurement_id=0000001000000] - // 0b001_0000001000000 = 8704 - assert_eq!(id_0, 8704, "First protection packet ID must pack pos=1 into the high bits"); - - // Test for the seventh protection index (idx = 6 -> pos = 7) - let idx_6: usize = 6; - let pos_7 = idx_6 as u16 + 1; - let id_6 = (pos_7 << 13) | measurement_id; - - // Expected binary pattern: [pos=111][measurement_id=0000001000000] - // 0b111_0000001000000 = 57856 - assert_eq!(id_6, 57856, "Seventh protection packet ID must pack pos=7 into the high bits"); - } - #[test] fn board_incorporates_synthetic_protection_packets() { - // Arrange: Create a temporary environment or setup standard board mocks - let temp_dir = std::env::temp_dir(); - let board_name = "H12_Test_Board"; - let rel_path = "test_board.json"; + // A scratch directory, unique per test invocation (pid + a counter) + // so parallel test runs never collide on the same path. + use std::sync::atomic::{AtomicU32, Ordering}; + static COUNTER: AtomicU32 = AtomicU32::new(0); + let unique = COUNTER.fetch_add(1, Ordering::Relaxed); + let dir = std::env::temp_dir().join(format!( + "software_core_adj_test_{}_{unique}", + std::process::id() + )); + + if std::fs::create_dir_all(&dir).is_err() { + unreachable!("should be able to create a scratch test directory"); + } - // Ensure you create valid mock JSON configuration files in temp_dir representing: - // 1. `test_board.json` (containing 1 measurement path and 1 packet path) - // 2. A measurement file containing 1 measurement (ID: 100) with exactly 2 protections. - // 3. A packet file containing 0 standard packets to cleanly isolate the test. + let board_json = r#"{ + "board_id": 99, + "mac": "aa:bb:cc:dd:ee:ff", + "board_ip": "127.0.0.1", + "measurements": ["measurements.json"], + "packets": ["packets.json"] + }"#; + let measurements_json = r#"[ + { + "id": 100, + "alias": "mock_alias", + "name": "Mock Measurement", + "type": "float32", + "protections": [ + { "type": "Equal", "value": [1.0], "fault": true }, + { "type": "Equal", "value": [2.0], "fault": true } + ] + } + ]"#; + + if std::fs::write(dir.join("test_board.json"), board_json).is_err() { + unreachable!("should be able to write the mock board file"); + } + if std::fs::write(dir.join("measurements.json"), measurements_json).is_err() { + unreachable!("should be able to write the mock measurements file"); + } + if std::fs::write(dir.join("packets.json"), "[]").is_err() { + unreachable!("should be able to write the mock packets file"); + } - // Act - let result = load_board(&temp_dir, board_name, rel_path); + let board_name = "H12_Test_Board"; + let result = load_board(&dir, board_name, "test_board.json"); + let _ = std::fs::remove_dir_all(&dir); - // Assert - assert!(result.is_ok(), "Board loading failed: {:?}", result.err()); - let board = result.unwrap(); + let board = match result { + Ok(board) => board, + Err(err) => unreachable!("board loading should succeed: {err}"), + }; - // Since we provided 0 standard packets and 2 protections, - // the total synthetic packets injected into the board must equal 2. - let protection_packets: Vec<_> = board.packets - .iter() + // We provided 0 standard packets and 2 protections, so the total + // synthetic packets injected into the board must equal 2. + let protection_count = board + .packets + .values() .filter(|p| p.kind == PacketKind::Protection) - .collect(); - - assert_eq!(protection_packets.len(), 2, "Board should contain exactly 2 protection packets"); + .count(); + assert_eq!( + protection_count, 2, + "board should contain exactly 2 protection packets" + ); - // Verify the bit-packed properties of the injected synthetic packets // For protection index 0 (pos = 1): (1 << 13) | 100 = 8192 | 100 = 8292 - assert_eq!(protection_packets[0].id, AdjId(8292)); - assert_eq!(protection_packets[0].name, format!("{}_mock_alias_protection_1", board_name)); + let Some(first) = board.packets.get(&AdjId(8292)) else { + unreachable!("first synthetic protection packet should be at id 8292"); + }; + assert_eq!(first.board, board.id); + assert_eq!(first.name, format!("{board_name}_mock_alias_protection_1")); // For protection index 1 (pos = 2): (2 << 13) | 100 = 16384 | 100 = 16484 - assert_eq!(protection_packets[1].id, AdjId(16484)); - assert_eq!(protection_packets[1].name, format!("{}_mock_alias_protection_2", board_name)); + let Some(second) = board.packets.get(&AdjId(16484)) else { + unreachable!("second synthetic protection packet should be at id 16484"); + }; + assert_eq!(second.name, format!("{board_name}_mock_alias_protection_2")); } - } From b6c387419c0a601c620009ddb40870eba4c8709a Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Fri, 9 Oct 2026 01:18:44 +0200 Subject: [PATCH 027/225] feat(adj & model): add port --- backend/crates/core/src/adj/info.rs | 5 +++-- backend/crates/core/src/adj/raw/loader.rs | 4 ++-- backend/crates/core/src/adj/raw/types.rs | 10 +++++++--- backend/crates/core/src/model.rs | 4 ++-- backend/crates/core/src/model/id.rs | 12 ++++++++++++ 5 files changed, 26 insertions(+), 9 deletions(-) diff --git a/backend/crates/core/src/adj/info.rs b/backend/crates/core/src/adj/info.rs index 02d9870b9..140ef6437 100644 --- a/backend/crates/core/src/adj/info.rs +++ b/backend/crates/core/src/adj/info.rs @@ -5,6 +5,7 @@ //! addresses, message-id conventions, and how to display a triggered //! protection. +use crate::model::Port; use std::collections::HashMap; /// A protection type's display text, as declared in `general_info.json`'s @@ -25,8 +26,8 @@ pub struct ProtectionTypeInfo { /// Backend-session metadata parsed from `general_info.json`. #[derive(Debug, Clone, PartialEq, Eq, Default)] pub struct AdjInfo { - /// Known port numbers, by name (e.g. `"TCP_SERVER"` -> `50500`). - pub ports: HashMap, + /// Known port numbers, by name (e.g. `"TCP_SERVER"` -> `Port(50500)`). + pub ports: HashMap, /// Known addresses, by name (e.g. `"backend"` -> `"192.168.0.9"`), kept /// as text: nothing in this crate needs them parsed as an `IpAddr` yet. pub addresses: HashMap, diff --git a/backend/crates/core/src/adj/raw/loader.rs b/backend/crates/core/src/adj/raw/loader.rs index 4e18f30de..21fe2107f 100644 --- a/backend/crates/core/src/adj/raw/loader.rs +++ b/backend/crates/core/src/adj/raw/loader.rs @@ -188,7 +188,7 @@ fn parse_mac(raw: &str) -> Option { mod tests { use super::*; use crate::adj::ProtectionTypeInfo; - use crate::model::{PacketKind, ProtectionKind, Severity}; + use crate::model::{PacketKind, Port, ProtectionKind, Severity}; use std::path::Path; use std::time::Duration; @@ -294,7 +294,7 @@ mod tests { assert_eq!(protection.time, Duration::ZERO); assert_eq!(protection.id, AdjId(1)); - assert_eq!(adj.info.ports["TCP_SERVER"], 50500); + assert_eq!(adj.info.ports["TCP_SERVER"], Port(50500)); assert_eq!(adj.info.addresses["backend"], "192.168.0.9"); assert_eq!(adj.info.message_ids["fault"], 2); assert_eq!( diff --git a/backend/crates/core/src/adj/raw/types.rs b/backend/crates/core/src/adj/raw/types.rs index dd95d21f9..a335678c5 100644 --- a/backend/crates/core/src/adj/raw/types.rs +++ b/backend/crates/core/src/adj/raw/types.rs @@ -8,7 +8,7 @@ use crate::adj::error::{MeasurementError, ProtectionError}; use crate::adj::info::{AdjInfo, ProtectionTypeInfo}; use crate::model::{ - AdjId, Measurement, MeasurementKind, NumericKind, Protection, ProtectionKind, Severity, + AdjId, Measurement, MeasurementKind, NumericKind, Port, Protection, ProtectionKind, Severity, }; use serde::Deserialize; use std::collections::HashMap; @@ -87,7 +87,11 @@ pub(crate) struct RawPacket { impl From for AdjInfo { fn from(raw: RawGeneralInfo) -> Self { AdjInfo { - ports: raw.ports, + ports: raw + .ports + .into_iter() + .map(|(name, port)| (name, Port(port))) + .collect(), addresses: raw.addresses, message_ids: raw.message_ids, protection_types: raw @@ -470,7 +474,7 @@ mod tests { let info = AdjInfo::from(raw); - assert_eq!(info.ports["TCP_SERVER"], 50500); + assert_eq!(info.ports["TCP_SERVER"], Port(50500)); assert_eq!(info.addresses["backend"], "192.168.0.9"); assert_eq!(info.message_ids["fault"], 2); assert!(info.protection_types["Range"].is_range); diff --git a/backend/crates/core/src/model.rs b/backend/crates/core/src/model.rs index 2ca135984..6cfdda92d 100644 --- a/backend/crates/core/src/model.rs +++ b/backend/crates/core/src/model.rs @@ -2,7 +2,7 @@ //! protections and boards. No I/O and no networking here, just data and //! the operations performed on it. //! -//! - `id` — `AdjId`, `BoardId`, `MacAddress`. +//! - `id` — `AdjId`, `BoardId`, `MacAddress`, `Port`. //! - `value` — `Value`, the result of decoding a measurement. //! - `measurement` — `Measurement`: what a field of a packet looks like. //! - `protections` — `Protection`: bounds declared for a measurement. @@ -18,7 +18,7 @@ mod protections; mod value; pub use board::{Board, PacketDef, PacketKind, PodData}; -pub use id::{AdjId, BoardId, MacAddress}; +pub use id::{AdjId, BoardId, MacAddress, Port}; pub use measurement::{Measurement, MeasurementKind, NumericKind, Range}; pub use packet::{ DataPacket, MessageLevel, MessagePacket, OrderPacket, Packet, ProtectionPacket, ShortTimestamp, diff --git a/backend/crates/core/src/model/id.rs b/backend/crates/core/src/model/id.rs index 878532e06..d6a6845a5 100644 --- a/backend/crates/core/src/model/id.rs +++ b/backend/crates/core/src/model/id.rs @@ -16,6 +16,10 @@ pub struct AdjId(pub u16); #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub struct BoardId(pub u16); +/// A TCP/UDP port number, as declared in `general_info.json`'s `ports`. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub struct Port(pub u16); + /// A board's physical MAC address, as 6 raw bytes. /// /// Kept as a fixed-size byte array instead of a `String` on purpose: a @@ -48,6 +52,14 @@ mod tests { assert_eq!(AdjId(1000), AdjId(1000)); } + #[test] + fn a_port_and_a_board_id_cannot_be_compared_to_each_other() { + // This wouldn't compile if you tried it: Port(1) == BoardId(1) + let port = Port(50500); + let board = BoardId(50500); + assert_eq!(port.0, board.0); // only the inner numbers can be compared + } + #[test] fn a_mac_address_displays_as_colon_separated_lowercase_hex() { let mac = MacAddress([0xaa, 0xbb, 0xcc, 0x0d, 0x0e, 0xff]); From bb2c605342af45f24dbb4db04aeeea1e0915bf68 Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Fri, 9 Oct 2026 01:21:56 +0200 Subject: [PATCH 028/225] fix(adj): use adj id to read data from info --- backend/crates/core/src/adj/info.rs | 8 +++++--- backend/crates/core/src/adj/raw/loader.rs | 2 +- backend/crates/core/src/adj/raw/types.rs | 8 ++++++-- 3 files changed, 12 insertions(+), 6 deletions(-) diff --git a/backend/crates/core/src/adj/info.rs b/backend/crates/core/src/adj/info.rs index 140ef6437..853d1cf7a 100644 --- a/backend/crates/core/src/adj/info.rs +++ b/backend/crates/core/src/adj/info.rs @@ -5,7 +5,7 @@ //! addresses, message-id conventions, and how to display a triggered //! protection. -use crate::model::Port; +use crate::model::{AdjId, Port}; use std::collections::HashMap; /// A protection type's display text, as declared in `general_info.json`'s @@ -31,8 +31,10 @@ pub struct AdjInfo { /// Known addresses, by name (e.g. `"backend"` -> `"192.168.0.9"`), kept /// as text: nothing in this crate needs them parsed as an `IpAddr` yet. pub addresses: HashMap, - /// Known message ids, by name (e.g. `"fault"` -> `2`). - pub message_ids: HashMap, + /// Known message ids, by name (e.g. `"fault"` -> `AdjId(2)`) — these + /// live in the ADJ's own special reserved id range (`[0, 511]`, see + /// [`AdjId`]'s own docs), not a separate numbering of their own. + pub message_ids: HashMap, /// Declared protection types, by name (e.g. `"Range"`). pub protection_types: HashMap, } diff --git a/backend/crates/core/src/adj/raw/loader.rs b/backend/crates/core/src/adj/raw/loader.rs index 21fe2107f..b07520e67 100644 --- a/backend/crates/core/src/adj/raw/loader.rs +++ b/backend/crates/core/src/adj/raw/loader.rs @@ -296,7 +296,7 @@ mod tests { assert_eq!(adj.info.ports["TCP_SERVER"], Port(50500)); assert_eq!(adj.info.addresses["backend"], "192.168.0.9"); - assert_eq!(adj.info.message_ids["fault"], 2); + assert_eq!(adj.info.message_ids["fault"], AdjId(2)); assert_eq!( adj.info.protection_types["Range"], ProtectionTypeInfo { diff --git a/backend/crates/core/src/adj/raw/types.rs b/backend/crates/core/src/adj/raw/types.rs index a335678c5..de5e68a6b 100644 --- a/backend/crates/core/src/adj/raw/types.rs +++ b/backend/crates/core/src/adj/raw/types.rs @@ -93,7 +93,11 @@ impl From for AdjInfo { .map(|(name, port)| (name, Port(port))) .collect(), addresses: raw.addresses, - message_ids: raw.message_ids, + message_ids: raw + .message_ids + .into_iter() + .map(|(name, id)| (name, AdjId(id))) + .collect(), protection_types: raw .protection_types .into_iter() @@ -476,7 +480,7 @@ mod tests { assert_eq!(info.ports["TCP_SERVER"], Port(50500)); assert_eq!(info.addresses["backend"], "192.168.0.9"); - assert_eq!(info.message_ids["fault"], 2); + assert_eq!(info.message_ids["fault"], AdjId(2)); assert!(info.protection_types["Range"].is_range); } From bc846217c36b68b8eaf3d5810530b38cbe44c906 Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Fri, 9 Oct 2026 11:47:40 +0200 Subject: [PATCH 029/225] fix(model adj): remove adj readme from test folder --- .../crates/core/src/adj/test/adj/README.md | 291 ------------------ 1 file changed, 291 deletions(-) delete mode 100644 backend/crates/core/src/adj/test/adj/README.md diff --git a/backend/crates/core/src/adj/test/adj/README.md b/backend/crates/core/src/adj/test/adj/README.md deleted file mode 100644 index 453182930..000000000 --- a/backend/crates/core/src/adj/test/adj/README.md +++ /dev/null @@ -1,291 +0,0 @@ -# ADJ v2 Specification - -This document defines the ADJ v2 configuration format used by the Hyperloop Control Station. The configuration is organized as a distributed collection of JSON files that define boards, measurements, packets, and general system information. - -## File Structure - -The ADJ configuration is organized in the following directory structure: - -``` -adj/ -├── general_info.json # System-wide configuration -├── boards.json # Board list and path mappings -└── boards/ # Board-specific configurations - └── {board_name}/ - ├── {board_name}.json # Main board configuration - ├── {board_name}_measurements.json # Board measurements - ├── packets.json # Data packets - ├── orders.json # Order packets - └── sockets.json # Board sockets -``` - -## Data Types - -### General Info (`general_info.json`) - -System-wide configuration including ports, addresses, units, and message IDs. - -```json -{ - "ports": { - "string": "number" - }, - "addresses": { - "string": "string" - }, - "units": { - "string": "string" - }, - "message_ids": { - "string": "number" - } -} -``` - -**Example:** -```json -{ - "ports": { - "main": 8080, - "data": 8081 - }, - "addresses": { - "primary": "192.168.1.100", - "secondary": "192.168.1.101" - }, - "units": { - "pressure": "PSI", - "temperature": "°C", - "voltage": "V" - }, - "message_ids": { - "status": 1, - "data": 2 - } -} -``` - -### Board List (`boards.json`) - -Mapping of board names to their configuration file paths. - -```json -{ - "string": "string" -} -``` - -**Example:** -```json -{ - "brake_board": "boards/brake_board/brake_board.json", - "sensor_board": "boards/sensor_board/sensor_board.json" -} -``` - -### Board Configuration (`{board_name}.json`) - -Main board configuration including ID, IP address, and references to measurements, packets and sockets files. - -```json -{ - "board_id": "number", - "board_ip": "string", - "measurements": ["string"], - "packets": ["string"], - "sockets": ["string"] -} -``` - -**Field Descriptions:** -- `board_id`: Unique 32-bit unsigned integer identifier for the board -- `board_ip`: IP address string for network communication -- `measurements`: Array of measurement file paths relative to board directory -- `packets`: Array of packet file paths relative to board directory - -**Example:** -```json -{ - "board_id": 1001, - "board_ip": "192.168.1.10", - "measurements": ["brake_board_measurements.json"], - "packets": ["packets.json", "orders.json"], - "sockets":["sockets.json"] -} -``` - -### Measurements (`{board_name}_measurements.json`) - -Array of measurement definitions for data collection and monitoring. - -```json -[ - { - "id": "string", - "name": "string", - "type": "string", - "podUnits": "string?", - "displayUnits": "string?", - "enumValues": ["string"]?, - "safeRange": "[number, number]?", - "warningRange": "[number, number]?" - } -] -``` - -**Field Descriptions:** -- `id`: Unique string identifier for the measurement -- `name`: Human-readable display name -- `type`: Data type - one of: `uint8`, `uint16`, `uint32`, `uint64`, `int8`, `int16`, `int32`, `int64`, `float32`, `float64` -- `podUnits`: Optional pod-side units (references `general_info.units`) -- `displayUnits`: Optional display units (references `general_info.units`) -- `enumValues`: Optional array of enumeration values for discrete measurements -- `safeRange`: Optional two-element array `[min, max]` defining safe operating range -- `warningRange`: Optional two-element array `[min, max]` defining warning thresholds - -**Example:** -```json -[ - { - "id": "brake_pressure", - "name": "Brake Pressure", - "type": "float32", - "podUnits": "PSI", - "displayUnits": "PSI", - "safeRange": [0.0, 100.0], - "warningRange": [80.0, 95.0] - }, - { - "id": "brake_status", - "name": "Brake Status", - "type": "uint8", - "enumValues": ["released", "engaged", "error"] - } -] -``` - -### Packets (`packets.json`, `orders.json`) - -Array of packet definitions for network communication. Packets are separated by type: -- `packets.json`: Data packets for telemetry and status -- `orders.json`: Command packets for control operations - -```json -[ - { - "id": "number?", - "type": "string", - "name": "string", - "variables": ["string"], - "period_type": "us/ms?", - "period": "number?", - "socket": "string?" - } -] -``` - -**Field Descriptions:** -- `id`: Optional 32-bit unsigned integer packet identifier -- `type`: Packet type string (e.g., "data", "order", "status") -- `name`: Human-readable packet name -- `variables`: Array of variable names/measurement IDs included in this packet -- `period_type`: Optional string specifying the type of measurement for period, either microseconds -or milliseconds -- `period`: Optional number specifying the transmission period in milliseconds or microseconds for periodic packets. Can be an integer or floating-point value -- `socket`: Optinal string that should match the name of the socket you want to transmit this packet trhough - -**Example:** -```json -[ - { - "id": 2001, - "type": "data", - "name": "Brake Telemetry", - "variables": ["brake_pressure", "brake_status", "brake_temperature"], - "period_type":"ms", - "period": 16.67, - "socket": "control_station_udp" - }, - { - "type": "order", - "name": "Brake Command", - "variables": ["brake_command", "target_pressure"] - } -] -``` - -### Sockets (`sockets.json`) - -Array of socket definitions for network communication. - -```json -{ - "type": "string", - "name": "string", - "port": "number?", - "local_port":"number?", - "remote_ip": "string?", - "remote_port":"number?" - -} -``` - -**Field Descriptions:** -- `type`: Socket type string(e.g., "ServerSocket","DatagramSocket","Socket") -- `name`: Socket name -- `port`: Optional number that describes the port number used for a ServerSocket or a DatagramSocket -- `local_port`: Optional number that describes the local port number used for a Socket -- `remote_ip`: Optional string that describes the remote ip you want to connect to in a DatagramSocket or Socket -- `remote_port`: Optional number that describes the remote port number used for a Socket - -**Example:** -```json -[ - { - "type": "ServerSocket", - "name": "control_station_tcp", - "port": 50500 - }, - - { - "type": "DatagramSocket", - "name": "control_station_udp", - "remote_ip":"192.168.0.9", - "port": 50400 - }, - - { - "type": "Socket", - "name": "pcu_tcp", - "local_port": 50501, - "remote_ip": "192.168.1.5", - "remote_port": 50500 - } -] -``` - -## Configuration Rules - -1. **Naming Convention**: Board directories and main configuration files must use the same name as the board key in `boards.json` - -2. **File References**: All file paths in board configurations are relative to the board's directory - -3. **Measurement References**: Packet `variables` arrays should reference measurement `id` values defined in the board's measurements files - -4. **Unit References**: Measurement `podUnits` and `displayUnits` should reference keys defined in `general_info.units` - -5. **ID Uniqueness**: Board IDs must be unique across all boards. Packet IDs should be unique within their type category. - -6. **Socket Naming**: The sockets referenced inside the packet definitions must use exact names as defined in `socket.json`. - -## Validation Notes - -- All numeric fields use standard JSON number format -- Optional fields may be omitted entirely or set to `null` -- Empty arrays are permitted for measurements and packets -- File paths use forward slashes (`/`) regardless of operating system -- IP addresses must be valid IPv4 format strings - -## Backward Compatibility - -This specification maintains compatibility with existing ADJ v1 configurations while supporting the new distributed file structure introduced in v2. The system can automatically migrate v1 configurations to the v2 format. From db66b30e7952b6f5b66ed02e56a3f217803ce439 Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Fri, 9 Oct 2026 11:49:21 +0200 Subject: [PATCH 030/225] docs(backend, model): mistaken comment --- backend/crates/core/src/model/board.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/backend/crates/core/src/model/board.rs b/backend/crates/core/src/model/board.rs index 00f0cce18..3692a74f9 100644 --- a/backend/crates/core/src/model/board.rs +++ b/backend/crates/core/src/model/board.rs @@ -44,7 +44,7 @@ pub struct PacketDef { pub board: BoardId, /// The human-readable name shown to the user. pub name: String, - /// Whether this is data or an order. + /// Whether this is data, order, protection or message. pub kind: PacketKind, /// The measurements this packet carries, in ADJ order. pub measurements: Vec, From 14c222fe4ffb35bbdd207e5c34a144344592419e Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Fri, 9 Oct 2026 12:05:02 +0200 Subject: [PATCH 031/225] fix(backend, adj): change ip as an string to a Ip Addr --- backend/crates/core/src/adj/error.rs | 13 ++++++ backend/crates/core/src/adj/info.rs | 6 +-- backend/crates/core/src/adj/raw/loader.rs | 7 +++- backend/crates/core/src/adj/raw/types.rs | 48 +++++++++++++++++++---- 4 files changed, 61 insertions(+), 13 deletions(-) diff --git a/backend/crates/core/src/adj/error.rs b/backend/crates/core/src/adj/error.rs index 6e173fce1..2f6d31764 100644 --- a/backend/crates/core/src/adj/error.rs +++ b/backend/crates/core/src/adj/error.rs @@ -45,6 +45,19 @@ pub enum LoadError { source: AddrParseError, }, + /// An address in `general_info.json`'s `addresses` isn't a valid IP + /// address. + #[error("address {name:?}: invalid IP address {raw:?}")] + InvalidAddress { + /// The address's name (e.g. `"backend"`). + name: String, + /// The text that failed to parse. + raw: String, + /// The underlying parse error. + #[source] + source: AddrParseError, + }, + /// A board's `mac` isn't a valid MAC address. #[error("board {board:?}: invalid MAC address {raw:?}")] InvalidMac { diff --git a/backend/crates/core/src/adj/info.rs b/backend/crates/core/src/adj/info.rs index 853d1cf7a..62c17fa9c 100644 --- a/backend/crates/core/src/adj/info.rs +++ b/backend/crates/core/src/adj/info.rs @@ -7,6 +7,7 @@ use crate::model::{AdjId, Port}; use std::collections::HashMap; +use std::net::IpAddr; /// A protection type's display text, as declared in `general_info.json`'s /// `protectionTypes`. @@ -28,9 +29,8 @@ pub struct ProtectionTypeInfo { pub struct AdjInfo { /// Known port numbers, by name (e.g. `"TCP_SERVER"` -> `Port(50500)`). pub ports: HashMap, - /// Known addresses, by name (e.g. `"backend"` -> `"192.168.0.9"`), kept - /// as text: nothing in this crate needs them parsed as an `IpAddr` yet. - pub addresses: HashMap, + /// Known addresses, by name (e.g. `"backend"` -> `192.168.0.9`). + pub addresses: HashMap, /// Known message ids, by name (e.g. `"fault"` -> `AdjId(2)`) — these /// live in the ADJ's own special reserved id range (`[0, 511]`, see /// [`AdjId`]'s own docs), not a separate numbering of their own. diff --git a/backend/crates/core/src/adj/raw/loader.rs b/backend/crates/core/src/adj/raw/loader.rs index b07520e67..02d4750a3 100644 --- a/backend/crates/core/src/adj/raw/loader.rs +++ b/backend/crates/core/src/adj/raw/loader.rs @@ -29,7 +29,7 @@ pub fn load_from_dir(path: &Path) -> Result { Ok(Adj { pod_data: PodData { boards }, - info: AdjInfo::from(general_info), + info: AdjInfo::try_from(general_info)?, }) } @@ -295,7 +295,10 @@ mod tests { assert_eq!(protection.id, AdjId(1)); assert_eq!(adj.info.ports["TCP_SERVER"], Port(50500)); - assert_eq!(adj.info.addresses["backend"], "192.168.0.9"); + assert_eq!( + adj.info.addresses["backend"], + IpAddr::from([192, 168, 0, 9]) + ); assert_eq!(adj.info.message_ids["fault"], AdjId(2)); assert_eq!( adj.info.protection_types["Range"], diff --git a/backend/crates/core/src/adj/raw/types.rs b/backend/crates/core/src/adj/raw/types.rs index de5e68a6b..0f130cb30 100644 --- a/backend/crates/core/src/adj/raw/types.rs +++ b/backend/crates/core/src/adj/raw/types.rs @@ -5,7 +5,7 @@ //! `socket`, `units`, `podUnits`), which are simply absent from these //! structs and therefore ignored by serde, not rejected. -use crate::adj::error::{MeasurementError, ProtectionError}; +use crate::adj::error::{LoadError, MeasurementError, ProtectionError}; use crate::adj::info::{AdjInfo, ProtectionTypeInfo}; use crate::model::{ AdjId, Measurement, MeasurementKind, NumericKind, Port, Protection, ProtectionKind, Severity, @@ -84,15 +84,29 @@ pub(crate) struct RawPacket { pub(crate) variables: Vec, } -impl From for AdjInfo { - fn from(raw: RawGeneralInfo) -> Self { - AdjInfo { +impl TryFrom for AdjInfo { + type Error = LoadError; + + fn try_from(raw: RawGeneralInfo) -> Result { + let mut addresses = HashMap::with_capacity(raw.addresses.len()); + for (name, raw_addr) in raw.addresses { + let addr = raw_addr + .parse() + .map_err(|source| LoadError::InvalidAddress { + name: name.clone(), + raw: raw_addr, + source, + })?; + addresses.insert(name, addr); + } + + Ok(AdjInfo { ports: raw .ports .into_iter() .map(|(name, port)| (name, Port(port))) .collect(), - addresses: raw.addresses, + addresses, message_ids: raw .message_ids .into_iter() @@ -112,7 +126,7 @@ impl From for AdjInfo { ) }) .collect(), - } + }) } } @@ -280,6 +294,7 @@ mod tests { use super::*; use crate::adj::raw::loader::load_board; use crate::model::PacketKind; + use std::net::IpAddr; fn raw_protection( kind: &str, @@ -476,14 +491,31 @@ mod tests { message_ids: HashMap::from([("fault".to_string(), 2u16)]), }; - let info = AdjInfo::from(raw); + let Ok(info) = AdjInfo::try_from(raw) else { + unreachable!("a well-formed RawGeneralInfo should convert cleanly"); + }; assert_eq!(info.ports["TCP_SERVER"], Port(50500)); - assert_eq!(info.addresses["backend"], "192.168.0.9"); + assert_eq!(info.addresses["backend"], IpAddr::from([192, 168, 0, 9])); assert_eq!(info.message_ids["fault"], AdjId(2)); assert!(info.protection_types["Range"].is_range); } + #[test] + fn general_info_rejects_an_invalid_address() { + let raw = RawGeneralInfo { + ports: HashMap::new(), + addresses: HashMap::from([("backend".to_string(), "not-an-ip".to_string())]), + protection_types: HashMap::new(), + message_ids: HashMap::new(), + }; + + assert!(matches!( + AdjInfo::try_from(raw), + Err(LoadError::InvalidAddress { .. }) + )); + } + #[test] fn measurement_with_too_many_protections() { let mut raw = RawMeasurement { From ae145fe6f6098dab1c61b402bc90809d13b30d0b Mon Sep 17 00:00:00 2001 From: Gazi Al Saad Halawani Date: Fri, 9 Oct 2026 12:25:18 +0200 Subject: [PATCH 032/225] Feat(backend): Created readMe for model crate. Half way done. --- backend/crates/core/src/model/README.md | 122 ++++++++++++++++++++++++ 1 file changed, 122 insertions(+) create mode 100644 backend/crates/core/src/model/README.md diff --git a/backend/crates/core/src/model/README.md b/backend/crates/core/src/model/README.md new file mode 100644 index 000000000..87043b080 --- /dev/null +++ b/backend/crates/core/src/model/README.md @@ -0,0 +1,122 @@ +# Model Module + +## Introduction + +This module is meant to store and organize all the different structs, enums and other data structures necessary for the backend project. + +## 1. `board.rs` +All structs and enums needed for the Pod can be found defined in this file. +### 1.1 `PacketKind` +Enum used to define the three different types of packets. + +#### `Data` +Measurement sent by a board. +#### `Protection` +Measurement with a protection. +#### `Order` +An order sent to a board. + +### 1.2 `PacketDef` +Struct used to define the structure of a packet a board can send or recieve. + +#### `id` +ID of a packet, using the AdjId type which is a u16. Structure of ID is defined by the ADJ documentation. +#### `name` +Human-readable String shown to the user to identify packet. +#### `kind` +PacketKind Enum used to classify each packet. +#### `measurements` +Vector list of measurements attached to a packet. + +### 1.3 `Board` +Struct used to identify a single board in the vehicle. + +#### `id` +Board's unique Id in u16 format. +#### `name` +Boards name. Eg. "BSU". +#### `ip` +Board's IpAddress used to open TCP/UDP connections. +#### `mac` +Board's MAC address +#### `packets` +The Vector list of packets this board can send or receive. + +### 1.4 `PodData` +Struct used to package all the structs of a vehicle. +#### `boards` +Vector list of boards in the Pod + + +## 2. `id.rs` +Defined as their own types (wrapping a `u16`) instead of using a plain `u16`, so the compiler won't let an `AdjId` be confused with a `BoardId` by mistake, even though both are just numbers underneath +### 2.1 `AdjId` +ID of an ADJ packet in u16. Structure of ID can be found in the ADJ documentation. +### 2.2 `BoardId` +Unique identifier of a board, defined by the ADJ documentation. +### 2.3 `MacAddress` +A board's physical MAC address, as 6 raw bytes. + + +## 3. `measurement.rs` +A `Measurement` describes a single field of a packet, as defined by the ADJ: whether it holds a number, a boolean, or the variant of an enum, and, for numeric measurements, its wire type and its safe and warning ranges. This is a *description*, not a decoded value — see`super::Value` for the value itself, once decoded. + +### 3.1 `NumericKind` +Enum used to classify every numerical value type a measurement can use. +- Unsigned 8-bit integer (`U8`) +- Unsigned 16-bit integer (`U16`) +- Unsigned 32-bit integer (`U32`) +- Unsigned 64-bit integer (`U64`) +- Signed 8-bit integer (`I8`) +- Signed 16-bit integer (`I16`) +- Signed 32-bit integer (`I32`) +- Signed 64-bit integer (`I64`) +- 32-bit floating point number (`F32`) +- 64-bit floating point number (`F64`) + +### 3.2 `Range` +Struct used to define a maximum and minimum value of any measurement. +#### `min` +#### `max` + +### 3.3 `MeasurementKind` +Enum used to classify the kind of measurement. +#### `Numeric` +#### `Boolean` +#### `Enum` + +### 3.4 `Measurement` +Struct used to define a measurement. +#### `id` +The measurement's numeric ADJ id. +#### `alias` +The legacy textual identifier, used by code generation +#### `name` +The human-readable string shown to the user. +#### `display_units` +Name of the unit of measurement to display to user. Eg. "ºC". +#### `kind` +Usees MeasurementKind enum to classify what type this measurement holds. +#### `protections` +Vector list of protections. Maximum of 7 per measurement. + +## 4. `packet.rs` +`Packet` is a single message actually sent or received over the wire, once decoded. This is the *instance* — as opposed to`super::Measurement` and `super::Protection`, which describe what a packet or a protection *can* look like, or `super::PacketDef`, which describes a whole packet. + +### 4.1 `ShortTimestamp` +A short timestamp carrying only the time of day: hour, minute, second and a sub-second fraction, each one byte. + +#### `hour` +Hour of Timestamp of values 0-23. +#### `minute` +Minute of Timestamp of values 0-60. +#### `second` +Second of Timestamp of values 0-60. +#### `subsecond` +The sub-second fraction, as the raw byte on the wire.Its exact unit (e.g. milliseconds, or 1/256ths of a second) hasn't been confirmed yet, so it is kept as a raw `u8` here instead of converted to something like a `Duration` — convert it once the unit is settled. + +### 4.2 `DataPacket` +Struct for the decoded values of the measurements a board just sent. + +#### `id` +AdjId of packet. \ No newline at end of file From 8cae7549708d5c548db6a1fff3e08d374e98367d Mon Sep 17 00:00:00 2001 From: Gazi Al Saad Halawani Date: Fri, 9 Oct 2026 12:48:11 +0200 Subject: [PATCH 033/225] Feat(backend): Final model Readme --- backend/crates/core/src/model/README.md | 124 ++++++++++++++++++++++-- 1 file changed, 116 insertions(+), 8 deletions(-) diff --git a/backend/crates/core/src/model/README.md b/backend/crates/core/src/model/README.md index 87043b080..c08c5d5a5 100644 --- a/backend/crates/core/src/model/README.md +++ b/backend/crates/core/src/model/README.md @@ -101,22 +101,130 @@ Usees MeasurementKind enum to classify what type this measurement holds. Vector list of protections. Maximum of 7 per measurement. ## 4. `packet.rs` -`Packet` is a single message actually sent or received over the wire, once decoded. This is the *instance* — as opposed to`super::Measurement` and `super::Protection`, which describe what a packet or a protection *can* look like, or `super::PacketDef`, which describes a whole packet. +- `Packet` is a single message actually sent or received over the wire, once decoded. This is the *instance* — as opposed to `super::Measurement` and `super::Protection`, which describe what a packet or a protection *can* look like, or `super::PacketDef`, which describes a whole packet. ### 4.1 `ShortTimestamp` -A short timestamp carrying only the time of day: hour, minute, second and a sub-second fraction, each one byte. +A short timestamp carrying only the time of day: hour, minute, second and a sub-second fraction, each one byte. Used by `ProtectionPacket` and `MessagePacket`. Only records *when today* something happened; the date is assumed to be the day the packet was received. #### `hour` -Hour of Timestamp of values 0-23. +Hour of Timestamp of values 0–23. #### `minute` -Minute of Timestamp of values 0-60. +Minute of Timestamp of values 0–59. #### `second` -Second of Timestamp of values 0-60. +Second of Timestamp of values 0–59. #### `subsecond` -The sub-second fraction, as the raw byte on the wire.Its exact unit (e.g. milliseconds, or 1/256ths of a second) hasn't been confirmed yet, so it is kept as a raw `u8` here instead of converted to something like a `Duration` — convert it once the unit is settled. +The sub-second fraction, as the raw byte on the wire. Its exact unit (e.g. milliseconds, or 1/256ths of a second) hasn't been confirmed yet, so it is kept as a raw `u8` here instead of converted to something like a `Duration` — convert it once the unit is settled. ### 4.2 `DataPacket` -Struct for the decoded values of the measurements a board just sent. +Struct for the decoded values of the measurements a board just sent. Values are positional: they are not individually tagged with their measurement ID, but written in the order their `Measurement`s appear in `PacketDef::measurements`. #### `id` -AdjId of packet. \ No newline at end of file +Which packet definition this is an instance of (`AdjId`). +#### `values` +Vector list of decoded values (`Vec`) corresponding positionally to the packet definition's measurements. + +### 4.3 `OrderPacket` +An order sent from the backend to a board. Also positional, matching field definitions in order. + +#### `id` +Which order definition this is an instance of (`AdjId`). +#### `fields` +Vector list of values (`Vec`) to set for each field of the order. + +### 4.4 `ProtectionPacket` +Sent by a board when one of its declared protections triggers. + +#### `measurement` +The measurement this protection watches (`AdjId`). +#### `protection` +Which of that measurement's protections triggered (`AdjId`). +#### `timestamp` +When the protection triggered (`ShortTimestamp`). +#### `value` +The value that triggered the protection (`Value`), decoded with the same wire type as the watched measurement. + +### 4.5 `MessageLevel` +Enum indicating how severe a message is (reusing `general_info.json`'s `message_ids`). Distinct from `Severity` because message and protection formats are separate in ADJv3. + +#### `Fault` +Stops the vehicle automatically. +#### `Warning` +Flags something unexpected, without stopping the vehicle. +#### `Info` +Informational message, no action implied. +#### `Panic` +An unrecoverable firmware error. + +### 4.6 `MessagePacket` +A free-text message sent by a board. + +#### `level` +How severe the message is (`MessageLevel`). +#### `timestamp` +When the message was sent (`ShortTimestamp`). +#### `origin` +Source identifier, such as a source file path (`String`). +#### `message` +The text contents of the message (`String`). + +### 4.7 `Packet` +Enum representing any packet actually sent or received over the wire, once decoded. + +#### `Data` +Wraps a `DataPacket` (measurement data sent by a board). +#### `Order` +Wraps an `OrderPacket` (command sent to a board). +#### `Protection` +Wraps a `ProtectionPacket` (triggered protection event). +#### `Message` +Wraps a `MessagePacket` (free-text log/diagnostic message). + +## 5. `protection.rs` +A `Protection` is a bound checked against a measurement's decoded value, as declared in the ADJ (`_measurements.json`). This defines the *declaration* (what to watch for, thresholds, and severity) rather than the runtime wire packet emitted when triggered (`ProtectionPacket` in `packet.rs`). In ADJv3, protections and messages are distinct formats with separate lifecycles. + +### 5.1 `ProtectionKind` +Enum defining the condition a protection evaluates and the associated threshold bound(s). Modeled as data-carrying variants to ensure compile-time validity instead of untyped lists. + +#### `Above` +Triggers when the value exceeds `limit` (`f64`). +#### `Below` +Triggers when the value drops below `limit` (`f64`). +#### `Equal` +Triggers when the value equals forbidden `target` (`f64`). +#### `NotEqual` +Triggers when the value deviates from expected `target` (`f64`). +#### `Range` +Triggers when the value leaves the closed `[min, max]` interval (`min: f64`, `max: f64`). Both bounds are strictly required. + +### 5.2 `Severity` +Enum indicating the operational severity level of a triggered protection. + +#### `Fault` +Critical error that stops the vehicle automatically. +#### `Warning` +Flags the condition as anomalous without halting vehicle operation. + +### 5.3 `Protection` +Struct defining a single protection rule attached to a measurement. + +#### `id` +The protection's relative slot index within its parent measurement's protection list, stored as an `AdjId` in the `1–7` range. This is a local index rather than a global ID; it forms the upper 3 bits of the compound wire identifier alongside the 13-bit measurement ID. +#### `kind` +The evaluation rule and threshold bounds (`ProtectionKind`). +#### `severity` +The operational impact level when triggered (`Severity`). +#### `time` +Duration the measured value must remain out of bounds before the protection trips (`Duration`). A value of `Duration::ZERO` indicates an instantaneous trigger. + +## 6. `value.rs` +Defines how the backend represents a piece of data once decoded, regardless of its original wire representation. While the ADJ supports various integer and floating-point types on the wire (captured during decoding by `NumericKind`), all numeric values normalize to `f64` once inside the backend. + +### 6.1 `Value` +Enum representing a single decoded measurement or field value. + +#### `Number(f64)` +A numeric measurement, regardless of its original wire type (`u8`, `i32`, `f32`, etc.). +#### `Bool(bool)` +A boolean measurement (`true` or `false`). +#### `Enum(String)` +The selected variant name of an enumerated measurement (e.g. `"Operational"`). \ No newline at end of file From 579fc5690099b757e94ca7d811f3f47db8ec2590 Mon Sep 17 00:00:00 2001 From: Gazi Al Saad Halawani Date: Fri, 9 Oct 2026 12:55:13 +0200 Subject: [PATCH 034/225] Feat(backend): Created ADJ crate README --- backend/crates/core/src/adj/README.md | 50 +++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 backend/crates/core/src/adj/README.md diff --git a/backend/crates/core/src/adj/README.md b/backend/crates/core/src/adj/README.md new file mode 100644 index 000000000..1b734a1f9 --- /dev/null +++ b/backend/crates/core/src/adj/README.md @@ -0,0 +1,50 @@ +# ADJ Module (`adj`) + +This module deserializes, validates, and loads ADJ JSON fixtures into the backend domain model. + +For schema specifications, packet/measurement ID conventions, and network requirements, refer directly to the official documentation in the **ADJ repository**. + +--- + +## The `Adj` Object Structure + +Calling `load_from_dir` produces a root `Adj` instance: + +```rust +pub struct Adj { + pub pod_data: PodData, + pub info: AdjInfo, +} +``` + +```text +Adj +├── pod_data (PodData) +│ └── boards: HashMap +│ ├── measurements: HashMap +│ └── packets: HashMap +│ ├── explicit (Data, Order, Message, Protection) +│ └── synthetic (Protection alerts derived from measurements) +└── info (AdjInfo) + ├── ports: HashMap + ├── addresses: HashMap + ├── message_ids: HashMap + └── protection_types: HashMap +``` + +--- + +## Why It Is Structured This Way + +The `Adj` object enforces a clear architectural boundary between **vehicle topology** and **session configuration**: + +### 1. Separation of Concerns (`PodData` vs. `AdjInfo`) +* **`pod_data` (Vehicle Domain)**: Represents telemetry, controls, and board topology intrinsic to the physical vehicle. It contains only what exists on the vehicle bus (boards, packets, measurements). +* **`info` (Session & Tooling Domain)**: Captures session-level networking and station UI requirements (host addresses, local server port bindings, and alert format strings like `text` and `textTime`). +* **Design rationale**: The vehicle itself does not know or care about backend socket configurations or display strings. Separating them prevents UI and orchestration details from polluting the core telemetry model. + +### 2. Standalone Loader Submodule (`raw`) +The raw deserialization types and the loader logic live isolated inside `raw`[cite: 2]. This enables non-station tools (such as bus sniffers, test runners, or simulators) to parse and ingest ADJ directories without dragging along application-level UI or station state logic. + +### 3. Unified Packet Map (`packets`) +Protections defined under measurements are materialized during loading as first-class `PacketKind::Protection` packets alongside explicit data and order packets. Downstream networking layers can route and handle every wire event uniformly via `Board::packets` without needing specialized traversal logic for nested measurement alarms. \ No newline at end of file From 0f42fd922b2e4d90c75d0ebc2d34f80b77bce9d2 Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Fri, 9 Oct 2026 14:16:07 +0200 Subject: [PATCH 035/225] fix(backend, adj/model): remove mesuraments for orders (partial reafactor) --- backend/crates/core/src/adj/README.md | 8 +-- backend/crates/core/src/adj/raw/loader.rs | 66 +++++++++++++++-------- backend/crates/core/src/adj/raw/types.rs | 2 +- backend/crates/core/src/model/README.md | 30 ++++++----- backend/crates/core/src/model/board.rs | 51 ++++++++++++------ backend/crates/core/src/model/packet.rs | 4 +- 6 files changed, 105 insertions(+), 56 deletions(-) diff --git a/backend/crates/core/src/adj/README.md b/backend/crates/core/src/adj/README.md index 1b734a1f9..33bdedb49 100644 --- a/backend/crates/core/src/adj/README.md +++ b/backend/crates/core/src/adj/README.md @@ -23,8 +23,10 @@ Adj │ └── boards: HashMap │ ├── measurements: HashMap │ └── packets: HashMap -│ ├── explicit (Data, Order, Message, Protection) -│ └── synthetic (Protection alerts derived from measurements) +│ ├── explicit (Data, Order, Message — declared in packets.json) +│ └── synthetic (Protection — one per declared protection, +│ derived from each measurement's own `protections`; +│ never declared directly in packets.json) └── info (AdjInfo) ├── ports: HashMap ├── addresses: HashMap @@ -47,4 +49,4 @@ The `Adj` object enforces a clear architectural boundary between **vehicle topol The raw deserialization types and the loader logic live isolated inside `raw`[cite: 2]. This enables non-station tools (such as bus sniffers, test runners, or simulators) to parse and ingest ADJ directories without dragging along application-level UI or station state logic. ### 3. Unified Packet Map (`packets`) -Protections defined under measurements are materialized during loading as first-class `PacketKind::Protection` packets alongside explicit data and order packets. Downstream networking layers can route and handle every wire event uniformly via `Board::packets` without needing specialized traversal logic for nested measurement alarms. \ No newline at end of file +Protections defined under measurements are materialized during loading as first-class `PacketKind::Protection(Measurement)` packets alongside the explicit data, order and message packets declared in `packets.json`. Downstream networking layers can route and handle every wire event uniformly via `Board::packets` without needing specialized traversal logic for nested measurement alarms. `packets.json` itself never declares a `"type": "protection"` entry directly — that shape only exists synthesized, one per protection a measurement declares, never as a free-standing declaration with its own arbitrary variable list. \ No newline at end of file diff --git a/backend/crates/core/src/adj/raw/loader.rs b/backend/crates/core/src/adj/raw/loader.rs index 02d4750a3..6d6f4be3c 100644 --- a/backend/crates/core/src/adj/raw/loader.rs +++ b/backend/crates/core/src/adj/raw/loader.rs @@ -79,8 +79,7 @@ pub(crate) fn load_board(root: &Path, name: &str, rel_path: &str) -> Result, ) -> Result { let kind = match raw.kind.as_str() { - "data" => PacketKind::Data, - "order" => PacketKind::Order, - "protection" => PacketKind::Protection, + "data" => PacketKind::Data(resolve_measurements( + board, + &raw.name, + &raw.variables, + measurements, + )?), + "order" => PacketKind::Order(resolve_measurements( + board, + &raw.name, + &raw.variables, + measurements, + )?), "message" => PacketKind::Message, other => { return Err(LoadError::UnknownPacketType { @@ -142,27 +150,36 @@ fn build_packet_def( } }; - let mut packet_measurements = Vec::with_capacity(raw.variables.len()); - for alias in &raw.variables { + Ok(PacketDef { + id: AdjId(raw.id), + board: board_id, + name: raw.name, + kind, + }) +} + +/// Resolves `variables` (a packet's declared measurement aliases) against +/// `measurements`, in order. +fn resolve_measurements( + board: &str, + packet_name: &str, + variables: &[String], + measurements: &HashMap, +) -> Result, LoadError> { + let mut resolved = Vec::with_capacity(variables.len()); + for alias in variables { let measurement = measurements .get(alias) .cloned() .ok_or_else(|| LoadError::UnknownAlias { board: board.to_string(), - name: raw.name.clone(), + name: packet_name.to_string(), alias: alias.clone(), })?; - packet_measurements.push(measurement); + resolved.push(measurement); } - - Ok(PacketDef { - id: AdjId(raw.id), - board: board_id, - name: raw.name, - kind, - measurements: packet_measurements, - }) + Ok(resolved) } /// Parses a MAC address text form, e.g. `"aa:bb:cc:dd:ee:ff"` or the @@ -269,12 +286,16 @@ mod tests { let Some(order) = vcu.packets.get(&AdjId(600)) else { unreachable!("VCU should have order 600"); }; - assert_eq!(order.kind, PacketKind::Order); + let PacketKind::Order(_) = &order.kind else { + unreachable!("order 600 should be an Order"); + }; assert_eq!(order.board, BoardId(3)); let Some(data) = vcu.packets.get(&AdjId(625)) else { unreachable!("VCU should have data packet 625"); }; - assert_eq!(data.kind, PacketKind::Data); + let PacketKind::Data(_) = &data.kind else { + unreachable!("data packet 625 should be Data"); + }; let Some(pcu) = adj.pod_data.boards.get(&BoardId(5)) else { unreachable!("PCU should be among the loaded boards"); @@ -282,7 +303,7 @@ mod tests { let Some(protected) = pcu .packets .values() - .flat_map(|p| &p.measurements) + .flat_map(|p| p.kind.measurements()) .find(|m| !m.protections.is_empty()) else { unreachable!("PCU should have a measurement with a protection"); @@ -314,7 +335,10 @@ mod tests { let Some(protection_packet) = pcu.packets.get(&AdjId((1u16 << 13) | protected.id.0)) else { unreachable!("PCU should have a synthetic protection packet"); }; - assert_eq!(protection_packet.kind, PacketKind::Protection); + let PacketKind::Protection(measurement) = &protection_packet.kind else { + unreachable!("protection_packet should be a Protection"); + }; + assert_eq!(measurement, protected); assert_eq!(protection_packet.board, pcu.id); } } diff --git a/backend/crates/core/src/adj/raw/types.rs b/backend/crates/core/src/adj/raw/types.rs index 0f130cb30..7b02ef51c 100644 --- a/backend/crates/core/src/adj/raw/types.rs +++ b/backend/crates/core/src/adj/raw/types.rs @@ -599,7 +599,7 @@ mod tests { let protection_count = board .packets .values() - .filter(|p| p.kind == PacketKind::Protection) + .filter(|p| matches!(p.kind, PacketKind::Protection(_))) .count(); assert_eq!( protection_count, 2, diff --git a/backend/crates/core/src/model/README.md b/backend/crates/core/src/model/README.md index c08c5d5a5..600ed0f68 100644 --- a/backend/crates/core/src/model/README.md +++ b/backend/crates/core/src/model/README.md @@ -7,26 +7,30 @@ This module is meant to store and organize all the different structs, enums and ## 1. `board.rs` All structs and enums needed for the Pod can be found defined in this file. ### 1.1 `PacketKind` -Enum used to define the three different types of packets. +Enum used to define what kind of packet a `PacketDef` declares. Not every kind carries the same shape, so each variant holds whatever measurement data is actually meaningful for it, instead of every packet being forced through one shared field. + +#### `Data(Vec)` +Telemetry sent by a board: one value per measurement, decoded positionally in this order. +#### `Protection(Measurement)` +The single measurement one of a board's declared protections watches. Always exactly one — never a list. +#### `Order(Vec)` +An order sent to a board. Many orders take no parameters at all, so this can be empty. +#### `Message` +A free-text log line. Never carries measurement data. -#### `Data` -Measurement sent by a board. -#### `Protection` -Measurement with a protection. -#### `Order` -An order sent to a board. +`PacketKind` also exposes a `measurements()` method that flattens any variant into a `&[Measurement]` slice, for code that just wants every measurement a packet references regardless of its kind. ### 1.2 `PacketDef` Struct used to define the structure of a packet a board can send or recieve. #### `id` ID of a packet, using the AdjId type which is a u16. Structure of ID is defined by the ADJ documentation. +#### `board` +The owning board's `BoardId`. Carried here too (not just reachable through the owning `Board`) so anything holding just a `&PacketDef` — e.g. a lookup table indexed by `AdjId` — knows which board it belongs to without a separate index back to it. #### `name` Human-readable String shown to the user to identify packet. #### `kind` -PacketKind Enum used to classify each packet. -#### `measurements` -Vector list of measurements attached to a packet. +`PacketKind` enum: both what kind of packet this is, and the measurement shape — if any — specific to that kind. ### 1.3 `Board` Struct used to identify a single board in the vehicle. @@ -40,12 +44,12 @@ Board's IpAddress used to open TCP/UDP connections. #### `mac` Board's MAC address #### `packets` -The Vector list of packets this board can send or receive. +The packets this board can send or receive, as a `HashMap` keyed by id — the ADJ gives packets no meaningful order, so this is a map, not a list. ### 1.4 `PodData` Struct used to package all the structs of a vehicle. #### `boards` -Vector list of boards in the Pod +Every board of the vehicle, as a `HashMap` keyed by id — the ADJ doesn't give boards any meaningful order either. ## 2. `id.rs` @@ -116,7 +120,7 @@ Second of Timestamp of values 0–59. The sub-second fraction, as the raw byte on the wire. Its exact unit (e.g. milliseconds, or 1/256ths of a second) hasn't been confirmed yet, so it is kept as a raw `u8` here instead of converted to something like a `Duration` — convert it once the unit is settled. ### 4.2 `DataPacket` -Struct for the decoded values of the measurements a board just sent. Values are positional: they are not individually tagged with their measurement ID, but written in the order their `Measurement`s appear in `PacketDef::measurements`. +Struct for the decoded values of the measurements a board just sent. Values are positional: they are not individually tagged with their measurement ID, but written in the order their `Measurement`s appear in this packet's `PacketKind::Data` list. #### `id` Which packet definition this is an instance of (`AdjId`). diff --git a/backend/crates/core/src/model/board.rs b/backend/crates/core/src/model/board.rs index 3692a74f9..18cef3c3e 100644 --- a/backend/crates/core/src/model/board.rs +++ b/backend/crates/core/src/model/board.rs @@ -14,19 +14,38 @@ use super::{AdjId, BoardId, MacAddress, Measurement}; use std::collections::HashMap; use std::net::IpAddr; -/// What kind of packet a [`PacketDef`] declares. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +/// What kind of packet a [`PacketDef`] declares, carrying whatever +/// measurement shape — if any — is specific to that kind. Not every kind +/// has measurements, so this says so in the type instead of forcing every +/// [`PacketDef`] through one shared `measurements: Vec` field +/// regardless of whether that's meaningful for it. +#[derive(Debug, Clone, PartialEq)] pub enum PacketKind { - /// Measurements sent by a board. - Data, - /// Protection associated with a measurement. - Protection, - /// An order sent to a board. - Order, - /// A message sent by a board. + /// A board's periodic telemetry: one value per measurement, decoded + /// positionally in this order. + Data(Vec), + /// The single measurement one of a board's declared protections + /// watches. + Protection(Measurement), + /// A command sent to a board. Many orders take no parameters at all. + Order(Vec), + /// A free-text log line. Never carries measurement data. Message, } +impl PacketKind { + /// Every measurement this packet's kind references, flattened — for + /// code that doesn't care which kind this is, just what measurements + /// it touches. + pub fn measurements(&self) -> &[Measurement] { + match self { + PacketKind::Data(measurements) | PacketKind::Order(measurements) => measurements, + PacketKind::Protection(measurement) => std::slice::from_ref(measurement), + PacketKind::Message => &[], + } + } +} + /// The declaration of a single packet a board can send or receive, as /// defined by the ADJ. /// @@ -44,10 +63,9 @@ pub struct PacketDef { pub board: BoardId, /// The human-readable name shown to the user. pub name: String, - /// Whether this is data, order, protection or message. + /// Whether this is data, order, protection or message — and the + /// measurement shape specific to that kind, if any. pub kind: PacketKind, - /// The measurements this packet carries, in ADJ order. - pub measurements: Vec, } /// A single board of the vehicle, as defined by the ADJ. @@ -112,8 +130,7 @@ mod tests { id: AdjId(1000), board: BoardId(1), name: "bcu_data".to_string(), - kind: PacketKind::Data, - measurements: vec![sample_measurement()], + kind: PacketKind::Data(vec![sample_measurement()]), }, )]), }; @@ -122,8 +139,10 @@ mod tests { let Some(packet) = board.packets.get(&AdjId(1000)) else { unreachable!("the packet we just inserted should be there"); }; - assert_eq!(packet.measurements.len(), 1); - assert_eq!(packet.kind, PacketKind::Data); + let PacketKind::Data(measurements) = &packet.kind else { + unreachable!("packet should be Data"); + }; + assert_eq!(measurements.len(), 1); assert_eq!(board.mac.to_string(), "00:11:22:33:44:55"); } } diff --git a/backend/crates/core/src/model/packet.rs b/backend/crates/core/src/model/packet.rs index 61a3bd797..7ac91f048 100644 --- a/backend/crates/core/src/model/packet.rs +++ b/backend/crates/core/src/model/packet.rs @@ -38,8 +38,8 @@ pub struct ShortTimestamp { /// The wire protocol is positional: values are not individually tagged /// with their measurement's id, just written back to back in the order /// their [`super::Measurement`]s appear in this packet's -/// [`super::PacketDef::measurements`]. `values[i]` is the decoded value of -/// `measurements[i]` in that definition — matching them up by position is +/// [`super::PacketKind::Data`] list. `values[i]` is the decoded value of +/// that list's `i`-th measurement — matching them up by position is /// `protocol`'s job, this type just holds the result in that same order. #[derive(Debug, Clone, PartialEq)] pub struct DataPacket { From 9451b98f2974a5e849198c94328bbd594d8afae7 Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Fri, 9 Oct 2026 14:19:46 +0200 Subject: [PATCH 036/225] feat(backend, prtotocol): update protocol --- backend/crates/core/src/lib.rs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/backend/crates/core/src/lib.rs b/backend/crates/core/src/lib.rs index e1eda88f6..009b6d295 100644 --- a/backend/crates/core/src/lib.rs +++ b/backend/crates/core/src/lib.rs @@ -10,3 +10,8 @@ pub mod model; /// [`model::PodData`], plus backend-session metadata not modeled as /// vehicle data. See [`adj::load_from_dir`]. pub mod adj; + +/// Translates bytes into typed packets and back, using the shapes +/// [`adj`] declares as the schema. See [`protocol::wire`], +/// [`protocol::tcp`], [`protocol::udp`]. +pub mod protocol; From dba85ba46e2d189f7d47dd381721d8cbe166a42d Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Fri, 9 Oct 2026 14:20:19 +0200 Subject: [PATCH 037/225] feat(backend, protocol): main structure --- backend/crates/core/src/protocol.rs | 24 ++ backend/crates/core/src/protocol/error.rs | 92 +++++ backend/crates/core/src/protocol/index.rs | 78 +++++ backend/crates/core/src/protocol/packet.rs | 11 + .../crates/core/src/protocol/packet/data.rs | 19 ++ .../core/src/protocol/packet/message.rs | 16 + .../crates/core/src/protocol/packet/order.rs | 18 + .../core/src/protocol/packet/protection.rs | 26 ++ backend/crates/core/src/protocol/tcp.rs | 49 +++ backend/crates/core/src/protocol/udp.rs | 17 + backend/crates/core/src/protocol/wire.rs | 316 ++++++++++++++++++ 11 files changed, 666 insertions(+) create mode 100644 backend/crates/core/src/protocol.rs create mode 100644 backend/crates/core/src/protocol/error.rs create mode 100644 backend/crates/core/src/protocol/index.rs create mode 100644 backend/crates/core/src/protocol/packet.rs create mode 100644 backend/crates/core/src/protocol/packet/data.rs create mode 100644 backend/crates/core/src/protocol/packet/message.rs create mode 100644 backend/crates/core/src/protocol/packet/order.rs create mode 100644 backend/crates/core/src/protocol/packet/protection.rs create mode 100644 backend/crates/core/src/protocol/tcp.rs create mode 100644 backend/crates/core/src/protocol/udp.rs create mode 100644 backend/crates/core/src/protocol/wire.rs diff --git a/backend/crates/core/src/protocol.rs b/backend/crates/core/src/protocol.rs new file mode 100644 index 000000000..4ee7cfdd1 --- /dev/null +++ b/backend/crates/core/src/protocol.rs @@ -0,0 +1,24 @@ +//! Translates bytes <-> typed packets ([`crate::model::Packet`] and +//! friends), using the shapes [`crate::adj`] already declared +//! (`PacketDef`, `Measurement`) as the schema. Never touches a real +//! socket — that's `core::net`'s job, which calls into this module's +//! functions and owns the actual `TcpStream`/`UdpSocket`. +//! +//! The TCP/UDP split lives in the *types* each submodule can produce: +//! [`crate::protocol::udp::decode_datagram`] can only ever return a +//! `DataPacket`, [`crate::protocol::tcp::decode_next`] only a +//! [`crate::protocol::tcp::TcpFrame`] (`Protection`/`Message`) — the +//! compiler enforces the separation the ADJ itself draws between what +//! travels over which transport, not runtime convention. `tcp`/`udp` +//! themselves are thin wrappers around [`crate::protocol::packet`], which +//! does the actual per-packet-kind work independent of transport. + +mod error; +mod index; +pub mod packet; +pub mod tcp; +pub mod udp; +pub mod wire; + +pub use error::{DecodeError, EncodeError}; +pub use index::Index; diff --git a/backend/crates/core/src/protocol/error.rs b/backend/crates/core/src/protocol/error.rs new file mode 100644 index 000000000..64660e696 --- /dev/null +++ b/backend/crates/core/src/protocol/error.rs @@ -0,0 +1,92 @@ +//! Errors produced while translating bytes into packets and back. + +use crate::model::AdjId; + +/// An error decoding bytes into a packet. +#[derive(Debug, thiserror::Error)] +pub enum DecodeError { + /// No packet is declared with this id. + #[error("unknown packet id {0:?}")] + UnknownId(AdjId), + + /// Ran out of bytes before a complete value could be decoded. + #[error("not enough bytes to decode a value")] + UnexpectedEof, + + /// An I/O error while reading from a stream (TCP only — a UDP + /// datagram is decoded from an in-memory buffer, never a stream). + #[error("I/O error reading a frame")] + Io(#[from] std::io::Error), + + /// A decoded enum value's index doesn't match any of its declared + /// options. + #[error("enum value {index} is out of range for {options} option(s)")] + InvalidEnumValue { + /// The decoded index. + index: u32, + /// How many options the measurement declares. + options: usize, + }, + + /// A free-text field (`origin`/`message`) had no terminating `0` byte + /// within its maximum length. + #[error("string field wasn't terminated within {max} bytes")] + UnterminatedString { + /// The field's maximum length. + max: usize, + }, + + /// A looked-up packet exists, but isn't the kind this function expects + /// (e.g. `packet::data::decode` found an id that resolves to an + /// `Order`). + #[error("packet {id:?} isn't the expected kind")] + WrongKind { + /// The packet whose kind didn't match. + id: AdjId, + }, +} + +/// An error encoding a packet into bytes. +#[derive(Debug, thiserror::Error)] +pub enum EncodeError { + /// No packet is declared with this id. + #[error("unknown packet id {0:?}")] + UnknownId(AdjId), + + /// The order didn't provide a value for every field its declaration + /// expects. + #[error("order needs {expected} field(s), got {got}")] + WrongFieldCount { + /// How many fields the order's `PacketDef` declares. + expected: usize, + /// How many fields were actually given. + got: usize, + }, + + /// A field's [`crate::model::Value`] doesn't match the kind its + /// [`crate::model::Measurement`] declares (e.g. a `Value::Bool` for a + /// numeric field). + #[error("value doesn't match its declared type")] + TypeMismatch, + + /// A numeric value doesn't fit the wire type's representable range + /// (or is NaN). + #[error("value {value} is out of range for this wire type ({min}..={max})")] + OutOfRange { + /// The value that didn't fit. + value: f64, + /// The wire type's minimum representable value. + min: f64, + /// The wire type's maximum representable value. + max: f64, + }, + + /// A looked-up packet exists, but isn't the kind this function expects + /// (e.g. `packet::order::encode` found an id that resolves to a + /// `Data` packet). + #[error("packet {id:?} isn't the expected kind")] + WrongKind { + /// The packet whose kind didn't match. + id: AdjId, + }, +} diff --git a/backend/crates/core/src/protocol/index.rs b/backend/crates/core/src/protocol/index.rs new file mode 100644 index 000000000..c23397bf8 --- /dev/null +++ b/backend/crates/core/src/protocol/index.rs @@ -0,0 +1,78 @@ +//! The `id -> PacketDef` lookup `tcp`/`udp` decode against. + +use crate::model::{AdjId, PacketDef, PodData}; +use std::collections::HashMap; + +/// A lookup table from a packet's [`AdjId`] to its declaration, built once +/// from a loaded ADJ's [`PodData`]. +/// +/// Owns its own copy of every [`PacketDef`] (cloned out of `PodData` at +/// construction) rather than borrowing, so it carries no lifetime and can +/// be shared across `tokio::spawn`ed tasks via `Arc` without a +/// fight with the borrow checker. Knows nothing about networking (no +/// `IpAddr`/`SocketAddr`) — that bookkeeping belongs to `core::net`, not +/// here. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct Index { + by_id: HashMap, +} + +impl Index { + /// Builds an index over every packet declared by every board in + /// `pod_data`. + pub fn new(pod_data: &PodData) -> Self { + let by_id = pod_data + .boards + .values() + .flat_map(|board| board.packets.values()) + .map(|packet| (packet.id, packet.clone())) + .collect(); + Self { by_id } + } + + /// Looks up a packet's declaration by id. + pub fn packet(&self, id: AdjId) -> Option<&PacketDef> { + self.by_id.get(&id) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::model::{Board, BoardId, MacAddress, PacketKind}; + use std::net::IpAddr; + + fn sample_pod_data() -> PodData { + let packet = PacketDef { + id: AdjId(1000), + board: BoardId(1), + name: "bcu_data".to_string(), + kind: PacketKind::Data(vec![]), + }; + let board = Board { + id: BoardId(1), + name: "BCU".to_string(), + ip: IpAddr::from([192, 168, 0, 10]), + mac: MacAddress([0; 6]), + packets: HashMap::from([(packet.id, packet)]), + }; + PodData { + boards: HashMap::from([(board.id, board)]), + } + } + + #[test] + fn finds_a_packet_declared_on_any_board() { + let index = Index::new(&sample_pod_data()); + let Some(packet) = index.packet(AdjId(1000)) else { + unreachable!("packet 1000 was declared in the sample pod data"); + }; + assert_eq!(packet.name, "bcu_data"); + } + + #[test] + fn unknown_id_is_not_found() { + let index = Index::new(&sample_pod_data()); + assert!(index.packet(AdjId(9999)).is_none()); + } +} diff --git a/backend/crates/core/src/protocol/packet.rs b/backend/crates/core/src/protocol/packet.rs new file mode 100644 index 000000000..b1c19e246 --- /dev/null +++ b/backend/crates/core/src/protocol/packet.rs @@ -0,0 +1,11 @@ +//! Encode/decode for one specific kind of packet, independent of which +//! transport carries it — that mapping lives in [`super::tcp`]/ +//! [`super::udp`], which are thin wrappers around these. Each kind only +//! implements whichever direction it actually needs: a `Data` packet is +//! only ever received (over UDP), an `Order` only ever sent (over TCP), +//! so there's no `encode` for the former or `decode` for the latter. + +pub mod data; +pub mod message; +pub mod order; +pub mod protection; diff --git a/backend/crates/core/src/protocol/packet/data.rs b/backend/crates/core/src/protocol/packet/data.rs new file mode 100644 index 000000000..bc613cc8c --- /dev/null +++ b/backend/crates/core/src/protocol/packet/data.rs @@ -0,0 +1,19 @@ +//! Decodes a `Data` packet: a board's periodic telemetry. Only ever +//! received, over UDP — a board never receives one back. + +use crate::model::DataPacket; +use crate::protocol::{DecodeError, Index}; + +/// Decodes a complete, already-delimited buffer into a [`DataPacket`], +/// resolving its field shapes against `index`. +pub fn decode(bytes: &[u8], index: &Index) -> Result { + let _ = (bytes, index); + todo!( + "read the leading 16-bit id; look up its PacketDef in `index` \ + (UnknownId if absent); match its `kind` for \ + PacketKind::Data(measurements) (WrongKind if it's some other \ + kind); decode each measurement's value positionally via \ + wire::decode_value, advancing through `bytes` using each \ + measurement's own wire width" + ) +} diff --git a/backend/crates/core/src/protocol/packet/message.rs b/backend/crates/core/src/protocol/packet/message.rs new file mode 100644 index 000000000..88f70bd9c --- /dev/null +++ b/backend/crates/core/src/protocol/packet/message.rs @@ -0,0 +1,16 @@ +//! Decodes a `Message` packet: a board's free-text log line. Only ever +//! received, over TCP. + +use crate::model::{MessageLevel, MessagePacket}; +use crate::protocol::DecodeError; +use std::io::Read; + +/// Decodes a message frame's remaining bytes, given the frame's +/// already-resolved severity level (`tcp::decode_next`'s job). +pub fn decode(reader: impl Read, level: MessageLevel) -> Result { + let _ = (reader, level); + todo!( + "read the timestamp, then the null-terminated `origin` (max 48 \ + bytes) and `message` (max 320 bytes) strings" + ) +} diff --git a/backend/crates/core/src/protocol/packet/order.rs b/backend/crates/core/src/protocol/packet/order.rs new file mode 100644 index 000000000..4eb11a6cf --- /dev/null +++ b/backend/crates/core/src/protocol/packet/order.rs @@ -0,0 +1,18 @@ +//! Encodes an `Order` packet: a command sent to a board. Only ever sent, +//! over TCP — the backend never receives one back. + +use crate::model::OrderPacket; +use crate::protocol::{EncodeError, Index}; + +/// Encodes `order` into the bytes to write to a board's connection, +/// resolving its field shapes against `index`. +pub fn encode(order: &OrderPacket, index: &Index) -> Result, EncodeError> { + let _ = (order, index); + todo!( + "look up order.id in `index` to get its PacketDef (UnknownId if \ + absent); match its `kind` for PacketKind::Order(measurements) \ + (WrongKind if it's some other kind); error with WrongFieldCount \ + if order.fields.len() doesn't match measurements.len(); encode \ + the id then each field positionally via wire::encode_value" + ) +} diff --git a/backend/crates/core/src/protocol/packet/protection.rs b/backend/crates/core/src/protocol/packet/protection.rs new file mode 100644 index 000000000..e00a4acec --- /dev/null +++ b/backend/crates/core/src/protocol/packet/protection.rs @@ -0,0 +1,26 @@ +//! Decodes a `Protection` packet: a board reporting one of its declared +//! protections triggered. Only ever received, over TCP. + +use crate::model::{AdjId, ProtectionPacket}; +use crate::protocol::{DecodeError, Index}; +use std::io::Read; + +/// Decodes a protection frame's remaining bytes, given the frame's +/// already-read compound id (`tcp::decode_next`'s job), resolving the +/// watched measurement's wire type against `index`. +pub fn decode( + reader: impl Read, + compound_id: AdjId, + index: &Index, +) -> Result { + let _ = (reader, compound_id, index); + todo!( + "look up compound_id's PacketDef in `index` (already keyed by \ + this exact compound id, see adj::raw::loader); match its `kind` \ + for PacketKind::Protection(measurement) (WrongKind if it's some \ + other kind) to get the watched measurement's wire type; \ + separately split compound_id's bits into (measurement, position) \ + to fill ProtectionPacket's `measurement`/`protection` fields; \ + read the timestamp, then the value via wire::decode_value" + ) +} diff --git a/backend/crates/core/src/protocol/tcp.rs b/backend/crates/core/src/protocol/tcp.rs new file mode 100644 index 000000000..af3882253 --- /dev/null +++ b/backend/crates/core/src/protocol/tcp.rs @@ -0,0 +1,49 @@ +//! Transport-level TCP framing: a board's dedicated connection carries +//! triggered protections and free-text messages from the board, and +//! orders to it. Never a `Data` packet — see the module doc on +//! [`super`]. +//! +//! Both functions here are thin: the actual per-kind decoding lives in +//! [`super::packet::protection`]/[`super::packet::message`]/ +//! [`super::packet::order`], independent of TCP. This module only adds +//! the transport-level guarantee — [`decode_next`] can only ever return +//! a [`TcpFrame`], never a `DataPacket`. + +use super::{DecodeError, EncodeError, Index, packet}; +use crate::model::{MessagePacket, OrderPacket, ProtectionPacket}; +use std::io::Read; + +/// A decoded TCP frame — everything a board can send to the backend over +/// its dedicated TCP connection. +#[derive(Debug, Clone, PartialEq)] +pub enum TcpFrame { + /// A protection triggered. + Protection(ProtectionPacket), + /// A free-text message. + Message(MessagePacket), +} + +/// Reads and decodes the next complete frame from `reader`, resolving +/// field shapes against `index`. +/// +/// Reads the frame's leading 16-bit id first, then decides which of +/// [`super::packet::protection::decode`] (the id's high 3 bits are a +/// protection's position, non-zero) or [`super::packet::message::decode`] +/// (the id matches one of `general_info.json`'s `message_ids`) to hand +/// the rest of the frame to, wrapping the result in the matching +/// [`TcpFrame`] variant. +pub fn decode_next(reader: impl Read, index: &Index) -> Result { + let _ = (reader, index); + todo!( + "read the leading 16-bit id; if its top 3 bits are non-zero, call \ + packet::protection::decode; otherwise resolve it against \ + general_info.json's message_ids (not yet reachable from `Index` \ + — needs AdjInfo too) and call packet::message::decode; wrap \ + either result in the matching TcpFrame variant" + ) +} + +/// Encodes `order` into the bytes to write to the board's connection. +pub fn encode_order(order: &OrderPacket, index: &Index) -> Result, EncodeError> { + packet::order::encode(order, index) +} diff --git a/backend/crates/core/src/protocol/udp.rs b/backend/crates/core/src/protocol/udp.rs new file mode 100644 index 000000000..4eb0d6723 --- /dev/null +++ b/backend/crates/core/src/protocol/udp.rs @@ -0,0 +1,17 @@ +//! Transport-level UDP framing: the shared socket carries periodic +//! telemetry (`Data` packets) from any board. Receive-only — the backend +//! never sends anything over this socket. +//! +//! The actual decoding lives in [`super::packet::data`], independent of +//! UDP — this module only adds the transport-level guarantee: a UDP +//! datagram is a complete, already-delimited buffer (the OS preserves +//! datagram boundaries even on a socket shared by every board), unlike +//! [`super::tcp::decode_next`]'s stream. + +use super::{DecodeError, Index, packet}; +use crate::model::DataPacket; + +/// Decodes a single UDP datagram's bytes into a [`DataPacket`]. +pub fn decode_datagram(bytes: &[u8], index: &Index) -> Result { + packet::data::decode(bytes, index) +} diff --git a/backend/crates/core/src/protocol/wire.rs b/backend/crates/core/src/protocol/wire.rs new file mode 100644 index 000000000..6dc151e04 --- /dev/null +++ b/backend/crates/core/src/protocol/wire.rs @@ -0,0 +1,316 @@ +//! Byte <-> [`Value`] codec for a single measurement, given its declared +//! [`MeasurementKind`]. The one piece of `protocol` with no framing or id +//! lookup — just "this type, these bytes, that value" and back. `tcp`/ +//! `udp` build their packet-level decoding on top of this. +//! +//! Every wire width here is fixed by the measurement's own `kind` (a +//! `NumericKind` always has a known byte width; booleans and enums are +//! fixed-width too), so decoding never needs to report back how many +//! bytes it consumed — the caller already has the `MeasurementKind` (from +//! the `Measurement` it's decoding) and can derive the width from it +//! directly if it needs to advance through a buffer. +//! +//! [`decode_value`]/[`encode_value`] are thin dispatchers: they only pick +//! which per-kind function to call. All the actual work lives in its own +//! public function (`decode_numeric`, `decode_boolean`, `decode_enum`...), +//! each independently implementable and testable. + +use super::{DecodeError, EncodeError}; +use crate::model::{MeasurementKind, NumericKind, Value}; + +/// Decodes a single value from the front of `bytes`, according to `kind`. +pub fn decode_value(bytes: &[u8], kind: &MeasurementKind) -> Result { + match kind { + MeasurementKind::Numeric { wire_type } => decode_numeric(bytes, *wire_type), + MeasurementKind::Boolean => decode_boolean(bytes), + MeasurementKind::Enum { options } => decode_enum(bytes, options), + } +} + +/// Encodes a single value according to `kind`. +pub fn encode_value(value: &Value, kind: &MeasurementKind) -> Result, EncodeError> { + match kind { + MeasurementKind::Numeric { wire_type } => encode_numeric(value, *wire_type), + MeasurementKind::Boolean => encode_boolean(value), + MeasurementKind::Enum { options } => encode_enum(value, options), + } +} + +/// Decodes a numeric value of the given wire type, little-endian. +pub fn decode_numeric(bytes: &[u8], wire_type: NumericKind) -> Result { + fn take(bytes: &[u8]) -> Result<[u8; N], DecodeError> { + bytes + .get(..N) + .and_then(|slice| slice.try_into().ok()) + .ok_or(DecodeError::UnexpectedEof) + } + + let number: f64 = match wire_type { + NumericKind::U8 => f64::from(u8::from_le_bytes(take::<1>(bytes)?)), + NumericKind::U16 => f64::from(u16::from_le_bytes(take::<2>(bytes)?)), + NumericKind::U32 => f64::from(u32::from_le_bytes(take::<4>(bytes)?)), + NumericKind::U64 => u64::from_le_bytes(take::<8>(bytes)?) as f64, + NumericKind::I8 => f64::from(i8::from_le_bytes(take::<1>(bytes)?)), + NumericKind::I16 => f64::from(i16::from_le_bytes(take::<2>(bytes)?)), + NumericKind::I32 => f64::from(i32::from_le_bytes(take::<4>(bytes)?)), + NumericKind::I64 => i64::from_le_bytes(take::<8>(bytes)?) as f64, + NumericKind::F32 => f64::from(f32::from_le_bytes(take::<4>(bytes)?)), + NumericKind::F64 => f64::from_le_bytes(take::<8>(bytes)?), + }; + + Ok(Value::Number(number)) +} + +/// Encodes a numeric value as the given wire type, little-endian. +/// +/// Errors with [`EncodeError::OutOfRange`] if `value` doesn't fit the +/// wire type's representable range (this also rejects NaN, which compares +/// false to every bound). +pub fn encode_numeric(value: &Value, wire_type: NumericKind) -> Result, EncodeError> { + let Value::Number(number) = value else { + return Err(EncodeError::TypeMismatch); + }; + let number = *number; + + let (min, max) = numeric_range(wire_type); + if !(min..=max).contains(&number) { + return Err(EncodeError::OutOfRange { + value: number, + min, + max, + }); + } + + Ok(match wire_type { + NumericKind::U8 => vec![number as u8], // no need to call `to_le_bytes` for a single byte + NumericKind::U16 => (number as u16).to_le_bytes().to_vec(), + NumericKind::U32 => (number as u32).to_le_bytes().to_vec(), + NumericKind::U64 => (number as u64).to_le_bytes().to_vec(), + NumericKind::I8 => (number as i8).to_le_bytes().to_vec(), + NumericKind::I16 => (number as i16).to_le_bytes().to_vec(), + NumericKind::I32 => (number as i32).to_le_bytes().to_vec(), + NumericKind::I64 => (number as i64).to_le_bytes().to_vec(), + NumericKind::F32 => (number as f32).to_le_bytes().to_vec(), + NumericKind::F64 => number.to_le_bytes().to_vec(), + }) +} + +/// The `[min, max]` range a wire type can represent, as `f64` bounds. +fn numeric_range(wire_type: NumericKind) -> (f64, f64) { + match wire_type { + NumericKind::U8 => (f64::from(u8::MIN), f64::from(u8::MAX)), + NumericKind::U16 => (f64::from(u16::MIN), f64::from(u16::MAX)), + NumericKind::U32 => (f64::from(u32::MIN), f64::from(u32::MAX)), + NumericKind::U64 => (u64::MIN as f64, u64::MAX as f64), + NumericKind::I8 => (f64::from(i8::MIN), f64::from(i8::MAX)), + NumericKind::I16 => (f64::from(i16::MIN), f64::from(i16::MAX)), + NumericKind::I32 => (f64::from(i32::MIN), f64::from(i32::MAX)), + NumericKind::I64 => (i64::MIN as f64, i64::MAX as f64), + NumericKind::F32 => (f64::from(f32::MIN), f64::from(f32::MAX)), + NumericKind::F64 => (f64::MIN, f64::MAX), + } +} + +/// Decodes a boolean value. +/// +/// Wire width isn't settled yet — not specified anywhere in the ADJv3 +/// spec read so far. Confirm against firmware before implementing. +pub fn decode_boolean(bytes: &[u8]) -> Result { + let _ = bytes; + todo!("confirm the wire width firmware uses for a boolean measurement") +} + +/// Encodes a boolean value. +pub fn encode_boolean(value: &Value) -> Result, EncodeError> { + let _ = value; + todo!("confirm the wire width firmware uses for a boolean measurement") +} + +/// Decodes an enum value: a single `uint8` byte, the index into +/// `options`. Returns the option's text, not its index — see +/// [`encode_enum`] for why that's not symmetric. +pub fn decode_enum(bytes: &[u8], options: &[String]) -> Result { + let &index = bytes.first().ok_or(DecodeError::UnexpectedEof)?; + let Some(option) = options.get(usize::from(index)) else { + return Err(DecodeError::InvalidEnumValue { + index: u32::from(index), + options: options.len(), + }); + }; + Ok(Value::Enum(option.clone())) +} + +/// Encodes an enum value as a single `uint8` byte. +/// +/// `value` is the already-selected index (e.g. a frontend dropdown +/// already resolved to its position in `options`), **not** the option's +/// text — unlike [`decode_enum`], which produces the text. Errors with +/// [`EncodeError::OutOfRange`] if the index isn't a whole number or +/// doesn't fall within `options`. +pub fn encode_enum(value: &Value, options: &[String]) -> Result, EncodeError> { + let Value::Number(index) = value else { + return Err(EncodeError::TypeMismatch); + }; + let index = *index; + let max = options.len().saturating_sub(1) as f64; + + let in_range = !options.is_empty() && index.fract() == 0.0 && (0.0..=max).contains(&index); + if !in_range { + return Err(EncodeError::OutOfRange { + value: index, + min: 0.0, + max, + }); + } + + Ok(vec![index as u8]) // no need to call `to_le_bytes` for a single byte +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn decodes_an_unsigned_integer_little_endian() { + let Ok(value) = decode_numeric(&[0x34, 0x12], NumericKind::U16) else { + unreachable!("decoding a well-formed U16 should succeed"); + }; + assert_eq!(value, Value::Number(0x1234 as f64)); + } + + #[test] + fn decodes_a_signed_integer_little_endian() { + let Ok(value) = decode_numeric(&[0xFF], NumericKind::I8) else { + unreachable!("decoding a well-formed I8 should succeed"); + }; + assert_eq!(value, Value::Number(-1.0)); + } + + #[test] + fn decodes_floats_little_endian() { + let bytes = 1.5f32.to_le_bytes(); + let Ok(value) = decode_numeric(&bytes, NumericKind::F32) else { + unreachable!("decoding a well-formed F32 should succeed"); + }; + assert_eq!(value, Value::Number(1.5)); + } + + #[test] + fn decode_numeric_rejects_short_input() { + assert!(matches!( + decode_numeric(&[0x00], NumericKind::U32), + Err(DecodeError::UnexpectedEof) + )); + } + + #[test] + fn numeric_round_trips_through_encode_then_decode() { + let value = Value::Number(1234.0); + let Ok(bytes) = encode_numeric(&value, NumericKind::U16) else { + unreachable!("encoding a well-formed value should succeed"); + }; + let Ok(decoded) = decode_numeric(&bytes, NumericKind::U16) else { + unreachable!("decoding what we just encoded should succeed"); + }; + assert_eq!(decoded, value); + } + + #[test] + fn encode_numeric_rejects_the_wrong_value_variant() { + assert!(matches!( + encode_numeric(&Value::Bool(true), NumericKind::U8), + Err(EncodeError::TypeMismatch) + )); + } + + #[test] + fn encode_numeric_rejects_out_of_range_values() { + assert!(matches!( + encode_numeric(&Value::Number(300.0), NumericKind::U8), + Err(EncodeError::OutOfRange { .. }) + )); + assert!(matches!( + encode_numeric(&Value::Number(-1.0), NumericKind::U8), + Err(EncodeError::OutOfRange { .. }) + )); + } + + #[test] + fn encode_numeric_accepts_the_exact_boundary_values() { + assert!(encode_numeric(&Value::Number(0.0), NumericKind::U8).is_ok()); + assert!(encode_numeric(&Value::Number(255.0), NumericKind::U8).is_ok()); + } + + #[test] + fn encode_numeric_rejects_nan() { + assert!(matches!( + encode_numeric(&Value::Number(f64::NAN), NumericKind::F32), + Err(EncodeError::OutOfRange { .. }) + )); + } + + #[test] + fn decodes_an_enum_value_by_index_into_its_text() { + let options = vec!["Idle".to_string(), "Fault".to_string()]; + let Ok(value) = decode_enum(&[1], &options) else { + unreachable!("decoding a valid enum index should succeed"); + }; + assert_eq!(value, Value::Enum("Fault".to_string())); + } + + #[test] + fn decode_enum_rejects_an_out_of_range_index() { + let options = vec!["Idle".to_string()]; + assert!(matches!( + decode_enum(&[5], &options), + Err(DecodeError::InvalidEnumValue { + index: 5, + options: 1 + }) + )); + } + + #[test] + fn decode_enum_rejects_empty_input() { + assert!(matches!( + decode_enum(&[], &[]), + Err(DecodeError::UnexpectedEof) + )); + } + + #[test] + fn encodes_an_enum_value_from_its_already_selected_index() { + let options = vec!["Idle".to_string(), "Fault".to_string()]; + let Ok(bytes) = encode_enum(&Value::Number(1.0), &options) else { + unreachable!("encoding a valid index should succeed"); + }; + assert_eq!(bytes, vec![1]); + } + + #[test] + fn encode_enum_rejects_an_out_of_range_index() { + let options = vec!["Idle".to_string()]; + assert!(matches!( + encode_enum(&Value::Number(1.0), &options), + Err(EncodeError::OutOfRange { .. }) + )); + } + + #[test] + fn encode_enum_rejects_a_fractional_index() { + let options = vec!["Idle".to_string(), "Fault".to_string()]; + assert!(matches!( + encode_enum(&Value::Number(0.5), &options), + Err(EncodeError::OutOfRange { .. }) + )); + } + + #[test] + fn encode_enum_rejects_the_wrong_value_variant() { + let options = vec!["Idle".to_string()]; + assert!(matches!( + encode_enum(&Value::Enum("Idle".to_string()), &options), + Err(EncodeError::TypeMismatch) + )); + } +} From 42f7c1ea6bb485e45ab536cae7454cc865315d37 Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Sat, 10 Oct 2026 17:17:17 +0200 Subject: [PATCH 038/225] docs: minor changes and clarifications --- backend/crates/core/src/ntp/README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/backend/crates/core/src/ntp/README.md b/backend/crates/core/src/ntp/README.md index 8fcaf15fa..aa75db9be 100644 --- a/backend/crates/core/src/ntp/README.md +++ b/backend/crates/core/src/ntp/README.md @@ -1,11 +1,11 @@ # NTP module -NTP (**Network Time Protocol**) is a protocol used to synchronize clocks between devices over a network. In this project, it is used to synchronize the boards in the pod. +NTP (**Network Time Protocol**) is a protocol used to synchronize clocks between devices over a network. In this project, it is used to synchronize the boards in the pod, with the *backend*. There are two related concepts worth mentioning: - **SNTP (Simple Network Time Protocol):** a simplified subset of NTP intended for simpler synchronization scenarios, such as clients using a single time server. -- **NTS (Network Time Security):** an extension to NTP that adds authentication and cryptographic security to time synchronization. +- **NTS (Network Time Security):** an extension to NTP that adds authentication and cryptographic security to time synchronization (not used in this project). The boards in this project use **SNTP**. However, this module implements an **NTP server**, since NTP and SNTP use compatible protocol messages and are interoperable. An SNTP client can therefore communicate with this NTP server as defined by RFC 5905. @@ -27,5 +27,5 @@ The standard NTP port is `123`, but this project uses `8123` as its default port The module documentation can be generated and opened with: ```bash -cargo doc --open -p software-core -F ntp +cargo doc --open -p software-core -F ntp --no-deps ``` \ No newline at end of file From c2b9b871281f2a5bf39f86c3a4110854181a27fa Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Sat, 10 Oct 2026 17:21:59 +0200 Subject: [PATCH 039/225] docs: add tracing use to readme --- backend/crates/core/src/ntp/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/backend/crates/core/src/ntp/README.md b/backend/crates/core/src/ntp/README.md index aa75db9be..682784f52 100644 --- a/backend/crates/core/src/ntp/README.md +++ b/backend/crates/core/src/ntp/README.md @@ -11,7 +11,7 @@ The boards in this project use **SNTP**. However, this module implements an **NT ## Implementation -The server is implemented using the [`ntp_usg-server`](https://crates.io/crates/ntp_usg-server) crate with the **Tokio** runtime. +The server is implemented using the [`ntp_usg-server`](https://crates.io/crates/ntp_usg-server) crate with the **Tokio** runtime. It also uses [`tracing`](https://crates.io/crates/tracing) crate for logging. The crate handles the NTP protocol logic, including request parsing and response generation, while this module is responsible for configuring and starting the server. From ab39194a138c6513b8b2b56485d6d2411b3ad25d Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Sat, 10 Oct 2026 17:25:02 +0200 Subject: [PATCH 040/225] fix(backend, adj): remove acta comunicaciones --- .../core/src/adj/Comunicaciones_Reunion01.qmd | 356 ------------------ 1 file changed, 356 deletions(-) delete mode 100644 backend/crates/core/src/adj/Comunicaciones_Reunion01.qmd diff --git a/backend/crates/core/src/adj/Comunicaciones_Reunion01.qmd b/backend/crates/core/src/adj/Comunicaciones_Reunion01.qmd deleted file mode 100644 index fe6540072..000000000 --- a/backend/crates/core/src/adj/Comunicaciones_Reunion01.qmd +++ /dev/null @@ -1,356 +0,0 @@ ---- -title: "ADJv3" -subtitle: Acta de la 1ª Reunión de comunicaciones -author: "Javier Ribal del Río" -date: 2026/09/16 -department: "ALL" # "SW" o "FW" -attendees: - - Javier Ribal del Río (SW-FW) (1ª y 2ª) - - Jorge Canut (FW) (1ª) - - Víctor López (FW) (1ª y 2ª) - - Aleksandr Globa (FW) (1ª y 2ª) - - Pau Minguet (SW) (2ª) - - Gazi Halawali (SW) (2ª) - - Pablo Pertusa (FW) (2ª) - - Boris Mladenov (2ª) - - Javier Lara (2ª) ---- - -## Contextualización - -El presente documento tiene como objetivo servir como especificación técnica para la implementación del `ADJv3`, partiendo de la base del `ADJv2` definido en el `README.md` del repositorio. El cambio más significativo se corresponde con la separación en forma y concepto de los `messages` y las `protections`. En el pasado, un `message` se correspondía con la información que enviaban las placas al vehículo, y las `protections` eran una implementación de los `messages`; es decir, una `protection` era un `message` con un tipo determinado. Asimismo, el documento también se corresponde con el acta de la primera reunión de comunicaciones. Debido a su larga duración, esta reunión se dividió en dos convocatorias (1ª y 2ª), celebradas los días 10 y 16 de septiembre de 2026, de ahí que el documento recoja las dos fechas y que la asistencia se indique por convocatoria. - -En el Drive del equipo hay unas diapositivas de la reunión que quizá arrojen algo de luz sobre el contenido de este texto. - -\newpage - -## Modificación de la estructura de los `measurements` y modificación de los `id` de los `packets/orders` - -Con el objetivo de dar soporte a las `protections` para cada `measurement`, el campo `id` pasa a ser un identificador único numérico común entre `packets` y `orders`. El rango de este identificador común es $[0, 8.191] = [0, 2^{13} - 1]$ ^[Podríamos definirlo como un `int13`]. Sin embargo, los `id` comprendidos en $[0, 511]$ se corresponden con los *ID* especiales: no asignados a `packets`, `orders` ni `protections`, o reservados para otros fines. - -Sin embargo, no podemos prescindir del `id` textual previamente definido, puesto que es empleado por la generación de código y no puede ser sustituido por el `id` numérico ^[Esto se debe a que actualmente la generación de código utiliza el `id` del `measurement` para generar su variable asociada]. Por ello, definimos un nuevo campo denominado `alias` que se corresponde con el antiguo campo `id` ^[Esta decisión de mantener un campo legado maximiza la compatibilidad con la `logging-view`]. Además, el campo `alias` se corresponde con el identificador para los archivos tipo `packets` y `orders`. - - - -## Incorporación de las `protections` al ADJ - -Las `protections` se desvinculan de la implementación de los `messages`, por lo que es necesario definir una nueva estructura para el paquete a enviar. - -### Estructura del paquete - -El paquete de una `protection` tiene longitud casi fija: una cabecera de 64 bits (`id` más -`timestamp`, con relleno de alineación) seguida del valor que ha disparado la protección, -cuyo tamaño depende del tipo del `measurement` vigilado. - -```{mermaid} -%%| label: fig-estructura-proteccion -%%| fig-cap: "Estructura del paquete de una protección. Las casillas van numeradas por su offset en bits. El campo `value` ocupa el mismo tamaño que el `measurement` asociado (de 8 a 64 bits); aquí se dibuja con 64." -%%| fig-width: 5.2 -%%| fig-pos: 'H' -%%{init: {"packet": {"bitWidth": 15, "rowHeight": 34, "bitsPerRow": 32, "showBits": true}}}%% -packet-beta -0-15: "id" -16-23: "hora" -24-31: "min" -32-39: "seg" -40-47: "subseg" -48-63: "resv" -64-127: "value" -``` - -- `id` (bits 0–15): identificador numérico de la protección. -- `timestamp` (bits 16–47): instante en que salta la protección, con `hora`, `min`, `seg` y - `subseg` en 8 bits cada uno. -- `resv` (bits 48–63): 2 bytes reservados, únicamente para alinear `value` a un offset - múltiplo de 8 bytes. -- `value` (bits 64 en adelante): valor que ha excedido el umbral. Ocupa exactamente el mismo - tamaño que el `measurement` que vigila la protección (de 8 a 64 bits según su `type`), de - modo que el receptor lo decodifica con el mismo codificador que ese `measurement`. - - -### Tipos de `protection` definidos en `general_info.json` - -Los tipos de `protection` que pueden saltar se declaran en `general_info.json`, en un objeto -`protectionTypes` que asocia el nombre de cada protección a su definición: - -``` -{ - "protectionTypes": { - "": { - "range": booleano?, - "text": "", - "textTime": "?" - } - } -} -``` - -- `range`: booleano opcional, `false` por defecto. Indica cuántos límites tiene la - protección: `false` para las de un solo valor (`Above`, `Below`, `Equal`…) y `true` para - las de intervalo (`Range`), en cuyo caso los dos límites se escriben con notación de - intervalo, p. ej. `[233, 333]`. -- `text`: plantilla del mensaje que se muestr aen la control station. Los `{}` se - sustituyen por los límites definidos para la protección (un único valor, o el intervalo - `[min, max]` si `range` es `true`) y el `%`, por el valor que los ha excedido. -- `textTime`: plantilla alternativa para las protecciones de acumulación temporal - (`time_accumulation`), que saltan cuando el valor se mantiene fuera de rango durante un - intervalo dado. Se usa en lugar de `text` y el `%` se sustituye por ese tiempo máximo, no - por el valor. - - -#### Ejemplos de tipos de `protection` - -- `Above` -- `Below` -- `Equal` -- `NotEqual` ^[La protección se encuentra definida en la `ST-LIB`, por el momento no se nos ha ocurrido su propósito] -- `Range` - -### Definición de `protections` en los `measurements` - -Cada `measurement` de `_measurements.json` incorpora los cambios anteriores (el `id` -pasa a ser numérico, de rango $[0, 8.191]$, y el identificador textual antiguo se conserva -en `alias`) y, además, una lista opcional `protections` con las protecciones que vigilan esa -medida: - -``` -{ - "id": número, - "alias": "", - "name": "", - "type": "", - "podUnits": "?", - "displayUnits": "?", - "enumValues": [""]?, - "protections": [ - { - "type": "", - "value": [número] | [número, número], - "fault": booleano?, - "time": "?" - } - ]? -} -``` - -`protections` *array* limitado a 7 protecciones. - -- `type`: uno de los tipos declarados en `protectionTypes` (`Above`, `Below`, `Equal`, - `NotEqual`, `Range`). -- `value`: lista con el o los límites de la protección. Un elemento para las de un solo - valor y dos, `[min, max]`, para `Range`. -- `fault`: booleano opcional, `true` por defecto. Fija la severidad con la que se emite la - protección: `true` la envía como *fault* y `false` como *warning*. -- `time`: opcional, solo para las protecciones de acumulación temporal. Cadena con valor y - unidad (`"500ms"`, `"3s"`…) que indica cuánto tiempo debe mantenerse la medida fuera de - rango antes de que la protección salte, por defecto `0`. - -### Id de las protecciones - -\begin{quote} -\fbox{\parbox{0.92\linewidth}{\raggedright -\textbf{¿Qué es \textit{bit-packing}?}\\[4pt] -Es la técnica de meter varios campos independientes dentro de un mismo entero, cada uno -ocupando solo los bits que necesita, en vez de reservarle un byte o un campo propio. Aquí -el \texttt{uint16} del \texttt{id} empaqueta dos campos: \texttt{pos} (3 bits) e -\texttt{id\_measurement} (13 bits). Se construye desplazando y combinando con operadores a -nivel de bit --- \texttt{(pos << 13) | id\_measurement} --- y se deshace igual, en el otro -sentido: \texttt{pos = id >> 13} e \texttt{id\_measurement = id \& 0x1FFF}. La ventaja es -que no se desperdicia ni un bit; el coste es que, si un consumidor no sabe que el campo va -empaquetado, lo interpreta mal sin que nada se lo avise. -}} -\end{quote} - -Esta codificación no es exclusiva del paquete de la `protection`: como `packets`, `orders` y -`protections` comparten el mismo campo `id` de 16 bits, se aplica al `id` de **cualquier** -paquete del protocolo. Al recibir un `id`, lo primero que se mira son sus 3 bits altos -(`pos`): si valen `000`, el resto son los 13 bits del `id` normal de un `packet`, `order` o -`measurement`; si no, indican qué `protection` (`1`–`7`) del `measurement` de esos 13 bits -ha saltado: - -$$\texttt{id} = (\texttt{pos} \ll 13) \mathbin{|} \texttt{id\_measurement}$$ - -```{mermaid} -%%| label: fig-id-protection -%%| fig-cap: "Id de 16 bits compartido por packets, orders y protections: 3 bits de posición (000 = id normal) + 13 bits del id de measurement/packet/order." -%%| fig-width: 4.6 -%%| fig-pos: 'H' -%%{init: {"packet": {"bitWidth": 22, "rowHeight": 34, "bitsPerRow": 16, "showBits": true}}}%% -packet-beta -0-12: "id measurement" -13-15: "pos" -``` - -| `pos` | Significado | -|:-----:|-------------------------------------------------| -| `000` | `id` normal: `packet`, `order` o `measurement` | -| `001` | `protections[0]` | -| `010` | `protections[1]` | -| `011` | `protections[2]` | -| `100` | `protections[3]` | -| `101` | `protections[4]` | -| `110` | `protections[5]` | -| `111` | `protections[6]` | - -Con `pos` de `1` a `7` caben exactamente las 7 `protections` por `measurement` fijadas -antes; `pos = 0` deja el `id` libre para su uso normal. Como el resto del protocolo, este -`id` compuesto viaja como un único `uint16` en *little-endian* ^[`pos` no ocupa un byte -aparte: son los 3 bits más altos de ese mismo `uint16`, así que quedan repartidos en el -byte alto junto con los 5 bits más significativos de `id_measurement`.]. - - -\newpage - - -## Refactor de los `messages` - -### Estructura del `message` - -```{mermaid} -%%| label: fig-estructura-message -%%| fig-cap: "Estructura del nuevo message. origin (máx. 48 bytes) y message (máx. 320 bytes) son cadenas terminadas en 0, de longitud variable; aquí se dibujan truncadas a 4 bytes." -%%| fig-width: 5.2 -%%| fig-pos: 'H' -%%{init: {"packet": {"bitWidth": 40, "rowHeight": 34, "bitsPerRow": 10, "showBits": true}}}%% -packet-beta -0-1: "id" -2-2: "hora" -3-3: "min" -4-4: "seg" -5-5: "subseg" -6-9: "origin (txt 0)" -10-13: "message (txt 0)" -``` - -- `id` (2 bytes): tipo de mensaje (`uint16`). Reutiliza `message_ids` de `general_info.json` - (ver más abajo): `10` = `fault`, `11` = `warning`, `12` = `info` y, como tipo nuevo, - `13` = `panic`^[Ya estaba definido en la `ST-LIB` y era enmascarado como un mensaje de `fault`, ahora queda incluido en el `ADJ`]. -- `timestamp` (4 bytes): el mismo formato que en las `protections` — `hora`, `min`, `seg` y - `subseg` en un byte cada uno. -- `origin` (hasta 48 bytes, cadena terminada en `0`): de dónde sale el mensaje. Actualmente - es la ruta absoluta del fichero de origen ^[Sería mejor que fuese la ruta relativa desde - la raíz del repositorio de la placa, no la ruta absoluta del sistema en el que se - compiló.]. -- `message` (hasta 320 bytes, cadena terminada en `0`): contenido del mensaje. - -`origin` y `message` llevan tamaño máximo pero longitud variable: al llegar al byte `0` se -entiende que la cadena ha terminado. - -#### Implementación en `general_info.json` - -Reutilizamos los `message_ids` definidos en `general_info.json`, que por el momento estaban -en desuso: - -``` -{ - "message_ids": { - "fault": 10, - "warning": 11, - "info": 12, - "panic": 13 - } -} -``` - -## Adición de la MAC a la información propia de cada placa - -En vista de lo acontecido en la EHW en H11^[Hubo MAC *curiosas* como `67:67:67:67:67:67` que causaban problemas y horas de *debugging*], se va a añadir un campo `mac` que se corresponde con la `MAC` de cada placa con el objetivo de que se use en la generación de código y sea validado por el `adj-validator`. - - -## Gestión de tiempos y `SNTP` - -Se comenta la posibilidad de realizar un *POC* para mirar la viabilidad de utilizar el protocolo `SNTP` para sincronizar reloj de las placas y el backend. Boris comenta que ya estaba implementado pero que no funcionaba. - -Se ocuparán Víctor y Javier Ribal. Mirar el `README` de `SNTP` en la `ST-LIB`. - - -## Módulo `units` - -Se abandona la implementación del `ADJv2`, se desimplementa `podUnits` y su contraparte en `general_info.json`. Se debate sobre la utilidad del módulo y su practicidad. - -Se acuerda implementarlo añadiendo a cada `measurement` un factor para cada operación. - -## Asignar `id` especiales para la `BLCU` - -Se reserva el rango $[20, 29]$ para los paquetes/órdenes asociados a la `BLCU`. - -## Verificación del `ADJ` *hash* - -Se reserva el `id` 2 para la comparación de commits. - -En caso de que estemos utilizando la `VCU` como `master`, durante la conexión `TCP` compararán el *hash* del `ADJ`; si coinciden todos, se pasará al `backend` (si no, se pasará `hash = 0x00...`). - -En la comparación en el `backend`, si coinciden todos, estará bien; si no, y únicamente si está marcada una nueva opción del `backend`, *Different ADJ hash Fault*, se irá a `fault`; si no, simplemente imprimiremos un `warning`. - - -### Formato - -```{mermaid} -%%| label: fig-formato-hash-adj -%%| fig-cap: "Formato del paquete de verificación del hash del `ADJ`: `id` fijo a `2` (uint16) seguido del `commit` (uint64) del `ADJ` vigente." -%%| fig-width: 5.2 -%%| fig-pos: 'H' -%%{init: {"packet": {"bitWidth": 15, "rowHeight": 34, "bitsPerRow": 32, "showBits": true}}}%% -packet-beta -0-15: "id (=2)" -16-79: "commit" -``` - -- `id` (16 bits): fijo a `2`, identifica este paquete como la comparación de *hash* del `ADJ`. -- `commit` (64 bits): *hash* del commit del `ADJ` que está usando la placa o el `backend`. - - - -## *Custom Keep-alive* - -Mantenemos el estilo: será el `backend` quien envíe el *keep-alive* y nos iremos a `fault` si no se recibe el `ack`. `FW` hará lo propio en las placas. - -Posibilidad de añadir un botón para desactivar el *keep-alive* del `backend`. - -## Propuesta de incorporación del `array` - -Autor: *Víctor López* - -Añadimos un atributo opcional a los measurements 'arrayLength'. - -Este atributo define la longitud de array para el measurement, si el measurement tiene protecciones, se comprobará la protección por cada elemento del array. - -Si se necesita envíar una alerta de que la protección ha detectado un fallo en un elemento del array, se envía en el campo `reserved` del mensaje de la protección el índice del array que ha fallado (empezando por el índice 0). - -Se vería así el paquete de protección entonces: - -```{mermaid} -%%| label: fig-proteccion-array -%%| fig-cap: "Estructura del paquete de una protección sobre un measurement de tipo array. El campo `resv` pasa a contener el índice del elemento que ha fallado (empezando por 0). El campo `value` ocupa el mismo tamaño que el elemento del array; aquí se dibuja con 64 bits." -%%| fig-width: 5.2 -%%| fig-pos: 'H' -%%{init: {"packet": {"bitWidth": 15, "rowHeight": 34, "bitsPerRow": 32, "showBits": true}}}%% -packet-beta -0-15: "id" -16-23: "hora" -24-31: "min" -32-39: "seg" -40-47: "subseg" -48-63: "índice" -64-127: "value" -``` - -```{mermaid} -%%| label: fig-packet-array -%%| fig-cap: "Estructura de un paquete para un measurement que es un array de `uint16` (aquí, con 3 elementos): el `id` seguido de los elementos consecutivos." -%%| fig-width: 5.2 -%%| fig-pos: 'H' -%%{init: {"packet": {"bitWidth": 15, "rowHeight": 34, "bitsPerRow": 32, "showBits": true}}}%% -packet-beta -0-15: "id" -16-31: "value[0]" -32-47: "value[1]" -48-63: "value[2]" -``` - -## Otros apuntes de la reunión - -Por la parte de FW, Víctor y Jorge Canut se muestran conformes con la implementación del refactor en la `ST-LIB`. Por otra parte, Javier Ribal comenta que al rehacerse el `backend` desde cero no ve ningún impedimiento en aplicar estos cambios. - -Primera reunión de Aleksandr Globa y Pablo Pertusa que se incorporan al subsistema de Firmware. - From 4ea86f26e63268068205968607b419f039ac7a46 Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Sat, 10 Oct 2026 17:32:59 +0200 Subject: [PATCH 041/225] fix(backend, adj): make adj::raw not a public module --- backend/crates/core/src/adj.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/backend/crates/core/src/adj.rs b/backend/crates/core/src/adj.rs index 3966e677d..839f4fa4a 100644 --- a/backend/crates/core/src/adj.rs +++ b/backend/crates/core/src/adj.rs @@ -13,7 +13,7 @@ mod error; mod info; -pub mod raw; +mod raw; pub use error::{LoadError, MeasurementError, ProtectionError}; pub use info::{AdjInfo, ProtectionTypeInfo}; From db3a1602e9a85723952ac5bd6af81c50c4e40623 Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Sat, 10 Oct 2026 17:44:22 +0200 Subject: [PATCH 042/225] fix(backend, ntp): add port form `model` at `ntp` --- backend/crates/core/src/ntp.rs | 22 +++++++++++++--------- 1 file changed, 13 insertions(+), 9 deletions(-) diff --git a/backend/crates/core/src/ntp.rs b/backend/crates/core/src/ntp.rs index 5cf85b712..7de54a6e5 100644 --- a/backend/crates/core/src/ntp.rs +++ b/backend/crates/core/src/ntp.rs @@ -1,3 +1,4 @@ +use crate::model::Port; use ntp_server::{protocol::Stratum, server::NtpServer}; use std::{ io, @@ -5,26 +6,26 @@ use std::{ }; use tracing::{debug, info, instrument}; -const NTP_DEFAULT_PORT: u16 = 8123; +const NTP_DEFAULT_PORT: Port = Port(8123); -/// Starts the NTP server with an interface and a port. +/// Starts the NTP server with an interface and a port. /// /// Arguments: /// - `interface`: IPv4 interface to bind to. If `None`, the default interface (`0.0.0.0`) is used. /// - `port`: Port to listen on. If `None`, the default NTP port (`8123`) is used. #[instrument(level = "info")] -pub async fn start_ntp_server(interface: Option, port: Option) -> io::Result<()> { +pub async fn start_ntp_server(interface: Option, port: Option) -> io::Result<()> { run_ntp_server(interface, port).await } -/// Starts the NTP server with a socket. +/// Starts the NTP server with a socket. /// /// Arguments: /// - `socket`: Complete IPv4 socket address. If `None` the default `SocketAddrV4` is used (`0.0.0.0:8123`). #[instrument(level = "info")] pub async fn start_ntp_server_with_socket(socket: Option) -> io::Result<()> { let (interface, port) = match socket { - Some(socket) => (Some(*socket.ip()), Some(socket.port())), + Some(socket) => (Some(*socket.ip()), Some(Port(socket.port()))), None => (None, None), }; @@ -32,19 +33,22 @@ pub async fn start_ntp_server_with_socket(socket: Option) -> io::R } #[instrument(level = "info")] -async fn run_ntp_server(interface: Option, port: Option) -> io::Result<()> { +async fn run_ntp_server(interface: Option, port: Option) -> io::Result<()> { let server = build_ntp_server(interface, port).await?; info!("Starting NTP server loop"); // Any internal log of server.run() will be wrapped within this function Span server.run().await } -async fn build_ntp_server(interface: Option, port: Option) -> io::Result { +async fn build_ntp_server( + interface: Option, + port: Option, +) -> io::Result { let interface = interface.unwrap_or(Ipv4Addr::UNSPECIFIED); // Same as Ipv4Addr::new(0,0,0,0); let port = port.unwrap_or(NTP_DEFAULT_PORT); - let socket_addr_v4 = SocketAddrV4::new(interface, port); + let socket_addr_v4 = SocketAddrV4::new(interface, port.0); // % -> use structured variables debug!(%socket_addr_v4, "Building NTP server"); @@ -87,7 +91,7 @@ mod test { init_tracing_for_tests(); // Create the NTP server - let server = build_ntp_server(Some(Ipv4Addr::LOCALHOST), Some(0)) + let server = build_ntp_server(Some(Ipv4Addr::LOCALHOST), Some(Port(0))) .await .expect("NTP server should bind to an ephemeral local port"); From bb6f5a51bf2dd824df65e0d2e6537f931ef2a50a Mon Sep 17 00:00:00 2001 From: Gazi Al Saad Halawani Date: Sat, 10 Oct 2026 21:03:08 +0200 Subject: [PATCH 043/225] Feat(backend, protocol): Implemented Order Encoding. --- .../crates/core/src/protocol/packet/order.rs | 50 +++++++++++++++---- 1 file changed, 40 insertions(+), 10 deletions(-) diff --git a/backend/crates/core/src/protocol/packet/order.rs b/backend/crates/core/src/protocol/packet/order.rs index 4eb11a6cf..3b5eac356 100644 --- a/backend/crates/core/src/protocol/packet/order.rs +++ b/backend/crates/core/src/protocol/packet/order.rs @@ -1,18 +1,48 @@ //! Encodes an `Order` packet: a command sent to a board. Only ever sent, //! over TCP — the backend never receives one back. -use crate::model::OrderPacket; -use crate::protocol::{EncodeError, Index}; +use crate::model::{OrderPacket, PacketKind}; +use crate::protocol::{wire, EncodeError, Index}; /// Encodes `order` into the bytes to write to a board's connection, /// resolving its field shapes against `index`. pub fn encode(order: &OrderPacket, index: &Index) -> Result, EncodeError> { - let _ = (order, index); - todo!( - "look up order.id in `index` to get its PacketDef (UnknownId if \ - absent); match its `kind` for PacketKind::Order(measurements) \ - (WrongKind if it's some other kind); error with WrongFieldCount \ - if order.fields.len() doesn't match measurements.len(); encode \ - the id then each field positionally via wire::encode_value" - ) + + //Unwrap PacketDef for kind + let packet_def = index + .packet(order.id) + .ok_or(EncodeError::UnknownId(order.id))?;// Question mark for error propagation and prevent crash + + //Check if packetdef is PacketKind::Order(measurement). Also returns the list of measurements + let measurements = match &packet_def.kind{ + PacketKind::Order(measurements) => measurements, + _ => return Err(EncodeError::WrongKind {id:order.id}) + }; + + //Check if length of list of fields matches number of measurements. + if order.fields.len() != measurements.len(){ + return Err(EncodeError::WrongFieldCount {expected:measurements.len(),got:order.fields.len()}) + } + + let mut bytes = Vec::new(); + + bytes.extend_from_slice(&order.id.0.to_be_bytes());//Header prefix of byte stream to 16 bit big-endian + + //Encoding to bytes + for (field,measurement) in order.fields.iter().zip(measurements){ //For each measurement + let field_bytes = wire::encode_value(field,&measurement.kind)?;// Encode field Value into bytes according to MeasurementKind + bytes.extend(field_bytes);// Adds to byte stream + } + + Ok(bytes) // Return bytes } + + + +// todo!( +// "look up order.id in `index` to get its PacketDef (UnknownId if \ +// absent); match its `kind` for PacketKind::Order(measurements) \ +// (WrongKind if it's some other kind); error with WrongFieldCount \ +// if order.fields.len() doesn't match measurements.len(); encode \ +// the id then each field positionally via wire::encode_value" +// ) \ No newline at end of file From 9a097fd40dfc5ee206905c2c292989643743b3cf Mon Sep 17 00:00:00 2001 From: Gazi Al Saad Halawani Date: Sat, 10 Oct 2026 23:02:35 +0200 Subject: [PATCH 044/225] Feat(backend, protocol): Changed byte encoding in Order.rs to Little-Endian instead of Big-Endian. --- backend/crates/core/src/protocol/packet/order.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/backend/crates/core/src/protocol/packet/order.rs b/backend/crates/core/src/protocol/packet/order.rs index 3b5eac356..16fa74c02 100644 --- a/backend/crates/core/src/protocol/packet/order.rs +++ b/backend/crates/core/src/protocol/packet/order.rs @@ -26,7 +26,7 @@ pub fn encode(order: &OrderPacket, index: &Index) -> Result, EncodeError let mut bytes = Vec::new(); - bytes.extend_from_slice(&order.id.0.to_be_bytes());//Header prefix of byte stream to 16 bit big-endian + bytes.extend_from_slice(&order.id.0.to_le_bytes());//Header prefix of byte stream to 16 bit little-endian //Encoding to bytes for (field,measurement) in order.fields.iter().zip(measurements){ //For each measurement From 9bfceab4680463570458a2608d96e36764136c11 Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Sun, 11 Oct 2026 18:38:04 +0200 Subject: [PATCH 045/225] feat(backend, git): implementation of ADJ update handling --- backend/Cargo.lock | 48 ++++ backend/crates/core/Cargo.toml | 8 +- backend/crates/core/src/git.rs | 396 +++++++++++++++++++++++++++++++++ backend/crates/core/src/lib.rs | 6 + 4 files changed, 455 insertions(+), 3 deletions(-) create mode 100644 backend/crates/core/src/git.rs diff --git a/backend/Cargo.lock b/backend/Cargo.lock index 0a8ad6631..147430cc4 100644 --- a/backend/Cargo.lock +++ b/backend/Cargo.lock @@ -361,6 +361,27 @@ dependencies = [ "crypto-common", ] +[[package]] +name = "dirs" +version = "7.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d57d423b3c82e89b9a24ca3091fee61f456a26edbd28d26c65906f4bc1dcd8f" +dependencies = [ + "dirs-sys", +] + +[[package]] +name = "dirs-sys" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e01a3366d27ee9890022452ee61b2b63a67e6f13f58900b651ff5665f0bb1fab" +dependencies = [ + "libc", + "option-ext", + "redox_users", + "windows-sys 0.61.2", +] + [[package]] name = "displaydoc" version = "0.2.7" @@ -1974,6 +1995,15 @@ version = "0.2.190" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ce5d3ddc6d3fa000eb1536d85e147bfe31aacaba692ed6a876f95cb7c855be78" +[[package]] +name = "libredox" +version = "0.1.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61ff90caf6077a803a240f62fdbe88645a890bbca49ef8174c3cb0404362171d" +dependencies = [ + "libc", +] + [[package]] name = "linux-raw-sys" version = "0.12.1" @@ -2087,6 +2117,12 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe" +[[package]] +name = "option-ext" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" + [[package]] name = "parking_lot" version = "0.12.5" @@ -2285,6 +2321,16 @@ dependencies = [ "bitflags 2.13.2", ] +[[package]] +name = "redox_users" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60dc65c0ff1a7ae1294b0c67b9f14baf70b644404010370171787bfac1038fc0" +dependencies = [ + "libredox", + "thiserror", +] + [[package]] name = "regex" version = "1.13.1" @@ -2681,8 +2727,10 @@ name = "software-core" version = "0.1.0" dependencies = [ "bytes", + "dirs", "gix", "serde", + "tempfile", "thiserror", "tokio", "tracing", diff --git a/backend/crates/core/Cargo.toml b/backend/crates/core/Cargo.toml index 878c62e3c..baa5e3012 100644 --- a/backend/crates/core/Cargo.toml +++ b/backend/crates/core/Cargo.toml @@ -12,8 +12,8 @@ repository.workspace = true default = [] # TCP/UDP transport (pulls in tokio) net = ["dep:tokio"] -# ADJ download through git (dependency added when the module is written) -git = [] +# ADJ download through git +git = ["dep:tempfile"] # Packet sniffing through pcap (dependency added when the module is written) pcap = ["net"] # CSV data logger (records, sessions, subloggers) @@ -29,7 +29,9 @@ tracing.workspace = true tokio = { workspace = true, optional = true } tracing-subscriber = { workspace = true, optional = true } tracing-appender = { workspace = true, optional = true } -gix = { version = "0.87.1", features = ["blocking-http-transport-reqwest-rust-tls"] } +gix = { version = "0.87.1", features = ["blocking-http-transport-reqwest-rust-tls", "blocking-network-client", "worktree-mutation"] } +dirs = "7.0.0" +tempfile = { version = "3.27", optional = true } # `workspace = true` can't be combined with extra lints in the same table, # so the workspace list is repeated here with `missing_docs` added: this is diff --git a/backend/crates/core/src/git.rs b/backend/crates/core/src/git.rs new file mode 100644 index 000000000..155fc3a1b --- /dev/null +++ b/backend/crates/core/src/git.rs @@ -0,0 +1,396 @@ +//! Blocking Git helpers for ADJ, an application-owned, replaceable data cache. + +use std::{ + fs, io, + net::{Ipv4Addr, SocketAddr, TcpStream}, + path::{Path, PathBuf}, + sync::atomic::AtomicBool, + time::Duration, +}; + +use gix::Repository; +use tracing::{debug, info, instrument, warn}; + +type BoxError = Box; + +const ADJ_URL: &str = "https://github.com/HyperloopUPV/adj.git"; +const GIT_REMOTE: &str = "origin"; + +/// Downloads the requested ADJ branch, replacing the application-managed cache. +/// +/// `path` is the repository directory, not its parent. If omitted, it defaults to +/// `/hyperloop-control-station/adj`. `branch` selects the branch +/// to clone when the connectivity probe succeeds. +/// +/// Online, local edits and commits are discarded only after a fresh checkout +/// succeeds. Offline, the current cached checkout is used without switching +/// branches, so it may differ from `branch`. Returns its full commit hash and +/// commit message, in that order. +/// +/// This performs blocking network and filesystem operations. Call during startup, +/// before readers use ADJ, with only one updater at a time. Replacement uses two +/// renames and is not atomic across a process crash. +/// +/// # Errors +/// +/// Returns an error if ADJ is missing offline, the path or repository is invalid +/// or inaccessible, cloning or checkout fails, or replacement fails. Clone errors +/// do not automatically fall back to the cache. If rollback fails, the error +/// includes the preserved backup's location. +#[instrument(level = "debug", err(level = "warn"))] +pub fn update_adj(path: Option, branch: &str) -> Result<(String, String), BoxError> { + let (repo, dir) = adj_exists_repo(path)?; + + if check_internet_connection() { + info!(path = ?dir, branch, "starting ADJ update"); + // Release repository handles before moving the existing cache directory. + drop(repo); + git_replace(&dir, branch, ADJ_URL) + } else if let Some(repo) = repo { + warn!(path = ?dir, requested_branch = branch, + "connectivity probe failed; using cached ADJ without switching branches"); + get_hash_and_message(&repo) + } else { + Err(io::Error::new( + io::ErrorKind::NotFound, + "ADJ is not available locally and cannot be downloaded", + ) + .into()) + } +} + +/// Lists locally cached remote-tracking branches without contacting the remote. +/// +/// `path` identifies the repository directory. Names retain the remote prefix, +/// such as `origin/main`; the results can be stale, are not explicitly sorted, +/// and may include symbolic references such as `origin/HEAD`. +/// +/// # Errors +/// +/// Returns an error if the repository cannot be opened or its references cannot +/// be read. +#[instrument(level = "debug", err(level = "warn"))] +pub fn list_remote_branches(path: PathBuf) -> Result, BoxError> { + let repo = gix::open(&path)?; + + let mut branches = Vec::new(); + + // Inspect local remote-tracking refs, not the remote server's advertised refs. + for reference in repo.references()?.remote_branches()? { + let reference = reference?; + branches.push(reference.name().shorten().to_string()); + } + + debug!( + ?path, + count = branches.len(), + "listed cached remote-tracking branches" + ); + Ok(branches) +} + +/// Opens an existing repository without fetching or changing its checkout. +/// +/// `path` is the repository directory. If omitted, it defaults to +/// `/hyperloop-control-station/adj`. This does not create ADJ. +/// +/// # Errors +/// +/// Returns an error if the cache directory cannot be resolved or the repository +/// is missing, invalid, or inaccessible. +#[instrument(level = "debug", err(level = "warn"))] +pub fn open_repo(path: Option) -> Result { + let path = unwrap_repo_path(path)?; + + let repo = gix::open(path)?; + + debug!(git_dir = ?repo.path(), "opened repository"); + Ok(repo) +} + +// Checks external TCP connectivity with a three-second timeout, not GitHub availability. +#[instrument(level = "debug")] +fn check_internet_connection() -> bool { + // Use a fixed IPv4 address to avoid a separate DNS lookup and its timeout. + let address = SocketAddr::from((Ipv4Addr::new(1, 1, 1, 1), 443)); + let timeout = Duration::from_secs(3); + + // Attempt only the TCP handshake; no application data is sent. + match TcpStream::connect_timeout(&address, timeout) { + Ok(_stream) => { + debug!(%address, "connectivity probe succeeded"); + true + } + Err(error) => { + // Record why the probe failed without treating it as an application error. + debug!(%address, %error, "connectivity probe failed"); + false + } + } +} + +// Preserve explicit paths; otherwise use the platform's user cache directory. +fn unwrap_repo_path(path: Option) -> Result { + let dir = match path { + Some(path) => path, + None => { + let path = dirs::cache_dir().ok_or_else(|| { + io::Error::new(io::ErrorKind::NotFound, "cache directory not found") + })?; + + path.join("hyperloop-control-station").join("adj") + } + }; + + debug!(path = ?dir, "resolved ADJ repository path"); + Ok(dir) +} + +// Only an absent directory is a cache miss; invalid repositories remain errors. +fn adj_exists_repo(path: Option) -> Result<(Option, PathBuf), BoxError> { + let dir = unwrap_repo_path(path)?; + + let res = if dir.try_exists()? { + Some(gix::open(&dir)?) + } else { + None + }; + + debug!(path = ?dir, exists = res.is_some(), "checked local ADJ repository"); + Ok((res, dir)) +} + +// Stage beside ADJ so both installation and rollback use same-filesystem renames. +#[instrument(level = "debug", skip(url))] +fn git_replace(path: &Path, branch: &str, url: &str) -> Result<(String, String), BoxError> { + let parent = path + .parent() + .filter(|p| !p.as_os_str().is_empty()) + .unwrap_or(Path::new(".")); + fs::create_dir_all(parent)?; + let staging = tempfile::Builder::new() + .prefix(".adj-") + .tempdir_in(parent)?; + let checkout = staging.path().join("new"); + let backup = staging.path().join("old"); + debug!(?checkout, ?backup, "created ADJ staging directory"); + + // Validate the new checkout and commit before touching the current cache. + // Early errors drop the staging directory, removing any incomplete clone. + let repo = git_clone(&checkout, branch, url)?; + let commit = get_hash_and_message(&repo)?; + // The repository contains paths into staging and must not survive the move. + drop(repo); + + let had_cache = path.try_exists()?; + if had_cache { + fs::rename(path, &backup)?; + debug!(?path, ?backup, "moved cached ADJ aside for replacement"); + } + if let Err(error) = fs::rename(&checkout, path) { + debug!(?path, %error, had_cache, "ADJ installation failed; restoring cache if present"); + if had_cache && let Err(rollback) = fs::rename(&backup, path) { + // Do not let temporary-directory cleanup delete the only remaining cache. + let saved = staging.keep(); + debug!(?backup, %rollback, "preserved ADJ backup after failed rollback"); + return Err(io::Error::other(format!( + "ADJ installation failed: {error}; rollback failed: {rollback}; backup kept at {}", + saved.join("old").display() + )) + .into()); + } + if had_cache { + debug!(?path, "restored cached ADJ after installation failure"); + } + return Err(error.into()); + } + + // Installation succeeded; cleanup now discards the old cache. A cleanup + // failure does not turn a successfully installed checkout into an error. + if let Err(error) = staging.close() { + warn!(?path, %error, "ADJ updated, but temporary directory cleanup failed"); + } + info!(?path, branch, commit = %commit.0, "ADJ updated"); + Ok(commit) +} + +/// Checks whether a remote-tracking branch is cached in `repo`. +/// +/// `remote` is the remote name, such as `origin`; `name` is the branch name, such +/// as `main` or `feature/example`. Looks up `refs/remotes//` without +/// contacting the server or checking local branches. `false` means the reference +/// is absent locally, not necessarily that the branch is absent on the server. +/// +/// # Errors +/// +/// Returns an error if the reference name is invalid or the reference cannot be +/// read. +#[instrument(level = "debug", skip(repo), err(level = "warn"))] +pub fn branch_exists(repo: &gix::Repository, remote: &str, name: &str) -> Result { + let full = format!("refs/remotes/{remote}/{name}"); + let exists = repo.try_find_reference(full.as_str())?.is_some(); + debug!(reference = %full, exists, "checked cached remote-tracking branch"); + Ok(exists) +} + +// Fetch and check out the requested branch instead of switching an existing repo. +#[instrument(level = "debug", skip(url))] +fn git_clone(path: &Path, branch: &str, url: &str) -> Result { + // These synchronous startup operations do not currently expose cancellation. + let interrupt = AtomicBool::new(false); + + debug!(?path, branch, "preparing shallow ADJ clone"); + // A depth of one keeps the current snapshot without downloading full history. + let mut prepare = gix::prepare_clone(url, path)? + .with_remote_name(GIT_REMOTE)? + .with_ref_name(Some(branch))? + .with_shallow(gix::remote::fetch::Shallow::DepthAtRemote( + std::num::NonZeroU32::MIN, + )); + + let (mut checkout, _) = prepare.fetch_then_checkout(gix::progress::Discard, &interrupt)?; + debug!( + ?path, + branch, "ADJ fetch completed; checking out working tree" + ); + let (repo, _) = checkout.main_worktree(gix::progress::Discard, &interrupt)?; + + debug!(?path, branch, "ADJ clone and checkout completed"); + Ok(repo) +} + +// Report the checked-out HEAD, which can differ from the requested branch offline. +fn get_hash_and_message(repo: &Repository) -> Result<(String, String), BoxError> { + let hash = repo.head_id()?.to_string(); + let message = repo.head_commit()?.decode()?.message.to_string(); + + // Log only the commit ID, not potentially large or sensitive message text. + debug!(commit = %hash, "read checked-out ADJ commit"); + Ok((hash, message)) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::process::Command; + + fn git(path: &Path, args: &[&str]) -> Result<(), BoxError> { + // Fixture commits need identity; disable signing, hooks, and templates + // so tests do not depend on the user's normal Git setup. + let output = Command::new("git") + .current_dir(path) + .args([ + "-c", + "user.name=ADJ tests", + "-c", + "user.email=adj@example.test", + "-c", + "commit.gpgSign=false", + "-c", + "core.hooksPath=", + "-c", + "init.templateDir=", + ]) + .args(args) + .output()?; + if !output.status.success() { + return Err(io::Error::other(String::from_utf8_lossy(&output.stderr)).into()); + } + Ok(()) + } + + fn source_repo(path: &Path) -> Result<(), BoxError> { + fs::create_dir(path)?; + git(path, &["init", "--initial-branch=main"])?; + fs::write(path.join("data.txt"), "main")?; + git(path, &["add", "."])?; + git(path, &["commit", "-m", "main data"])?; + // Leave HEAD on another branch to verify explicit clone branch selection. + git(path, &["checkout", "-b", "testing"])?; + fs::write(path.join("data.txt"), "testing")?; + git(path, &["commit", "-am", "testing data"]) + } + + // Distinguish missing, invalid, and valid local repositories. + #[test] + fn detects_missing_and_invalid_repositories() -> Result<(), BoxError> { + let temp = tempfile::tempdir()?; + let path = temp.path().join("adj"); + assert!(adj_exists_repo(Some(path.clone()))?.0.is_none()); + fs::create_dir(&path)?; + assert!(adj_exists_repo(Some(path.clone())).is_err()); + git(&path, &["init"])?; + assert!(adj_exists_repo(Some(path))?.0.is_some()); + Ok(()) + } + + // Verify branch selection, newer commits, and removal of stale cache files. + #[test] + fn clones_and_replaces_with_requested_branch() -> Result<(), BoxError> { + let temp = tempfile::tempdir()?; + let source = temp.path().join("source"); + let cache = temp.path().join("cache").join("adj"); + source_repo(&source)?; + let url = source.to_str().ok_or("non-UTF-8 test path")?; + + let first = git_replace(&cache, "main", url)?; + assert_eq!(first.1, "main data\n"); + assert_eq!(fs::read_to_string(cache.join("data.txt"))?, "main"); + // Replacement must discard old cache files, not just update tracked ones. + fs::write(cache.join("stale.txt"), "discard this cache file")?; + + // Add a newer remote commit and request a different branch on replacement. + fs::write(source.join("data.txt"), "latest testing")?; + git(&source, &["commit", "-am", "updated testing data"])?; + let expected = get_hash_and_message(&gix::open(&source)?)?; + assert_eq!(git_replace(&cache, "testing", url)?, expected); + assert_ne!(first.0, expected.0); + assert_eq!(get_hash_and_message(&gix::open(&cache)?)?, expected); + assert_eq!( + fs::read_to_string(cache.join("data.txt"))?, + "latest testing" + ); + assert!(!cache.join("stale.txt").exists()); + // Successful replacement must also remove staging and backup directories. + assert_eq!( + fs::read_dir(cache.parent().ok_or("missing parent")?)?.count(), + 1 + ); + Ok(()) + } + + // Verify clone failures preserve cached ADJ and leave no staging debris. + #[test] + fn failed_clone_preserves_existing_cache() -> Result<(), BoxError> { + let temp = tempfile::tempdir()?; + let source = temp.path().join("source"); + let cache = temp.path().join("adj"); + source_repo(&source)?; + let url = source.to_str().ok_or("non-UTF-8 test path")?; + + // A failed first clone must not install a partial checkout. + assert!(git_replace(&cache, "missing-branch", url).is_err()); + assert!(!cache.exists()); + let expected = git_replace(&cache, "main", url)?; + fs::write(cache.join("stale.txt"), "keep on failure")?; + // Both an invalid branch and an unavailable source must leave ADJ intact. + assert!(git_replace(&cache, "missing-branch", url).is_err()); + let missing = temp.path().join("missing-source"); + assert!( + git_replace( + &cache, + "main", + missing.to_str().ok_or("non-UTF-8 test path")? + ) + .is_err() + ); + assert_eq!(get_hash_and_message(&gix::open(&cache)?)?, expected); + assert_eq!(fs::read_to_string(cache.join("data.txt"))?, "main"); + assert_eq!( + fs::read_to_string(cache.join("stale.txt"))?, + "keep on failure" + ); + assert_eq!(fs::read_dir(temp.path())?.count(), 2); + Ok(()) + } +} diff --git a/backend/crates/core/src/lib.rs b/backend/crates/core/src/lib.rs index a85bf01dd..0420745c0 100644 --- a/backend/crates/core/src/lib.rs +++ b/backend/crates/core/src/lib.rs @@ -1,3 +1,9 @@ //! Componentes reutilizables de Hyperloop UPV. pub mod hello_world; + +/// # Git module +/// Handles updates and changes within the ADJ. +/// Checks the ADJ Github repository and +#[cfg(feature = "git")] +pub mod git; \ No newline at end of file From 58d320bd4678da2ae7707bae383ce6f5a8ac6e36 Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Sun, 11 Oct 2026 18:38:43 +0200 Subject: [PATCH 046/225] docs(backend, git): README --- backend/crates/core/src/git/README.md | 60 +++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 backend/crates/core/src/git/README.md diff --git a/backend/crates/core/src/git/README.md b/backend/crates/core/src/git/README.md new file mode 100644 index 000000000..950249435 --- /dev/null +++ b/backend/crates/core/src/git/README.md @@ -0,0 +1,60 @@ +# ADJ Git helpers + +This module manages ADJ as an application-owned, replaceable data cache using +`gix`, with `tracing` for logging. It does not preserve local edits or commits +when updating online. + +## Workflow + +`update_adj(path, branch)` returns the checked-out commit hash and full message. +A custom path identifies the ADJ repository itself. The default is +`/hyperloop-control-station/adj`, using `dirs::cache_dir()`. +An existing invalid repository or inaccessible path returns an error. + +The existing connectivity check attempts a TCP connection to `1.1.1.1:443` +with a three-second timeout. This checks external TCP connectivity, not GitHub +availability. + +### Online + +- Shallow-clone the requested branch into a temporary directory beside ADJ. +- Complete checkout and read its commit information before touching the cache. +- Move the old cache aside and install the new checkout. +- Restore the old cache if installation fails. If restoration also fails, + preserve the backup and include its location in the error. +- Remove the old cache after successful installation. + +A clone error leaves the old cache untouched and is returned directly; it does +not automatically fall back to offline operation. No fetch, merge, or branch +switch is needed because the checkout is replaced. + +### Offline + +- If ADJ exists, return its current commit without updating or switching branches. +- Otherwise, return `ADJ is not available locally and cannot be downloaded`. + +The cached branch may differ from the requested branch when offline. + +## Other Helpers + +- `open_repo` opens the custom or default repository path. +- `list_remote_branches` lists cached remote-tracking references, without making + a network request. Results can be stale and include the remote name. +- `branch_exists` checks for a cached `refs/remotes//` reference. + +## Limitations + +Replacement is intended for startup, before the backend reads ADJ, with one +updater at a time. The backup and installation renames are not jointly atomic +across a process crash. The connectivity probe can succeed when GitHub is +unreachable, or fail when GitHub is reachable. + +## Verification + +Tests use temporary local Git repositories and the Git CLI to create fixtures; +they do not require external network access. Production Git operations use `gix`. + +```bash +cargo test -p software-core -F git +cargo doc --open -p software-core -F git --no-deps +``` From db7782341df2ff04a79cc34cb884d1c93f3af7d3 Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Sun, 11 Oct 2026 18:48:36 +0200 Subject: [PATCH 047/225] docs(backend, git): add some more comments --- backend/crates/core/src/git.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/backend/crates/core/src/git.rs b/backend/crates/core/src/git.rs index 155fc3a1b..ca56adf36 100644 --- a/backend/crates/core/src/git.rs +++ b/backend/crates/core/src/git.rs @@ -11,6 +11,7 @@ use std::{ use gix::Repository; use tracing::{debug, info, instrument, warn}; +// Common error type for filesystem and Git failures; Send + Sync allows cross-thread use. type BoxError = Box; const ADJ_URL: &str = "https://github.com/HyperloopUPV/adj.git"; @@ -37,6 +38,7 @@ const GIT_REMOTE: &str = "origin"; /// or inaccessible, cloning or checkout fails, or replacement fails. Clone errors /// do not automatically fall back to the cache. If rollback fails, the error /// includes the preserved backup's location. +// Log returned errors at the public boundary; helpers trace progress without duplicate warnings. #[instrument(level = "debug", err(level = "warn"))] pub fn update_adj(path: Option, branch: &str) -> Result<(String, String), BoxError> { let (repo, dir) = adj_exists_repo(path)?; @@ -163,6 +165,7 @@ fn adj_exists_repo(path: Option) -> Result<(Option, PathBuf // Stage beside ADJ so both installation and rollback use same-filesystem renames. #[instrument(level = "debug", skip(url))] fn git_replace(path: &Path, branch: &str, url: &str) -> Result<(String, String), BoxError> { + // A relative path like "adj" has an empty parent; stage in the current directory. let parent = path .parent() .filter(|p| !p.as_os_str().is_empty()) From 553e3dd7f940642af4062f82b5f0cc948facf224 Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Sun, 11 Oct 2026 23:47:17 +0200 Subject: [PATCH 048/225] feat(backend, protocol): function that returns the number of bytes that require each numeric kind --- backend/crates/core/src/protocol/wire.rs | 53 ++++++++++++++++++++++-- 1 file changed, 50 insertions(+), 3 deletions(-) diff --git a/backend/crates/core/src/protocol/wire.rs b/backend/crates/core/src/protocol/wire.rs index 6dc151e04..8809c7126 100644 --- a/backend/crates/core/src/protocol/wire.rs +++ b/backend/crates/core/src/protocol/wire.rs @@ -6,9 +6,9 @@ //! Every wire width here is fixed by the measurement's own `kind` (a //! `NumericKind` always has a known byte width; booleans and enums are //! fixed-width too), so decoding never needs to report back how many -//! bytes it consumed — the caller already has the `MeasurementKind` (from -//! the `Measurement` it's decoding) and can derive the width from it -//! directly if it needs to advance through a buffer. +//! bytes it consumed — [`byte_width`] derives it straight from the +//! `MeasurementKind`, for a caller that needs to advance through a buffer +//! or know how much to read off a stream before decoding. //! //! [`decode_value`]/[`encode_value`] are thin dispatchers: they only pick //! which per-kind function to call. All the actual work lives in its own @@ -36,6 +36,23 @@ pub fn encode_value(value: &Value, kind: &MeasurementKind) -> Result, En } } +/// How many bytes `kind` takes on the wire. +pub fn byte_width(kind: &MeasurementKind) -> usize { + match kind { + MeasurementKind::Numeric { wire_type } => match wire_type { + NumericKind::U8 | NumericKind::I8 => 1, + NumericKind::U16 | NumericKind::I16 => 2, + NumericKind::U32 | NumericKind::I32 | NumericKind::F32 => 4, + NumericKind::U64 | NumericKind::I64 | NumericKind::F64 => 8, + }, + // Not yet confirmed against firmware — see `decode_boolean`. + MeasurementKind::Boolean => { + todo!("confirm the wire width firmware uses for a boolean measurement") + } + MeasurementKind::Enum { .. } => 1, + } +} + /// Decodes a numeric value of the given wire type, little-endian. pub fn decode_numeric(bytes: &[u8], wire_type: NumericKind) -> Result { fn take(bytes: &[u8]) -> Result<[u8; N], DecodeError> { @@ -170,6 +187,36 @@ pub fn encode_enum(value: &Value, options: &[String]) -> Result, EncodeE mod tests { use super::*; + #[test] + fn byte_width_matches_each_numeric_kinds_wire_size() { + let cases = [ + (NumericKind::U8, 1), + (NumericKind::I8, 1), + (NumericKind::U16, 2), + (NumericKind::I16, 2), + (NumericKind::U32, 4), + (NumericKind::I32, 4), + (NumericKind::F32, 4), + (NumericKind::U64, 8), + (NumericKind::I64, 8), + (NumericKind::F64, 8), + ]; + + for (wire_type, expected) in cases { + assert_eq!(byte_width(&MeasurementKind::Numeric { wire_type }), expected); + } + } + + #[test] + fn byte_width_of_an_enum_is_always_one() { + assert_eq!( + byte_width(&MeasurementKind::Enum { + options: vec!["Idle".to_string(), "Fault".to_string()] + }), + 1 + ); + } + #[test] fn decodes_an_unsigned_integer_little_endian() { let Ok(value) = decode_numeric(&[0x34, 0x12], NumericKind::U16) else { From 0edcd3ae5ac5cf28d807392279679560ca100d4d Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Mon, 12 Oct 2026 00:18:37 +0200 Subject: [PATCH 049/225] fix(backend, adj): add methods to ADJID to separate get messurement Id from protection id --- backend/crates/core/src/adj/raw/loader.rs | 9 ++++--- backend/crates/core/src/model/README.md | 10 ++++--- backend/crates/core/src/model/id.rs | 33 +++++++++++++++++++++++ backend/crates/core/src/model/packet.rs | 26 +++++++++--------- 4 files changed, 58 insertions(+), 20 deletions(-) diff --git a/backend/crates/core/src/adj/raw/loader.rs b/backend/crates/core/src/adj/raw/loader.rs index 6d6f4be3c..6f252d48c 100644 --- a/backend/crates/core/src/adj/raw/loader.rs +++ b/backend/crates/core/src/adj/raw/loader.rs @@ -71,9 +71,12 @@ pub(crate) fn load_board(root: &Path, name: &str, rel_path: &str) -> Result` keyed by id — the A Defined as their own types (wrapping a `u16`) instead of using a plain `u16`, so the compiler won't let an `AdjId` be confused with a `BoardId` by mistake, even though both are just numbers underneath ### 2.1 `AdjId` ID of an ADJ packet in u16. Structure of ID can be found in the ADJ documentation. + +For a protection's compound id (the high 3 bits are the protection's position, the low 13 bits the watched measurement's id — see the struct's own docs for the full range table), `AdjId` exposes the split as two methods instead of leaving every caller to redo the shift/mask: +- `protection_position() -> u8`: the high 3 bits (`0` for a normal, non-protection id). +- `measurement_id() -> AdjId`: the id with its high 3 bits zeroed out — the watched measurement's own id. ### 2.2 `BoardId` Unique identifier of a board, defined by the ADJ documentation. ### 2.3 `MacAddress` @@ -138,10 +142,8 @@ Vector list of values (`Vec`) to set for each field of the order. ### 4.4 `ProtectionPacket` Sent by a board when one of its declared protections triggers. -#### `measurement` -The measurement this protection watches (`AdjId`). -#### `protection` -Which of that measurement's protections triggered (`AdjId`). +#### `id` +The compound wire id this protection triggered under (`AdjId`). Use `id.measurement_id()` for the measurement it watches and `id.protection_position()` for which of that measurement's protections this is (see `Protection::id`). Kept as a single field rather than storing both halves separately — they're never independent of each other, so a second field would only add a second place for them to disagree. #### `timestamp` When the protection triggered (`ShortTimestamp`). #### `value` diff --git a/backend/crates/core/src/model/id.rs b/backend/crates/core/src/model/id.rs index d6a6845a5..a8278993d 100644 --- a/backend/crates/core/src/model/id.rs +++ b/backend/crates/core/src/model/id.rs @@ -12,6 +12,24 @@ #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub struct AdjId(pub u16); +impl AdjId { + /// The high 3 bits: `0` for a normal `packet`/`order`/`measurement` + /// id, `1`-`7` for which of the watched measurement's protections this + /// is. + pub fn protection_position(self) -> u8 { + (self.0 >> 13) as u8 + } + + /// The watched measurement's id: this id with its high 3 bits (the + /// protection's position) zeroed out. + /// + /// For a normal, non-protection id (`protection_position() == 0`), + /// this is just the id itself. + pub fn measurement_id(self) -> AdjId { + AdjId(self.0 & 0x1FFF) + } +} + /// Unique identifier of a board, defined by the ADJ. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub struct BoardId(pub u16); @@ -74,4 +92,19 @@ mod tests { let board = BoardId(1); assert_eq!(packet.0, board.0); // only the inner numbers can be compared } + + #[test] + fn a_normal_ids_position_is_zero_and_it_is_its_own_measurement_id() { + let id = AdjId(3000); + assert_eq!(id.protection_position(), 0); + assert_eq!(id.measurement_id(), AdjId(3000)); + } + + #[test] + fn a_protections_compound_id_splits_into_position_and_measurement() { + // (3 << 13) | 100 = 24576 | 100 = 24676 + let compound = AdjId((3u16 << 13) | 100); + assert_eq!(compound.protection_position(), 3); + assert_eq!(compound.measurement_id(), AdjId(100)); + } } diff --git a/backend/crates/core/src/model/packet.rs b/backend/crates/core/src/model/packet.rs index 7ac91f048..7cba9ae47 100644 --- a/backend/crates/core/src/model/packet.rs +++ b/backend/crates/core/src/model/packet.rs @@ -64,16 +64,16 @@ pub struct OrderPacket { /// A protection packet: sent by a board when one of its declared /// [`super::Protection`]s triggers. /// -/// `measurement` and `protection` together are the two halves of the -/// compound wire id — decoding that split is `protocol`'s job, this type -/// just holds the result. +/// `id` is the compound wire id: [`AdjId::measurement_id`] gives the +/// watched measurement, [`AdjId::protection_position`] which of that +/// measurement's protections triggered (see [`super::Protection::id`]). +/// Kept as a single field rather than storing both halves separately — +/// they're never independent of each other, so there's nothing a second +/// field would add beyond a second place for them to disagree. #[derive(Debug, Clone, PartialEq)] pub struct ProtectionPacket { - /// The measurement this protection watches. - pub measurement: AdjId, - /// Which of that measurement's protections triggered — see - /// [`super::Protection::id`]. - pub protection: AdjId, + /// The compound id this protection triggered under. + pub id: AdjId, /// When it triggered. pub timestamp: ShortTimestamp, /// The value that triggered it, decoded with the same wire type as the @@ -164,10 +164,10 @@ mod tests { } #[test] - fn a_protection_packet_carries_its_measurement_and_its_own_position_separately() { + fn a_protection_packets_id_splits_into_its_measurement_and_its_own_position() { + // (1 << 13) | 3000 = 8192 | 3000 = 11192 let packet = ProtectionPacket { - measurement: AdjId(3000), - protection: AdjId(1), + id: AdjId((1u16 << 13) | 3000), timestamp: ShortTimestamp { hour: 12, minute: 0, @@ -177,8 +177,8 @@ mod tests { value: Value::Number(53.2), }; - assert_eq!(packet.measurement, AdjId(3000)); - assert_eq!(packet.protection, AdjId(1)); + assert_eq!(packet.id.measurement_id(), AdjId(3000)); + assert_eq!(packet.id.protection_position(), 1); } #[test] From a44ab1f977fbc89c88deabdc5d7b3fab2c7c34b4 Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Sat, 10 Oct 2026 19:34:16 +0200 Subject: [PATCH 050/225] chore(github): remove template issues --- .github/ISSUE_TEMPLATE/bug.md | 28 ---------------------------- .github/ISSUE_TEMPLATE/feature.md | 17 ----------------- .github/ISSUE_TEMPLATE/task.md | 17 ----------------- 3 files changed, 62 deletions(-) delete mode 100644 .github/ISSUE_TEMPLATE/bug.md delete mode 100644 .github/ISSUE_TEMPLATE/feature.md delete mode 100644 .github/ISSUE_TEMPLATE/task.md diff --git a/.github/ISSUE_TEMPLATE/bug.md b/.github/ISSUE_TEMPLATE/bug.md deleted file mode 100644 index 941c8a099..000000000 --- a/.github/ISSUE_TEMPLATE/bug.md +++ /dev/null @@ -1,28 +0,0 @@ ---- -name: Bug -about: Notify that an error has ben found on the app and what happened. -title: '' -labels: Bug -assignees: '' - ---- - -**Bug Description** -What is happening? - -**Steps to reproduce** -How do I replicate the issue, what where you doing? - -**Screenshots** -Provide screenshots, videos, links, etc. - -**Context** -What is your environment? - -Fill the following information and add any relevant information: -*OS*: Windows, Mac, Linux, Android, iOS... -*Browser*: Chrome, Opera, Firefox, Safari... -*App Version*: v1.0.0 - -**Notes** -Extra information relevant to the issue. diff --git a/.github/ISSUE_TEMPLATE/feature.md b/.github/ISSUE_TEMPLATE/feature.md deleted file mode 100644 index 6aee6e0d5..000000000 --- a/.github/ISSUE_TEMPLATE/feature.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -name: Feature -about: Propose a feature to be added to the application. -title: '' -labels: Feature -assignees: '' - ---- - -**Feature description** -What is the feature supposed to do, what will it include? - -**Possible solutions** -What are the possible ways to implement this feature that you can think of? - -**Notes** -What context / extra information is required to understand the proposal? diff --git a/.github/ISSUE_TEMPLATE/task.md b/.github/ISSUE_TEMPLATE/task.md deleted file mode 100644 index 8a717356d..000000000 --- a/.github/ISSUE_TEMPLATE/task.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -name: Task -about: Tasks are units of work assigned to members to be completed. -title: '' -labels: Task -assignees: '' - ---- - -**Description** -Brief description of the task and important details - -**Related** -Related Issues, PRs, Documents, etc. - -**Notes** -Extra information that might be good to know about it From 2607edb06de37c4dc11d280c841a0589074dacc7 Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Sat, 10 Oct 2026 20:14:11 +0200 Subject: [PATCH 051/225] chore(repo): configure recomended extension --- .vscode/extensions.json | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 .vscode/extensions.json diff --git a/.vscode/extensions.json b/.vscode/extensions.json new file mode 100644 index 000000000..37006f2d8 --- /dev/null +++ b/.vscode/extensions.json @@ -0,0 +1,9 @@ +{ + "recommendations": [ + "rust-lang.rust-analyzer", + "dbaeumer.vscode-eslint", + "esbenp.prettier-vscode", + "ms-python.python", + "tamasfe.even-better-toml" + ] +} From 04a4c013e964f247575d12d37de36a60597e6a5e Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Sat, 10 Oct 2026 20:14:27 +0200 Subject: [PATCH 052/225] chore(repo, backend): configure debugger --- .vscode/launch.json | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 .vscode/launch.json diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100644 index 000000000..62e3453a9 --- /dev/null +++ b/.vscode/launch.json @@ -0,0 +1,15 @@ +{ + "version": "0.2.0", + "configurations": [ + { + "type": "lldb", + "request": "launch", + "name": "Debug Backend (Rust)", + "program": "${workspaceFolder}/backend/target/debug/station", + "args": [], + "cwd": "${workspaceFolder}/backend/crates/station", + "preLaunchTask": "cargo build (station)", + "sourceLanguages": ["rust"] + } + ] +} From 424749d04375e41764c0a58af3301b8ed943c760 Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Sat, 10 Oct 2026 20:15:00 +0200 Subject: [PATCH 053/225] chore(repo): configure lint --- .vscode/settings.json | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/.vscode/settings.json b/.vscode/settings.json index 9ef398bb3..6f381d6a0 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -50,5 +50,33 @@ "editor.codeActionsOnSave": { "source.fixAll.rust-analyzer": "explicit" } + }, + "rust-analyzer.linkedProjects": ["backend/Cargo.toml"], + "rust-analyzer.check.command": "clippy", + "rust-analyzer.check.extraArgs": ["--all-targets"], + + // ESLint: each frontend/* package has its own flat eslint.config.js + "eslint.workingDirectories": [{ "mode": "auto" }], + + // Python: blcu-programming is the only Python project, venv created by + // its postinstall script (blcu-programming/scripts/setup.mjs) + "python.defaultInterpreterPath": "${workspaceFolder}/blcu-programming/.venv/bin/python", + + // Keep VS Code from indexing/watching generated and vendored trees + "files.watcherExclude": { + "**/node_modules/**": true, + "**/target/**": true, + "**/dist/**": true, + "**/.venv/**": true, + "**/.venv-build/**": true, + "**/.turbo/**": true + }, + "search.exclude": { + "**/node_modules": true, + "**/target": true, + "**/dist": true, + "**/.venv": true, + "**/.venv-build": true, + "**/.turbo": true } } From d8cade58f71ae800b56e29f33bd78c202190fce6 Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Sat, 10 Oct 2026 22:01:23 +0200 Subject: [PATCH 054/225] chore: set up repo for vscode --- .vscode/launch.json | 2 +- .vscode/tasks.json | 165 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 166 insertions(+), 1 deletion(-) create mode 100644 .vscode/tasks.json diff --git a/.vscode/launch.json b/.vscode/launch.json index 62e3453a9..617eff252 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -8,7 +8,7 @@ "program": "${workspaceFolder}/backend/target/debug/station", "args": [], "cwd": "${workspaceFolder}/backend/crates/station", - "preLaunchTask": "cargo build (station)", + "preLaunchTask": "Build Backend (Rust)", "sourceLanguages": ["rust"] } ] diff --git a/.vscode/tasks.json b/.vscode/tasks.json new file mode 100644 index 000000000..a2168caa4 --- /dev/null +++ b/.vscode/tasks.json @@ -0,0 +1,165 @@ +{ + "version": "2.0.0", + "tasks": [ + { + "label": "Run Testing View", + "type": "shell", + "command": "pnpm", + "args": ["dev", "--filter", "testing-view"], + "options": { + "cwd": "${workspaceFolder}" + }, + "problemMatcher": [], + "presentation": { + "reveal": "always", + "panel": "dedicated" + } + }, + { + "label": "Run Competition View", + "type": "shell", + "command": "pnpm", + "args": ["dev", "--filter", "competition-view"], + "options": { + "cwd": "${workspaceFolder}" + }, + "problemMatcher": [], + "presentation": { + "reveal": "always", + "panel": "dedicated" + } + }, + { + "label": "Run Flashing View", + "type": "shell", + "command": "pnpm", + "args": ["dev", "--filter", "flashing-view"], + "options": { + "cwd": "${workspaceFolder}" + }, + "problemMatcher": [], + "presentation": { + "reveal": "always", + "panel": "dedicated" + } + }, + { + "label": "Run Logging View", + "type": "shell", + "command": "pnpm", + "args": ["dev", "--filter", "logging-view"], + "options": { + "cwd": "${workspaceFolder}" + }, + "problemMatcher": [], + "presentation": { + "reveal": "always", + "panel": "dedicated" + } + }, + { + "label": "Run ADJ View", + "type": "shell", + "command": "pnpm", + "args": ["dev", "--filter", "adj-view"], + "options": { + "cwd": "${workspaceFolder}" + }, + "problemMatcher": [], + "presentation": { + "reveal": "always", + "panel": "dedicated" + } + }, + { + "label": "Run Backend (Rust)", + "type": "shell", + "command": "cargo", + "args": ["run", "--package", "station"], + "options": { + "cwd": "${workspaceFolder}/backend" + }, + "problemMatcher": ["$rustc"], + "presentation": { + "reveal": "always", + "panel": "dedicated" + } + }, + { + "label": "Run Python (BLCU Programming)", + "type": "shell", + "command": "pnpm", + "args": ["dev", "--filter", "blcu-programming"], + "options": { + "cwd": "${workspaceFolder}" + }, + "problemMatcher": [], + "presentation": { + "reveal": "always", + "panel": "dedicated" + } + }, + { + "label": "Build App", + "type": "shell", + "command": "pnpm", + "args": ["run", "build"], + "options": { + "cwd": "${workspaceFolder}" + }, + "problemMatcher": [], + "group": "build" + }, + { + "label": "Build Backend (Rust)", + "type": "shell", + "command": "cargo", + "args": ["build", "--package", "station"], + "options": { + "cwd": "${workspaceFolder}/backend" + }, + "problemMatcher": ["$rustc"], + "group": "build" + }, + { + "label": "Test App", + "type": "shell", + "command": "pnpm", + "args": ["run", "test"], + "options": { + "cwd": "${workspaceFolder}" + }, + "problemMatcher": [], + "group": "test" + }, + { + "label": "Test Backend (Rust)", + "type": "shell", + "command": "cargo test ${input:rustTestScope} ${input:rustTestFilter}", + "options": { + "cwd": "${workspaceFolder}/backend" + }, + "problemMatcher": ["$rustc"], + "group": "test" + } + ], + "inputs": [ + { + "id": "rustTestScope", + "type": "pickString", + "description": "¿Qué crate del backend querés testear?", + "options": [ + { "label": "Todo el workspace", "value": "--workspace" }, + { "label": "software-core", "value": "-p software-core" }, + { "label": "station", "value": "-p station" } + ], + "default": "--workspace" + }, + { + "id": "rustTestFilter", + "type": "promptString", + "description": "Filtro de test/módulo dentro del crate elegido (ej. adj::tests, vacío = todos)", + "default": "" + } + ] +} From dfcbcc00ba943c2e32deb19949104b4cc11ae4f5 Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Sat, 10 Oct 2026 22:12:44 +0200 Subject: [PATCH 055/225] chore: rust --- .vscode/tasks.json | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/.vscode/tasks.json b/.vscode/tasks.json index a2168caa4..10489440d 100644 --- a/.vscode/tasks.json +++ b/.vscode/tasks.json @@ -141,6 +141,28 @@ }, "problemMatcher": ["$rustc"], "group": "test" + }, + { + "label": "Clippy Backend (Rust)", + "type": "shell", + "command": "cargo", + "args": ["clippy", "--workspace", "--all-targets", "--", "-D", "warnings"], + "options": { + "cwd": "${workspaceFolder}/backend" + }, + "problemMatcher": ["$rustc"], + "group": "test" + }, + { + "label": "Format Backend (Rust)", + "type": "shell", + "command": "cargo", + "args": ["fmt", "--all"], + "options": { + "cwd": "${workspaceFolder}/backend" + }, + "problemMatcher": [], + "group": "none" } ], "inputs": [ From 83cde99df6d0e2f30bff04ccf6a3393c14126725 Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Sat, 10 Oct 2026 22:27:47 +0200 Subject: [PATCH 056/225] chore(workflows): rust tests --- .github/workflows/rust-tests.yaml | 35 +++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 .github/workflows/rust-tests.yaml diff --git a/.github/workflows/rust-tests.yaml b/.github/workflows/rust-tests.yaml new file mode 100644 index 000000000..a64b89ebe --- /dev/null +++ b/.github/workflows/rust-tests.yaml @@ -0,0 +1,35 @@ +name: Rust Tests + +on: + pull_request: + branches: + - main + - develop + - production + - "backend/**" + paths: + - "backend/**" + - ".github/workflows/rust-tests.yaml" + +jobs: + test: + name: Test (${{ matrix.crate }}) + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + crate: [software-core, station] + steps: + - uses: actions/checkout@v4 + + - name: Set up Rust + uses: dtolnay/rust-toolchain@stable + + - name: Cache cargo + uses: Swatinem/rust-cache@v2 + with: + workspaces: backend + + - name: Run tests + working-directory: backend + run: cargo test --package ${{ matrix.crate }} From edd0f8c68bf67e938fcf22f8df52ad21f6ee5740 Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Sat, 10 Oct 2026 22:32:45 +0200 Subject: [PATCH 057/225] chore(.gitignore): exclude vscode settings --- .gitignore | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index bc66fec72..35fee63ab 100644 --- a/.gitignore +++ b/.gitignore @@ -1,7 +1,11 @@ # Monorepo / IDE node_modules/ .turbo/ -.vscode/ +.vscode/* +!.vscode/settings.json +!.vscode/extensions.json +!.vscode/launch.json +!.vscode/tasks.json .DS_Store *.code-workspace From bb210e7c8a84ec285e0592536f97a7e61dd96050 Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Sat, 10 Oct 2026 22:34:29 +0200 Subject: [PATCH 058/225] test: workflow --- .github/workflows/rust-tests.yaml | 5 ----- 1 file changed, 5 deletions(-) diff --git a/.github/workflows/rust-tests.yaml b/.github/workflows/rust-tests.yaml index a64b89ebe..6ab44a9ce 100644 --- a/.github/workflows/rust-tests.yaml +++ b/.github/workflows/rust-tests.yaml @@ -2,11 +2,6 @@ name: Rust Tests on: pull_request: - branches: - - main - - develop - - production - - "backend/**" paths: - "backend/**" - ".github/workflows/rust-tests.yaml" From d5e7e4b5c72a0be5a7daa802b8ced26328985dd9 Mon Sep 17 00:00:00 2001 From: Gazi Al Saad Halawani Date: Mon, 12 Oct 2026 15:36:08 +0200 Subject: [PATCH 059/225] Feat(backend, protocol): Removed todos and left as comments. Implemented Decoding of data. --- .../crates/core/src/protocol/packet/data.rs | 72 ++++++++++++++++--- .../crates/core/src/protocol/packet/order.rs | 4 +- 2 files changed, 63 insertions(+), 13 deletions(-) diff --git a/backend/crates/core/src/protocol/packet/data.rs b/backend/crates/core/src/protocol/packet/data.rs index bc613cc8c..5f2fa1d86 100644 --- a/backend/crates/core/src/protocol/packet/data.rs +++ b/backend/crates/core/src/protocol/packet/data.rs @@ -1,19 +1,69 @@ //! Decodes a `Data` packet: a board's periodic telemetry. Only ever //! received, over UDP — a board never receives one back. -use crate::model::DataPacket; -use crate::protocol::{DecodeError, Index}; +use crate::model::{AdjId, DataPacket, MeasurementKind, NumericKind, PacketKind}; +use crate::protocol::{DecodeError, Index, wire}; /// Decodes a complete, already-delimited buffer into a [`DataPacket`], /// resolving its field shapes against `index`. pub fn decode(bytes: &[u8], index: &Index) -> Result { - let _ = (bytes, index); - todo!( - "read the leading 16-bit id; look up its PacketDef in `index` \ - (UnknownId if absent); match its `kind` for \ - PacketKind::Data(measurements) (WrongKind if it's some other \ - kind); decode each measurement's value positionally via \ - wire::decode_value, advancing through `bytes` using each \ - measurement's own wire width" - ) + if bytes.len() < 2 { + // If less than 2 bytes return error + return Err(DecodeError::UnexpectedEof); + } + + let id: [u8; 2] = bytes[0..2] // Recieve first two bytes + .try_into() // Tries to make it into desired type + .map_err(|_| DecodeError::UnexpectedEof)?; // If fails, return error + + let adj_id = AdjId(u16::from_le_bytes(id)); // Parse into u16 and make it AdjId type + + let packet_def = index.get(adj_id).ok_or(DecodeError::UnknownId(adj_id))?; // Get packet definition from index + + let measurements = match &packet_def.kind { + // Get measurements from packet definition + PacketKind::Data(measurements) => measurements, // If packet kind is data, return measurements + _ => return Err(DecodeError::WrongKind { id: adj_id }), // If not, return Error + }; + + let mut values = Vec::with_capacity(measurements.len()); // Create vectir list of values same size as measurements + + let mut pointer = 2; // Pointer to after ID in bytes + + for measurement in measurements { + let width = match &measurement.kind { // Set width of measurement according to the type. + MeasurementKind::Numeric { wire_type } => match wire_type { + NumericKind::U8 | NumericKind::I8 => 1, + NumericKind::U16 | NumericKind::I16 => 2, + NumericKind::U32 | NumericKind::I32 | NumericKind::F32 => 4, + NumericKind::U64 | NumericKind::I64 | NumericKind::F64 => 8, + }, + MeasurementKind::Boolean => 1, + MeasurementKind::Enum { .. } => 1 + }; + + let next = pointer + width; + + if bytes.len() < next { + // Check if there is enough bytes left + return Err(DecodeError::UnexpectedEof); + } + + let field = &bytes[pointer..next]; // Size of field (bytes between pointer and next position) + let value = wire::decode_value(field, &measurement.kind)?; // Decode value from field size and measurement width + values.push(value); //Add to list of values + + pointer = next; // Next position + } + + Ok(DataPacket { id: adj_id, values }) // Return data packet } + +// +// "read the leading 16-bit id; look up its PacketDef in `index` \ +// (UnknownId if absent); match its `kind` for \ +// PacketKind::Data(measurements) (WrongKind if it's some other \ +// kind); decode each measurement's value positionally via \ +// wire::decode_value, advancing through `bytes` using each \ +// measurement's own wire width" +// diff --git a/backend/crates/core/src/protocol/packet/order.rs b/backend/crates/core/src/protocol/packet/order.rs index 16fa74c02..1f6c98109 100644 --- a/backend/crates/core/src/protocol/packet/order.rs +++ b/backend/crates/core/src/protocol/packet/order.rs @@ -39,10 +39,10 @@ pub fn encode(order: &OrderPacket, index: &Index) -> Result, EncodeError -// todo!( +// // "look up order.id in `index` to get its PacketDef (UnknownId if \ // absent); match its `kind` for PacketKind::Order(measurements) \ // (WrongKind if it's some other kind); error with WrongFieldCount \ // if order.fields.len() doesn't match measurements.len(); encode \ // the id then each field positionally via wire::encode_value" -// ) \ No newline at end of file +// \ No newline at end of file From e8180bde43d6173c8b84f8c26ec3875e0b0c1771 Mon Sep 17 00:00:00 2001 From: Gazi Al Saad Halawani Date: Mon, 12 Oct 2026 15:50:23 +0200 Subject: [PATCH 060/225] Feat(backend, protocol): used new function to retrieve the width of a measurement in data.rs decoding data function. --- backend/crates/core/src/protocol/packet/data.rs | 13 ++----------- 1 file changed, 2 insertions(+), 11 deletions(-) diff --git a/backend/crates/core/src/protocol/packet/data.rs b/backend/crates/core/src/protocol/packet/data.rs index 5f2fa1d86..a649a9db8 100644 --- a/backend/crates/core/src/protocol/packet/data.rs +++ b/backend/crates/core/src/protocol/packet/data.rs @@ -1,7 +1,7 @@ //! Decodes a `Data` packet: a board's periodic telemetry. Only ever //! received, over UDP — a board never receives one back. -use crate::model::{AdjId, DataPacket, MeasurementKind, NumericKind, PacketKind}; +use crate::model::{AdjId, DataPacket, PacketKind}; use crate::protocol::{DecodeError, Index, wire}; /// Decodes a complete, already-delimited buffer into a [`DataPacket`], @@ -31,16 +31,7 @@ pub fn decode(bytes: &[u8], index: &Index) -> Result { let mut pointer = 2; // Pointer to after ID in bytes for measurement in measurements { - let width = match &measurement.kind { // Set width of measurement according to the type. - MeasurementKind::Numeric { wire_type } => match wire_type { - NumericKind::U8 | NumericKind::I8 => 1, - NumericKind::U16 | NumericKind::I16 => 2, - NumericKind::U32 | NumericKind::I32 | NumericKind::F32 => 4, - NumericKind::U64 | NumericKind::I64 | NumericKind::F64 => 8, - }, - MeasurementKind::Boolean => 1, - MeasurementKind::Enum { .. } => 1 - }; + let width = wire::byte_width(&measurement.kind); let next = pointer + width; From 9670faef7ca239a156e6b858dc707564666df82e Mon Sep 17 00:00:00 2001 From: Gazi Al Saad Halawani Date: Mon, 12 Oct 2026 15:36:08 +0200 Subject: [PATCH 061/225] Feat(backend, protocol): Removed todos and left as comments. Implemented Decoding of data. --- .../crates/core/src/protocol/packet/data.rs | 72 ++++++++++++++++--- .../crates/core/src/protocol/packet/order.rs | 4 +- 2 files changed, 63 insertions(+), 13 deletions(-) diff --git a/backend/crates/core/src/protocol/packet/data.rs b/backend/crates/core/src/protocol/packet/data.rs index bc613cc8c..5f2fa1d86 100644 --- a/backend/crates/core/src/protocol/packet/data.rs +++ b/backend/crates/core/src/protocol/packet/data.rs @@ -1,19 +1,69 @@ //! Decodes a `Data` packet: a board's periodic telemetry. Only ever //! received, over UDP — a board never receives one back. -use crate::model::DataPacket; -use crate::protocol::{DecodeError, Index}; +use crate::model::{AdjId, DataPacket, MeasurementKind, NumericKind, PacketKind}; +use crate::protocol::{DecodeError, Index, wire}; /// Decodes a complete, already-delimited buffer into a [`DataPacket`], /// resolving its field shapes against `index`. pub fn decode(bytes: &[u8], index: &Index) -> Result { - let _ = (bytes, index); - todo!( - "read the leading 16-bit id; look up its PacketDef in `index` \ - (UnknownId if absent); match its `kind` for \ - PacketKind::Data(measurements) (WrongKind if it's some other \ - kind); decode each measurement's value positionally via \ - wire::decode_value, advancing through `bytes` using each \ - measurement's own wire width" - ) + if bytes.len() < 2 { + // If less than 2 bytes return error + return Err(DecodeError::UnexpectedEof); + } + + let id: [u8; 2] = bytes[0..2] // Recieve first two bytes + .try_into() // Tries to make it into desired type + .map_err(|_| DecodeError::UnexpectedEof)?; // If fails, return error + + let adj_id = AdjId(u16::from_le_bytes(id)); // Parse into u16 and make it AdjId type + + let packet_def = index.get(adj_id).ok_or(DecodeError::UnknownId(adj_id))?; // Get packet definition from index + + let measurements = match &packet_def.kind { + // Get measurements from packet definition + PacketKind::Data(measurements) => measurements, // If packet kind is data, return measurements + _ => return Err(DecodeError::WrongKind { id: adj_id }), // If not, return Error + }; + + let mut values = Vec::with_capacity(measurements.len()); // Create vectir list of values same size as measurements + + let mut pointer = 2; // Pointer to after ID in bytes + + for measurement in measurements { + let width = match &measurement.kind { // Set width of measurement according to the type. + MeasurementKind::Numeric { wire_type } => match wire_type { + NumericKind::U8 | NumericKind::I8 => 1, + NumericKind::U16 | NumericKind::I16 => 2, + NumericKind::U32 | NumericKind::I32 | NumericKind::F32 => 4, + NumericKind::U64 | NumericKind::I64 | NumericKind::F64 => 8, + }, + MeasurementKind::Boolean => 1, + MeasurementKind::Enum { .. } => 1 + }; + + let next = pointer + width; + + if bytes.len() < next { + // Check if there is enough bytes left + return Err(DecodeError::UnexpectedEof); + } + + let field = &bytes[pointer..next]; // Size of field (bytes between pointer and next position) + let value = wire::decode_value(field, &measurement.kind)?; // Decode value from field size and measurement width + values.push(value); //Add to list of values + + pointer = next; // Next position + } + + Ok(DataPacket { id: adj_id, values }) // Return data packet } + +// +// "read the leading 16-bit id; look up its PacketDef in `index` \ +// (UnknownId if absent); match its `kind` for \ +// PacketKind::Data(measurements) (WrongKind if it's some other \ +// kind); decode each measurement's value positionally via \ +// wire::decode_value, advancing through `bytes` using each \ +// measurement's own wire width" +// diff --git a/backend/crates/core/src/protocol/packet/order.rs b/backend/crates/core/src/protocol/packet/order.rs index 16fa74c02..1f6c98109 100644 --- a/backend/crates/core/src/protocol/packet/order.rs +++ b/backend/crates/core/src/protocol/packet/order.rs @@ -39,10 +39,10 @@ pub fn encode(order: &OrderPacket, index: &Index) -> Result, EncodeError -// todo!( +// // "look up order.id in `index` to get its PacketDef (UnknownId if \ // absent); match its `kind` for PacketKind::Order(measurements) \ // (WrongKind if it's some other kind); error with WrongFieldCount \ // if order.fields.len() doesn't match measurements.len(); encode \ // the id then each field positionally via wire::encode_value" -// ) \ No newline at end of file +// \ No newline at end of file From abf0e44291373a331f8ae302cdf71e1ce447ecc1 Mon Sep 17 00:00:00 2001 From: Gazi Al Saad Halawani Date: Mon, 12 Oct 2026 15:50:23 +0200 Subject: [PATCH 062/225] Feat(backend, protocol): used new function to retrieve the width of a measurement in data.rs decoding data function. --- backend/crates/core/src/protocol/packet/data.rs | 13 ++----------- 1 file changed, 2 insertions(+), 11 deletions(-) diff --git a/backend/crates/core/src/protocol/packet/data.rs b/backend/crates/core/src/protocol/packet/data.rs index 5f2fa1d86..a649a9db8 100644 --- a/backend/crates/core/src/protocol/packet/data.rs +++ b/backend/crates/core/src/protocol/packet/data.rs @@ -1,7 +1,7 @@ //! Decodes a `Data` packet: a board's periodic telemetry. Only ever //! received, over UDP — a board never receives one back. -use crate::model::{AdjId, DataPacket, MeasurementKind, NumericKind, PacketKind}; +use crate::model::{AdjId, DataPacket, PacketKind}; use crate::protocol::{DecodeError, Index, wire}; /// Decodes a complete, already-delimited buffer into a [`DataPacket`], @@ -31,16 +31,7 @@ pub fn decode(bytes: &[u8], index: &Index) -> Result { let mut pointer = 2; // Pointer to after ID in bytes for measurement in measurements { - let width = match &measurement.kind { // Set width of measurement according to the type. - MeasurementKind::Numeric { wire_type } => match wire_type { - NumericKind::U8 | NumericKind::I8 => 1, - NumericKind::U16 | NumericKind::I16 => 2, - NumericKind::U32 | NumericKind::I32 | NumericKind::F32 => 4, - NumericKind::U64 | NumericKind::I64 | NumericKind::F64 => 8, - }, - MeasurementKind::Boolean => 1, - MeasurementKind::Enum { .. } => 1 - }; + let width = wire::byte_width(&measurement.kind); let next = pointer + width; From c3b2939f1b72f9153e7c660d75cf1407ed379226 Mon Sep 17 00:00:00 2001 From: Gazi Al Saad Halawani Date: Mon, 12 Oct 2026 16:14:16 +0200 Subject: [PATCH 063/225] Feat(backend, protocol): Refactored to merge data.rs and order.rs to data_order.rs --- backend/crates/core/src/model.rs | 2 +- backend/crates/core/src/model/packet.rs | 21 +++---- backend/crates/core/src/protocol/packet.rs | 3 +- .../packet/{data.rs => data_order.rs} | 56 +++++++++++++++++-- .../crates/core/src/protocol/packet/order.rs | 48 ---------------- 5 files changed, 60 insertions(+), 70 deletions(-) rename backend/crates/core/src/protocol/packet/{data.rs => data_order.rs} (51%) delete mode 100644 backend/crates/core/src/protocol/packet/order.rs diff --git a/backend/crates/core/src/model.rs b/backend/crates/core/src/model.rs index 6cfdda92d..ccef505c5 100644 --- a/backend/crates/core/src/model.rs +++ b/backend/crates/core/src/model.rs @@ -21,7 +21,7 @@ pub use board::{Board, PacketDef, PacketKind, PodData}; pub use id::{AdjId, BoardId, MacAddress, Port}; pub use measurement::{Measurement, MeasurementKind, NumericKind, Range}; pub use packet::{ - DataPacket, MessageLevel, MessagePacket, OrderPacket, Packet, ProtectionPacket, ShortTimestamp, + DataPacket, MessageLevel, MessagePacket, OrderPacket, Packet, ProtectionPacket, ShortTimestamp, DataOrderPacket }; pub use protections::{Protection, ProtectionKind, Severity}; pub use value::Value; diff --git a/backend/crates/core/src/model/packet.rs b/backend/crates/core/src/model/packet.rs index 7ac91f048..54727d403 100644 --- a/backend/crates/core/src/model/packet.rs +++ b/backend/crates/core/src/model/packet.rs @@ -32,7 +32,7 @@ pub struct ShortTimestamp { pub subsecond: u8, } -/// A data packet: the decoded values of the measurements a board just +/// A Data/Order packet: the decoded values of the measurements a board just /// sent. /// /// The wire protocol is positional: values are not individually tagged @@ -41,25 +41,18 @@ pub struct ShortTimestamp { /// [`super::PacketKind::Data`] list. `values[i]` is the decoded value of /// that list's `i`-th measurement — matching them up by position is /// `protocol`'s job, this type just holds the result in that same order. + #[derive(Debug, Clone, PartialEq)] -pub struct DataPacket { - /// Which packet definition this is an instance of. +pub struct DataOrderPacket{ pub id: AdjId, - /// The decoded value of each measurement in the packet, positional — - /// see the struct-level docs above. - pub values: Vec, + pub values: Vec, } /// An order sent from the backend to a board. /// /// Positional, the same way [`DataPacket::values`] is: see its docs. -#[derive(Debug, Clone, PartialEq)] -pub struct OrderPacket { - /// Which order definition this is an instance of. - pub id: AdjId, - /// The value to set for each field of the order, positional. - pub fields: Vec, -} +pub type OrderPacket = DataOrderPacket; +pub type DataPacket = DataOrderPacket; /// A protection packet: sent by a board when one of its declared /// [`super::Protection`]s triggers. @@ -218,7 +211,7 @@ mod tests { }); let order = Packet::Order(OrderPacket { id: AdjId(2000), - fields: vec![], + values: vec![], }); assert_ne!(data, order); diff --git a/backend/crates/core/src/protocol/packet.rs b/backend/crates/core/src/protocol/packet.rs index b1c19e246..7f357df8f 100644 --- a/backend/crates/core/src/protocol/packet.rs +++ b/backend/crates/core/src/protocol/packet.rs @@ -5,7 +5,6 @@ //! only ever received (over UDP), an `Order` only ever sent (over TCP), //! so there's no `encode` for the former or `decode` for the latter. -pub mod data; pub mod message; -pub mod order; pub mod protection; +pub mod data_order; diff --git a/backend/crates/core/src/protocol/packet/data.rs b/backend/crates/core/src/protocol/packet/data_order.rs similarity index 51% rename from backend/crates/core/src/protocol/packet/data.rs rename to backend/crates/core/src/protocol/packet/data_order.rs index a649a9db8..e9cc5e210 100644 --- a/backend/crates/core/src/protocol/packet/data.rs +++ b/backend/crates/core/src/protocol/packet/data_order.rs @@ -1,12 +1,58 @@ +use crate::model::{AdjId, DataPacket, PacketKind, Value, DataOrderPacket}; +use crate::protocol::{wire, EncodeError, Index, DecodeError}; + + +//! Encodes an `Order` packet: a command sent to a board. Only ever sent, +//! over TCP — the backend never receives one back. + +/// Encodes `order` into the bytes to write to a board's connection, +/// resolving its field shapes against `index`. +pub fn encode(order: &DataOrderPacket, index: &Index) -> Result, EncodeError> { + + //Unwrap PacketDef for kind + let packet_def = index + .packet(order.id) + .ok_or(EncodeError::UnknownId(order.id))?;// Question mark for error propagation and prevent crash + + //Check if packetdef is PacketKind::Order(measurement). Also returns the list of measurements + let measurements = match &packet_def.kind{ + PacketKind::Order(measurements) => measurements, + _ => return Err(EncodeError::WrongKind {id:order.id}) + }; + + //Check if length of list of fields matches number of measurements. + if order.values.len() != measurements.len(){ + return Err(EncodeError::WrongFieldCount {expected:measurements.len(),got:order.values.len()}) + } + + let mut bytes = Vec::new(); + + bytes.extend_from_slice(&order.id.0.to_le_bytes());//Header prefix of byte stream to 16 bit little-endian + + //Encoding to bytes + for (field,measurement) in order.values.iter().zip(measurements){ //For each measurement + let field_bytes = wire::encode_value(field,&measurement.kind)?;// Encode field Value into bytes according to MeasurementKind + bytes.extend(field_bytes);// Adds to byte stream + } + + Ok(bytes) // Return bytes +} + + +// +// "look up order.id in `index` to get its PacketDef (UnknownId if \ +// absent); match its `kind` for PacketKind::Order(measurements) \ +// (WrongKind if it's some other kind); error with WrongFieldCount \ +// if order.fields.len() doesn't match measurements.len(); encode \ +// the id then each field positionally via wire::encode_value" +// + //! Decodes a `Data` packet: a board's periodic telemetry. Only ever //! received, over UDP — a board never receives one back. -use crate::model::{AdjId, DataPacket, PacketKind}; -use crate::protocol::{DecodeError, Index, wire}; - /// Decodes a complete, already-delimited buffer into a [`DataPacket`], /// resolving its field shapes against `index`. -pub fn decode(bytes: &[u8], index: &Index) -> Result { +pub fn decode(bytes: &[u8], index: &Index) -> Result, DecodeError> { if bytes.len() < 2 { // If less than 2 bytes return error return Err(DecodeError::UnexpectedEof); @@ -57,4 +103,4 @@ pub fn decode(bytes: &[u8], index: &Index) -> Result { // kind); decode each measurement's value positionally via \ // wire::decode_value, advancing through `bytes` using each \ // measurement's own wire width" -// +// \ No newline at end of file diff --git a/backend/crates/core/src/protocol/packet/order.rs b/backend/crates/core/src/protocol/packet/order.rs deleted file mode 100644 index 1f6c98109..000000000 --- a/backend/crates/core/src/protocol/packet/order.rs +++ /dev/null @@ -1,48 +0,0 @@ -//! Encodes an `Order` packet: a command sent to a board. Only ever sent, -//! over TCP — the backend never receives one back. - -use crate::model::{OrderPacket, PacketKind}; -use crate::protocol::{wire, EncodeError, Index}; - -/// Encodes `order` into the bytes to write to a board's connection, -/// resolving its field shapes against `index`. -pub fn encode(order: &OrderPacket, index: &Index) -> Result, EncodeError> { - - //Unwrap PacketDef for kind - let packet_def = index - .packet(order.id) - .ok_or(EncodeError::UnknownId(order.id))?;// Question mark for error propagation and prevent crash - - //Check if packetdef is PacketKind::Order(measurement). Also returns the list of measurements - let measurements = match &packet_def.kind{ - PacketKind::Order(measurements) => measurements, - _ => return Err(EncodeError::WrongKind {id:order.id}) - }; - - //Check if length of list of fields matches number of measurements. - if order.fields.len() != measurements.len(){ - return Err(EncodeError::WrongFieldCount {expected:measurements.len(),got:order.fields.len()}) - } - - let mut bytes = Vec::new(); - - bytes.extend_from_slice(&order.id.0.to_le_bytes());//Header prefix of byte stream to 16 bit little-endian - - //Encoding to bytes - for (field,measurement) in order.fields.iter().zip(measurements){ //For each measurement - let field_bytes = wire::encode_value(field,&measurement.kind)?;// Encode field Value into bytes according to MeasurementKind - bytes.extend(field_bytes);// Adds to byte stream - } - - Ok(bytes) // Return bytes -} - - - -// -// "look up order.id in `index` to get its PacketDef (UnknownId if \ -// absent); match its `kind` for PacketKind::Order(measurements) \ -// (WrongKind if it's some other kind); error with WrongFieldCount \ -// if order.fields.len() doesn't match measurements.len(); encode \ -// the id then each field positionally via wire::encode_value" -// \ No newline at end of file From d9d2b4df61feadb354d258631a0bbf3c6f142441 Mon Sep 17 00:00:00 2001 From: Gazi Al Saad Halawani Date: Mon, 12 Oct 2026 16:20:31 +0200 Subject: [PATCH 064/225] Feat(backend, protocol): Created tests for data_order.rs. --- .../core/src/protocol/packet/data_order.rs | 204 +++++++++++++++++- 1 file changed, 203 insertions(+), 1 deletion(-) diff --git a/backend/crates/core/src/protocol/packet/data_order.rs b/backend/crates/core/src/protocol/packet/data_order.rs index e9cc5e210..eaa4cb84d 100644 --- a/backend/crates/core/src/protocol/packet/data_order.rs +++ b/backend/crates/core/src/protocol/packet/data_order.rs @@ -103,4 +103,206 @@ pub fn decode(bytes: &[u8], index: &Index) -> Result, Dec // kind); decode each measurement's value positionally via \ // wire::decode_value, advancing through `bytes` using each \ // measurement's own wire width" -// \ No newline at end of file +// + +#[cfg(test)] +mod tests { + use super::*; + use crate::model::{ + Board, BoardId, MacAddress, Measurement, MeasurementKind, NumericKind, PacketDef, + PacketKind, PodData, Value, + }; + use std::collections::HashMap; + use std::net::IpAddr; + + fn sample_measurement(id: u16, kind: MeasurementKind) -> Measurement { + Measurement { + id: AdjId(id), + alias: format!("field_{id}"), + name: format!("Field {id}"), + display_units: String::new(), + kind, + protections: vec![], + } + } + + fn sample_packet_def(id: AdjId, kind: PacketKind) -> PacketDef { + PacketDef { + id, + board: BoardId(1), + name: "TestPacket".into(), + kind, + } + } + + fn make_test_index(defs: Vec) -> Index { + let packets: HashMap = defs.into_iter().map(|p| (p.id, p)).collect(); + let board = Board { + id: BoardId(1), + name: "TestBoard".to_string(), + ip: IpAddr::from([127, 0, 0, 1]), + mac: MacAddress([0; 6]), + packets, + }; + let pod_data = PodData { + boards: HashMap::from([(board.id, board)]), + }; + Index::new(&pod_data) + } + + // --- ENCODE TESTS --- + + #[test] + fn encode_success_little_endian_and_positional_fields() { + let order_id = AdjId(1001); + let packet_def = sample_packet_def( + order_id, + PacketKind::Order(vec![ + sample_measurement(1, MeasurementKind::Numeric { wire_type: NumericKind::U16 }), + sample_measurement(2, MeasurementKind::Boolean), + ]), + ); + + let index = make_test_index(vec![packet_def]); + + let packet = DataOrderPacket { + id: order_id, + values: vec![Value::Number(300.0), Value::Bool(true)], + }; + + let encoded = encode(&packet, &index).expect("encoding should succeed"); + + // 1001 in little-endian u16: [0xE9, 0x03] + // 300 in little-endian u16: [0x2C, 0x01] + // true: [0x01] + assert_eq!(encoded, vec![0xE9, 0x03, 0x2C, 0x01, 0x01]); + } + + #[test] + fn encode_fails_on_unknown_id() { + let index = make_test_index(vec![]); + let packet = DataOrderPacket { + id: AdjId(9999), + values: vec![], + }; + + let err = encode(&packet, &index).unwrap_err(); + assert_eq!(err, EncodeError::UnknownId(AdjId(9999))); + } + + #[test] + fn encode_fails_on_wrong_kind() { + let data_id = AdjId(2001); + let packet_def = sample_packet_def(data_id, PacketKind::Data(vec![])); + + let index = make_test_index(vec![packet_def]); + let packet = DataOrderPacket { + id: data_id, + values: vec![], + }; + + let err = encode(&packet, &index).unwrap_err(); + assert_eq!(err, EncodeError::WrongKind { id: data_id }); + } + + #[test] + fn encode_fails_on_wrong_field_count() { + let order_id = AdjId(1002); + let packet_def = sample_packet_def( + order_id, + PacketKind::Order(vec![ + sample_measurement(1, MeasurementKind::Numeric { wire_type: NumericKind::U8 }), + sample_measurement(2, MeasurementKind::Numeric { wire_type: NumericKind::U8 }), + ]), + ); + + let index = make_test_index(vec![packet_def]); + let packet = DataOrderPacket { + id: order_id, + values: vec![Value::Number(10.0)], + }; + + let err = encode(&packet, &index).unwrap_err(); + assert_eq!( + err, + EncodeError::WrongFieldCount { + expected: 2, + got: 1, + } + ); + } + + // --- DECODE TESTS --- + + #[test] + fn decode_success_little_endian_and_values() { + let data_id = AdjId(3001); + let packet_def = sample_packet_def( + data_id, + PacketKind::Data(vec![ + sample_measurement(1, MeasurementKind::Numeric { wire_type: NumericKind::U16 }), + sample_measurement(2, MeasurementKind::Boolean), + ]), + ); + + let index = make_test_index(vec![packet_def]); + + // 3001 in little-endian u16: [0xB9, 0x0B] + // 500 in little-endian u16: [0xF4, 0x01] + // false: [0x00] + let raw_bytes = [0xB9, 0x0B, 0xF4, 0x01, 0x00]; + + let decoded = decode(&raw_bytes, &index).expect("decoding should succeed"); + + assert_eq!(decoded.id, data_id); + assert_eq!( + decoded.values, + vec![Value::Number(500.0), Value::Bool(false)] + ); + } + + #[test] + fn decode_fails_when_buffer_is_shorter_than_header() { + let index = make_test_index(vec![]); + let err = decode(&[0x01], &index).unwrap_err(); + assert_eq!(err, DecodeError::UnexpectedEof); + } + + #[test] + fn decode_fails_on_unexpected_eof_in_payload() { + let data_id = AdjId(3002); + let packet_def = sample_packet_def( + data_id, + PacketKind::Data(vec![ + sample_measurement(1, MeasurementKind::Numeric { wire_type: NumericKind::U32 }), + ]), + ); + + let index = make_test_index(vec![packet_def]); + + let raw_bytes = [0xBA, 0x0B, 0x01, 0x02]; + let err = decode(&raw_bytes, &index).unwrap_err(); + assert_eq!(err, DecodeError::UnexpectedEof); + } + + #[test] + fn decode_fails_on_unknown_id() { + let index = make_test_index(vec![]); + let raw_bytes = [0x88, 0x13]; + + let err = decode(&raw_bytes, &index).unwrap_err(); + assert_eq!(err, DecodeError::UnknownId(AdjId(5000))); + } + + #[test] + fn decode_fails_on_wrong_kind() { + let order_id = AdjId(4001); + let packet_def = sample_packet_def(order_id, PacketKind::Order(vec![])); + + let index = make_test_index(vec![packet_def]); + let raw_bytes = [0xA1, 0x0F]; + + let err = decode(&raw_bytes, &index).unwrap_err(); + assert_eq!(err, DecodeError::WrongKind { id: order_id }); + } +} \ No newline at end of file From 71258e56a0c9d36a49d9b649bc28f363b37be26f Mon Sep 17 00:00:00 2001 From: Gazi Al Saad Halawani Date: Mon, 12 Oct 2026 16:40:58 +0200 Subject: [PATCH 065/225] Feat(backend, protocol): Created ReadMe for the protocol directory. --- backend/crates/core/src/protocol/README.md | 157 +++++++++++++++++++++ 1 file changed, 157 insertions(+) create mode 100644 backend/crates/core/src/protocol/README.md diff --git a/backend/crates/core/src/protocol/README.md b/backend/crates/core/src/protocol/README.md new file mode 100644 index 000000000..1d81566f4 --- /dev/null +++ b/backend/crates/core/src/protocol/README.md @@ -0,0 +1,157 @@ +# Protocol Module + +This module handles encoding and decoding of packets for communication with hardware boards over TCP and UDP transports. It implements the ADJ protocol for telemetry data, commands, messages, and protection events. + +## Architecture + +The protocol module follows a layered architecture: + +``` +┌─────────────────────────────────────────┐ +│ Transport Layer │ +│ (tcp.rs, udp.rs) │ +├─────────────────────────────────────────┤ +│ Packet Layer │ +│ (packet/data_order.rs, │ +│ packet/message.rs, │ +│ packet/protection.rs) │ +├─────────────────────────────────────────┤ +│ Wire Layer │ +│ (wire.rs) │ +└─────────────────────────────────────────┘ +``` + +## Directory Structure + +``` +protocol/ +├── index.rs # Packet definition lookup table +├── error.rs # Decode and encode error types +├── wire.rs # Low-level byte ↔ value conversion +├── packet.rs # Packet-level encoding/decoding module +│ ├── data_order.rs # Data (telemetry) & Order (command) packets +│ ├── message.rs # Free-text log message packets (stub) +│ └── protection.rs # Protection trigger packets (stub) +├── tcp.rs # TCP transport framing (stub) +└── udp.rs # UDP transport framing +``` + +## Modules + +### `index.rs` - Packet Definition Lookup + +Provides a fast lookup table from packet IDs (`AdjId`) to their declarations (`PacketDef`). Built once from loaded ADJ configuration data (`PodData`), it owns cloned copies of packet definitions so it can be shared across async tasks via `Arc`. + +**Key types:** +- `Index` - HashMap-based lookup from `AdjId` to `PacketDef` + +### `error.rs` - Error Types + +Defines errors that can occur during packet encoding and decoding. + +**Key types:** +- `DecodeError` - Errors when converting bytes to packets + - `UnknownId` - No packet declared with this ID + - `UnexpectedEof` - Ran out of bytes during decode + - `Io` - I/O error reading from stream (TCP only) + - `InvalidEnumValue` - Enum index out of range + - `UnterminatedString` - String field not null-terminated + - `WrongKind` - Packet exists but isn't expected kind + +- `EncodeError` - Errors when converting packets to bytes + - `UnknownId` - No packet declared with this ID + - `WrongFieldCount` - Missing or extra fields in order + - `TypeMismatch` - Value doesn't match declared type + - `OutOfRange` - Numeric value doesn't fit wire type + - `WrongKind` - Packet exists but isn't expected kind + +### `wire.rs` - Low-Level Byte Codec + +Handles conversion between raw bytes and `Value` types for individual measurements, based on their declared `MeasurementKind`. All numeric types use little-endian encoding. + +**Key functions:** +- `decode_value(bytes, kind)` - Decode a single value from bytes +- `encode_value(value, kind)` - Encode a single value to bytes +- `byte_width(kind)` - Get the wire width in bytes for a measurement kind + +**Supported types:** +- **Numeric** (U8, U16, U32, U64, I8, I16, I32, I64, F32, F64) - ✓ Implemented +- **Enum** (single byte index) - ✓ Implemented +- **Boolean** - ⚠ Stub (wire width not yet confirmed with firmware) + +### `packet/` - Packet-Level Encoding/Decoding + +Contains per-packet-kind encoding and decoding logic, independent of transport. + +#### `data_order.rs` + +Handles two packet kinds: +- **Order packets** (commands sent to boards) - Encoded only, sent over TCP +- **Data packets** (periodic telemetry from boards) - Decoded only, received over UDP + +**Key functions:** +- `encode(order, index)` - Encode an Order packet into bytes +- `decode(bytes, index)` - Decode a Data packet from bytes + +#### `message.rs` ⚠ Stub + +Decodes free-text log messages from boards over TCP. Not yet implemented. + +#### `protection.rs` ⚠ Stub + +Decodes protection trigger events from boards over TCP. Not yet implemented. + +### `tcp.rs` - TCP Transport Framing ⚠ Partial + +Handles the dedicated TCP connection to each board. A TCP connection carries: +- Protection events (board → backend) +- Free-text messages (board → backend) +- Order commands (backend → board) + +**Key types:** +- `TcpFrame` - Enum of frames that can be received over TCP (Protection, Message) + +**Key functions:** +- `decode_next(reader, index)` - ⚠ Stub - Decode the next frame from a TCP stream +- `encode_order(order, index)` - ✓ Implemented - Encode an order for sending + +### `udp.rs` - UDP Transport Framing + +Handles the shared UDP socket for periodic telemetry. UDP datagrams are complete, already-delimited buffers containing Data packets. + +**Key functions:** +- `decode_datagram(bytes, index)` - ✓ Implemented - Decode a UDP datagram into a DataPacket + +## Packet Types Summary + +| Packet Type | Direction | Transport | Status | +|-------------|-----------|-----------|--------| +| Data (telemetry) | Board → Backend | UDP | ✓ Implemented | +| Order (command) | Backend → Board | TCP | ✓ Implemented | +| Message (log) | Board → Backend | TCP | ⚠ Stub | +| Protection (event) | Board → Backend | TCP | ⚠ Stub | + +## Implementation Status + +- ✅ **Data packets** - Full encode/decode with tests +- ✅ **Order packets** - Full encode/decode with tests +- ✅ **Wire-level numeric types** - All numeric kinds supported with tests +- ✅ **Wire-level enum types** - Full encode/decode with tests +- ⚠️ **Wire-level boolean types** - Stub (awaiting firmware confirmation) +- ⚠️ **Message packets** - Stub (decode not implemented) +- ⚠️ **Protection packets** - Stub (decode not implemented) +- ⚠️ **TCP framing** - Partial (decode_next not implemented) + +## Testing + +The module includes comprehensive unit tests for: +- Wire-level encoding/decoding for all numeric types +- Enum encoding/decoding with boundary checks +- Order packet encoding with field validation +- Data packet decoding with error handling +- Error propagation for unknown IDs, wrong kinds, and type mismatches + +Run tests with: +```bash +cargo test -p core protocol +``` From 71ccb294e8a5b904452d96f9254be6bb26e98751 Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Mon, 12 Oct 2026 17:09:57 +0200 Subject: [PATCH 066/225] feat(backend, git): separate module in submodules and propagate GitError instead of BoxError --- backend/crates/core/src/git.rs | 447 +++------------------- backend/crates/core/src/git/clone.rs | 245 ++++++++++++ backend/crates/core/src/git/repository.rs | 113 ++++++ backend/crates/core/src/git/update.rs | 135 +++++++ 4 files changed, 554 insertions(+), 386 deletions(-) create mode 100644 backend/crates/core/src/git/clone.rs create mode 100644 backend/crates/core/src/git/repository.rs create mode 100644 backend/crates/core/src/git/update.rs diff --git a/backend/crates/core/src/git.rs b/backend/crates/core/src/git.rs index ca56adf36..f73566257 100644 --- a/backend/crates/core/src/git.rs +++ b/backend/crates/core/src/git.rs @@ -1,399 +1,74 @@ //! Blocking Git helpers for ADJ, an application-owned, replaceable data cache. -use std::{ - fs, io, - net::{Ipv4Addr, SocketAddr, TcpStream}, - path::{Path, PathBuf}, - sync::atomic::AtomicBool, - time::Duration, -}; +mod clone; +mod repository; +mod update; -use gix::Repository; -use tracing::{debug, info, instrument, warn}; +pub use clone::CloneError; +pub use repository::{RepositoryError, branch_exists, list_remote_branches, open_repo}; +pub use update::update_adj; -// Common error type for filesystem and Git failures; Send + Sync allows cross-thread use. -type BoxError = Box; - -const ADJ_URL: &str = "https://github.com/HyperloopUPV/adj.git"; -const GIT_REMOTE: &str = "origin"; - -/// Downloads the requested ADJ branch, replacing the application-managed cache. -/// -/// `path` is the repository directory, not its parent. If omitted, it defaults to -/// `/hyperloop-control-station/adj`. `branch` selects the branch -/// to clone when the connectivity probe succeeds. -/// -/// Online, local edits and commits are discarded only after a fresh checkout -/// succeeds. Offline, the current cached checkout is used without switching -/// branches, so it may differ from `branch`. Returns its full commit hash and -/// commit message, in that order. -/// -/// This performs blocking network and filesystem operations. Call during startup, -/// before readers use ADJ, with only one updater at a time. Replacement uses two -/// renames and is not atomic across a process crash. +/// Errors produced while reading, downloading, or replacing the ADJ cache. /// -/// # Errors +/// Five categories identify the failed operation and preserve its underlying +/// error as [`std::error::Error::source`]. [`RepositoryError`] and [`CloneError`] +/// retain concrete `gix` causes and are boxed to keep this enum small. Only +/// [`RepositoryError::ReferenceItem`] uses a dynamically typed cause, as exposed +/// by the `gix` iterator. /// -/// Returns an error if ADJ is missing offline, the path or repository is invalid -/// or inaccessible, cloning or checkout fails, or replacement fails. Clone errors -/// do not automatically fall back to the cache. If rollback fails, the error -/// includes the preserved backup's location. -// Log returned errors at the public boundary; helpers trace progress without duplicate warnings. -#[instrument(level = "debug", err(level = "warn"))] -pub fn update_adj(path: Option, branch: &str) -> Result<(String, String), BoxError> { - let (repo, dir) = adj_exists_repo(path)?; - - if check_internet_connection() { - info!(path = ?dir, branch, "starting ADJ update"); - // Release repository handles before moving the existing cache directory. - drop(repo); - git_replace(&dir, branch, ADJ_URL) - } else if let Some(repo) = repo { - warn!(path = ?dir, requested_branch = branch, - "connectivity probe failed; using cached ADJ without switching branches"); - get_hash_and_message(&repo) - } else { - Err(io::Error::new( - io::ErrorKind::NotFound, - "ADJ is not available locally and cannot be downloaded", - ) - .into()) - } +/// A failed connectivity probe is not itself an error when cached ADJ exists. +/// If no cache exists, the operation returns [`GitError::UnavailableOffline`]. +#[derive(Debug, thiserror::Error)] +pub enum GitError { + /// Resolving, inspecting, or preparing the cache directory failed. + #[error("ADJ path operation failed: {0}")] + Path(#[source] std::io::Error), + + /// Opening the repository or reading its references or HEAD failed. + /// An absent reference is not itself an error. + #[error("ADJ repository operation failed: {0}")] + Repository(#[source] Box), + + /// Preparing, downloading, or checking out the requested branch failed. + /// + /// This can indicate a network, configuration, or remote-reference failure; + /// it does not necessarily mean that internet connectivity is unavailable. + #[error("ADJ clone failed: {0}")] + Clone(#[source] Box), + + /// Moving the old cache aside or installing the new checkout failed. + /// + /// When restoration also fails, `rollback` holds its error and the preserved + /// backup's location. Otherwise, the old cache was restored or never moved. + #[error( + "ADJ cache replacement failed: {source}{recovery}", + recovery = .rollback.as_ref().map(|(error, path)| { + format!("; rollback failed: {error}; backup kept at {}", path.display()) + }).unwrap_or_default() + )] + Replacement { + /// The original error moving the old cache or installing the new checkout. + #[source] + source: std::io::Error, + /// Restoration error and preserved backup path, if rollback failed. + rollback: Option<(std::io::Error, std::path::PathBuf)>, + }, + + /// The connectivity probe failed and no local ADJ cache was available. + #[error("ADJ is not available locally and cannot be downloaded")] + UnavailableOffline, } -/// Lists locally cached remote-tracking branches without contacting the remote. -/// -/// `path` identifies the repository directory. Names retain the remote prefix, -/// such as `origin/main`; the results can be stale, are not explicitly sorted, -/// and may include symbolic references such as `origin/HEAD`. -/// -/// # Errors -/// -/// Returns an error if the repository cannot be opened or its references cannot -/// be read. -#[instrument(level = "debug", err(level = "warn"))] -pub fn list_remote_branches(path: PathBuf) -> Result, BoxError> { - let repo = gix::open(&path)?; - - let mut branches = Vec::new(); - - // Inspect local remote-tracking refs, not the remote server's advertised refs. - for reference in repo.references()?.remote_branches()? { - let reference = reference?; - branches.push(reference.name().shorten().to_string()); +// Convert repository errors for '?' propagation, boxing the concrete error to keep GitError small. +impl From for GitError { + fn from(error: RepositoryError) -> Self { + Self::Repository(Box::new(error)) } - - debug!( - ?path, - count = branches.len(), - "listed cached remote-tracking branches" - ); - Ok(branches) } -/// Opens an existing repository without fetching or changing its checkout. -/// -/// `path` is the repository directory. If omitted, it defaults to -/// `/hyperloop-control-station/adj`. This does not create ADJ. -/// -/// # Errors -/// -/// Returns an error if the cache directory cannot be resolved or the repository -/// is missing, invalid, or inaccessible. -#[instrument(level = "debug", err(level = "warn"))] -pub fn open_repo(path: Option) -> Result { - let path = unwrap_repo_path(path)?; - - let repo = gix::open(path)?; - - debug!(git_dir = ?repo.path(), "opened repository"); - Ok(repo) -} - -// Checks external TCP connectivity with a three-second timeout, not GitHub availability. -#[instrument(level = "debug")] -fn check_internet_connection() -> bool { - // Use a fixed IPv4 address to avoid a separate DNS lookup and its timeout. - let address = SocketAddr::from((Ipv4Addr::new(1, 1, 1, 1), 443)); - let timeout = Duration::from_secs(3); - - // Attempt only the TCP handshake; no application data is sent. - match TcpStream::connect_timeout(&address, timeout) { - Ok(_stream) => { - debug!(%address, "connectivity probe succeeded"); - true - } - Err(error) => { - // Record why the probe failed without treating it as an application error. - debug!(%address, %error, "connectivity probe failed"); - false - } - } -} - -// Preserve explicit paths; otherwise use the platform's user cache directory. -fn unwrap_repo_path(path: Option) -> Result { - let dir = match path { - Some(path) => path, - None => { - let path = dirs::cache_dir().ok_or_else(|| { - io::Error::new(io::ErrorKind::NotFound, "cache directory not found") - })?; - - path.join("hyperloop-control-station").join("adj") - } - }; - - debug!(path = ?dir, "resolved ADJ repository path"); - Ok(dir) -} - -// Only an absent directory is a cache miss; invalid repositories remain errors. -fn adj_exists_repo(path: Option) -> Result<(Option, PathBuf), BoxError> { - let dir = unwrap_repo_path(path)?; - - let res = if dir.try_exists()? { - Some(gix::open(&dir)?) - } else { - None - }; - - debug!(path = ?dir, exists = res.is_some(), "checked local ADJ repository"); - Ok((res, dir)) -} - -// Stage beside ADJ so both installation and rollback use same-filesystem renames. -#[instrument(level = "debug", skip(url))] -fn git_replace(path: &Path, branch: &str, url: &str) -> Result<(String, String), BoxError> { - // A relative path like "adj" has an empty parent; stage in the current directory. - let parent = path - .parent() - .filter(|p| !p.as_os_str().is_empty()) - .unwrap_or(Path::new(".")); - fs::create_dir_all(parent)?; - let staging = tempfile::Builder::new() - .prefix(".adj-") - .tempdir_in(parent)?; - let checkout = staging.path().join("new"); - let backup = staging.path().join("old"); - debug!(?checkout, ?backup, "created ADJ staging directory"); - - // Validate the new checkout and commit before touching the current cache. - // Early errors drop the staging directory, removing any incomplete clone. - let repo = git_clone(&checkout, branch, url)?; - let commit = get_hash_and_message(&repo)?; - // The repository contains paths into staging and must not survive the move. - drop(repo); - - let had_cache = path.try_exists()?; - if had_cache { - fs::rename(path, &backup)?; - debug!(?path, ?backup, "moved cached ADJ aside for replacement"); - } - if let Err(error) = fs::rename(&checkout, path) { - debug!(?path, %error, had_cache, "ADJ installation failed; restoring cache if present"); - if had_cache && let Err(rollback) = fs::rename(&backup, path) { - // Do not let temporary-directory cleanup delete the only remaining cache. - let saved = staging.keep(); - debug!(?backup, %rollback, "preserved ADJ backup after failed rollback"); - return Err(io::Error::other(format!( - "ADJ installation failed: {error}; rollback failed: {rollback}; backup kept at {}", - saved.join("old").display() - )) - .into()); - } - if had_cache { - debug!(?path, "restored cached ADJ after installation failure"); - } - return Err(error.into()); - } - - // Installation succeeded; cleanup now discards the old cache. A cleanup - // failure does not turn a successfully installed checkout into an error. - if let Err(error) = staging.close() { - warn!(?path, %error, "ADJ updated, but temporary directory cleanup failed"); - } - info!(?path, branch, commit = %commit.0, "ADJ updated"); - Ok(commit) -} - -/// Checks whether a remote-tracking branch is cached in `repo`. -/// -/// `remote` is the remote name, such as `origin`; `name` is the branch name, such -/// as `main` or `feature/example`. Looks up `refs/remotes//` without -/// contacting the server or checking local branches. `false` means the reference -/// is absent locally, not necessarily that the branch is absent on the server. -/// -/// # Errors -/// -/// Returns an error if the reference name is invalid or the reference cannot be -/// read. -#[instrument(level = "debug", skip(repo), err(level = "warn"))] -pub fn branch_exists(repo: &gix::Repository, remote: &str, name: &str) -> Result { - let full = format!("refs/remotes/{remote}/{name}"); - let exists = repo.try_find_reference(full.as_str())?.is_some(); - debug!(reference = %full, exists, "checked cached remote-tracking branch"); - Ok(exists) -} - -// Fetch and check out the requested branch instead of switching an existing repo. -#[instrument(level = "debug", skip(url))] -fn git_clone(path: &Path, branch: &str, url: &str) -> Result { - // These synchronous startup operations do not currently expose cancellation. - let interrupt = AtomicBool::new(false); - - debug!(?path, branch, "preparing shallow ADJ clone"); - // A depth of one keeps the current snapshot without downloading full history. - let mut prepare = gix::prepare_clone(url, path)? - .with_remote_name(GIT_REMOTE)? - .with_ref_name(Some(branch))? - .with_shallow(gix::remote::fetch::Shallow::DepthAtRemote( - std::num::NonZeroU32::MIN, - )); - - let (mut checkout, _) = prepare.fetch_then_checkout(gix::progress::Discard, &interrupt)?; - debug!( - ?path, - branch, "ADJ fetch completed; checking out working tree" - ); - let (repo, _) = checkout.main_worktree(gix::progress::Discard, &interrupt)?; - - debug!(?path, branch, "ADJ clone and checkout completed"); - Ok(repo) -} - -// Report the checked-out HEAD, which can differ from the requested branch offline. -fn get_hash_and_message(repo: &Repository) -> Result<(String, String), BoxError> { - let hash = repo.head_id()?.to_string(); - let message = repo.head_commit()?.decode()?.message.to_string(); - - // Log only the commit ID, not potentially large or sensitive message text. - debug!(commit = %hash, "read checked-out ADJ commit"); - Ok((hash, message)) -} - -#[cfg(test)] -mod tests { - use super::*; - use std::process::Command; - - fn git(path: &Path, args: &[&str]) -> Result<(), BoxError> { - // Fixture commits need identity; disable signing, hooks, and templates - // so tests do not depend on the user's normal Git setup. - let output = Command::new("git") - .current_dir(path) - .args([ - "-c", - "user.name=ADJ tests", - "-c", - "user.email=adj@example.test", - "-c", - "commit.gpgSign=false", - "-c", - "core.hooksPath=", - "-c", - "init.templateDir=", - ]) - .args(args) - .output()?; - if !output.status.success() { - return Err(io::Error::other(String::from_utf8_lossy(&output.stderr)).into()); - } - Ok(()) - } - - fn source_repo(path: &Path) -> Result<(), BoxError> { - fs::create_dir(path)?; - git(path, &["init", "--initial-branch=main"])?; - fs::write(path.join("data.txt"), "main")?; - git(path, &["add", "."])?; - git(path, &["commit", "-m", "main data"])?; - // Leave HEAD on another branch to verify explicit clone branch selection. - git(path, &["checkout", "-b", "testing"])?; - fs::write(path.join("data.txt"), "testing")?; - git(path, &["commit", "-am", "testing data"]) - } - - // Distinguish missing, invalid, and valid local repositories. - #[test] - fn detects_missing_and_invalid_repositories() -> Result<(), BoxError> { - let temp = tempfile::tempdir()?; - let path = temp.path().join("adj"); - assert!(adj_exists_repo(Some(path.clone()))?.0.is_none()); - fs::create_dir(&path)?; - assert!(adj_exists_repo(Some(path.clone())).is_err()); - git(&path, &["init"])?; - assert!(adj_exists_repo(Some(path))?.0.is_some()); - Ok(()) - } - - // Verify branch selection, newer commits, and removal of stale cache files. - #[test] - fn clones_and_replaces_with_requested_branch() -> Result<(), BoxError> { - let temp = tempfile::tempdir()?; - let source = temp.path().join("source"); - let cache = temp.path().join("cache").join("adj"); - source_repo(&source)?; - let url = source.to_str().ok_or("non-UTF-8 test path")?; - - let first = git_replace(&cache, "main", url)?; - assert_eq!(first.1, "main data\n"); - assert_eq!(fs::read_to_string(cache.join("data.txt"))?, "main"); - // Replacement must discard old cache files, not just update tracked ones. - fs::write(cache.join("stale.txt"), "discard this cache file")?; - - // Add a newer remote commit and request a different branch on replacement. - fs::write(source.join("data.txt"), "latest testing")?; - git(&source, &["commit", "-am", "updated testing data"])?; - let expected = get_hash_and_message(&gix::open(&source)?)?; - assert_eq!(git_replace(&cache, "testing", url)?, expected); - assert_ne!(first.0, expected.0); - assert_eq!(get_hash_and_message(&gix::open(&cache)?)?, expected); - assert_eq!( - fs::read_to_string(cache.join("data.txt"))?, - "latest testing" - ); - assert!(!cache.join("stale.txt").exists()); - // Successful replacement must also remove staging and backup directories. - assert_eq!( - fs::read_dir(cache.parent().ok_or("missing parent")?)?.count(), - 1 - ); - Ok(()) - } - - // Verify clone failures preserve cached ADJ and leave no staging debris. - #[test] - fn failed_clone_preserves_existing_cache() -> Result<(), BoxError> { - let temp = tempfile::tempdir()?; - let source = temp.path().join("source"); - let cache = temp.path().join("adj"); - source_repo(&source)?; - let url = source.to_str().ok_or("non-UTF-8 test path")?; - - // A failed first clone must not install a partial checkout. - assert!(git_replace(&cache, "missing-branch", url).is_err()); - assert!(!cache.exists()); - let expected = git_replace(&cache, "main", url)?; - fs::write(cache.join("stale.txt"), "keep on failure")?; - // Both an invalid branch and an unavailable source must leave ADJ intact. - assert!(git_replace(&cache, "missing-branch", url).is_err()); - let missing = temp.path().join("missing-source"); - assert!( - git_replace( - &cache, - "main", - missing.to_str().ok_or("non-UTF-8 test path")? - ) - .is_err() - ); - assert_eq!(get_hash_and_message(&gix::open(&cache)?)?, expected); - assert_eq!(fs::read_to_string(cache.join("data.txt"))?, "main"); - assert_eq!( - fs::read_to_string(cache.join("stale.txt"))?, - "keep on failure" - ); - assert_eq!(fs::read_dir(temp.path())?.count(), 2); - Ok(()) +// Convert clone errors for '?' propagation, boxing the concrete error to keep GitError small. +impl From for GitError { + fn from(error: CloneError) -> Self { + Self::Clone(Box::new(error)) } } diff --git a/backend/crates/core/src/git/clone.rs b/backend/crates/core/src/git/clone.rs new file mode 100644 index 000000000..006f127ab --- /dev/null +++ b/backend/crates/core/src/git/clone.rs @@ -0,0 +1,245 @@ +use super::{GitError, update::get_commit_hash}; +use gix::Repository; +use std::{fs, path::Path, sync::atomic::AtomicBool}; +use tracing::{debug, info, instrument, warn}; + +const GIT_REMOTE: &str = "origin"; + +/// Concrete clone failures wrapped by [`GitError::Clone`]. +/// +/// Preparation, name validation, fetching, and checkout expose different `gix` +/// error types. These variants retain each original error as their source. +#[derive(Debug, thiserror::Error)] +pub enum CloneError { + /// Clone preparation failed before downloading repository data. + #[error("clone preparation failed: {0}")] + Prepare(#[from] gix::clone::Error), + + /// The configured remote name was invalid. + #[error("remote name is invalid: {0}")] + RemoteName(#[from] gix::remote::name::Error), + + /// The requested branch name was not a valid Git reference name. + #[error("branch name is invalid: {0}")] + BranchName(#[from] gix::validate::reference::name::Error), + + /// Fetching failed, including a missing requested branch. + /// This can indicate network, configuration, or remote-reference failures. + #[error("fetch failed: {0}")] + Fetch(#[from] gix::clone::fetch::Error), + + /// Downloaded data could not be checked out into the working tree. + #[error("checkout failed: {0}")] + Checkout(#[from] gix::clone::checkout::main_worktree::Error), +} + +// Fetch and check out the requested branch instead of switching an existing repo. +#[instrument(level = "debug", skip(url))] +fn git_clone(path: &Path, branch: &str, url: &str) -> Result { + // These synchronous startup operations do not currently expose cancellation. + let interrupt = AtomicBool::new(false); + + debug!(?path, branch, "preparing shallow ADJ clone"); + // A depth of one keeps the current snapshot without downloading full history. + let mut prepare = gix::prepare_clone(url, path) + .map_err(CloneError::from)? + .with_remote_name(GIT_REMOTE) + .map_err(CloneError::from)? + .with_ref_name(Some(branch)) + .map_err(CloneError::from)? + .with_shallow(gix::remote::fetch::Shallow::DepthAtRemote( + std::num::NonZeroU32::MIN, + )); + + let (mut checkout, _) = prepare + .fetch_then_checkout(gix::progress::Discard, &interrupt) + .map_err(CloneError::from)?; + debug!( + ?path, + branch, "ADJ fetch completed; checking out working tree" + ); + let (repo, _) = checkout + .main_worktree(gix::progress::Discard, &interrupt) + .map_err(CloneError::from)?; + + debug!(?path, branch, "ADJ clone and checkout completed"); + Ok(repo) +} + +// Stage beside ADJ so both installation and rollback use same-filesystem renames. +#[instrument(level = "debug", skip(url))] +pub(crate) fn git_replace(path: &Path, branch: &str, url: &str) -> Result { + // A relative path like "adj" has an empty parent; stage in the current directory. + let parent = path + .parent() + .filter(|p| !p.as_os_str().is_empty()) + .unwrap_or(Path::new(".")); + fs::create_dir_all(parent).map_err(GitError::Path)?; + let staging = tempfile::Builder::new() + .prefix(".adj-") + .tempdir_in(parent) + .map_err(GitError::Path)?; + let checkout = staging.path().join("new"); + let backup = staging.path().join("old"); + debug!(?checkout, ?backup, "created ADJ staging directory"); + + // Validate the new checkout and commit before touching the current cache. + // Early errors drop the staging directory, removing any incomplete clone. + let repo = git_clone(&checkout, branch, url)?; + let commit = get_commit_hash(&repo)?; + // The repository contains paths into staging and must not survive the move. + drop(repo); + + let had_cache = path.try_exists().map_err(GitError::Path)?; + if had_cache { + fs::rename(path, &backup).map_err(|source| GitError::Replacement { + source, + rollback: None, + })?; + debug!(?path, ?backup, "moved cached ADJ aside for replacement"); + } + if let Err(error) = fs::rename(&checkout, path) { + debug!(?path, %error, had_cache, "ADJ installation failed; restoring cache if present"); + if had_cache && let Err(rollback) = fs::rename(&backup, path) { + // Do not let temporary-directory cleanup delete the only remaining cache. + let saved = staging.keep(); + debug!(?backup, %rollback, "preserved ADJ backup after failed rollback"); + return Err(GitError::Replacement { + source: error, + rollback: Some((rollback, saved.join("old"))), + }); + } + if had_cache { + debug!(?path, "restored cached ADJ after installation failure"); + } + return Err(GitError::Replacement { + source: error, + rollback: None, + }); + } + + // Installation succeeded; cleanup now discards the old cache. A cleanup + // failure does not turn a successfully installed checkout into an error. + if let Err(error) = staging.close() { + warn!(?path, %error, "ADJ updated, but temporary directory cleanup failed"); + } + info!(?path, branch, commit = %commit, "ADJ updated"); + Ok(commit) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::{io, process::Command}; + + fn git(path: &Path, args: &[&str]) -> Result<(), Box> { + // Fixture commits need identity; disable signing, hooks, and templates + // so tests do not depend on the user's normal Git setup. + let output = Command::new("git") + .current_dir(path) + .args([ + "-c", + "user.name=ADJ tests", + "-c", + "user.email=adj@example.test", + "-c", + "commit.gpgSign=false", + "-c", + "core.hooksPath=", + "-c", + "init.templateDir=", + ]) + .args(args) + .output()?; + if !output.status.success() { + return Err(io::Error::other(String::from_utf8_lossy(&output.stderr)).into()); + } + Ok(()) + } + + fn source_repo(path: &Path) -> Result<(), Box> { + fs::create_dir(path)?; + git(path, &["init", "--initial-branch=main"])?; + fs::write(path.join("data.txt"), "main")?; + git(path, &["add", "."])?; + git(path, &["commit", "-m", "main data"])?; + // Leave HEAD on another branch to verify explicit clone branch selection. + git(path, &["checkout", "-b", "testing"])?; + fs::write(path.join("data.txt"), "testing")?; + git(path, &["commit", "-am", "testing data"]) + } + + // Verify branch selection, newer commits, and removal of stale cache files. + #[test] + fn clones_and_replaces_with_requested_branch() -> Result<(), Box> { + let temp = tempfile::tempdir()?; + let source = temp.path().join("source"); + let cache = temp.path().join("cache").join("adj"); + source_repo(&source)?; + let url = source.to_str().ok_or("non-UTF-8 test path")?; + + let first = git_replace(&cache, "main", url)?; + let main_hash = gix::open(&source)? + .find_reference("refs/heads/main")? + .id() + .to_string(); + assert_eq!(first, main_hash); + assert_eq!(fs::read_to_string(cache.join("data.txt"))?, "main"); + // Replacement must discard old cache files, not just update tracked ones. + fs::write(cache.join("stale.txt"), "discard this cache file")?; + + // Add a newer remote commit and request a different branch on replacement. + fs::write(source.join("data.txt"), "latest testing")?; + git(&source, &["commit", "-am", "updated testing data"])?; + let expected = get_commit_hash(&gix::open(&source)?)?; + assert_eq!(git_replace(&cache, "testing", url)?, expected); + assert_ne!(first, expected); + assert_eq!(get_commit_hash(&gix::open(&cache)?)?, expected); + assert_eq!( + fs::read_to_string(cache.join("data.txt"))?, + "latest testing" + ); + assert!(!cache.join("stale.txt").exists()); + // Successful replacement must also remove staging and backup directories. + assert_eq!( + fs::read_dir(cache.parent().ok_or("missing parent")?)?.count(), + 1 + ); + Ok(()) + } + + // Verify clone failures preserve cached ADJ and leave no staging debris. + #[test] + fn failed_clone_preserves_existing_cache() -> Result<(), Box> { + let temp = tempfile::tempdir()?; + let source = temp.path().join("source"); + let cache = temp.path().join("adj"); + source_repo(&source)?; + let url = source.to_str().ok_or("non-UTF-8 test path")?; + + // A failed first clone must not install a partial checkout. + assert!(git_replace(&cache, "missing-branch", url).is_err()); + assert!(!cache.exists()); + let expected = git_replace(&cache, "main", url)?; + fs::write(cache.join("stale.txt"), "keep on failure")?; + // Both an invalid branch and an unavailable source must leave ADJ intact. + assert!(git_replace(&cache, "missing-branch", url).is_err()); + let missing = temp.path().join("missing-source"); + assert!( + git_replace( + &cache, + "main", + missing.to_str().ok_or("non-UTF-8 test path")? + ) + .is_err() + ); + assert_eq!(get_commit_hash(&gix::open(&cache)?)?, expected); + assert_eq!(fs::read_to_string(cache.join("data.txt"))?, "main"); + assert_eq!( + fs::read_to_string(cache.join("stale.txt"))?, + "keep on failure" + ); + assert_eq!(fs::read_dir(temp.path())?.count(), 2); + Ok(()) + } +} diff --git a/backend/crates/core/src/git/repository.rs b/backend/crates/core/src/git/repository.rs new file mode 100644 index 000000000..b844c29e9 --- /dev/null +++ b/backend/crates/core/src/git/repository.rs @@ -0,0 +1,113 @@ +use super::{GitError, update::unwrap_repo_path}; +use gix::Repository; +use std::path::PathBuf; +use tracing::{debug, instrument}; + +/// Concrete repository failures wrapped by [`GitError::Repository`]. +/// +/// Variants identify the failed read operation and preserve the original `gix` +/// error as their source. Only [`RepositoryError::ReferenceItem`] has a dynamic +/// source because the reference iterator returns boxed errors. +#[derive(Debug, thiserror::Error)] +pub enum RepositoryError { + /// An existing repository could not be opened or validated. + #[error("repository could not be opened: {0}")] + Open(#[from] gix::open::Error), + + /// HEAD could not be resolved to a commit ID, including an unborn HEAD. + #[error("HEAD could not be resolved: {0}")] + Head(#[from] gix::reference::head_id::Error), + + /// The repository's reference storage could not be opened. + #[error("reference storage could not be opened: {0}")] + References(#[from] gix::reference::iter::Error), + + /// Iteration over cached remote-tracking references could not be initialized. + #[error("reference iteration could not be initialized: {0}")] + InitReferences(#[from] gix::reference::iter::init::Error), + + /// An individual reference could not be read during iteration. + /// The boxed source retains its original type and error chain. + #[error("reference could not be read: {0}")] + ReferenceItem(#[from] Box), + + /// Looking up a reference failed; an absent reference is not an error. + #[error("reference lookup failed: {0}")] + FindReference(#[from] gix::reference::find::Error), +} + +/// Opens an existing repository without fetching or changing its checkout. +/// +/// `path` is the repository directory. If omitted, it defaults to +/// `/hyperloop-control-station/adj`. This does not create ADJ. +/// +/// # Errors +/// +/// Returns [`GitError::Path`] if the cache directory cannot be resolved, or +/// [`GitError::Repository`] if the repository is missing, invalid, or inaccessible. +#[instrument(level = "debug", err(level = "warn"))] +pub fn open_repo(path: Option) -> Result { + let path = unwrap_repo_path(path)?; + + let repo = gix::open(path).map_err(RepositoryError::from)?; + + debug!(git_dir = ?repo.path(), "opened repository"); + Ok(repo) +} + +/// Lists locally cached remote-tracking branches without contacting the remote. +/// +/// `path` identifies the repository directory. Names retain the remote prefix, +/// such as `origin/main`; the results can be stale, are not explicitly sorted, +/// and may include symbolic references such as `origin/HEAD`. +/// +/// # Errors +/// +/// Returns [`GitError::Repository`] if the repository cannot be opened or its +/// references cannot be read. +#[instrument(level = "debug", err(level = "warn"))] +pub fn list_remote_branches(path: PathBuf) -> Result, GitError> { + let repo = gix::open(&path).map_err(RepositoryError::from)?; + + let mut branches = Vec::new(); + + // Inspect local remote-tracking refs, not the remote server's advertised refs. + for reference in repo + .references() + .map_err(RepositoryError::from)? + .remote_branches() + .map_err(RepositoryError::from)? + { + let reference = reference.map_err(RepositoryError::from)?; + branches.push(reference.name().shorten().to_string()); + } + + debug!( + ?path, + count = branches.len(), + "listed cached remote-tracking branches" + ); + Ok(branches) +} + +/// Checks whether a remote-tracking branch is cached in `repo`. +/// +/// `remote` is the remote name, such as `origin`; `name` is the branch name, such +/// as `main` or `feature/example`. Looks up `refs/remotes//` without +/// contacting the server or checking local branches. `false` means the reference +/// is absent locally, not necessarily that the branch is absent on the server. +/// +/// # Errors +/// +/// Returns [`GitError::Repository`] if the reference name is invalid or the +/// reference cannot be read. A missing reference returns `Ok(false)`. +#[instrument(level = "debug", skip(repo), err(level = "warn"))] +pub fn branch_exists(repo: &gix::Repository, remote: &str, name: &str) -> Result { + let full = format!("refs/remotes/{remote}/{name}"); + let exists = repo + .try_find_reference(full.as_str()) + .map_err(RepositoryError::from)? + .is_some(); + debug!(reference = %full, exists, "checked cached remote-tracking branch"); + Ok(exists) +} diff --git a/backend/crates/core/src/git/update.rs b/backend/crates/core/src/git/update.rs new file mode 100644 index 000000000..8fa1fd1fb --- /dev/null +++ b/backend/crates/core/src/git/update.rs @@ -0,0 +1,135 @@ +use super::{GitError, RepositoryError, clone::git_replace}; +use gix::Repository; +use std::{ + io, + net::{Ipv4Addr, SocketAddr, TcpStream}, + path::PathBuf, + time::Duration, +}; +use tracing::{debug, info, instrument, warn}; + +const ADJ_URL: &str = "https://github.com/Hyperloop-UPV/adj.git"; + +/// Downloads the requested ADJ branch, replacing the application-managed cache. +/// +/// `path` is the repository directory, not its parent. If omitted, it defaults to +/// `/hyperloop-control-station/adj`. `branch` selects the branch +/// to clone when the connectivity probe succeeds. +/// +/// Online, local edits and commits are discarded only after a fresh checkout +/// succeeds. Offline, the current cached checkout is used without switching +/// branches, so it may differ from `branch`. Returns its full commit hash. +/// +/// This performs blocking network and filesystem operations. Call during startup, +/// before readers use ADJ, with only one updater at a time. Replacement uses two +/// renames and is not atomic across a process crash. +/// +/// # Errors +/// +/// Returns [`GitError::UnavailableOffline`] if ADJ is missing offline. Other +/// variants identify path, repository, cloning, checkout, or replacement failures. +/// Clone errors do not automatically fall back to the cache. If restoration fails, +/// [`GitError::Replacement`] preserves both errors and the backup's location. +// Log returned errors at the public boundary; helpers trace progress without duplicate warnings. +#[instrument(level = "debug", err(level = "warn"))] +pub fn update_adj(path: Option, branch: &str) -> Result { + let (repo, dir) = adj_exists_repo(path)?; + + if check_internet_connection() { + info!(path = ?dir, branch, "starting ADJ update"); + // Release repository handles before moving the existing cache directory. + drop(repo); + git_replace(&dir, branch, ADJ_URL) + } else if let Some(repo) = repo { + warn!(path = ?dir, requested_branch = branch, + "connectivity probe failed; using cached ADJ without switching branches"); + get_commit_hash(&repo) + } else { + Err(GitError::UnavailableOffline) + } +} + +// Checks external TCP connectivity with a three-second timeout, not GitHub availability. +#[instrument(level = "info")] +fn check_internet_connection() -> bool { + // Use a fixed IPv4 address to avoid a separate DNS lookup and its timeout. + let address = SocketAddr::from((Ipv4Addr::new(1, 1, 1, 1), 443)); + let timeout = Duration::from_secs(3); + + // Attempt only the TCP handshake; no application data is sent. + match TcpStream::connect_timeout(&address, timeout) { + Ok(_stream) => { + info!(%address, "connectivity probe succeeded"); + true + } + Err(error) => { + // Record why the probe failed without treating it as an application error. + info!(%address, %error, "connectivity probe failed"); + false + } + } +} + +// Preserve explicit paths; otherwise use the platform's user cache directory. +pub(crate) fn unwrap_repo_path(path: Option) -> Result { + let dir = match path { + Some(path) => path, + None => { + let path = dirs::cache_dir().ok_or_else(|| { + GitError::Path(io::Error::new( + io::ErrorKind::NotFound, + "cache directory not found", + )) + })?; + + path.join("hyperloop-control-station").join("adj") + } + }; + + debug!(path = ?dir, "resolved ADJ repository path"); + Ok(dir) +} + +// Only an absent directory is a cache miss; invalid repositories remain errors. +pub(crate) fn adj_exists_repo( + path: Option, +) -> Result<(Option, PathBuf), GitError> { + let dir = unwrap_repo_path(path)?; + + let res = if dir.try_exists().map_err(GitError::Path)? { + Some(gix::open(&dir).map_err(RepositoryError::from)?) + } else { + None + }; + + debug!(path = ?dir, exists = res.is_some(), "checked local ADJ repository"); + Ok((res, dir)) +} + +// Report the checked-out HEAD, which can differ from the requested branch offline. +pub(crate) fn get_commit_hash(repo: &Repository) -> Result { + let hash = repo.head_id().map_err(RepositoryError::from)?.to_string(); + + // Log only the commit ID, not potentially large or sensitive message text. + debug!(commit = %hash, "read checked-out ADJ commit"); + Ok(hash) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::fs; + + // Distinguish missing, invalid, and valid local repositories. + #[test] + fn detects_missing_and_invalid_repositories() -> Result<(), Box> { + let temp = tempfile::tempdir()?; + let path = temp.path().join("adj"); + assert!(adj_exists_repo(Some(path.clone()))?.0.is_none()); + fs::create_dir(&path)?; + assert!(adj_exists_repo(Some(path.clone())).is_err()); + gix::init(&path)?; + assert!(adj_exists_repo(Some(path))?.0.is_some()); + Ok(()) + } +} From f8f04b02849e91b818380b0e6aebfad48827e624 Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Mon, 12 Oct 2026 17:11:06 +0200 Subject: [PATCH 067/225] docs(backend, git): update README --- backend/crates/core/src/git/README.md | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/backend/crates/core/src/git/README.md b/backend/crates/core/src/git/README.md index 950249435..f2e3615ed 100644 --- a/backend/crates/core/src/git/README.md +++ b/backend/crates/core/src/git/README.md @@ -6,7 +6,7 @@ when updating online. ## Workflow -`update_adj(path, branch)` returns the checked-out commit hash and full message. +`update_adj(path, branch)` returns the full hash of the checked-out commit. A custom path identifies the ADJ repository itself. The default is `/hyperloop-control-station/adj`, using `dirs::cache_dir()`. An existing invalid repository or inaccessible path returns an error. @@ -18,7 +18,7 @@ availability. ### Online - Shallow-clone the requested branch into a temporary directory beside ADJ. -- Complete checkout and read its commit information before touching the cache. +- Complete checkout and read its commit hash before touching the cache. - Move the old cache aside and install the new checkout. - Restore the old cache if installation fails. If restoration also fails, preserve the backup and include its location in the error. @@ -30,7 +30,7 @@ switch is needed because the checkout is replaced. ### Offline -- If ADJ exists, return its current commit without updating or switching branches. +- If ADJ exists, return its current commit hash without updating or switching branches. - Otherwise, return `ADJ is not available locally and cannot be downloaded`. The cached branch may differ from the requested branch when offline. @@ -49,6 +49,15 @@ updater at a time. The backup and installation renames are not jointly atomic across a process crash. The connectivity probe can succeed when GitHub is unreachable, or fail when GitHub is reachable. +## Errors + +Public helpers return `GitError` with five categories: `Path`, `Repository`, +`Clone`, `Replacement`, and `UnavailableOffline`. `RepositoryError` and +`CloneError` group the concrete `gix` causes inside the corresponding categories. +Only individual reference-iteration errors retain a dynamic source, as exposed +by `gix`. If rollback fails, `Replacement` also retains the restoration error +and backup path for recovery. + ## Verification Tests use temporary local Git repositories and the Git CLI to create fixtures; From a33f6505876c2c3d522a9c509b6635156622845a Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Mon, 12 Oct 2026 17:11:30 +0200 Subject: [PATCH 068/225] update(backend, git): update cargo packages --- backend/Cargo.lock | 62 +++++++++++++++++++++++----------------------- 1 file changed, 31 insertions(+), 31 deletions(-) diff --git a/backend/Cargo.lock b/backend/Cargo.lock index 5a9a19ea9..3d6daa45d 100644 --- a/backend/Cargo.lock +++ b/backend/Cargo.lock @@ -46,9 +46,9 @@ checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" [[package]] name = "aws-lc-rs" -version = "1.18.1" +version = "1.18.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b281d307588d634de920874890732659e2e7672f72b5e10e81badc1a8a83621e" +checksum = "faac5829c2b74c28f830747e7818ccfb684261b5f48a1118b1e2a13d36dfab13" dependencies = [ "aws-lc-sys", "zeroize", @@ -56,9 +56,9 @@ dependencies = [ [[package]] name = "aws-lc-sys" -version = "0.45.0" +version = "0.46.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9bff6c3b54fad79a2e60b8102caf565819711497c1f5f092f49508e2f5c31b27" +checksum = "f1622d8446a2d4b2ce0c7eefc73dd43a99779028d5ee5c2dd8073a658ba8a2bc" dependencies = [ "cc", "cmake", @@ -137,9 +137,9 @@ checksum = "7354288c522e7e980fafd2075d63d1285794c3a6a16cdd492f189ea406e5f18b" [[package]] name = "cc" -version = "1.6.0" +version = "1.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f74872d07caf508b30a21f6836e7d7016a2eaf7d9ff4f48deaa58cd8a0407630" +checksum = "6651c9ed80effdc7db0ff72512157f901af5e3549e341e24b1dd4887d836d838" dependencies = [ "find-msvc-tools", "jobserver", @@ -390,7 +390,7 @@ checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" dependencies = [ "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.9", ] [[package]] @@ -2624,14 +2624,14 @@ checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" dependencies = [ "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.9", ] [[package]] name = "serde_json" -version = "1.0.151" +version = "1.0.154" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" dependencies = [ "itoa", "memchr", @@ -2642,9 +2642,9 @@ dependencies = [ [[package]] name = "serde_spanned" -version = "1.1.1" +version = "1.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6662b5879511e06e8999a8a235d848113e942c9124f211511b16466ee2995f26" +checksum = "4e7523beb55eece201a2356bee0bbca0d1ab466c14c07703b2e0ee6d42cb0c2c" dependencies = [ "serde_core", ] @@ -2729,9 +2729,9 @@ checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" [[package]] name = "smallvec" -version = "1.16.2" +version = "1.16.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f9395f0f0eee849a9b707b2f06bb92a6a422090e2123bb2ef8e87a0e61892a8e" +checksum = "5b3dc8af474f516a851ff4bd12db780f948b9250ad37211e4eec0bccea54e01b" [[package]] name = "socket2" @@ -2805,9 +2805,9 @@ dependencies = [ [[package]] name = "syn" -version = "3.0.6" +version = "3.0.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8593e8e72159ed2257d083c7a454a85cbf854f37a0966d8d483aff8c8a3ebcee" +checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" dependencies = [ "proc-macro2", "quote", @@ -2831,7 +2831,7 @@ checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" dependencies = [ "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.9", ] [[package]] @@ -2864,7 +2864,7 @@ checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" dependencies = [ "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.9", ] [[package]] @@ -2946,7 +2946,7 @@ checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" dependencies = [ "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.9", ] [[package]] @@ -2961,9 +2961,9 @@ dependencies = [ [[package]] name = "tokio-util" -version = "0.7.19" +version = "0.7.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "494815d09bf52b5548659851081238f0ca39ff638363907596da739561c62c52" +checksum = "e464cf451ba96ebfc6f9b6542f17ee8b8956e33f1e40d9690624e59d7a7f8a4b" dependencies = [ "bytes", "futures-core", @@ -2999,18 +2999,18 @@ dependencies = [ [[package]] name = "toml_parser" -version = "1.1.3+spec-1.1.0" +version = "1.1.5+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d38ac1cf9b95face32296c0a3ede1fdc270627c9d9c02a7274dd6d960dc4d56" +checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c" dependencies = [ "winnow 1.0.4", ] [[package]] name = "toml_writer" -version = "1.1.2+spec-1.1.0" +version = "1.1.3+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7d56353a2a665ad0f41a421187180aab746c8c325620617ad883a99a1cbe66d2" +checksum = "06bdbd8cfc056b8d2e2e85f29b56a3bdbecb527cef81eb39e3e7b98af4652770" [[package]] name = "tower" @@ -3174,9 +3174,9 @@ checksum = "7eec5d1121208364f6793f7d2e222bf75a915c19557537745b195b253dd64217" [[package]] name = "unicode-ident" -version = "1.0.26" +version = "1.0.27" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" [[package]] name = "unicode-normalization" @@ -3291,7 +3291,7 @@ dependencies = [ "bumpalo", "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.9", "wasm-bindgen-shared", ] @@ -3489,7 +3489,7 @@ checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" dependencies = [ "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.9", "synstructure", ] @@ -3510,7 +3510,7 @@ checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" dependencies = [ "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.9", "synstructure", ] @@ -3550,7 +3550,7 @@ checksum = "34df6fc39dbd26ddc9c10e6a2984476e13acce22e64e4487636ef494369225da" dependencies = [ "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.9", ] [[package]] From 60dfd9c8ade7b5e3220d6fd57be3e2dfbbe85ac7 Mon Sep 17 00:00:00 2001 From: Gazi Al Saad Halawani Date: Mon, 12 Oct 2026 16:14:16 +0200 Subject: [PATCH 069/225] Feat(backend, protocol): Refactored to merge data.rs and order.rs to data_order.rs --- backend/crates/core/src/model.rs | 2 +- backend/crates/core/src/model/packet.rs | 21 +++---- backend/crates/core/src/protocol/packet.rs | 3 +- .../packet/{data.rs => data_order.rs} | 56 +++++++++++++++++-- .../crates/core/src/protocol/packet/order.rs | 48 ---------------- 5 files changed, 60 insertions(+), 70 deletions(-) rename backend/crates/core/src/protocol/packet/{data.rs => data_order.rs} (51%) delete mode 100644 backend/crates/core/src/protocol/packet/order.rs diff --git a/backend/crates/core/src/model.rs b/backend/crates/core/src/model.rs index 6cfdda92d..ccef505c5 100644 --- a/backend/crates/core/src/model.rs +++ b/backend/crates/core/src/model.rs @@ -21,7 +21,7 @@ pub use board::{Board, PacketDef, PacketKind, PodData}; pub use id::{AdjId, BoardId, MacAddress, Port}; pub use measurement::{Measurement, MeasurementKind, NumericKind, Range}; pub use packet::{ - DataPacket, MessageLevel, MessagePacket, OrderPacket, Packet, ProtectionPacket, ShortTimestamp, + DataPacket, MessageLevel, MessagePacket, OrderPacket, Packet, ProtectionPacket, ShortTimestamp, DataOrderPacket }; pub use protections::{Protection, ProtectionKind, Severity}; pub use value::Value; diff --git a/backend/crates/core/src/model/packet.rs b/backend/crates/core/src/model/packet.rs index 7cba9ae47..4c249fb53 100644 --- a/backend/crates/core/src/model/packet.rs +++ b/backend/crates/core/src/model/packet.rs @@ -32,7 +32,7 @@ pub struct ShortTimestamp { pub subsecond: u8, } -/// A data packet: the decoded values of the measurements a board just +/// A Data/Order packet: the decoded values of the measurements a board just /// sent. /// /// The wire protocol is positional: values are not individually tagged @@ -41,25 +41,18 @@ pub struct ShortTimestamp { /// [`super::PacketKind::Data`] list. `values[i]` is the decoded value of /// that list's `i`-th measurement — matching them up by position is /// `protocol`'s job, this type just holds the result in that same order. + #[derive(Debug, Clone, PartialEq)] -pub struct DataPacket { - /// Which packet definition this is an instance of. +pub struct DataOrderPacket{ pub id: AdjId, - /// The decoded value of each measurement in the packet, positional — - /// see the struct-level docs above. - pub values: Vec, + pub values: Vec, } /// An order sent from the backend to a board. /// /// Positional, the same way [`DataPacket::values`] is: see its docs. -#[derive(Debug, Clone, PartialEq)] -pub struct OrderPacket { - /// Which order definition this is an instance of. - pub id: AdjId, - /// The value to set for each field of the order, positional. - pub fields: Vec, -} +pub type OrderPacket = DataOrderPacket; +pub type DataPacket = DataOrderPacket; /// A protection packet: sent by a board when one of its declared /// [`super::Protection`]s triggers. @@ -218,7 +211,7 @@ mod tests { }); let order = Packet::Order(OrderPacket { id: AdjId(2000), - fields: vec![], + values: vec![], }); assert_ne!(data, order); diff --git a/backend/crates/core/src/protocol/packet.rs b/backend/crates/core/src/protocol/packet.rs index b1c19e246..7f357df8f 100644 --- a/backend/crates/core/src/protocol/packet.rs +++ b/backend/crates/core/src/protocol/packet.rs @@ -5,7 +5,6 @@ //! only ever received (over UDP), an `Order` only ever sent (over TCP), //! so there's no `encode` for the former or `decode` for the latter. -pub mod data; pub mod message; -pub mod order; pub mod protection; +pub mod data_order; diff --git a/backend/crates/core/src/protocol/packet/data.rs b/backend/crates/core/src/protocol/packet/data_order.rs similarity index 51% rename from backend/crates/core/src/protocol/packet/data.rs rename to backend/crates/core/src/protocol/packet/data_order.rs index a649a9db8..e9cc5e210 100644 --- a/backend/crates/core/src/protocol/packet/data.rs +++ b/backend/crates/core/src/protocol/packet/data_order.rs @@ -1,12 +1,58 @@ +use crate::model::{AdjId, DataPacket, PacketKind, Value, DataOrderPacket}; +use crate::protocol::{wire, EncodeError, Index, DecodeError}; + + +//! Encodes an `Order` packet: a command sent to a board. Only ever sent, +//! over TCP — the backend never receives one back. + +/// Encodes `order` into the bytes to write to a board's connection, +/// resolving its field shapes against `index`. +pub fn encode(order: &DataOrderPacket, index: &Index) -> Result, EncodeError> { + + //Unwrap PacketDef for kind + let packet_def = index + .packet(order.id) + .ok_or(EncodeError::UnknownId(order.id))?;// Question mark for error propagation and prevent crash + + //Check if packetdef is PacketKind::Order(measurement). Also returns the list of measurements + let measurements = match &packet_def.kind{ + PacketKind::Order(measurements) => measurements, + _ => return Err(EncodeError::WrongKind {id:order.id}) + }; + + //Check if length of list of fields matches number of measurements. + if order.values.len() != measurements.len(){ + return Err(EncodeError::WrongFieldCount {expected:measurements.len(),got:order.values.len()}) + } + + let mut bytes = Vec::new(); + + bytes.extend_from_slice(&order.id.0.to_le_bytes());//Header prefix of byte stream to 16 bit little-endian + + //Encoding to bytes + for (field,measurement) in order.values.iter().zip(measurements){ //For each measurement + let field_bytes = wire::encode_value(field,&measurement.kind)?;// Encode field Value into bytes according to MeasurementKind + bytes.extend(field_bytes);// Adds to byte stream + } + + Ok(bytes) // Return bytes +} + + +// +// "look up order.id in `index` to get its PacketDef (UnknownId if \ +// absent); match its `kind` for PacketKind::Order(measurements) \ +// (WrongKind if it's some other kind); error with WrongFieldCount \ +// if order.fields.len() doesn't match measurements.len(); encode \ +// the id then each field positionally via wire::encode_value" +// + //! Decodes a `Data` packet: a board's periodic telemetry. Only ever //! received, over UDP — a board never receives one back. -use crate::model::{AdjId, DataPacket, PacketKind}; -use crate::protocol::{DecodeError, Index, wire}; - /// Decodes a complete, already-delimited buffer into a [`DataPacket`], /// resolving its field shapes against `index`. -pub fn decode(bytes: &[u8], index: &Index) -> Result { +pub fn decode(bytes: &[u8], index: &Index) -> Result, DecodeError> { if bytes.len() < 2 { // If less than 2 bytes return error return Err(DecodeError::UnexpectedEof); @@ -57,4 +103,4 @@ pub fn decode(bytes: &[u8], index: &Index) -> Result { // kind); decode each measurement's value positionally via \ // wire::decode_value, advancing through `bytes` using each \ // measurement's own wire width" -// +// \ No newline at end of file diff --git a/backend/crates/core/src/protocol/packet/order.rs b/backend/crates/core/src/protocol/packet/order.rs deleted file mode 100644 index 1f6c98109..000000000 --- a/backend/crates/core/src/protocol/packet/order.rs +++ /dev/null @@ -1,48 +0,0 @@ -//! Encodes an `Order` packet: a command sent to a board. Only ever sent, -//! over TCP — the backend never receives one back. - -use crate::model::{OrderPacket, PacketKind}; -use crate::protocol::{wire, EncodeError, Index}; - -/// Encodes `order` into the bytes to write to a board's connection, -/// resolving its field shapes against `index`. -pub fn encode(order: &OrderPacket, index: &Index) -> Result, EncodeError> { - - //Unwrap PacketDef for kind - let packet_def = index - .packet(order.id) - .ok_or(EncodeError::UnknownId(order.id))?;// Question mark for error propagation and prevent crash - - //Check if packetdef is PacketKind::Order(measurement). Also returns the list of measurements - let measurements = match &packet_def.kind{ - PacketKind::Order(measurements) => measurements, - _ => return Err(EncodeError::WrongKind {id:order.id}) - }; - - //Check if length of list of fields matches number of measurements. - if order.fields.len() != measurements.len(){ - return Err(EncodeError::WrongFieldCount {expected:measurements.len(),got:order.fields.len()}) - } - - let mut bytes = Vec::new(); - - bytes.extend_from_slice(&order.id.0.to_le_bytes());//Header prefix of byte stream to 16 bit little-endian - - //Encoding to bytes - for (field,measurement) in order.fields.iter().zip(measurements){ //For each measurement - let field_bytes = wire::encode_value(field,&measurement.kind)?;// Encode field Value into bytes according to MeasurementKind - bytes.extend(field_bytes);// Adds to byte stream - } - - Ok(bytes) // Return bytes -} - - - -// -// "look up order.id in `index` to get its PacketDef (UnknownId if \ -// absent); match its `kind` for PacketKind::Order(measurements) \ -// (WrongKind if it's some other kind); error with WrongFieldCount \ -// if order.fields.len() doesn't match measurements.len(); encode \ -// the id then each field positionally via wire::encode_value" -// \ No newline at end of file From e6587150b3aaaf00dbab67550f46b897ba38a3e4 Mon Sep 17 00:00:00 2001 From: Gazi Al Saad Halawani Date: Mon, 12 Oct 2026 16:20:31 +0200 Subject: [PATCH 070/225] Feat(backend, protocol): Created tests for data_order.rs. --- .../core/src/protocol/packet/data_order.rs | 204 +++++++++++++++++- 1 file changed, 203 insertions(+), 1 deletion(-) diff --git a/backend/crates/core/src/protocol/packet/data_order.rs b/backend/crates/core/src/protocol/packet/data_order.rs index e9cc5e210..eaa4cb84d 100644 --- a/backend/crates/core/src/protocol/packet/data_order.rs +++ b/backend/crates/core/src/protocol/packet/data_order.rs @@ -103,4 +103,206 @@ pub fn decode(bytes: &[u8], index: &Index) -> Result, Dec // kind); decode each measurement's value positionally via \ // wire::decode_value, advancing through `bytes` using each \ // measurement's own wire width" -// \ No newline at end of file +// + +#[cfg(test)] +mod tests { + use super::*; + use crate::model::{ + Board, BoardId, MacAddress, Measurement, MeasurementKind, NumericKind, PacketDef, + PacketKind, PodData, Value, + }; + use std::collections::HashMap; + use std::net::IpAddr; + + fn sample_measurement(id: u16, kind: MeasurementKind) -> Measurement { + Measurement { + id: AdjId(id), + alias: format!("field_{id}"), + name: format!("Field {id}"), + display_units: String::new(), + kind, + protections: vec![], + } + } + + fn sample_packet_def(id: AdjId, kind: PacketKind) -> PacketDef { + PacketDef { + id, + board: BoardId(1), + name: "TestPacket".into(), + kind, + } + } + + fn make_test_index(defs: Vec) -> Index { + let packets: HashMap = defs.into_iter().map(|p| (p.id, p)).collect(); + let board = Board { + id: BoardId(1), + name: "TestBoard".to_string(), + ip: IpAddr::from([127, 0, 0, 1]), + mac: MacAddress([0; 6]), + packets, + }; + let pod_data = PodData { + boards: HashMap::from([(board.id, board)]), + }; + Index::new(&pod_data) + } + + // --- ENCODE TESTS --- + + #[test] + fn encode_success_little_endian_and_positional_fields() { + let order_id = AdjId(1001); + let packet_def = sample_packet_def( + order_id, + PacketKind::Order(vec![ + sample_measurement(1, MeasurementKind::Numeric { wire_type: NumericKind::U16 }), + sample_measurement(2, MeasurementKind::Boolean), + ]), + ); + + let index = make_test_index(vec![packet_def]); + + let packet = DataOrderPacket { + id: order_id, + values: vec![Value::Number(300.0), Value::Bool(true)], + }; + + let encoded = encode(&packet, &index).expect("encoding should succeed"); + + // 1001 in little-endian u16: [0xE9, 0x03] + // 300 in little-endian u16: [0x2C, 0x01] + // true: [0x01] + assert_eq!(encoded, vec![0xE9, 0x03, 0x2C, 0x01, 0x01]); + } + + #[test] + fn encode_fails_on_unknown_id() { + let index = make_test_index(vec![]); + let packet = DataOrderPacket { + id: AdjId(9999), + values: vec![], + }; + + let err = encode(&packet, &index).unwrap_err(); + assert_eq!(err, EncodeError::UnknownId(AdjId(9999))); + } + + #[test] + fn encode_fails_on_wrong_kind() { + let data_id = AdjId(2001); + let packet_def = sample_packet_def(data_id, PacketKind::Data(vec![])); + + let index = make_test_index(vec![packet_def]); + let packet = DataOrderPacket { + id: data_id, + values: vec![], + }; + + let err = encode(&packet, &index).unwrap_err(); + assert_eq!(err, EncodeError::WrongKind { id: data_id }); + } + + #[test] + fn encode_fails_on_wrong_field_count() { + let order_id = AdjId(1002); + let packet_def = sample_packet_def( + order_id, + PacketKind::Order(vec![ + sample_measurement(1, MeasurementKind::Numeric { wire_type: NumericKind::U8 }), + sample_measurement(2, MeasurementKind::Numeric { wire_type: NumericKind::U8 }), + ]), + ); + + let index = make_test_index(vec![packet_def]); + let packet = DataOrderPacket { + id: order_id, + values: vec![Value::Number(10.0)], + }; + + let err = encode(&packet, &index).unwrap_err(); + assert_eq!( + err, + EncodeError::WrongFieldCount { + expected: 2, + got: 1, + } + ); + } + + // --- DECODE TESTS --- + + #[test] + fn decode_success_little_endian_and_values() { + let data_id = AdjId(3001); + let packet_def = sample_packet_def( + data_id, + PacketKind::Data(vec![ + sample_measurement(1, MeasurementKind::Numeric { wire_type: NumericKind::U16 }), + sample_measurement(2, MeasurementKind::Boolean), + ]), + ); + + let index = make_test_index(vec![packet_def]); + + // 3001 in little-endian u16: [0xB9, 0x0B] + // 500 in little-endian u16: [0xF4, 0x01] + // false: [0x00] + let raw_bytes = [0xB9, 0x0B, 0xF4, 0x01, 0x00]; + + let decoded = decode(&raw_bytes, &index).expect("decoding should succeed"); + + assert_eq!(decoded.id, data_id); + assert_eq!( + decoded.values, + vec![Value::Number(500.0), Value::Bool(false)] + ); + } + + #[test] + fn decode_fails_when_buffer_is_shorter_than_header() { + let index = make_test_index(vec![]); + let err = decode(&[0x01], &index).unwrap_err(); + assert_eq!(err, DecodeError::UnexpectedEof); + } + + #[test] + fn decode_fails_on_unexpected_eof_in_payload() { + let data_id = AdjId(3002); + let packet_def = sample_packet_def( + data_id, + PacketKind::Data(vec![ + sample_measurement(1, MeasurementKind::Numeric { wire_type: NumericKind::U32 }), + ]), + ); + + let index = make_test_index(vec![packet_def]); + + let raw_bytes = [0xBA, 0x0B, 0x01, 0x02]; + let err = decode(&raw_bytes, &index).unwrap_err(); + assert_eq!(err, DecodeError::UnexpectedEof); + } + + #[test] + fn decode_fails_on_unknown_id() { + let index = make_test_index(vec![]); + let raw_bytes = [0x88, 0x13]; + + let err = decode(&raw_bytes, &index).unwrap_err(); + assert_eq!(err, DecodeError::UnknownId(AdjId(5000))); + } + + #[test] + fn decode_fails_on_wrong_kind() { + let order_id = AdjId(4001); + let packet_def = sample_packet_def(order_id, PacketKind::Order(vec![])); + + let index = make_test_index(vec![packet_def]); + let raw_bytes = [0xA1, 0x0F]; + + let err = decode(&raw_bytes, &index).unwrap_err(); + assert_eq!(err, DecodeError::WrongKind { id: order_id }); + } +} \ No newline at end of file From 8218e7476abb5dce583baa2a58cc929df3081dc1 Mon Sep 17 00:00:00 2001 From: Gazi Al Saad Halawani Date: Mon, 12 Oct 2026 16:40:58 +0200 Subject: [PATCH 071/225] Feat(backend, protocol): Created ReadMe for the protocol directory. --- backend/crates/core/src/protocol/README.md | 157 +++++++++++++++++++++ 1 file changed, 157 insertions(+) create mode 100644 backend/crates/core/src/protocol/README.md diff --git a/backend/crates/core/src/protocol/README.md b/backend/crates/core/src/protocol/README.md new file mode 100644 index 000000000..1d81566f4 --- /dev/null +++ b/backend/crates/core/src/protocol/README.md @@ -0,0 +1,157 @@ +# Protocol Module + +This module handles encoding and decoding of packets for communication with hardware boards over TCP and UDP transports. It implements the ADJ protocol for telemetry data, commands, messages, and protection events. + +## Architecture + +The protocol module follows a layered architecture: + +``` +┌─────────────────────────────────────────┐ +│ Transport Layer │ +│ (tcp.rs, udp.rs) │ +├─────────────────────────────────────────┤ +│ Packet Layer │ +│ (packet/data_order.rs, │ +│ packet/message.rs, │ +│ packet/protection.rs) │ +├─────────────────────────────────────────┤ +│ Wire Layer │ +│ (wire.rs) │ +└─────────────────────────────────────────┘ +``` + +## Directory Structure + +``` +protocol/ +├── index.rs # Packet definition lookup table +├── error.rs # Decode and encode error types +├── wire.rs # Low-level byte ↔ value conversion +├── packet.rs # Packet-level encoding/decoding module +│ ├── data_order.rs # Data (telemetry) & Order (command) packets +│ ├── message.rs # Free-text log message packets (stub) +│ └── protection.rs # Protection trigger packets (stub) +├── tcp.rs # TCP transport framing (stub) +└── udp.rs # UDP transport framing +``` + +## Modules + +### `index.rs` - Packet Definition Lookup + +Provides a fast lookup table from packet IDs (`AdjId`) to their declarations (`PacketDef`). Built once from loaded ADJ configuration data (`PodData`), it owns cloned copies of packet definitions so it can be shared across async tasks via `Arc`. + +**Key types:** +- `Index` - HashMap-based lookup from `AdjId` to `PacketDef` + +### `error.rs` - Error Types + +Defines errors that can occur during packet encoding and decoding. + +**Key types:** +- `DecodeError` - Errors when converting bytes to packets + - `UnknownId` - No packet declared with this ID + - `UnexpectedEof` - Ran out of bytes during decode + - `Io` - I/O error reading from stream (TCP only) + - `InvalidEnumValue` - Enum index out of range + - `UnterminatedString` - String field not null-terminated + - `WrongKind` - Packet exists but isn't expected kind + +- `EncodeError` - Errors when converting packets to bytes + - `UnknownId` - No packet declared with this ID + - `WrongFieldCount` - Missing or extra fields in order + - `TypeMismatch` - Value doesn't match declared type + - `OutOfRange` - Numeric value doesn't fit wire type + - `WrongKind` - Packet exists but isn't expected kind + +### `wire.rs` - Low-Level Byte Codec + +Handles conversion between raw bytes and `Value` types for individual measurements, based on their declared `MeasurementKind`. All numeric types use little-endian encoding. + +**Key functions:** +- `decode_value(bytes, kind)` - Decode a single value from bytes +- `encode_value(value, kind)` - Encode a single value to bytes +- `byte_width(kind)` - Get the wire width in bytes for a measurement kind + +**Supported types:** +- **Numeric** (U8, U16, U32, U64, I8, I16, I32, I64, F32, F64) - ✓ Implemented +- **Enum** (single byte index) - ✓ Implemented +- **Boolean** - ⚠ Stub (wire width not yet confirmed with firmware) + +### `packet/` - Packet-Level Encoding/Decoding + +Contains per-packet-kind encoding and decoding logic, independent of transport. + +#### `data_order.rs` + +Handles two packet kinds: +- **Order packets** (commands sent to boards) - Encoded only, sent over TCP +- **Data packets** (periodic telemetry from boards) - Decoded only, received over UDP + +**Key functions:** +- `encode(order, index)` - Encode an Order packet into bytes +- `decode(bytes, index)` - Decode a Data packet from bytes + +#### `message.rs` ⚠ Stub + +Decodes free-text log messages from boards over TCP. Not yet implemented. + +#### `protection.rs` ⚠ Stub + +Decodes protection trigger events from boards over TCP. Not yet implemented. + +### `tcp.rs` - TCP Transport Framing ⚠ Partial + +Handles the dedicated TCP connection to each board. A TCP connection carries: +- Protection events (board → backend) +- Free-text messages (board → backend) +- Order commands (backend → board) + +**Key types:** +- `TcpFrame` - Enum of frames that can be received over TCP (Protection, Message) + +**Key functions:** +- `decode_next(reader, index)` - ⚠ Stub - Decode the next frame from a TCP stream +- `encode_order(order, index)` - ✓ Implemented - Encode an order for sending + +### `udp.rs` - UDP Transport Framing + +Handles the shared UDP socket for periodic telemetry. UDP datagrams are complete, already-delimited buffers containing Data packets. + +**Key functions:** +- `decode_datagram(bytes, index)` - ✓ Implemented - Decode a UDP datagram into a DataPacket + +## Packet Types Summary + +| Packet Type | Direction | Transport | Status | +|-------------|-----------|-----------|--------| +| Data (telemetry) | Board → Backend | UDP | ✓ Implemented | +| Order (command) | Backend → Board | TCP | ✓ Implemented | +| Message (log) | Board → Backend | TCP | ⚠ Stub | +| Protection (event) | Board → Backend | TCP | ⚠ Stub | + +## Implementation Status + +- ✅ **Data packets** - Full encode/decode with tests +- ✅ **Order packets** - Full encode/decode with tests +- ✅ **Wire-level numeric types** - All numeric kinds supported with tests +- ✅ **Wire-level enum types** - Full encode/decode with tests +- ⚠️ **Wire-level boolean types** - Stub (awaiting firmware confirmation) +- ⚠️ **Message packets** - Stub (decode not implemented) +- ⚠️ **Protection packets** - Stub (decode not implemented) +- ⚠️ **TCP framing** - Partial (decode_next not implemented) + +## Testing + +The module includes comprehensive unit tests for: +- Wire-level encoding/decoding for all numeric types +- Enum encoding/decoding with boundary checks +- Order packet encoding with field validation +- Data packet decoding with error handling +- Error propagation for unknown IDs, wrong kinds, and type mismatches + +Run tests with: +```bash +cargo test -p core protocol +``` From b615ec814970816e2efcf4decc4dbe1d9f7c3a59 Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Mon, 12 Oct 2026 17:52:32 +0200 Subject: [PATCH 072/225] fix(backend, model): use phantom type to diferenciate betwen orders and data packets --- backend/crates/core/src/model.rs | 3 +- backend/crates/core/src/model/README.md | 46 +++++++---- backend/crates/core/src/model/packet.rs | 103 +++++++++++++++++++----- 3 files changed, 118 insertions(+), 34 deletions(-) diff --git a/backend/crates/core/src/model.rs b/backend/crates/core/src/model.rs index ccef505c5..54754b45b 100644 --- a/backend/crates/core/src/model.rs +++ b/backend/crates/core/src/model.rs @@ -21,7 +21,8 @@ pub use board::{Board, PacketDef, PacketKind, PodData}; pub use id::{AdjId, BoardId, MacAddress, Port}; pub use measurement::{Measurement, MeasurementKind, NumericKind, Range}; pub use packet::{ - DataPacket, MessageLevel, MessagePacket, OrderPacket, Packet, ProtectionPacket, ShortTimestamp, DataOrderPacket + Data, DataOrderPacket, DataPacket, MessageLevel, MessagePacket, Order, OrderPacket, Packet, + ProtectionPacket, ShortTimestamp, }; pub use protections::{Protection, ProtectionKind, Severity}; pub use value::Value; diff --git a/backend/crates/core/src/model/README.md b/backend/crates/core/src/model/README.md index fb85173ea..dc1d58f49 100644 --- a/backend/crates/core/src/model/README.md +++ b/backend/crates/core/src/model/README.md @@ -123,23 +123,39 @@ Second of Timestamp of values 0–59. #### `subsecond` The sub-second fraction, as the raw byte on the wire. Its exact unit (e.g. milliseconds, or 1/256ths of a second) hasn't been confirmed yet, so it is kept as a raw `u8` here instead of converted to something like a `Duration` — convert it once the unit is settled. -### 4.2 `DataPacket` -Struct for the decoded values of the measurements a board just sent. Values are positional: they are not individually tagged with their measurement ID, but written in the order their `Measurement`s appear in this packet's `PacketKind::Data` list. +### 4.2 `DataOrderPacket` — a phantom type +`DataPacket` and `OrderPacket` hold the exact same shape (`id: AdjId`, `values: Vec`, both positional — see below), so they're both built on one generic struct, `DataOrderPacket`, instead of being copy-pasted. The two used to just be `type` aliases for the very same concrete struct (`type OrderPacket = DataOrderPacket; type DataPacket = DataOrderPacket;`) — which meant they weren't actually distinct types at all: nothing stopped a `DataPacket` just decoded off the UDP socket from being passed to `protocol::tcp::encode_order` (which wants an *order* to send) by mistake, the compiler had no way to tell them apart. -#### `id` -Which packet definition this is an instance of (`AdjId`). -#### `values` -Vector list of decoded values (`Vec`) corresponding positionally to the packet definition's measurements. +`Kind` fixes that. It's a *phantom* type parameter — `DataOrderPacket` doesn't actually store a `Kind` value (there's nothing to store, see `Data`/`Order` below), it only exists so the compiler tracks which one a given packet was built as: +```rust +pub struct DataOrderPacket { + pub id: AdjId, + pub values: Vec, + _marker: PhantomData, +} +``` +`_marker` is private, so a `DataOrderPacket` can't be built with struct-literal syntax from outside `packet.rs` — use `DataOrderPacket::new(id, values)` (or, through the aliases below, `DataPacket::new(...)`/`OrderPacket::new(...)`) instead. + +#### `Data` / `Order` +Two empty marker structs — the only two types `Kind` is ever instantiated with. Neither is ever actually constructed; they only ever appear as a type argument. That's what makes the whole thing *phantom*: the type parameter has no representation in the compiled struct, it's erased after type-checking, the same way `id.rs` (§2) uses distinct `AdjId`/`BoardId` types so the compiler won't confuse two different kinds of `u16`. -### 4.3 `OrderPacket` -An order sent from the backend to a board. Also positional, matching field definitions in order. +#### `DataPacket` / `OrderPacket` +```rust +pub type DataPacket = DataOrderPacket; +pub type OrderPacket = DataOrderPacket; +``` +Now genuinely different types: a function that takes an `OrderPacket` cannot be called with a `DataPacket`, even though both just wrap the same `(AdjId, Vec)` underneath — the mix-up is a compile error instead of a bug waiting to happen. `DataOrderPacket`'s own doc comment has a `compile_fail` doctest proving exactly that (run by `cargo test`, like any other doctest). + +`DataPacket` holds the decoded values of the measurements a board just sent — positional, not individually tagged with their measurement ID, just written in the order their `Measurement`s appear in this packet's `PacketKind::Data` list. + +`OrderPacket` holds an order sent from the backend to a board — positional the same way, matching `PacketKind::Order`'s measurement list. #### `id` -Which order definition this is an instance of (`AdjId`). -#### `fields` -Vector list of values (`Vec`) to set for each field of the order. +Which packet/order definition this is an instance of (`AdjId`). +#### `values` +Vector list of decoded values (`Vec`) corresponding positionally to the packet definition's measurements. -### 4.4 `ProtectionPacket` +### 4.3 `ProtectionPacket` Sent by a board when one of its declared protections triggers. #### `id` @@ -149,7 +165,7 @@ When the protection triggered (`ShortTimestamp`). #### `value` The value that triggered the protection (`Value`), decoded with the same wire type as the watched measurement. -### 4.5 `MessageLevel` +### 4.4 `MessageLevel` Enum indicating how severe a message is (reusing `general_info.json`'s `message_ids`). Distinct from `Severity` because message and protection formats are separate in ADJv3. #### `Fault` @@ -161,7 +177,7 @@ Informational message, no action implied. #### `Panic` An unrecoverable firmware error. -### 4.6 `MessagePacket` +### 4.5 `MessagePacket` A free-text message sent by a board. #### `level` @@ -173,7 +189,7 @@ Source identifier, such as a source file path (`String`). #### `message` The text contents of the message (`String`). -### 4.7 `Packet` +### 4.6 `Packet` Enum representing any packet actually sent or received over the wire, once decoded. #### `Data` diff --git a/backend/crates/core/src/model/packet.rs b/backend/crates/core/src/model/packet.rs index 4c249fb53..ca766809a 100644 --- a/backend/crates/core/src/model/packet.rs +++ b/backend/crates/core/src/model/packet.rs @@ -7,6 +7,7 @@ //! describes a whole packet. use super::{AdjId, Value}; +use std::marker::PhantomData; /// A short timestamp carrying only the time of day: hour, minute, second /// and a sub-second fraction, each one byte. @@ -32,8 +33,22 @@ pub struct ShortTimestamp { pub subsecond: u8, } +/// Tags a [`DataOrderPacket`] as a board's periodic telemetry +/// ([`DataPacket`]) rather than a command sent to one. +/// +/// Carries no data — see [`DataOrderPacket`] for why it exists at all. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub struct Data; + +/// Tags a [`DataOrderPacket`] as a command sent to a board +/// ([`OrderPacket`]) rather than telemetry received from one. +/// +/// Carries no data — see [`DataOrderPacket`] for why it exists at all. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub struct Order; + /// A Data/Order packet: the decoded values of the measurements a board just -/// sent. +/// sent, or that an order is about to send to one. /// /// The wire protocol is positional: values are not individually tagged /// with their measurement's id, just written back to back in the order @@ -41,18 +56,58 @@ pub struct ShortTimestamp { /// [`super::PacketKind::Data`] list. `values[i]` is the decoded value of /// that list's `i`-th measurement — matching them up by position is /// `protocol`'s job, this type just holds the result in that same order. - +/// +/// `Kind` is a phantom type parameter (either [`Data`] or [`Order`], never +/// anything else — see [`DataPacket`]/[`OrderPacket`]): the struct stores +/// no `Kind` value, nothing to store (`Data`/`Order` carry no data), it +/// only exists so the compiler can tell a [`DataPacket`] apart from an +/// [`OrderPacket`], the same way [`super::AdjId`]/[`super::BoardId`] +/// (`id.rs`) are distinct types so the compiler won't let one be confused +/// with the other, even though both are just a `u16` underneath. Before +/// this, [`DataPacket`] and [`OrderPacket`] were both plain aliases for +/// the same concrete struct — nothing stopped a `DataPacket`, decoded off +/// the UDP socket, from being passed to [`crate::protocol::tcp::encode_order`] +/// by mistake; that mix-up is now a compile error: +/// +/// ```compile_fail +/// use software_core::model::{AdjId, DataPacket, OrderPacket}; +/// +/// fn send_order(_order: OrderPacket) {} +/// +/// let data = DataPacket::new(AdjId(1000), vec![]); +/// send_order(data); // doesn't compile: `DataPacket` isn't an `OrderPacket` +/// ``` #[derive(Debug, Clone, PartialEq)] -pub struct DataOrderPacket{ +pub struct DataOrderPacket { + /// The packet's id. pub id: AdjId, - pub values: Vec, + /// Each measurement's decoded value, in the same order as the + /// matching [`super::PacketKind::Data`]/[`super::PacketKind::Order`] + /// list. + pub values: Vec, + _marker: PhantomData, +} + +impl DataOrderPacket { + /// Builds a packet tagged as `Kind`, e.g. `DataPacket::new(id, values)` + /// or `OrderPacket::new(id, values)`. + pub fn new(id: AdjId, values: Vec) -> Self { + Self { + id, + values, + _marker: PhantomData, + } + } } /// An order sent from the backend to a board. /// /// Positional, the same way [`DataPacket::values`] is: see its docs. -pub type OrderPacket = DataOrderPacket; -pub type DataPacket = DataOrderPacket; +pub type OrderPacket = DataOrderPacket; +/// A set of measurements sent by a board. +/// +/// Positional, the same way [`DataOrderPacket::values`] is: see its docs. +pub type DataPacket = DataOrderPacket; /// A protection packet: sent by a board when one of its declared /// [`super::Protection`]s triggers. @@ -194,10 +249,7 @@ mod tests { fn data_packet_values_are_positional_not_tagged_with_an_id() { // values[0] is whatever measurements[0] is in this packet's // PacketDef — there is no id stored alongside each value here. - let packet = DataPacket { - id: AdjId(1000), - values: vec![Value::Number(53.2), Value::Bool(true)], - }; + let packet = DataPacket::new(AdjId(1000), vec![Value::Number(53.2), Value::Bool(true)]); assert_eq!(packet.values[0], Value::Number(53.2)); assert_eq!(packet.values[1], Value::Bool(true)); @@ -205,14 +257,8 @@ mod tests { #[test] fn packet_wraps_each_kind_without_mixing_them_up() { - let data = Packet::Data(DataPacket { - id: AdjId(1000), - values: vec![], - }); - let order = Packet::Order(OrderPacket { - id: AdjId(2000), - values: vec![], - }); + let data = Packet::Data(DataPacket::new(AdjId(1000), vec![])); + let order = Packet::Order(OrderPacket::new(AdjId(2000), vec![])); assert_ne!(data, order); match data { @@ -220,4 +266,25 @@ mod tests { _ => unreachable!("this is a Packet::Data"), } } + + #[test] + fn two_data_packets_with_the_same_id_and_values_are_equal() { + let a = DataPacket::new(AdjId(1000), vec![Value::Number(1.0)]); + let b = DataPacket::new(AdjId(1000), vec![Value::Number(1.0)]); + assert_eq!(a, b); + } + + #[test] + fn an_order_packet_and_a_data_packet_built_from_the_same_id_and_values_are_different_types() { + // This is the whole point of tagging `DataOrderPacket` with a + // phantom `Kind`: `DataPacket` and `OrderPacket` used to be plain + // aliases for the same concrete struct, so nothing here would even + // have been a type error before. There's no runtime assertion to + // make for that — see this module's `compile_fail` doctest on + // `DataOrderPacket`, which proves the mix-up doesn't compile. + let data = DataPacket::new(AdjId(1000), vec![]); + let order = OrderPacket::new(AdjId(1000), vec![]); + assert_eq!(data.id, order.id); + assert_eq!(data.values, order.values); + } } From fc7216b2da11fe7901c4f9f4eb7c669787d13011 Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Mon, 12 Oct 2026 17:58:00 +0200 Subject: [PATCH 073/225] fix(backend, protocol): changes due to unification of data_order --- backend/crates/core/src/protocol/packet.rs | 1 + backend/crates/core/src/protocol/tcp.rs | 2 +- backend/crates/core/src/protocol/udp.rs | 2 +- 3 files changed, 3 insertions(+), 2 deletions(-) diff --git a/backend/crates/core/src/protocol/packet.rs b/backend/crates/core/src/protocol/packet.rs index 7f357df8f..7d17cc623 100644 --- a/backend/crates/core/src/protocol/packet.rs +++ b/backend/crates/core/src/protocol/packet.rs @@ -5,6 +5,7 @@ //! only ever received (over UDP), an `Order` only ever sent (over TCP), //! so there's no `encode` for the former or `decode` for the latter. +pub mod data_order; pub mod message; pub mod protection; pub mod data_order; diff --git a/backend/crates/core/src/protocol/tcp.rs b/backend/crates/core/src/protocol/tcp.rs index af3882253..5adf7edd8 100644 --- a/backend/crates/core/src/protocol/tcp.rs +++ b/backend/crates/core/src/protocol/tcp.rs @@ -45,5 +45,5 @@ pub fn decode_next(reader: impl Read, index: &Index) -> Result Result, EncodeError> { - packet::order::encode(order, index) + packet::data_order::encode(order, index) } diff --git a/backend/crates/core/src/protocol/udp.rs b/backend/crates/core/src/protocol/udp.rs index 4eb0d6723..35e918ce0 100644 --- a/backend/crates/core/src/protocol/udp.rs +++ b/backend/crates/core/src/protocol/udp.rs @@ -13,5 +13,5 @@ use crate::model::DataPacket; /// Decodes a single UDP datagram's bytes into a [`DataPacket`]. pub fn decode_datagram(bytes: &[u8], index: &Index) -> Result { - packet::data::decode(bytes, index) + packet::data_order::decode(bytes, index) } From 45642f856d66ca659c471b6e6055c4cd1da58f10 Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Mon, 12 Oct 2026 17:58:29 +0200 Subject: [PATCH 074/225] fix(backend, protocol): implement partial eq manually for decode error (due to IO error) --- backend/crates/core/src/protocol/error.rs | 27 ++++++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/backend/crates/core/src/protocol/error.rs b/backend/crates/core/src/protocol/error.rs index 64660e696..1ffd3b638 100644 --- a/backend/crates/core/src/protocol/error.rs +++ b/backend/crates/core/src/protocol/error.rs @@ -46,8 +46,33 @@ pub enum DecodeError { }, } +impl PartialEq for DecodeError { + // `Io`'s `std::io::Error` doesn't implement `PartialEq`, so this can't + // be derived — compare by `ErrorKind` instead for that variant. + fn eq(&self, other: &Self) -> bool { + match (self, other) { + (Self::UnknownId(a), Self::UnknownId(b)) => a == b, + (Self::UnexpectedEof, Self::UnexpectedEof) => true, + (Self::Io(a), Self::Io(b)) => a.kind() == b.kind(), + ( + Self::InvalidEnumValue { + index: a_index, + options: a_options, + }, + Self::InvalidEnumValue { + index: b_index, + options: b_options, + }, + ) => a_index == b_index && a_options == b_options, + (Self::UnterminatedString { max: a }, Self::UnterminatedString { max: b }) => a == b, + (Self::WrongKind { id: a }, Self::WrongKind { id: b }) => a == b, + _ => false, + } + } +} + /// An error encoding a packet into bytes. -#[derive(Debug, thiserror::Error)] +#[derive(Debug, thiserror::Error, PartialEq)] pub enum EncodeError { /// No packet is declared with this id. #[error("unknown packet id {0:?}")] From 7f6364467f77feeb179b6f1a4fbc456b4460e1e4 Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Mon, 12 Oct 2026 17:59:01 +0200 Subject: [PATCH 075/225] docs(backend, protocol): update docs --- backend/crates/core/src/protocol/tcp.rs | 21 ++++++++++----------- backend/crates/core/src/protocol/udp.rs | 2 +- 2 files changed, 11 insertions(+), 12 deletions(-) diff --git a/backend/crates/core/src/protocol/tcp.rs b/backend/crates/core/src/protocol/tcp.rs index 5adf7edd8..9d4169087 100644 --- a/backend/crates/core/src/protocol/tcp.rs +++ b/backend/crates/core/src/protocol/tcp.rs @@ -5,7 +5,7 @@ //! //! Both functions here are thin: the actual per-kind decoding lives in //! [`super::packet::protection`]/[`super::packet::message`]/ -//! [`super::packet::order`], independent of TCP. This module only adds +//! [`super::packet::data_order`], independent of TCP. This module only adds //! the transport-level guarantee — [`decode_next`] can only ever return //! a [`TcpFrame`], never a `DataPacket`. @@ -27,19 +27,18 @@ pub enum TcpFrame { /// field shapes against `index`. /// /// Reads the frame's leading 16-bit id first, then decides which of -/// [`super::packet::protection::decode`] (the id's high 3 bits are a -/// protection's position, non-zero) or [`super::packet::message::decode`] -/// (the id matches one of `general_info.json`'s `message_ids`) to hand -/// the rest of the frame to, wrapping the result in the matching -/// [`TcpFrame`] variant. +/// [`super::packet::protection::decode`] ([`crate::model::AdjId::protection_position`] +/// is non-zero) or [`super::packet::message::decode`] (the id matches one +/// of `general_info.json`'s `message_ids`) to hand the rest of the frame +/// to, wrapping the result in the matching [`TcpFrame`] variant. pub fn decode_next(reader: impl Read, index: &Index) -> Result { let _ = (reader, index); todo!( - "read the leading 16-bit id; if its top 3 bits are non-zero, call \ - packet::protection::decode; otherwise resolve it against \ - general_info.json's message_ids (not yet reachable from `Index` \ - — needs AdjInfo too) and call packet::message::decode; wrap \ - either result in the matching TcpFrame variant" + "read the leading 16-bit id; if its AdjId::protection_position() is \ + non-zero, call packet::protection::decode; otherwise resolve it \ + against general_info.json's message_ids (not yet reachable from \ + `Index` — needs AdjInfo too) and call packet::message::decode; \ + wrap either result in the matching TcpFrame variant" ) } diff --git a/backend/crates/core/src/protocol/udp.rs b/backend/crates/core/src/protocol/udp.rs index 35e918ce0..05c44c3c0 100644 --- a/backend/crates/core/src/protocol/udp.rs +++ b/backend/crates/core/src/protocol/udp.rs @@ -2,7 +2,7 @@ //! telemetry (`Data` packets) from any board. Receive-only — the backend //! never sends anything over this socket. //! -//! The actual decoding lives in [`super::packet::data`], independent of +//! The actual decoding lives in [`super::packet::data_order`], independent of //! UDP — this module only adds the transport-level guarantee: a UDP //! datagram is a complete, already-delimited buffer (the OS preserves //! datagram boundaries even on a socket shared by every board), unlike From 5a99aa40279ca5092873662b000b9eeaf5f590b5 Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Mon, 12 Oct 2026 17:59:31 +0200 Subject: [PATCH 076/225] fix(backend, protocol): format --- backend/crates/core/src/protocol/wire.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/backend/crates/core/src/protocol/wire.rs b/backend/crates/core/src/protocol/wire.rs index 8809c7126..89bf317e1 100644 --- a/backend/crates/core/src/protocol/wire.rs +++ b/backend/crates/core/src/protocol/wire.rs @@ -203,7 +203,10 @@ mod tests { ]; for (wire_type, expected) in cases { - assert_eq!(byte_width(&MeasurementKind::Numeric { wire_type }), expected); + assert_eq!( + byte_width(&MeasurementKind::Numeric { wire_type }), + expected + ); } } From 3e13e0985e904d3828e98e1a8d854371b82a25f2 Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Mon, 12 Oct 2026 18:00:17 +0200 Subject: [PATCH 077/225] fix(backend, protocol): remove duplicated data_order exportation --- backend/crates/core/src/protocol/packet.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/backend/crates/core/src/protocol/packet.rs b/backend/crates/core/src/protocol/packet.rs index 7d17cc623..4bf19cc13 100644 --- a/backend/crates/core/src/protocol/packet.rs +++ b/backend/crates/core/src/protocol/packet.rs @@ -8,4 +8,3 @@ pub mod data_order; pub mod message; pub mod protection; -pub mod data_order; From 618e696adbd7f63217cf3225dca955c22d451e43 Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Mon, 12 Oct 2026 19:23:05 +0200 Subject: [PATCH 078/225] fix(backend, model): include kind --- backend/crates/core/src/model.rs | 4 ++-- backend/crates/core/src/model/README.md | 11 +++++++++ backend/crates/core/src/model/packet.rs | 30 ++++++++++++++++++++++++- 3 files changed, 42 insertions(+), 3 deletions(-) diff --git a/backend/crates/core/src/model.rs b/backend/crates/core/src/model.rs index 54754b45b..04f933cb3 100644 --- a/backend/crates/core/src/model.rs +++ b/backend/crates/core/src/model.rs @@ -21,8 +21,8 @@ pub use board::{Board, PacketDef, PacketKind, PodData}; pub use id::{AdjId, BoardId, MacAddress, Port}; pub use measurement::{Measurement, MeasurementKind, NumericKind, Range}; pub use packet::{ - Data, DataOrderPacket, DataPacket, MessageLevel, MessagePacket, Order, OrderPacket, Packet, - ProtectionPacket, ShortTimestamp, + Data, DataOrderPacket, DataPacket, KindTag, MessageLevel, MessagePacket, Order, OrderPacket, + Packet, ProtectionPacket, ShortTimestamp, }; pub use protections::{Protection, ProtectionKind, Severity}; pub use value::Value; diff --git a/backend/crates/core/src/model/README.md b/backend/crates/core/src/model/README.md index dc1d58f49..aa088648c 100644 --- a/backend/crates/core/src/model/README.md +++ b/backend/crates/core/src/model/README.md @@ -139,6 +139,17 @@ pub struct DataOrderPacket { #### `Data` / `Order` Two empty marker structs — the only two types `Kind` is ever instantiated with. Neither is ever actually constructed; they only ever appear as a type argument. That's what makes the whole thing *phantom*: the type parameter has no representation in the compiled struct, it's erased after type-checking, the same way `id.rs` (§2) uses distinct `AdjId`/`BoardId` types so the compiler won't confuse two different kinds of `u16`. +#### `KindTag` +The compiler erases `Kind` after type-checking, so nothing at runtime can look at a `DataOrderPacket` and ask "is this actually a `Data` one?" — `KindTag` is how code that's generic over `Kind` answers that anyway, by asking the question of the *type* instead of the *value*: +```rust +pub trait KindTag { + fn matches(kind: &PacketKind) -> bool; +} +``` +`Data`/`Order` each implement it by checking which `PacketKind` (§1.1) variant they stand for (`matches!(kind, PacketKind::Data(_))` / `PacketKind::Order(_)`). This is the only thing `KindTag` decides — once a `PacketDef`'s kind is confirmed to match, the actual measurement list still comes from the existing `PacketKind::measurements()` (§1.1), not from `KindTag` itself. + +`protocol::packet::data_order`'s `encode`/`decode` use this to be generic over `Kind`: written once, they work for both `DataPacket` and `OrderPacket` instead of needing a near-duplicate pair of functions per kind. + #### `DataPacket` / `OrderPacket` ```rust pub type DataPacket = DataOrderPacket; diff --git a/backend/crates/core/src/model/packet.rs b/backend/crates/core/src/model/packet.rs index ca766809a..56b9c60e8 100644 --- a/backend/crates/core/src/model/packet.rs +++ b/backend/crates/core/src/model/packet.rs @@ -6,7 +6,7 @@ //! packet or a protection *can* look like, or [`super::PacketDef`], which //! describes a whole packet. -use super::{AdjId, Value}; +use super::{AdjId, PacketKind, Value}; use std::marker::PhantomData; /// A short timestamp carrying only the time of day: hour, minute, second @@ -47,6 +47,34 @@ pub struct Data; #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub struct Order; +/// Bridges a [`DataOrderPacket`]'s phantom `Kind` to the runtime +/// [`PacketKind`] variant it stands for. +/// +/// `protocol::packet::data_order`'s `encode`/`decode` are generic over +/// `Kind`: they're written once and work for both [`Data`] and [`Order`], +/// instead of needing a near-identical copy per kind. This trait is the +/// one yes/no question that generic code can't answer on its own — +/// "is this `PacketDef`'s kind actually the one I was asked to +/// encode/decode?" — everything after that (pulling out the +/// measurements) is already handled by [`PacketKind::measurements`], +/// kind-agnostic, so there's no need to redo that here. +pub trait KindTag { + /// Whether `kind` is the variant this `Kind` stands for. + fn matches(kind: &PacketKind) -> bool; +} + +impl KindTag for Data { + fn matches(kind: &PacketKind) -> bool { + matches!(kind, PacketKind::Data(_)) + } +} + +impl KindTag for Order { + fn matches(kind: &PacketKind) -> bool { + matches!(kind, PacketKind::Order(_)) + } +} + /// A Data/Order packet: the decoded values of the measurements a board just /// sent, or that an order is about to send to one. /// From d47baea1b06b93c3c7944a2160402da1c98401d0 Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Mon, 12 Oct 2026 19:24:13 +0200 Subject: [PATCH 079/225] feat(backend, protocol): implement boolean --- backend/crates/core/src/protocol/wire.rs | 74 +++++++++++++++++++----- 1 file changed, 61 insertions(+), 13 deletions(-) diff --git a/backend/crates/core/src/protocol/wire.rs b/backend/crates/core/src/protocol/wire.rs index 89bf317e1..9ebe6ab8b 100644 --- a/backend/crates/core/src/protocol/wire.rs +++ b/backend/crates/core/src/protocol/wire.rs @@ -45,10 +45,7 @@ pub fn byte_width(kind: &MeasurementKind) -> usize { NumericKind::U32 | NumericKind::I32 | NumericKind::F32 => 4, NumericKind::U64 | NumericKind::I64 | NumericKind::F64 => 8, }, - // Not yet confirmed against firmware — see `decode_boolean`. - MeasurementKind::Boolean => { - todo!("confirm the wire width firmware uses for a boolean measurement") - } + MeasurementKind::Boolean => 1, MeasurementKind::Enum { .. } => 1, } } @@ -128,19 +125,20 @@ fn numeric_range(wire_type: NumericKind) -> (f64, f64) { } } -/// Decodes a boolean value. -/// -/// Wire width isn't settled yet — not specified anywhere in the ADJv3 -/// spec read so far. Confirm against firmware before implementing. +/// Decodes a boolean value: a single byte, zero for `false`, any other +/// value for `true`. pub fn decode_boolean(bytes: &[u8]) -> Result { - let _ = bytes; - todo!("confirm the wire width firmware uses for a boolean measurement") + let &byte = bytes.first().ok_or(DecodeError::UnexpectedEof)?; + Ok(Value::Bool(byte != 0)) } -/// Encodes a boolean value. +/// Encodes a boolean value as a single byte: `0x00` for `false`, `0x01` +/// for `true`. pub fn encode_boolean(value: &Value) -> Result, EncodeError> { - let _ = value; - todo!("confirm the wire width firmware uses for a boolean measurement") + let Value::Bool(value) = value else { + return Err(EncodeError::TypeMismatch); + }; + Ok(vec![u8::from(*value)]) } /// Decodes an enum value: a single `uint8` byte, the index into @@ -220,6 +218,56 @@ mod tests { ); } + #[test] + fn byte_width_of_a_boolean_is_one() { + assert_eq!(byte_width(&MeasurementKind::Boolean), 1); + } + + #[test] + fn decodes_a_zero_byte_as_false() { + let Ok(value) = decode_boolean(&[0x00]) else { + unreachable!("decoding a zero byte should succeed"); + }; + assert_eq!(value, Value::Bool(false)); + } + + #[test] + fn decodes_any_nonzero_byte_as_true() { + let Ok(value) = decode_boolean(&[0xFF]) else { + unreachable!("decoding a nonzero byte should succeed"); + }; + assert_eq!(value, Value::Bool(true)); + } + + #[test] + fn decode_boolean_rejects_empty_input() { + assert!(matches!( + decode_boolean(&[]), + Err(DecodeError::UnexpectedEof) + )); + } + + #[test] + fn boolean_round_trips_through_encode_then_decode() { + for value in [true, false] { + let Ok(bytes) = encode_boolean(&Value::Bool(value)) else { + unreachable!("encoding a well-formed boolean should succeed"); + }; + let Ok(decoded) = decode_boolean(&bytes) else { + unreachable!("decoding what we just encoded should succeed"); + }; + assert_eq!(decoded, Value::Bool(value)); + } + } + + #[test] + fn encode_boolean_rejects_the_wrong_value_variant() { + assert!(matches!( + encode_boolean(&Value::Number(1.0)), + Err(EncodeError::TypeMismatch) + )); + } + #[test] fn decodes_an_unsigned_integer_little_endian() { let Ok(value) = decode_numeric(&[0x34, 0x12], NumericKind::U16) else { From 87c015931e37c1cb9205319a74d9581917155a53 Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Mon, 12 Oct 2026 19:25:01 +0200 Subject: [PATCH 080/225] fix(backend, protocol): solve issues and add comments --- .../core/src/protocol/packet/data_order.rs | 342 ++++++++++++------ 1 file changed, 230 insertions(+), 112 deletions(-) diff --git a/backend/crates/core/src/protocol/packet/data_order.rs b/backend/crates/core/src/protocol/packet/data_order.rs index eaa4cb84d..d4643a050 100644 --- a/backend/crates/core/src/protocol/packet/data_order.rs +++ b/backend/crates/core/src/protocol/packet/data_order.rs @@ -1,120 +1,129 @@ -use crate::model::{AdjId, DataPacket, PacketKind, Value, DataOrderPacket}; -use crate::protocol::{wire, EncodeError, Index, DecodeError}; - - -//! Encodes an `Order` packet: a command sent to a board. Only ever sent, -//! over TCP — the backend never receives one back. - -/// Encodes `order` into the bytes to write to a board's connection, +//! Encodes and decodes a positional Data/Order packet — see +//! [`crate::model::DataOrderPacket`] for why both share this one wire +//! shape under a phantom `Kind`. +//! +//! [`encode`]/[`decode`] are generic over that `Kind` via +//! [`crate::model::KindTag`], so they're written once and work for either +//! [`crate::model::Data`] or [`crate::model::Order`] — the backend itself +//! only ever calls `encode::` (via [`super::super::tcp`]) and +//! `decode::` (via [`super::super::udp`]), but that restriction +//! lives at the transport layer, not here. [`crate::model::KindTag`] only +//! answers whether a `PacketDef`'s kind matches `Kind` at all; the actual +//! measurement list comes from [`crate::model::PacketKind::measurements`] +//! either way. + +use crate::model::{AdjId, DataOrderPacket, KindTag}; +use crate::protocol::{DecodeError, EncodeError, Index, wire}; + +/// Encodes `packet` into the bytes to write to a board's connection, /// resolving its field shapes against `index`. -pub fn encode(order: &DataOrderPacket, index: &Index) -> Result, EncodeError> { - - //Unwrap PacketDef for kind +pub fn encode( + packet: &DataOrderPacket, + index: &Index, +) -> Result, EncodeError> { + // Look up the packet definition for this packet's id let packet_def = index - .packet(order.id) - .ok_or(EncodeError::UnknownId(order.id))?;// Question mark for error propagation and prevent crash + .packet(packet.id) + .ok_or(EncodeError::UnknownId(packet.id))?; - //Check if packetdef is PacketKind::Order(measurement). Also returns the list of measurements - let measurements = match &packet_def.kind{ - PacketKind::Order(measurements) => measurements, - _ => return Err(EncodeError::WrongKind {id:order.id}) - }; + // Check that the packet is an order or data, as expected by the generic KindTag + if !Kind::matches(&packet_def.kind) { + return Err(EncodeError::WrongKind { id: packet.id }); + } + + // Get the measurements for this packet + let measurements = packet_def.kind.measurements(); - //Check if length of list of fields matches number of measurements. - if order.values.len() != measurements.len(){ - return Err(EncodeError::WrongFieldCount {expected:measurements.len(),got:order.values.len()}) + // Check that the number of values that we want to encode matches the number of measurements in the packet definition + if packet.values.len() != measurements.len() { + return Err(EncodeError::WrongFieldCount { + expected: measurements.len(), + got: packet.values.len(), + }); } + // Encode the packet id as little-endian u16 let mut bytes = Vec::new(); + bytes.extend_from_slice(&packet.id.0.to_le_bytes()); - bytes.extend_from_slice(&order.id.0.to_le_bytes());//Header prefix of byte stream to 16 bit little-endian + // for each value in the packet encode it according to the corresponding measurements + for (field, measurement) in packet.values.iter().zip(measurements) { + // Encode the field value according to the measurement's kind + let field_bytes = wire::encode_value(field, &measurement.kind)?; - //Encoding to bytes - for (field,measurement) in order.values.iter().zip(measurements){ //For each measurement - let field_bytes = wire::encode_value(field,&measurement.kind)?;// Encode field Value into bytes according to MeasurementKind - bytes.extend(field_bytes);// Adds to byte stream + // Append the encoded field bytes to the output vector + bytes.extend(field_bytes); } - Ok(bytes) // Return bytes + Ok(bytes) } - -// -// "look up order.id in `index` to get its PacketDef (UnknownId if \ -// absent); match its `kind` for PacketKind::Order(measurements) \ -// (WrongKind if it's some other kind); error with WrongFieldCount \ -// if order.fields.len() doesn't match measurements.len(); encode \ -// the id then each field positionally via wire::encode_value" -// - -//! Decodes a `Data` packet: a board's periodic telemetry. Only ever -//! received, over UDP — a board never receives one back. - -/// Decodes a complete, already-delimited buffer into a [`DataPacket`], -/// resolving its field shapes against `index`. -pub fn decode(bytes: &[u8], index: &Index) -> Result, DecodeError> { +/// Decodes a complete, already-delimited buffer into a +/// [`DataOrderPacket`], resolving its field shapes against `index`. +pub fn decode( + bytes: &[u8], + index: &Index, +) -> Result, DecodeError> { + // The first two bytes are the packet id, in little-endian u16 if bytes.len() < 2 { - // If less than 2 bytes return error return Err(DecodeError::UnexpectedEof); } - let id: [u8; 2] = bytes[0..2] // Recieve first two bytes - .try_into() // Tries to make it into desired type - .map_err(|_| DecodeError::UnexpectedEof)?; // If fails, return error - - let adj_id = AdjId(u16::from_le_bytes(id)); // Parse into u16 and make it AdjId type + // generate the packet id from the first two bytes + let id: [u8; 2] = bytes[0..2] + .try_into() + .map_err(|_| DecodeError::UnexpectedEof)?; - let packet_def = index.get(adj_id).ok_or(DecodeError::UnknownId(adj_id))?; // Get packet definition from index + // generate ADJ id from the little-endian bytes + let adj_id = AdjId(u16::from_le_bytes(id)); - let measurements = match &packet_def.kind { - // Get measurements from packet definition - PacketKind::Data(measurements) => measurements, // If packet kind is data, return measurements - _ => return Err(DecodeError::WrongKind { id: adj_id }), // If not, return Error - }; + // Look up the packet definition for this id if not found return an UnknownId error + let packet_def = index.packet(adj_id).ok_or(DecodeError::UnknownId(adj_id))?; - let mut values = Vec::with_capacity(measurements.len()); // Create vectir list of values same size as measurements + // Check that the packet is an order or data, as expected by the generic KindTag + if !Kind::matches(&packet_def.kind) { + return Err(DecodeError::WrongKind { id: adj_id }); + } + // Get the measurements for this packet + let measurements = packet_def.kind.measurements(); - let mut pointer = 2; // Pointer to after ID in bytes + // Prepare a vector to hold the decoded values and a pointer to track the current position in the byte slice + let mut values = Vec::with_capacity(measurements.len()); + let mut pointer = 2; + // For each measurement, decode the corresponding bytes from the input slice for measurement in measurements { let width = wire::byte_width(&measurement.kind); - let next = pointer + width; + // Check if there are enough bytes to decode the field if bytes.len() < next { - // Check if there is enough bytes left return Err(DecodeError::UnexpectedEof); } - let field = &bytes[pointer..next]; // Size of field (bytes between pointer and next position) - let value = wire::decode_value(field, &measurement.kind)?; // Decode value from field size and measurement width - values.push(value); //Add to list of values + // Slice the bytes for the current field and decode it according to the measurement's kind + let field = &bytes[pointer..next]; + let value = wire::decode_value(field, &measurement.kind)?; // Append the decoded value to the values vector + values.push(value); - pointer = next; // Next position + pointer = next; } - Ok(DataPacket { id: adj_id, values }) // Return data packet + Ok(DataOrderPacket::new(adj_id, values)) } -// -// "read the leading 16-bit id; look up its PacketDef in `index` \ -// (UnknownId if absent); match its `kind` for \ -// PacketKind::Data(measurements) (WrongKind if it's some other \ -// kind); decode each measurement's value positionally via \ -// wire::decode_value, advancing through `bytes` using each \ -// measurement's own wire width" -// - #[cfg(test)] mod tests { use super::*; use crate::model::{ - Board, BoardId, MacAddress, Measurement, MeasurementKind, NumericKind, PacketDef, - PacketKind, PodData, Value, + Board, BoardId, Data, DataPacket, MacAddress, Measurement, MeasurementKind, NumericKind, + Order, OrderPacket, PacketDef, PacketKind, PodData, Value, }; use std::collections::HashMap; use std::net::IpAddr; + // Auxiliar function to create a sample measurement for testing + fn sample_measurement(id: u16, kind: MeasurementKind) -> Measurement { Measurement { id: AdjId(id), @@ -158,35 +167,43 @@ mod tests { let packet_def = sample_packet_def( order_id, PacketKind::Order(vec![ - sample_measurement(1, MeasurementKind::Numeric { wire_type: NumericKind::U16 }), - sample_measurement(2, MeasurementKind::Boolean), + sample_measurement( + 1, + MeasurementKind::Numeric { + wire_type: NumericKind::U16, + }, + ), + sample_measurement( + 2, + MeasurementKind::Enum { + options: vec!["Off".to_string(), "On".to_string()], + }, + ), ]), ); let index = make_test_index(vec![packet_def]); - let packet = DataOrderPacket { - id: order_id, - values: vec![Value::Number(300.0), Value::Bool(true)], - }; + let packet = OrderPacket::new(order_id, vec![Value::Number(300.0), Value::Number(1.0)]); - let encoded = encode(&packet, &index).expect("encoding should succeed"); + let Ok(encoded) = encode(&packet, &index) else { + unreachable!("encoding a well-formed order should succeed"); + }; // 1001 in little-endian u16: [0xE9, 0x03] // 300 in little-endian u16: [0x2C, 0x01] - // true: [0x01] + // enum index 1: [0x01] assert_eq!(encoded, vec![0xE9, 0x03, 0x2C, 0x01, 0x01]); } #[test] fn encode_fails_on_unknown_id() { let index = make_test_index(vec![]); - let packet = DataOrderPacket { - id: AdjId(9999), - values: vec![], - }; + let packet = OrderPacket::new(AdjId(9999), vec![]); - let err = encode(&packet, &index).unwrap_err(); + let Err(err) = encode(&packet, &index) else { + unreachable!("encoding an unknown id should fail"); + }; assert_eq!(err, EncodeError::UnknownId(AdjId(9999))); } @@ -196,12 +213,11 @@ mod tests { let packet_def = sample_packet_def(data_id, PacketKind::Data(vec![])); let index = make_test_index(vec![packet_def]); - let packet = DataOrderPacket { - id: data_id, - values: vec![], - }; + let packet = OrderPacket::new(data_id, vec![]); - let err = encode(&packet, &index).unwrap_err(); + let Err(err) = encode(&packet, &index) else { + unreachable!("encoding the wrong packet kind should fail"); + }; assert_eq!(err, EncodeError::WrongKind { id: data_id }); } @@ -211,18 +227,27 @@ mod tests { let packet_def = sample_packet_def( order_id, PacketKind::Order(vec![ - sample_measurement(1, MeasurementKind::Numeric { wire_type: NumericKind::U8 }), - sample_measurement(2, MeasurementKind::Numeric { wire_type: NumericKind::U8 }), + sample_measurement( + 1, + MeasurementKind::Numeric { + wire_type: NumericKind::U8, + }, + ), + sample_measurement( + 2, + MeasurementKind::Numeric { + wire_type: NumericKind::U8, + }, + ), ]), ); let index = make_test_index(vec![packet_def]); - let packet = DataOrderPacket { - id: order_id, - values: vec![Value::Number(10.0)], - }; + let packet = OrderPacket::new(order_id, vec![Value::Number(10.0)]); - let err = encode(&packet, &index).unwrap_err(); + let Err(err) = encode(&packet, &index) else { + unreachable!("encoding with the wrong field count should fail"); + }; assert_eq!( err, EncodeError::WrongFieldCount { @@ -240,8 +265,18 @@ mod tests { let packet_def = sample_packet_def( data_id, PacketKind::Data(vec![ - sample_measurement(1, MeasurementKind::Numeric { wire_type: NumericKind::U16 }), - sample_measurement(2, MeasurementKind::Boolean), + sample_measurement( + 1, + MeasurementKind::Numeric { + wire_type: NumericKind::U16, + }, + ), + sample_measurement( + 2, + MeasurementKind::Enum { + options: vec!["Off".to_string(), "On".to_string()], + }, + ), ]), ); @@ -249,22 +284,26 @@ mod tests { // 3001 in little-endian u16: [0xB9, 0x0B] // 500 in little-endian u16: [0xF4, 0x01] - // false: [0x00] + // enum index 0: [0x00] let raw_bytes = [0xB9, 0x0B, 0xF4, 0x01, 0x00]; - let decoded = decode(&raw_bytes, &index).expect("decoding should succeed"); + let Ok(decoded) = decode::(&raw_bytes, &index) else { + unreachable!("decoding a well-formed data packet should succeed"); + }; assert_eq!(decoded.id, data_id); assert_eq!( decoded.values, - vec![Value::Number(500.0), Value::Bool(false)] + vec![Value::Number(500.0), Value::Enum("Off".to_string())] ); } #[test] fn decode_fails_when_buffer_is_shorter_than_header() { let index = make_test_index(vec![]); - let err = decode(&[0x01], &index).unwrap_err(); + let Err(err) = decode::(&[0x01], &index) else { + unreachable!("decoding a buffer shorter than the header should fail"); + }; assert_eq!(err, DecodeError::UnexpectedEof); } @@ -273,15 +312,20 @@ mod tests { let data_id = AdjId(3002); let packet_def = sample_packet_def( data_id, - PacketKind::Data(vec![ - sample_measurement(1, MeasurementKind::Numeric { wire_type: NumericKind::U32 }), - ]), + PacketKind::Data(vec![sample_measurement( + 1, + MeasurementKind::Numeric { + wire_type: NumericKind::U32, + }, + )]), ); let index = make_test_index(vec![packet_def]); let raw_bytes = [0xBA, 0x0B, 0x01, 0x02]; - let err = decode(&raw_bytes, &index).unwrap_err(); + let Err(err) = decode::(&raw_bytes, &index) else { + unreachable!("decoding a truncated payload should fail"); + }; assert_eq!(err, DecodeError::UnexpectedEof); } @@ -290,7 +334,9 @@ mod tests { let index = make_test_index(vec![]); let raw_bytes = [0x88, 0x13]; - let err = decode(&raw_bytes, &index).unwrap_err(); + let Err(err) = decode::(&raw_bytes, &index) else { + unreachable!("decoding an unknown id should fail"); + }; assert_eq!(err, DecodeError::UnknownId(AdjId(5000))); } @@ -302,7 +348,79 @@ mod tests { let index = make_test_index(vec![packet_def]); let raw_bytes = [0xA1, 0x0F]; - let err = decode(&raw_bytes, &index).unwrap_err(); + let Err(err) = decode::(&raw_bytes, &index) else { + unreachable!("decoding the wrong packet kind should fail"); + }; assert_eq!(err, DecodeError::WrongKind { id: order_id }); } -} \ No newline at end of file + + // --- ROUND-TRIP TESTS --- + // + // `encode`/`decode` are generic over `Kind`, so the same `PacketDef` + // works for both directions here — that genericity is the whole + // point of giving `DataOrderPacket` a phantom `Kind` in the first + // place, instead of writing one hardcoded pair of functions per kind. + // + // Enum fields are left out of both: `encode_enum` takes an + // already-selected index (`Value::Number`) but `decode_enum` returns + // the option's text (`Value::Enum`) — see `wire.rs` — so an enum + // field's `Value` is never expected to round-trip unchanged, only its + // underlying byte. + + fn numeric_measurements() -> Vec { + vec![ + sample_measurement( + 1, + MeasurementKind::Numeric { + wire_type: NumericKind::U16, + }, + ), + sample_measurement( + 2, + MeasurementKind::Numeric { + wire_type: NumericKind::I8, + }, + ), + ] + } + + #[test] + fn an_order_packet_round_trips_through_encode_then_decode() { + let id = AdjId(6001); + let index = make_test_index(vec![sample_packet_def( + id, + PacketKind::Order(numeric_measurements()), + )]); + let original = OrderPacket::new(id, vec![Value::Number(1234.0), Value::Number(-5.0)]); + + let Ok(bytes) = encode(&original, &index) else { + unreachable!("encoding this well-formed order should succeed"); + }; + let Ok(decoded) = decode::(&bytes, &index) else { + unreachable!("decoding what we just encoded should succeed"); + }; + + assert_eq!(decoded.id, original.id); + assert_eq!(decoded.values, original.values); + } + + #[test] + fn a_data_packet_round_trips_through_encode_then_decode() { + let id = AdjId(6002); + let index = make_test_index(vec![sample_packet_def( + id, + PacketKind::Data(numeric_measurements()), + )]); + let original = DataPacket::new(id, vec![Value::Number(42.0), Value::Number(-1.0)]); + + let Ok(bytes) = encode(&original, &index) else { + unreachable!("encoding this well-formed data packet should succeed"); + }; + let Ok(decoded) = decode::(&bytes, &index) else { + unreachable!("decoding what we just encoded should succeed"); + }; + + assert_eq!(decoded.id, original.id); + assert_eq!(decoded.values, original.values); + } +} From 1a2127f29a8baf91aa0fc9018618b3f1edd00124 Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Mon, 12 Oct 2026 21:22:47 +0200 Subject: [PATCH 081/225] feat(backend, protocol): protection --- .../core/src/protocol/packet/protection.rs | 425 +++++++++++++++++- 1 file changed, 411 insertions(+), 14 deletions(-) diff --git a/backend/crates/core/src/protocol/packet/protection.rs b/backend/crates/core/src/protocol/packet/protection.rs index e00a4acec..af6eb53f5 100644 --- a/backend/crates/core/src/protocol/packet/protection.rs +++ b/backend/crates/core/src/protocol/packet/protection.rs @@ -1,26 +1,423 @@ //! Decodes a `Protection` packet: a board reporting one of its declared -//! protections triggered. Only ever received, over TCP. +//! protections triggered. Only ever received, over TCP. Also provides +//! `encode`, purely so tests can build well-formed frames without +//! hand-written byte arrays — nothing in the real backend calls it, since +//! a protection never travels backend -> board. +//! Structure +//! ``` +//! | 0-1 | 2 | 3 | 4 | 5 | 6-9 | 10-13 | 14-17 | 18-21 | 22-25 | 26-29 | 30-33 | +//! |-------|-------|-------|-------|-------|-------|-------|-------| 30-33 | 34-37 | 38-41 | 42-45 | +//! | id | hora | min | seg | subseg| resv | resv | value | value | value | value | value | +//! | 34-37 | 38-41 | 42-45 | +//! |-------| 34-37 | 38-41 | 42-45 | +//! | value | value | value | +//! ``` +//! -use crate::model::{AdjId, ProtectionPacket}; -use crate::protocol::{DecodeError, Index}; +use crate::model::{AdjId, PacketKind, ProtectionPacket, ShortTimestamp}; +use crate::protocol::{DecodeError, EncodeError, Index, wire}; use std::io::Read; /// Decodes a protection frame's remaining bytes, given the frame's /// already-read compound id (`tcp::decode_next`'s job), resolving the /// watched measurement's wire type against `index`. pub fn decode( - reader: impl Read, + mut reader: impl Read, compound_id: AdjId, index: &Index, ) -> Result { - let _ = (reader, compound_id, index); - todo!( - "look up compound_id's PacketDef in `index` (already keyed by \ - this exact compound id, see adj::raw::loader); match its `kind` \ - for PacketKind::Protection(measurement) (WrongKind if it's some \ - other kind) to get the watched measurement's wire type; \ - separately split compound_id's bits into (measurement, position) \ - to fill ProtectionPacket's `measurement`/`protection` fields; \ - read the timestamp, then the value via wire::decode_value" - ) + // Look up the packet definition for this compound id, and ensure it's a + // protection packet. If not, the frame is malformed and we can't decode it. + let packet_def = index + .packet(compound_id) + .ok_or(DecodeError::UnknownId(compound_id))?; + + let PacketKind::Protection(measurement) = &packet_def.kind else { + return Err(DecodeError::WrongKind { id: compound_id }); + }; + + // `hora`/`min`/`seg`/`subseg` (1 byte each), then 2 bytes of `resv` + // padding that only exist to align `value` to an 8-byte offset — read + // and discarded, there's nowhere to put them in `ProtectionPacket`. + let mut header = [0u8; 6]; + reader.read_exact(&mut header)?; + let timestamp = ShortTimestamp { + hour: header[0], + minute: header[1], + second: header[2], + subsecond: header[3], + }; + + // Read the `value` bytes, whose length is determined by the measurement's wire type, and decode them into a `Value`. + let mut value_bytes = vec![0u8; wire::byte_width(&measurement.kind)]; + reader.read_exact(&mut value_bytes)?; + let value = wire::decode_value(&value_bytes, &measurement.kind)?; + + Ok(ProtectionPacket { + id: compound_id, + timestamp, + value, + }) +} + +/// Encodes a [`ProtectionPacket`] back into the bytes [`decode`] expects. +/// +/// Nothing in the real backend calls this — per the ADJ spec, protection +/// packets only ever travel board -> backend. This exists purely so +/// tests can build well-formed frames without hand-written byte arrays, +/// and to prove `decode` recovers exactly what was encoded. +/// +/// Like `decode`, doesn't write the leading compound id (`packet.id`) — +/// `decode` doesn't read it either, since that's resolved one level up, +/// by whatever dispatches to this function in the first place. +pub fn encode(packet: &ProtectionPacket, index: &Index) -> Result, EncodeError> { + let packet_def = index + .packet(packet.id) + .ok_or(EncodeError::UnknownId(packet.id))?; + + let PacketKind::Protection(measurement) = &packet_def.kind else { + return Err(EncodeError::WrongKind { id: packet.id }); + }; + + // `hora`/`min`/`seg`/`subseg` (1 byte each), then 2 bytes of `resv` + let header = [ + packet.timestamp.hour, + packet.timestamp.minute, + packet.timestamp.second, + packet.timestamp.subsecond, + 0, // resv — decode discards these, nothing to round-trip + 0, // resv + ]; + let mut bytes = header.to_vec(); + + bytes.extend(wire::encode_value(&packet.value, &measurement.kind)?); + + Ok(bytes) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::model::{ + AdjId, Board, BoardId, MacAddress, Measurement, MeasurementKind, NumericKind, PacketDef, + PodData, Value, + }; + use std::collections::HashMap; + use std::io::Cursor; + use std::net::IpAddr; + + fn sample_measurement(id: u16, kind: MeasurementKind) -> Measurement { + Measurement { + id: AdjId(id), + alias: "mock_alias".to_string(), + name: "Mock Measurement".to_string(), + display_units: String::new(), + kind, + protections: vec![], + } + } + + fn index_with_protection(measurement: Measurement, position: u16) -> (Index, AdjId) { + let compound_id = AdjId((position << 13) | measurement.id.0); + let packet = PacketDef { + id: compound_id, + board: BoardId(1), + name: "mock_protection".to_string(), + kind: PacketKind::Protection(measurement), + }; + let board = Board { + id: BoardId(1), + name: "MOCK".to_string(), + ip: IpAddr::from([127, 0, 0, 1]), + mac: MacAddress([0; 6]), + packets: HashMap::from([(packet.id, packet)]), + }; + let pod_data = PodData { + boards: HashMap::from([(board.id, board)]), + }; + (Index::new(&pod_data), compound_id) + } + + #[test] + fn decodes_a_numeric_protections_timestamp_and_value() { + let measurement = sample_measurement( + 100, + MeasurementKind::Numeric { + wire_type: NumericKind::F32, + }, + ); + let (index, compound_id) = index_with_protection(measurement, 1); + + let mut bytes = vec![12, 30, 5, 0, 0, 0]; // hora, min, seg, subseg, resv(2) + bytes.extend(53.2f32.to_le_bytes()); + let reader = Cursor::new(bytes); + + let Ok(packet) = decode(reader, compound_id, &index) else { + unreachable!("decoding a well-formed protection frame should succeed"); + }; + + assert_eq!(packet.id.measurement_id(), AdjId(100)); + assert_eq!(packet.id.protection_position(), 1); + assert_eq!(packet.timestamp.hour, 12); + assert_eq!(packet.timestamp.minute, 30); + assert_eq!(packet.timestamp.second, 5); + assert_eq!(packet.value, Value::Number(f64::from(53.2f32))); + } + + #[test] + fn unknown_compound_id_is_an_error() { + let measurement = sample_measurement( + 100, + MeasurementKind::Numeric { + wire_type: NumericKind::U8, + }, + ); + let (index, _) = index_with_protection(measurement, 1); + let unknown_id = AdjId((2 << 13) | 100); + + assert!(matches!( + decode(Cursor::new(vec![]), unknown_id, &index), + Err(DecodeError::UnknownId(id)) if id == unknown_id + )); + } + + #[test] + fn a_non_protection_packet_at_that_id_is_the_wrong_kind() { + let measurement = sample_measurement( + 200, + MeasurementKind::Numeric { + wire_type: NumericKind::U8, + }, + ); + let compound_id = AdjId(200); // pos = 0: a normal, non-protection id + let packet = PacketDef { + id: compound_id, + board: BoardId(1), + name: "mock_data".to_string(), + kind: PacketKind::Data(vec![measurement]), + }; + let board = Board { + id: BoardId(1), + name: "MOCK".to_string(), + ip: IpAddr::from([127, 0, 0, 1]), + mac: MacAddress([0; 6]), + packets: HashMap::from([(packet.id, packet)]), + }; + let pod_data = PodData { + boards: HashMap::from([(board.id, board)]), + }; + let index = Index::new(&pod_data); + + assert!(matches!( + decode(Cursor::new(vec![]), compound_id, &index), + Err(DecodeError::WrongKind { id }) if id == compound_id + )); + } + + #[test] + fn truncated_frame_is_unexpected_eof() { + let measurement = sample_measurement( + 100, + MeasurementKind::Numeric { + wire_type: NumericKind::U32, + }, + ); + let (index, compound_id) = index_with_protection(measurement, 1); + + // Header alone, no value bytes at all. + let reader = Cursor::new(vec![0u8; 6]); + + assert!(matches!( + decode(reader, compound_id, &index), + Err(DecodeError::Io(_)) + )); + } + + // --- ENCODE TESTS --- + + #[test] + fn encode_then_decode_round_trips_timestamp_and_value() { + let measurement = sample_measurement( + 100, + MeasurementKind::Numeric { + wire_type: NumericKind::F32, + }, + ); + let (index, compound_id) = index_with_protection(measurement, 1); + + let original = ProtectionPacket { + id: compound_id, + timestamp: ShortTimestamp { + hour: 12, + minute: 30, + second: 5, + subsecond: 0, + }, + value: Value::Number(f64::from(53.2f32)), + }; + + let Ok(bytes) = encode(&original, &index) else { + unreachable!("encoding a well-formed protection packet should succeed"); + }; + let Ok(decoded) = decode(Cursor::new(bytes), compound_id, &index) else { + unreachable!("decoding what we just encoded should succeed"); + }; + + assert_eq!(decoded, original); + } + + #[test] + fn encode_zeroes_the_reserved_bytes() { + let measurement = sample_measurement( + 100, + MeasurementKind::Numeric { + wire_type: NumericKind::U8, + }, + ); + let (index, compound_id) = index_with_protection(measurement, 1); + + let packet = ProtectionPacket { + id: compound_id, + timestamp: ShortTimestamp { + hour: 1, + minute: 2, + second: 3, + subsecond: 4, + }, + value: Value::Number(7.0), + }; + + let Ok(bytes) = encode(&packet, &index) else { + unreachable!("encoding a well-formed protection packet should succeed"); + }; + + assert_eq!(bytes[4], 0); + assert_eq!(bytes[5], 0); + } + + #[test] + fn encode_fails_on_unknown_id() { + let measurement = sample_measurement( + 100, + MeasurementKind::Numeric { + wire_type: NumericKind::U8, + }, + ); + let (index, _) = index_with_protection(measurement, 1); + let unknown_id = AdjId((2 << 13) | 100); + + let packet = ProtectionPacket { + id: unknown_id, + timestamp: ShortTimestamp { + hour: 0, + minute: 0, + second: 0, + subsecond: 0, + }, + value: Value::Number(0.0), + }; + + let Err(err) = encode(&packet, &index) else { + unreachable!("encoding an unknown id should fail"); + }; + assert_eq!(err, EncodeError::UnknownId(unknown_id)); + } + + #[test] + fn encode_fails_on_wrong_kind() { + let measurement = sample_measurement( + 200, + MeasurementKind::Numeric { + wire_type: NumericKind::U8, + }, + ); + let compound_id = AdjId(200); // pos = 0: a normal, non-protection id + let packet_def = PacketDef { + id: compound_id, + board: BoardId(1), + name: "mock_data".to_string(), + kind: PacketKind::Data(vec![measurement]), + }; + let board = Board { + id: BoardId(1), + name: "MOCK".to_string(), + ip: IpAddr::from([127, 0, 0, 1]), + mac: MacAddress([0; 6]), + packets: HashMap::from([(packet_def.id, packet_def)]), + }; + let pod_data = PodData { + boards: HashMap::from([(board.id, board)]), + }; + let index = Index::new(&pod_data); + + let packet = ProtectionPacket { + id: compound_id, + timestamp: ShortTimestamp { + hour: 0, + minute: 0, + second: 0, + subsecond: 0, + }, + value: Value::Number(0.0), + }; + + let Err(err) = encode(&packet, &index) else { + unreachable!("encoding the wrong packet kind should fail"); + }; + assert_eq!(err, EncodeError::WrongKind { id: compound_id }); + } + + #[test] + fn encode_bubbles_up_type_mismatch() { + let measurement = sample_measurement( + 100, + MeasurementKind::Numeric { + wire_type: NumericKind::U8, + }, + ); + let (index, compound_id) = index_with_protection(measurement, 1); + + let packet = ProtectionPacket { + id: compound_id, + timestamp: ShortTimestamp { + hour: 0, + minute: 0, + second: 0, + subsecond: 0, + }, + value: Value::Bool(true), + }; + + let Err(err) = encode(&packet, &index) else { + unreachable!("encoding a value of the wrong variant should fail"); + }; + assert_eq!(err, EncodeError::TypeMismatch); + } + + #[test] + fn encode_bubbles_up_out_of_range() { + let measurement = sample_measurement( + 100, + MeasurementKind::Numeric { + wire_type: NumericKind::U8, + }, + ); + let (index, compound_id) = index_with_protection(measurement, 1); + + let packet = ProtectionPacket { + id: compound_id, + timestamp: ShortTimestamp { + hour: 0, + minute: 0, + second: 0, + subsecond: 0, + }, + value: Value::Number(300.0), + }; + + let Err(err) = encode(&packet, &index) else { + unreachable!("encoding an out-of-range value should fail"); + }; + assert!(matches!(err, EncodeError::OutOfRange { .. })); + } } From 149be35ab50be950cfb59d97cc370b682d953208 Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Mon, 12 Oct 2026 21:28:58 +0200 Subject: [PATCH 082/225] fix(backend, git): fix implementation of list_remote_branches and branch_exists. Also add tests for new implementation --- backend/crates/core/src/git.rs | 8 +- backend/crates/core/src/git/repository.rs | 283 +++++++++++++++++----- 2 files changed, 229 insertions(+), 62 deletions(-) diff --git a/backend/crates/core/src/git.rs b/backend/crates/core/src/git.rs index f73566257..46c854cef 100644 --- a/backend/crates/core/src/git.rs +++ b/backend/crates/core/src/git.rs @@ -12,9 +12,7 @@ pub use update::update_adj; /// /// Five categories identify the failed operation and preserve its underlying /// error as [`std::error::Error::source`]. [`RepositoryError`] and [`CloneError`] -/// retain concrete `gix` causes and are boxed to keep this enum small. Only -/// [`RepositoryError::ReferenceItem`] uses a dynamically typed cause, as exposed -/// by the `gix` iterator. +/// retain concrete `gix` causes and are boxed to keep this enum small. /// /// A failed connectivity probe is not itself an error when cached ADJ exists. /// If no cache exists, the operation returns [`GitError::UnavailableOffline`]. @@ -24,8 +22,8 @@ pub enum GitError { #[error("ADJ path operation failed: {0}")] Path(#[source] std::io::Error), - /// Opening the repository or reading its references or HEAD failed. - /// An absent reference is not itself an error. + /// Opening the repository, reading HEAD, or querying local or remote refs failed. + /// A branch missing from a successful remote listing is not an error. #[error("ADJ repository operation failed: {0}")] Repository(#[source] Box), diff --git a/backend/crates/core/src/git/repository.rs b/backend/crates/core/src/git/repository.rs index b844c29e9..eeb8b2ff6 100644 --- a/backend/crates/core/src/git/repository.rs +++ b/backend/crates/core/src/git/repository.rs @@ -5,9 +5,8 @@ use tracing::{debug, instrument}; /// Concrete repository failures wrapped by [`GitError::Repository`]. /// -/// Variants identify the failed read operation and preserve the original `gix` -/// error as their source. Only [`RepositoryError::ReferenceItem`] has a dynamic -/// source because the reference iterator returns boxed errors. +/// Variants identify local reads or remote-reference queries and preserve the +/// original `gix` error as their source. #[derive(Debug, thiserror::Error)] pub enum RepositoryError { /// An existing repository could not be opened or validated. @@ -18,22 +17,21 @@ pub enum RepositoryError { #[error("HEAD could not be resolved: {0}")] Head(#[from] gix::reference::head_id::Error), - /// The repository's reference storage could not be opened. - #[error("reference storage could not be opened: {0}")] - References(#[from] gix::reference::iter::Error), + /// No default fetch remote could be determined, including ambiguous configurations. + #[error("no default fetch remote could be determined")] + NoDefaultRemote, - /// Iteration over cached remote-tracking references could not be initialized. - #[error("reference iteration could not be initialized: {0}")] - InitReferences(#[from] gix::reference::iter::init::Error), + /// The selected default remote could not be loaded from repository configuration. + #[error("default fetch remote could not be loaded: {0}")] + FindDefaultRemote(#[from] gix::remote::find::existing::Error), - /// An individual reference could not be read during iteration. - /// The boxed source retains its original type and error chain. - #[error("reference could not be read: {0}")] - ReferenceItem(#[from] Box), + /// A transport connection to the selected remote could not be prepared. + #[error("remote connection failed: {0}")] + RemoteConnect(#[from] gix::remote::connect::Error), - /// Looking up a reference failed; an absent reference is not an error. - #[error("reference lookup failed: {0}")] - FindReference(#[from] gix::reference::find::Error), + /// The remote handshake or query of advertised references failed. + #[error("remote reference query failed: {0}")] + RemoteRefMap(#[from] gix::remote::ref_map::Error), } /// Opens an existing repository without fetching or changing its checkout. @@ -55,59 +53,230 @@ pub fn open_repo(path: Option) -> Result { Ok(repo) } -/// Lists locally cached remote-tracking branches without contacting the remote. +/// Lists the branch names advertised by the repository's default fetch remote. /// -/// `path` identifies the repository directory. Names retain the remote prefix, -/// such as `origin/main`; the results can be stale, are not explicitly sorted, -/// and may include symbolic references such as `origin/HEAD`. +/// `repo` supplies the configuration used to select the default fetch remote. +/// Returns sorted short names such as `main` or `feature/example`, excluding tags +/// and `HEAD`. Queries the remote without downloading objects or updating local +/// references. Configured fetch refspecs do not limit the advertised branches. +/// This is a blocking operation and requires access to the remote. /// /// # Errors /// -/// Returns [`GitError::Repository`] if the repository cannot be opened or its -/// references cannot be read. -#[instrument(level = "debug", err(level = "warn"))] -pub fn list_remote_branches(path: PathBuf) -> Result, GitError> { - let repo = gix::open(&path).map_err(RepositoryError::from)?; - - let mut branches = Vec::new(); - - // Inspect local remote-tracking refs, not the remote server's advertised refs. - for reference in repo - .references() - .map_err(RepositoryError::from)? - .remote_branches() - .map_err(RepositoryError::from)? - { - let reference = reference.map_err(RepositoryError::from)?; - branches.push(reference.name().shorten().to_string()); - } +/// Returns [`GitError::Repository`] if no default remote can be determined, or +/// remote configuration, connection, or reference discovery fails. Does not fall +/// back to cached branches on failure. +#[instrument(level = "debug", skip(repo), err(level = "warn"))] +pub fn list_remote_branches(repo: &Repository) -> Result, GitError> { + let remote = repo + .find_default_remote(gix::remote::Direction::Fetch) + .ok_or(RepositoryError::NoDefaultRemote)? + .map_err(RepositoryError::from)?; + + debug!( + git_dir = ?repo.path(), + "querying branches advertised by the default fetch remote" + ); + let conexion = remote + .connect(gix::remote::Direction::Fetch) + .map_err(RepositoryError::from)?; + let (mapa, _handshake) = conexion + .ref_map( + gix::progress::Discard, + gix::remote::ref_map::Options { + // Protocol v2 must not restrict ls-refs to a single-branch refspec. + prefix_from_spec_as_filter_on_remote: false, + ..Default::default() + }, + ) + .map_err(RepositoryError::from)?; + + let mut ramas: Vec = mapa + .remote_refs + .iter() + .filter_map(|r| { + let (nombre, _, _) = r.unpack(); + nombre + .to_string() + .strip_prefix("refs/heads/") + .map(str::to_string) + }) + .collect(); + ramas.sort(); debug!( - ?path, - count = branches.len(), - "listed cached remote-tracking branches" + git_dir = ?repo.path(), + count = ramas.len(), + "listed advertised remote branches" ); - Ok(branches) + Ok(ramas) } -/// Checks whether a remote-tracking branch is cached in `repo`. +/// Checks whether the default fetch remote advertises the requested branch. /// -/// `remote` is the remote name, such as `origin`; `name` is the branch name, such -/// as `main` or `feature/example`. Looks up `refs/remotes//` without -/// contacting the server or checking local branches. `false` means the reference -/// is absent locally, not necessarily that the branch is absent on the server. +/// `repo` selects the remote and `name` is its exact short branch name, such as +/// `main` or `feature/example`, without an `origin/` prefix. Calls +/// [`list_remote_branches`] and returns `true` if the name is in the result. +/// `false` means the query succeeded but the remote did not advertise that name. +/// This is a blocking remote query, not a check of cached references. /// /// # Errors /// -/// Returns [`GitError::Repository`] if the reference name is invalid or the -/// reference cannot be read. A missing reference returns `Ok(false)`. -#[instrument(level = "debug", skip(repo), err(level = "warn"))] -pub fn branch_exists(repo: &gix::Repository, remote: &str, name: &str) -> Result { - let full = format!("refs/remotes/{remote}/{name}"); - let exists = repo - .try_find_reference(full.as_str()) - .map_err(RepositoryError::from)? - .is_some(); - debug!(reference = %full, exists, "checked cached remote-tracking branch"); +/// Propagates the original [`GitError`] from [`list_remote_branches`]. A missing +/// remote or failed connection is an error, never `Ok(false)`. +// The delegated listing logs failures; do not emit the same warning twice. +#[instrument(level = "debug", skip(repo))] +pub fn branch_exists(repo: &Repository, name: &str) -> Result { + let branches = list_remote_branches(repo)?; + let exists = branches.iter().any(|branch| branch == name); + debug!(name, exists, "checked advertised remote branch"); Ok(exists) } + +#[cfg(test)] +mod tests { + use super::*; + use std::{fs, io, path::Path, process::Command}; + + type TestResult = Result>; + + fn git(path: &Path, args: &[&str]) -> TestResult { + // Provide fixture identity and disable user signing, hooks, and templates. + let output = Command::new("git") + .current_dir(path) + .args([ + "-c", + "user.name=ADJ tests", + "-c", + "user.email=adj@example.test", + "-c", + "commit.gpgSign=false", + "-c", + "tag.gpgSign=false", + "-c", + "core.hooksPath=", + "-c", + "init.templateDir=", + ]) + .args(args) + .output()?; + if !output.status.success() { + return Err(io::Error::other(String::from_utf8_lossy(&output.stderr)).into()); + } + Ok(()) + } + + fn local_remote() -> TestResult<(tempfile::TempDir, Repository)> { + let temp = tempfile::tempdir()?; + let remote = temp.path().join("remote"); + let client = temp.path().join("client"); + fs::create_dir(&remote)?; + fs::create_dir(&client)?; + git(&remote, &["init", "--initial-branch=main"])?; + fs::write(remote.join("data.txt"), "ADJ fixture")?; + git(&remote, &["add", "."])?; + git(&remote, &["commit", "-m", "fixture data"])?; + git(&remote, &["branch", "software"])?; + git(&remote, &["branch", "feature/example"])?; + git(&remote, &["tag", "v1"])?; + + // No clone or fetch: only main is tracked, and no remote refs are cached. + git(&client, &["init", "--initial-branch=main"])?; + git( + &client, + &[ + "remote", + "add", + "-t", + "main", + "origin", + remote.to_str().ok_or("non-UTF-8 test path")?, + ], + )?; + // Exercise ls-refs prefix filtering rather than protocol v1's full advertisement. + git(&client, &["config", "protocol.version", "2"])?; + let repo = gix::open(&client)?; + Ok((temp, repo)) + } + + // List all advertised branches despite a main-only refspec, without fetching. + #[test] + fn lists_all_remote_branches_without_fetching() -> TestResult { + let (temp, repo) = local_remote()?; + assert_eq!( + list_remote_branches(&repo)?, + ["feature/example", "main", "software"] + ); + for name in ["feature/example", "main", "software"] { + let reference = format!("refs/remotes/origin/{name}"); + assert!(repo.try_find_reference(reference.as_str())?.is_none()); + } + let remote_commit = gix::open(temp.path().join("remote"))?.head_id()?.detach(); + assert!(repo.find_object(remote_commit).is_err()); + Ok(()) + } + + // Remote existence must not depend on having the branch cached locally. + #[test] + fn finds_uncached_remote_branch() -> TestResult { + let (_temp, repo) = local_remote()?; + assert!( + repo.try_find_reference("refs/remotes/origin/feature/example")? + .is_none() + ); + assert!(branch_exists(&repo, "feature/example")?); + Ok(()) + } + + // Only exact short names match after a successful remote query. + #[test] + fn rejects_missing_and_remote_prefixed_branch_names() -> TestResult { + let (_temp, repo) = local_remote()?; + assert!(!branch_exists(&repo, "missing-branch")?); + assert!(!branch_exists(&repo, "origin/main")?); + Ok(()) + } + + // Missing remote configuration is an explicit error for both helpers. + #[test] + fn propagates_missing_default_remote() -> TestResult { + let temp = tempfile::tempdir()?; + let repo = gix::init(temp.path())?; + for result in [ + list_remote_branches(&repo).map(|_| ()), + branch_exists(&repo, "main").map(|_| ()), + ] { + assert!(matches!(result, Err(GitError::Repository(error)) + if matches!(*error, RepositoryError::NoDefaultRemote))); + } + Ok(()) + } + + // An unreachable source must remain an error, not false or an empty listing. + #[test] + fn propagates_inaccessible_remote() -> TestResult { + let (temp, _) = local_remote()?; + let client = temp.path().join("client"); + let missing = temp.path().join("missing-remote"); + git( + &client, + &[ + "remote", + "set-url", + "origin", + missing.to_str().ok_or("non-UTF-8 test path")?, + ], + )?; + // Reopen to pick up the changed remote URL instead of the old config snapshot. + let repo = gix::open(&client)?; + for result in [ + list_remote_branches(&repo).map(|_| ()), + branch_exists(&repo, "main").map(|_| ()), + ] { + assert!(matches!(result, Err(GitError::Repository(error)) + if matches!(*error, + RepositoryError::RemoteConnect(_) | RepositoryError::RemoteRefMap(_)))); + } + Ok(()) + } +} From cda8fb6aa3acfbeb24f47141d69aaf9caf8d2b66 Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Mon, 12 Oct 2026 21:29:07 +0200 Subject: [PATCH 083/225] docs(backend, git): small changes in README --- backend/crates/core/src/git/README.md | 24 +++++++++++++----------- 1 file changed, 13 insertions(+), 11 deletions(-) diff --git a/backend/crates/core/src/git/README.md b/backend/crates/core/src/git/README.md index f2e3615ed..e06a8f6fe 100644 --- a/backend/crates/core/src/git/README.md +++ b/backend/crates/core/src/git/README.md @@ -1,8 +1,6 @@ # ADJ Git helpers -This module manages ADJ as an application-owned, replaceable data cache using -`gix`, with `tracing` for logging. It does not preserve local edits or commits -when updating online. +This module downloads and updates the local [ADJ repository](https://github.com/Hyperloop-UPV/adj) using [`gix`](https://crates.io/crates/gix), with [`tracing`](https://crates.io/crates/tracing) for logging. It supports branch selection and offline use of an existing local checkout. ## Workflow @@ -17,6 +15,8 @@ availability. ### Online +Online updates replace the local checkout and do not preserve local edits or commits. + - Shallow-clone the requested branch into a temporary directory beside ADJ. - Complete checkout and read its commit hash before touching the cache. - Move the old cache aside and install the new checkout. @@ -25,8 +25,8 @@ availability. - Remove the old cache after successful installation. A clone error leaves the old cache untouched and is returned directly; it does -not automatically fall back to offline operation. No fetch, merge, or branch -switch is needed because the checkout is replaced. +not automatically fall back to offline operation. No separate fetch of the +existing cache, merge, or branch switch is needed because the checkout is replaced. ### Offline @@ -38,9 +38,12 @@ The cached branch may differ from the requested branch when offline. ## Other Helpers - `open_repo` opens the custom or default repository path. -- `list_remote_branches` lists cached remote-tracking references, without making - a network request. Results can be stale and include the remote name. -- `branch_exists` checks for a cached `refs/remotes//` reference. +- `list_remote_branches(repo)` queries the default fetch remote and returns sorted short + branch names, without downloading objects or updating local references. It + requires remote access and does not fall back to cached branches on failure. +- `branch_exists(repo, name)` uses that listing to check an exact short branch + name. Query errors are propagated; `false` means a successful query did not + find the branch, not that the remote was unreachable. ## Limitations @@ -54,9 +57,8 @@ unreachable, or fail when GitHub is reachable. Public helpers return `GitError` with five categories: `Path`, `Repository`, `Clone`, `Replacement`, and `UnavailableOffline`. `RepositoryError` and `CloneError` group the concrete `gix` causes inside the corresponding categories. -Only individual reference-iteration errors retain a dynamic source, as exposed -by `gix`. If rollback fails, `Replacement` also retains the restoration error -and backup path for recovery. +If rollback fails, `Replacement` also retains the restoration error and backup +path for recovery. ## Verification From 7e632fbe688eb34b316b5e19c08c6a18c0343283 Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Mon, 12 Oct 2026 22:51:13 +0200 Subject: [PATCH 084/225] feat(backend, protection): optional id --- .../core/src/protocol/packet/protection.rs | 111 +++++++++++++----- 1 file changed, 80 insertions(+), 31 deletions(-) diff --git a/backend/crates/core/src/protocol/packet/protection.rs b/backend/crates/core/src/protocol/packet/protection.rs index af6eb53f5..b3d99b2d0 100644 --- a/backend/crates/core/src/protocol/packet/protection.rs +++ b/backend/crates/core/src/protocol/packet/protection.rs @@ -3,29 +3,45 @@ //! `encode`, purely so tests can build well-formed frames without //! hand-written byte arrays — nothing in the real backend calls it, since //! a protection never travels backend -> board. -//! Structure -//! ``` -//! | 0-1 | 2 | 3 | 4 | 5 | 6-9 | 10-13 | 14-17 | 18-21 | 22-25 | 26-29 | 30-33 | -//! |-------|-------|-------|-------|-------|-------|-------|-------| 30-33 | 34-37 | 38-41 | 42-45 | -//! | id | hora | min | seg | subseg| resv | resv | value | value | value | value | value | -//! | 34-37 | 38-41 | 42-45 | -//! |-------| 34-37 | 38-41 | 42-45 | -//! | value | value | value | -//! ``` //! +//! Wire structure (whole frame, including the leading id): +//! ```text +//! | byte(s) | 0-1 | 2 | 3 | 4 | 5 | 6-7 | 8.. | +//! |---------|-----|------|-----|-----|--------|------|--------------| +//! | field | id | hora | min | seg | subseg | resv | value | +//! ``` +//! `id` (2 bytes) is normally read by a TCP dispatcher before it even +//! knows to call [`decode`] (it needs the id first, to decide this is a +//! protection and not a message) — when that's the case, pass it as +//! `Some`, and `reader` should start right at byte 2 above. Otherwise +//! pass `None`: `reader` should then start at byte 0, id included, and +//! `decode` reads it itself — all of this frame's byte parsing stays in +//! this file either way, never split out into whatever dispatches here. +//! `resv` (2 bytes) only exists to align `value` to an 8-byte offset; +//! it's read and discarded, never stored. `value`'s width is whatever +//! [`crate::protocol::wire::byte_width`] says for the watched +//! measurement's kind — not fixed, unlike every other field here. use crate::model::{AdjId, PacketKind, ProtectionPacket, ShortTimestamp}; use crate::protocol::{DecodeError, EncodeError, Index, wire}; use std::io::Read; -/// Decodes a protection frame's remaining bytes, given the frame's -/// already-read compound id (`tcp::decode_next`'s job), resolving the -/// watched measurement's wire type against `index`. +/// Decodes a protection frame, resolving the watched measurement's wire +/// type against `index`. +/// +/// `compound_id`: `Some` if the caller already read it (see this +/// module's doc comment); `None` to have `decode` read it itself off +/// `reader`'s first 2 bytes. pub fn decode( mut reader: impl Read, - compound_id: AdjId, + compound_id: Option, index: &Index, ) -> Result { + let compound_id = match compound_id { + Some(id) => id, + None => read_id(&mut reader)?, + }; + // Look up the packet definition for this compound id, and ensure it's a // protection packet. If not, the frame is malformed and we can't decode it. let packet_def = index @@ -60,16 +76,22 @@ pub fn decode( }) } -/// Encodes a [`ProtectionPacket`] back into the bytes [`decode`] expects. +/// Reads a raw little-endian 16-bit id off the front of `reader`. The +/// one piece of byte parsing [`decode`]/[`encode`] share, so it only +/// lives here once instead of wherever else might need an `AdjId`. +fn read_id(reader: &mut impl Read) -> Result { + let mut bytes = [0u8; 2]; + reader.read_exact(&mut bytes)?; + Ok(AdjId(u16::from_le_bytes(bytes))) +} + +/// Encodes a [`ProtectionPacket`] back into the bytes [`decode`] expects +/// — a complete, self-contained frame, leading id included. /// /// Nothing in the real backend calls this — per the ADJ spec, protection /// packets only ever travel board -> backend. This exists purely so /// tests can build well-formed frames without hand-written byte arrays, /// and to prove `decode` recovers exactly what was encoded. -/// -/// Like `decode`, doesn't write the leading compound id (`packet.id`) — -/// `decode` doesn't read it either, since that's resolved one level up, -/// by whatever dispatches to this function in the first place. pub fn encode(packet: &ProtectionPacket, index: &Index) -> Result, EncodeError> { let packet_def = index .packet(packet.id) @@ -79,17 +101,17 @@ pub fn encode(packet: &ProtectionPacket, index: &Index) -> Result, Encod return Err(EncodeError::WrongKind { id: packet.id }); }; + let mut bytes = packet.id.0.to_le_bytes().to_vec(); // `hora`/`min`/`seg`/`subseg` (1 byte each), then 2 bytes of `resv` - let header = [ + // — decode discards these, nothing to round-trip. + bytes.extend([ packet.timestamp.hour, packet.timestamp.minute, packet.timestamp.second, packet.timestamp.subsecond, - 0, // resv — decode discards these, nothing to round-trip - 0, // resv - ]; - let mut bytes = header.to_vec(); - + 0, + 0, + ]); bytes.extend(wire::encode_value(&packet.value, &measurement.kind)?); Ok(bytes) @@ -152,7 +174,7 @@ mod tests { bytes.extend(53.2f32.to_le_bytes()); let reader = Cursor::new(bytes); - let Ok(packet) = decode(reader, compound_id, &index) else { + let Ok(packet) = decode(reader, Some(compound_id), &index) else { unreachable!("decoding a well-formed protection frame should succeed"); }; @@ -164,6 +186,30 @@ mod tests { assert_eq!(packet.value, Value::Number(f64::from(53.2f32))); } + #[test] + fn decode_reads_the_id_itself_when_not_given_one() { + let measurement = sample_measurement( + 100, + MeasurementKind::Numeric { + wire_type: NumericKind::F32, + }, + ); + let (index, compound_id) = index_with_protection(measurement, 1); + + // Full frame, id included — nobody's pre-read it for us. + let mut bytes = compound_id.0.to_le_bytes().to_vec(); + bytes.extend([12, 30, 5, 0, 0, 0]); // hora, min, seg, subseg, resv(2) + bytes.extend(53.2f32.to_le_bytes()); + + let Ok(packet) = decode(Cursor::new(bytes), None, &index) else { + unreachable!("decoding a well-formed protection frame should succeed"); + }; + + assert_eq!(packet.id, compound_id); + assert_eq!(packet.timestamp.hour, 12); + assert_eq!(packet.value, Value::Number(f64::from(53.2f32))); + } + #[test] fn unknown_compound_id_is_an_error() { let measurement = sample_measurement( @@ -176,7 +222,7 @@ mod tests { let unknown_id = AdjId((2 << 13) | 100); assert!(matches!( - decode(Cursor::new(vec![]), unknown_id, &index), + decode(Cursor::new(vec![]), Some(unknown_id), &index), Err(DecodeError::UnknownId(id)) if id == unknown_id )); } @@ -209,7 +255,7 @@ mod tests { let index = Index::new(&pod_data); assert!(matches!( - decode(Cursor::new(vec![]), compound_id, &index), + decode(Cursor::new(vec![]), Some(compound_id), &index), Err(DecodeError::WrongKind { id }) if id == compound_id )); } @@ -228,7 +274,7 @@ mod tests { let reader = Cursor::new(vec![0u8; 6]); assert!(matches!( - decode(reader, compound_id, &index), + decode(reader, Some(compound_id), &index), Err(DecodeError::Io(_)) )); } @@ -259,7 +305,9 @@ mod tests { let Ok(bytes) = encode(&original, &index) else { unreachable!("encoding a well-formed protection packet should succeed"); }; - let Ok(decoded) = decode(Cursor::new(bytes), compound_id, &index) else { + // `encode` writes the id too, so `decode` can read it back itself — + // proves the full frame round-trips, not just the body. + let Ok(decoded) = decode(Cursor::new(bytes), None, &index) else { unreachable!("decoding what we just encoded should succeed"); }; @@ -291,8 +339,9 @@ mod tests { unreachable!("encoding a well-formed protection packet should succeed"); }; - assert_eq!(bytes[4], 0); - assert_eq!(bytes[5], 0); + // bytes[0..2] = id, [2..6] = timestamp, [6..8] = resv. + assert_eq!(bytes[6], 0); + assert_eq!(bytes[7], 0); } #[test] From 57197879777782a5a4b551bb208f8136690cff73 Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Mon, 12 Oct 2026 23:04:59 +0200 Subject: [PATCH 085/225] fix(backend, adj-model): read messages id as a proper package --- backend/crates/core/src/adj/README.md | 26 ++++++++++++- backend/crates/core/src/adj/info.rs | 20 +++++++++- backend/crates/core/src/adj/raw/types.rs | 38 ++++++++++++++---- backend/crates/core/src/model/README.md | 7 ++++ backend/crates/core/src/model/packet.rs | 49 ++++++++++++++++++++++++ 5 files changed, 131 insertions(+), 9 deletions(-) diff --git a/backend/crates/core/src/adj/README.md b/backend/crates/core/src/adj/README.md index 33bdedb49..f1bda8b73 100644 --- a/backend/crates/core/src/adj/README.md +++ b/backend/crates/core/src/adj/README.md @@ -30,10 +30,34 @@ Adj └── info (AdjInfo) ├── ports: HashMap ├── addresses: HashMap - ├── message_ids: HashMap + ├── message_ids: HashMap -- name -> id, straight from the ADJ + ├── message_levels: HashMap -- id -> severity, the reverse └── protection_types: HashMap ``` +`message_ids` is the ADJ's own direction: a name (e.g. `"fault"`) to its +id. Not every entry is one of `model::MessageLevel`'s four severities — +other reserved names (e.g. `add_state_order`) share this same map. + +`message_levels` is the direction decoding actually needs: a wire id +(all a decoder ever has) straight to its severity, with no name in +between. It's the reverse of `message_ids`, restricted to whichever of +`MessageLevel::ALL`'s four names `message_ids` declares — built once in +`adj::raw::types`'s `TryFrom for AdjInfo`, right after +`message_ids` itself, so it can never drift out of sync with it: + +```rust +let message_levels: HashMap = MessageLevel::ALL + .into_iter() + .filter_map(|level| message_ids.get(level.name()).map(|&id| (id, level))) + .collect(); +``` + +Which ADJ name corresponds to which `MessageLevel` is **not** decided +here — `level.name()` (see `model/README.md` §4.4) is the one place +that association is spelled out, so `adj` doesn't hardcode +`"fault"`/`"warning"`/`"info"`/`"panic"` itself. + --- ## Why It Is Structured This Way diff --git a/backend/crates/core/src/adj/info.rs b/backend/crates/core/src/adj/info.rs index 62c17fa9c..57ddc175e 100644 --- a/backend/crates/core/src/adj/info.rs +++ b/backend/crates/core/src/adj/info.rs @@ -5,7 +5,7 @@ //! addresses, message-id conventions, and how to display a triggered //! protection. -use crate::model::{AdjId, Port}; +use crate::model::{AdjId, MessageLevel, Port}; use std::collections::HashMap; use std::net::IpAddr; @@ -34,7 +34,25 @@ pub struct AdjInfo { /// Known message ids, by name (e.g. `"fault"` -> `AdjId(2)`) — these /// live in the ADJ's own special reserved id range (`[0, 511]`, see /// [`AdjId`]'s own docs), not a separate numbering of their own. + /// This is the ADJ's own direction: a severity's *name* to its id. + /// Not every entry here is one of [`MessageLevel`]'s four severities + /// — other reserved names (e.g. `add_state_order`) share this same + /// map — see [`MessageLevel::name`] for which ones are. pub message_ids: HashMap, + /// The reverse of [`AdjInfo::message_ids`], and only for the four + /// entries that actually are a [`MessageLevel`]: a wire id straight + /// to its severity. + /// + /// Decoding a free-text log frame only ever has the raw id off the + /// wire, not its name — without this, every decoder would have to + /// search `message_ids` by value (or re-derive this same reverse + /// map itself) just to answer "which severity is id 2?". Built once + /// here, when the ADJ is loaded (see `adj::raw::types`'s + /// `TryFrom for AdjInfo`), + /// from `message_ids` and [`MessageLevel::ALL`]/[`MessageLevel::name`] + /// — never constructed by hand, and never out of sync with + /// `message_ids` since it's derived from it. + pub message_levels: HashMap, /// Declared protection types, by name (e.g. `"Range"`). pub protection_types: HashMap, } diff --git a/backend/crates/core/src/adj/raw/types.rs b/backend/crates/core/src/adj/raw/types.rs index 7b02ef51c..3942a3bc7 100644 --- a/backend/crates/core/src/adj/raw/types.rs +++ b/backend/crates/core/src/adj/raw/types.rs @@ -8,7 +8,8 @@ use crate::adj::error::{LoadError, MeasurementError, ProtectionError}; use crate::adj::info::{AdjInfo, ProtectionTypeInfo}; use crate::model::{ - AdjId, Measurement, MeasurementKind, NumericKind, Port, Protection, ProtectionKind, Severity, + AdjId, Measurement, MeasurementKind, MessageLevel, NumericKind, Port, Protection, + ProtectionKind, Severity, }; use serde::Deserialize; use std::collections::HashMap; @@ -100,6 +101,21 @@ impl TryFrom for AdjInfo { addresses.insert(name, addr); } + let message_ids: HashMap = raw + .message_ids + .into_iter() + .map(|(name, id)| (name, AdjId(id))) + .collect(); + + // The reverse of `message_ids`, restricted to the four names + // that are actually a `MessageLevel` — see `AdjInfo::message_levels`'s + // own doc comment for why this is worth precomputing here rather + // than leaving every caller to search `message_ids` by value. + let message_levels: HashMap = MessageLevel::ALL + .into_iter() + .filter_map(|level| message_ids.get(level.name()).map(|&id| (id, level))) + .collect(); + Ok(AdjInfo { ports: raw .ports @@ -107,11 +123,8 @@ impl TryFrom for AdjInfo { .map(|(name, port)| (name, Port(port))) .collect(), addresses, - message_ids: raw - .message_ids - .into_iter() - .map(|(name, id)| (name, AdjId(id))) - .collect(), + message_ids, + message_levels, protection_types: raw .protection_types .into_iter() @@ -488,7 +501,12 @@ mod tests { ports: HashMap::from([("TCP_SERVER".to_string(), 50500u16)]), addresses: HashMap::from([("backend".to_string(), "192.168.0.9".to_string())]), protection_types, - message_ids: HashMap::from([("fault".to_string(), 2u16)]), + message_ids: HashMap::from([ + ("fault".to_string(), 2u16), + // Not a `MessageLevel` — shares `message_ids` with the + // four severities, but shouldn't appear in `message_levels`. + ("add_state_order".to_string(), 5u16), + ]), }; let Ok(info) = AdjInfo::try_from(raw) else { @@ -498,7 +516,13 @@ mod tests { assert_eq!(info.ports["TCP_SERVER"], Port(50500)); assert_eq!(info.addresses["backend"], IpAddr::from([192, 168, 0, 9])); assert_eq!(info.message_ids["fault"], AdjId(2)); + assert_eq!(info.message_ids["add_state_order"], AdjId(5)); assert!(info.protection_types["Range"].is_range); + + // `message_levels` is the reverse of `message_ids`, but only for + // the one entry that's actually a `MessageLevel`. + assert_eq!(info.message_levels.len(), 1); + assert_eq!(info.message_levels[&AdjId(2)], MessageLevel::Fault); } #[test] diff --git a/backend/crates/core/src/model/README.md b/backend/crates/core/src/model/README.md index aa088648c..8d1e190d0 100644 --- a/backend/crates/core/src/model/README.md +++ b/backend/crates/core/src/model/README.md @@ -188,6 +188,13 @@ Informational message, no action implied. #### `Panic` An unrecoverable firmware error. +`MessageLevel` also exposes: +- `ALL: [MessageLevel; 4]` — every severity, for code that needs to go through each one (e.g. building a lookup from a loaded ADJ's `message_ids`). +- `name(self) -> &'static str` — this severity's key in `general_info.json`'s `message_ids` (`"fault"`, `"warning"`, `"info"`, `"panic"`). +- `from_name(name: &str) -> Option` — the inverse of `name()`; `None` if `name` isn't one of the four. + +This is deliberately where the name↔severity association lives — in `model`, not `adj` or `protocol` — since it's domain knowledge about the severity itself. `adj::AdjInfo::message_levels` (see `adj/README.md`) calls into `name()`/`ALL` to build its id→severity lookup rather than hardcoding `"fault"`/`"warning"`/`"info"`/`"panic"` itself. + ### 4.5 `MessagePacket` A free-text message sent by a board. diff --git a/backend/crates/core/src/model/packet.rs b/backend/crates/core/src/model/packet.rs index 56b9c60e8..d53c83df3 100644 --- a/backend/crates/core/src/model/packet.rs +++ b/backend/crates/core/src/model/packet.rs @@ -175,6 +175,41 @@ pub enum MessageLevel { Panic, } +impl MessageLevel { + /// All four severities, in no particular order — for code that needs + /// to go through each one, e.g. building a lookup from a loaded + /// ADJ's `general_info.json` `message_ids` (see [`MessageLevel::name`]). + pub const ALL: [MessageLevel; 4] = [ + MessageLevel::Fault, + MessageLevel::Warning, + MessageLevel::Info, + MessageLevel::Panic, + ]; + + /// This severity's key in `general_info.json`'s `message_ids` map + /// (ADJv3: `"fault"`, `"warning"`, `"info"`, `"panic"`). That map + /// only gives a severity's *name*, not which `MessageLevel` it is — + /// this is the one place that association is spelled out, so + /// nothing else has to hardcode these four strings again. + pub fn name(self) -> &'static str { + match self { + MessageLevel::Fault => "fault", + MessageLevel::Warning => "warning", + MessageLevel::Info => "info", + MessageLevel::Panic => "panic", + } + } + + /// The inverse of [`MessageLevel::name`]: the severity named `name`, + /// or `None` if `name` isn't one of the four (e.g. `general_info.json` + /// declares other, unrelated reserved names in that same map). + pub fn from_name(name: &str) -> Option { + MessageLevel::ALL + .into_iter() + .find(|level| level.name() == name) + } +} + /// A free-text message sent by a board. #[derive(Debug, Clone, PartialEq)] pub struct MessagePacket { @@ -273,6 +308,20 @@ mod tests { } } + #[test] + fn each_message_levels_name_matches_the_adj_and_is_distinct() { + let names: Vec<&str> = MessageLevel::ALL.iter().map(|level| level.name()).collect(); + assert_eq!(names, vec!["fault", "warning", "info", "panic"]); + } + + #[test] + fn from_name_is_the_inverse_of_name() { + for level in MessageLevel::ALL { + assert_eq!(MessageLevel::from_name(level.name()), Some(level)); + } + assert_eq!(MessageLevel::from_name("not_a_severity"), None); + } + #[test] fn data_packet_values_are_positional_not_tagged_with_an_id() { // values[0] is whatever measurements[0] is in this packet's From e3aa05ef6a9f13972f8565eec636c14ff0e672f0 Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Mon, 12 Oct 2026 23:26:07 +0200 Subject: [PATCH 086/225] fix(backend, adj, model): define messages packets in the same way as protections and datapackets --- backend/crates/core/src/adj/README.md | 24 ++++++++++--- backend/crates/core/src/adj/error.rs | 10 ++++++ backend/crates/core/src/adj/raw/loader.rs | 41 +++++++++++++++++++++-- backend/crates/core/src/model/README.md | 8 ++--- backend/crates/core/src/model/board.rs | 10 +++--- backend/crates/core/src/model/id.rs | 7 ++++ backend/crates/core/src/model/packet.rs | 11 ++++-- 7 files changed, 95 insertions(+), 16 deletions(-) diff --git a/backend/crates/core/src/adj/README.md b/backend/crates/core/src/adj/README.md index f1bda8b73..815cbb6e1 100644 --- a/backend/crates/core/src/adj/README.md +++ b/backend/crates/core/src/adj/README.md @@ -23,7 +23,10 @@ Adj │ └── boards: HashMap │ ├── measurements: HashMap │ └── packets: HashMap -│ ├── explicit (Data, Order, Message — declared in packets.json) +│ ├── explicit (Data, Order, Message — declared in packets.json; +│ │ a "message"-type packet's own `name` must be one of +│ │ MessageLevel::ALL's four severities, resolved via +│ │ MessageLevel::from_name — UnknownMessageSeverity if not) │ └── synthetic (Protection — one per declared protection, │ derived from each measurement's own `protections`; │ never declared directly in packets.json) @@ -54,9 +57,22 @@ let message_levels: HashMap = MessageLevel::ALL ``` Which ADJ name corresponds to which `MessageLevel` is **not** decided -here — `level.name()` (see `model/README.md` §4.4) is the one place -that association is spelled out, so `adj` doesn't hardcode -`"fault"`/`"warning"`/`"info"`/`"panic"` itself. +here — `level.name()`/`MessageLevel::from_name` (see `model/README.md` +§4.4) is the one place that association is spelled out, so `adj` +doesn't hardcode `"fault"`/`"warning"`/`"info"`/`"panic"` itself. + +**One layer up, `protocol::Index` is what actually turns +`message_levels` into something a decoder can look up a packet by.** +`Index::new(pod_data, message_levels)` takes `message_levels` as +`Option<&HashMap>` — `None` for callers with no +`AdjInfo` at all (most tests in this crate, which only build a bare +`PodData`) — and, for each entry, synthesizes a +`PacketDef { kind: PacketKind::Message(level), board: BoardId(0), .. }` +into the very same `AdjId -> PacketDef` table every other packet lives +in. `BoardId(0)` (reserved, not validated — see `AdjId`/`BoardId`'s own +docs) because a severity isn't owned by any one board — any board's +free-text log frame can reuse the same `"fault"` id. See +`protocol/README.md`'s `index.rs` section for the full picture. --- diff --git a/backend/crates/core/src/adj/error.rs b/backend/crates/core/src/adj/error.rs index 2f6d31764..53fcf1bed 100644 --- a/backend/crates/core/src/adj/error.rs +++ b/backend/crates/core/src/adj/error.rs @@ -85,6 +85,16 @@ pub enum LoadError { type_name: String, }, + /// A `"type": "message"` packet's `name` isn't one of + /// [`crate::model::MessageLevel`]'s four severities. + #[error("board {board:?}, packet {name:?}: not a known message severity")] + UnknownMessageSeverity { + /// The board declaring this message packet. + board: String, + /// The packet's name — the text that failed to match a severity. + name: String, + }, + /// A packet or order references a measurement alias that doesn't exist /// among that board's own measurements. #[error("board {board:?}, packet {name:?}: unknown measurement alias {alias:?}")] diff --git a/backend/crates/core/src/adj/raw/loader.rs b/backend/crates/core/src/adj/raw/loader.rs index 6f252d48c..53390d252 100644 --- a/backend/crates/core/src/adj/raw/loader.rs +++ b/backend/crates/core/src/adj/raw/loader.rs @@ -4,7 +4,7 @@ use super::types::{RawBoard, RawGeneralInfo, RawMeasurement, RawPacket}; use crate::adj::error::LoadError; use crate::adj::{Adj, AdjInfo}; use crate::model::{ - AdjId, Board, BoardId, MacAddress, Measurement, PacketDef, PacketKind, PodData, + AdjId, Board, BoardId, MacAddress, Measurement, MessageLevel, PacketDef, PacketKind, PodData, }; use serde::de::DeserializeOwned; use std::collections::HashMap; @@ -143,7 +143,16 @@ fn build_packet_def( &raw.variables, measurements, )?), - "message" => PacketKind::Message, + // The packet's own `name` must be one of `MessageLevel`'s four + // severities (`"fault"`/`"warning"`/`"info"`/`"panic"`) — that's + // the only way a `"message"`-type packet in `packets.json` says + // which severity it is; nothing else in its JSON shape does. + "message" => PacketKind::Message(MessageLevel::from_name(&raw.name).ok_or_else(|| { + LoadError::UnknownMessageSeverity { + board: board.to_string(), + name: raw.name.clone(), + } + })?), other => { return Err(LoadError::UnknownPacketType { board: board.to_string(), @@ -264,6 +273,34 @@ mod tests { )); } + #[test] + fn build_packet_def_resolves_a_message_packets_severity_from_its_name() { + let raw = RawPacket { + id: 2, + kind: "message".to_string(), + name: "fault".to_string(), + variables: vec![], + }; + let Ok(packet) = build_packet_def("VCU", BoardId(3), raw, &HashMap::new()) else { + unreachable!("\"fault\" is a known message severity"); + }; + assert_eq!(packet.kind, PacketKind::Message(MessageLevel::Fault)); + } + + #[test] + fn build_packet_def_rejects_a_message_whose_name_isnt_a_severity() { + let raw = RawPacket { + id: 2, + kind: "message".to_string(), + name: "not_a_severity".to_string(), + variables: vec![], + }; + assert!(matches!( + build_packet_def("VCU", BoardId(3), raw, &HashMap::new()), + Err(LoadError::UnknownMessageSeverity { .. }) + )); + } + #[test] fn loads_the_sample_adj_fixture() { let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("src/adj/test/adj"); diff --git a/backend/crates/core/src/model/README.md b/backend/crates/core/src/model/README.md index 8d1e190d0..eaa09367e 100644 --- a/backend/crates/core/src/model/README.md +++ b/backend/crates/core/src/model/README.md @@ -15,8 +15,8 @@ Telemetry sent by a board: one value per measurement, decoded positionally in th The single measurement one of a board's declared protections watches. Always exactly one — never a list. #### `Order(Vec)` An order sent to a board. Many orders take no parameters at all, so this can be empty. -#### `Message` -A free-text log line. Never carries measurement data. +#### `Message(MessageLevel)` +A free-text log line of this severity. Never carries measurement data — the severity is the only thing that tells one `Message` `PacketDef` apart from another. Lives here, on `PacketKind`, rather than as a separate field on `PacketDef`: a message's severity is as much part of "what kind of packet is this" as a `Data` packet's measurement list is. `PacketKind` also exposes a `measurements()` method that flattens any variant into a `&[Measurement]` slice, for code that just wants every measurement a packet references regardless of its kind. @@ -198,8 +198,8 @@ This is deliberately where the name↔severity association lives — in `model`, ### 4.5 `MessagePacket` A free-text message sent by a board. -#### `level` -How severe the message is (`MessageLevel`). +#### `id` +The wire id this message was sent under — one of the severities declared in `general_info.json`'s `message_ids`. Not a `MessageLevel` directly, the same way `ProtectionPacket::id` isn't a `Protection`: resolving it to a severity means looking it up (`PacketKind::Message`/`protocol::Index`), not storing a second, redundant copy of it here. #### `timestamp` When the message was sent (`ShortTimestamp`). #### `origin` diff --git a/backend/crates/core/src/model/board.rs b/backend/crates/core/src/model/board.rs index 18cef3c3e..b00e3a82c 100644 --- a/backend/crates/core/src/model/board.rs +++ b/backend/crates/core/src/model/board.rs @@ -10,7 +10,7 @@ //! left out rather than guessed — add them once the packet-level JSON //! shape is settled. -use super::{AdjId, BoardId, MacAddress, Measurement}; +use super::{AdjId, BoardId, MacAddress, Measurement, MessageLevel}; use std::collections::HashMap; use std::net::IpAddr; @@ -29,8 +29,10 @@ pub enum PacketKind { Protection(Measurement), /// A command sent to a board. Many orders take no parameters at all. Order(Vec), - /// A free-text log line. Never carries measurement data. - Message, + /// A free-text log line of this severity. Never carries measurement + /// data — the severity is the only thing that tells one `Message` + /// `PacketDef` apart from another. + Message(MessageLevel), } impl PacketKind { @@ -41,7 +43,7 @@ impl PacketKind { match self { PacketKind::Data(measurements) | PacketKind::Order(measurements) => measurements, PacketKind::Protection(measurement) => std::slice::from_ref(measurement), - PacketKind::Message => &[], + PacketKind::Message(_) => &[], } } } diff --git a/backend/crates/core/src/model/id.rs b/backend/crates/core/src/model/id.rs index a8278993d..948e71b98 100644 --- a/backend/crates/core/src/model/id.rs +++ b/backend/crates/core/src/model/id.rs @@ -31,6 +31,13 @@ impl AdjId { } /// Unique identifier of a board, defined by the ADJ. +/// +/// `BoardId(0)` is reserved: no real board uses it. [`crate::protocol::Index`] +/// uses it as the `board` for a synthesized [`super::PacketDef`] that +/// isn't owned by any one board at all — a message severity, a +/// session-wide id any board's free-text log frame can reuse. Not +/// validated anywhere; just a convention, the same way `0` is excluded +/// from [`AdjId`]'s own special range above. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub struct BoardId(pub u16); diff --git a/backend/crates/core/src/model/packet.rs b/backend/crates/core/src/model/packet.rs index d53c83df3..948d77834 100644 --- a/backend/crates/core/src/model/packet.rs +++ b/backend/crates/core/src/model/packet.rs @@ -213,8 +213,15 @@ impl MessageLevel { /// A free-text message sent by a board. #[derive(Debug, Clone, PartialEq)] pub struct MessagePacket { - /// How severe the message is. - pub level: MessageLevel, + /// The wire id this message was sent under — one of the severities + /// declared in `general_info.json`'s `message_ids`. + /// + /// Not a [`MessageLevel`] directly, the same way [`ProtectionPacket::id`] + /// isn't a [`super::Protection`]: this is what was actually on the + /// wire, and resolving it to a severity means looking it up (see + /// [`PacketKind::Message`]/[`crate::protocol::Index`]), not storing + /// a second, redundant copy of it here. + pub id: AdjId, /// When it was sent. pub timestamp: ShortTimestamp, /// Where it came from, e.g. a source file path. From cfa789cb909f615be79eb2edbdbfb12923c1d031 Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Mon, 12 Oct 2026 23:56:12 +0200 Subject: [PATCH 087/225] feat(backend, protocol): allow index to index packets --- backend/crates/core/src/protocol/index.rs | 64 ++++++++++++++++--- .../core/src/protocol/packet/data_order.rs | 2 +- .../core/src/protocol/packet/protection.rs | 6 +- 3 files changed, 60 insertions(+), 12 deletions(-) diff --git a/backend/crates/core/src/protocol/index.rs b/backend/crates/core/src/protocol/index.rs index c23397bf8..117802a3a 100644 --- a/backend/crates/core/src/protocol/index.rs +++ b/backend/crates/core/src/protocol/index.rs @@ -1,10 +1,11 @@ //! The `id -> PacketDef` lookup `tcp`/`udp` decode against. -use crate::model::{AdjId, PacketDef, PodData}; +use crate::model::{AdjId, BoardId, MessageLevel, PacketDef, PacketKind, PodData}; use std::collections::HashMap; /// A lookup table from a packet's [`AdjId`] to its declaration, built once -/// from a loaded ADJ's [`PodData`]. +/// from a loaded ADJ's [`PodData`] — and, optionally, its message +/// severities too. /// /// Owns its own copy of every [`PacketDef`] (cloned out of `PodData` at /// construction) rather than borrowing, so it carries no lifetime and can @@ -19,18 +20,47 @@ pub struct Index { impl Index { /// Builds an index over every packet declared by every board in - /// `pod_data`. - pub fn new(pod_data: &PodData) -> Self { - let by_id = pod_data + /// `pod_data`, plus one synthesized [`PacketDef`] per entry in + /// `message_levels` (an ADJ's `general_info.json`-derived + /// [`crate::adj::AdjInfo::message_levels`]). + /// + /// `message_levels` is `Option` rather than a plain reference so + /// that callers with no [`crate::adj::AdjInfo`] at hand — most tests + /// in this crate, which only ever build a bare [`PodData`] — can + /// just pass `None` instead of having to construct an empty map. + /// + /// A message severity isn't declared by any one board (any board's + /// free-text log frame can reuse the same `"fault"` id), so its + /// synthesized `PacketDef` gets the reserved `BoardId(0)` — no real + /// board uses that id — instead of a real one. + pub fn new(pod_data: &PodData, message_levels: Option<&HashMap>) -> Self { + let mut by_id: HashMap = pod_data .boards .values() .flat_map(|board| board.packets.values()) .map(|packet| (packet.id, packet.clone())) .collect(); + + if let Some(message_levels) = message_levels { + for (&id, &level) in message_levels { + by_id.insert( + id, + PacketDef { + id, + board: BoardId(0), + name: level.name().to_string(), + kind: PacketKind::Message(level), + }, + ); + } + } + Self { by_id } } - /// Looks up a packet's declaration by id. + /// Looks up a packet's declaration by id — a message severity + /// resolves through here too, as a synthesized `PacketDef` with + /// `kind: PacketKind::Message(level)`; see this type's doc comment. pub fn packet(&self, id: AdjId) -> Option<&PacketDef> { self.by_id.get(&id) } @@ -63,7 +93,7 @@ mod tests { #[test] fn finds_a_packet_declared_on_any_board() { - let index = Index::new(&sample_pod_data()); + let index = Index::new(&sample_pod_data(), None); let Some(packet) = index.packet(AdjId(1000)) else { unreachable!("packet 1000 was declared in the sample pod data"); }; @@ -72,7 +102,25 @@ mod tests { #[test] fn unknown_id_is_not_found() { - let index = Index::new(&sample_pod_data()); + let index = Index::new(&sample_pod_data(), None); assert!(index.packet(AdjId(9999)).is_none()); } + + #[test] + fn a_message_severity_resolves_as_a_synthesized_packet_def() { + let message_levels = HashMap::from([(AdjId(2), MessageLevel::Fault)]); + let index = Index::new(&sample_pod_data(), Some(&message_levels)); + + let Some(packet) = index.packet(AdjId(2)) else { + unreachable!("the \"fault\" severity was declared at id 2"); + }; + assert_eq!(packet.kind, PacketKind::Message(MessageLevel::Fault)); + assert_eq!(packet.board, BoardId(0)); + } + + #[test] + fn with_no_message_levels_given_only_board_packets_resolve() { + let index = Index::new(&sample_pod_data(), None); + assert_eq!(index.packet(AdjId(2)), None); + } } diff --git a/backend/crates/core/src/protocol/packet/data_order.rs b/backend/crates/core/src/protocol/packet/data_order.rs index d4643a050..c01971d35 100644 --- a/backend/crates/core/src/protocol/packet/data_order.rs +++ b/backend/crates/core/src/protocol/packet/data_order.rs @@ -156,7 +156,7 @@ mod tests { let pod_data = PodData { boards: HashMap::from([(board.id, board)]), }; - Index::new(&pod_data) + Index::new(&pod_data, None) } // --- ENCODE TESTS --- diff --git a/backend/crates/core/src/protocol/packet/protection.rs b/backend/crates/core/src/protocol/packet/protection.rs index b3d99b2d0..29d171356 100644 --- a/backend/crates/core/src/protocol/packet/protection.rs +++ b/backend/crates/core/src/protocol/packet/protection.rs @@ -157,7 +157,7 @@ mod tests { let pod_data = PodData { boards: HashMap::from([(board.id, board)]), }; - (Index::new(&pod_data), compound_id) + (Index::new(&pod_data, None), compound_id) } #[test] @@ -252,7 +252,7 @@ mod tests { let pod_data = PodData { boards: HashMap::from([(board.id, board)]), }; - let index = Index::new(&pod_data); + let index = Index::new(&pod_data, None); assert!(matches!( decode(Cursor::new(vec![]), Some(compound_id), &index), @@ -397,7 +397,7 @@ mod tests { let pod_data = PodData { boards: HashMap::from([(board.id, board)]), }; - let index = Index::new(&pod_data); + let index = Index::new(&pod_data, None); let packet = ProtectionPacket { id: compound_id, From cc65fbef2ab669ee88c3a69b346464e7d6bbfa63 Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Mon, 12 Oct 2026 23:59:03 +0200 Subject: [PATCH 088/225] feat(backend, protocol): messages decode & encode --- backend/crates/core/src/protocol/README.md | 102 +++- backend/crates/core/src/protocol/error.rs | 18 + backend/crates/core/src/protocol/packet.rs | 19 +- .../crates/core/src/protocol/packet/README.md | 90 ++++ .../core/src/protocol/packet/message.rs | 459 +++++++++++++++++- 5 files changed, 648 insertions(+), 40 deletions(-) create mode 100644 backend/crates/core/src/protocol/packet/README.md diff --git a/backend/crates/core/src/protocol/README.md b/backend/crates/core/src/protocol/README.md index 1d81566f4..a62b38c26 100644 --- a/backend/crates/core/src/protocol/README.md +++ b/backend/crates/core/src/protocol/README.md @@ -30,8 +30,8 @@ protocol/ ├── wire.rs # Low-level byte ↔ value conversion ├── packet.rs # Packet-level encoding/decoding module │ ├── data_order.rs # Data (telemetry) & Order (command) packets -│ ├── message.rs # Free-text log message packets (stub) -│ └── protection.rs # Protection trigger packets (stub) +│ ├── message.rs # Free-text log message packets +│ └── protection.rs # Protection trigger packets ├── tcp.rs # TCP transport framing (stub) └── udp.rs # UDP transport framing ``` @@ -42,8 +42,14 @@ protocol/ Provides a fast lookup table from packet IDs (`AdjId`) to their declarations (`PacketDef`). Built once from loaded ADJ configuration data (`PodData`), it owns cloned copies of packet definitions so it can be shared across async tasks via `Arc`. +A message severity is not a separate lookup bolted onto `Index` — it's just another `PacketDef`. `Index::new(pod_data, message_levels)` takes `message_levels` as `Option<&HashMap>` (an ADJ's `adj::AdjInfo::message_levels` — `None` for callers with no `AdjInfo` at all, e.g. most tests here) and, for each entry, synthesizes a `PacketDef { kind: PacketKind::Message(level), board: BoardId(0), .. }` into the very same `AdjId -> PacketDef` table as every board's own packets. `BoardId(0)` (reserved, not validated — see `AdjId`/`BoardId`'s own docs) because a severity isn't owned by any one board. Resolving a message is then `Index::packet(id)` + matching `PacketKind::Message(level)`, exactly like `packet::protection` already does for `PacketKind::Protection`. + **Key types:** -- `Index` - HashMap-based lookup from `AdjId` to `PacketDef` +- `Index` - HashMap-based lookup from `AdjId` to `PacketDef` (synthesized `Message` entries included) + +**Key functions:** +- `Index::new(pod_data, message_levels)` - Build an index from a loaded ADJ's `PodData` and, optionally, its `AdjInfo::message_levels` +- `Index::packet(id)` - Look up a packet's declaration by id — `Data`, `Order`, `Protection` or `Message` alike ### `error.rs` - Error Types @@ -56,6 +62,7 @@ Defines errors that can occur during packet encoding and decoding. - `Io` - I/O error reading from stream (TCP only) - `InvalidEnumValue` - Enum index out of range - `UnterminatedString` - String field not null-terminated + - `InvalidUtf8` - String field's bytes weren't valid UTF-8 - `WrongKind` - Packet exists but isn't expected kind - `EncodeError` - Errors when converting packets to bytes @@ -64,6 +71,8 @@ Defines errors that can occur during packet encoding and decoding. - `TypeMismatch` - Value doesn't match declared type - `OutOfRange` - Numeric value doesn't fit wire type - `WrongKind` - Packet exists but isn't expected kind + - `StringTooLong` - String field + terminator doesn't fit the max length + - `EmbeddedNulByte` - String field contains a `\0` byte ### `wire.rs` - Low-Level Byte Codec @@ -77,29 +86,73 @@ Handles conversion between raw bytes and `Value` types for individual measuremen **Supported types:** - **Numeric** (U8, U16, U32, U64, I8, I16, I32, I64, F32, F64) - ✓ Implemented - **Enum** (single byte index) - ✓ Implemented -- **Boolean** - ⚠ Stub (wire width not yet confirmed with firmware) +- **Boolean** (single byte, zero = `false`, nonzero = `true`) - ✓ Implemented ### `packet/` - Packet-Level Encoding/Decoding -Contains per-packet-kind encoding and decoding logic, independent of transport. +Contains per-packet-kind encoding and decoding logic, independent of +transport. **Hard rule for this directory: all byte-level parsing for a +packet kind lives in its own file here, never in `tcp.rs`/`udp.rs`.** +See **[`packet/README.md`](packet/README.md)** for the full design +rationale (the `Option` pattern below, and exactly what `tcp.rs` +is and isn't allowed to do). #### `data_order.rs` -Handles two packet kinds: -- **Order packets** (commands sent to boards) - Encoded only, sent over TCP -- **Data packets** (periodic telemetry from boards) - Decoded only, received over UDP +Handles the positional Data/Order wire shape shared by both packet kinds +(see `model::DataOrderPacket`'s phantom `Kind`). `encode`/`decode` are +generic over `Kind`, written once for both: +- **Order packets** (commands sent to boards) - sent over TCP +- **Data packets** (periodic telemetry from boards) - received over UDP + +Self-contained both ways: they always read/write the leading 2-byte id +themselves (there's no dispatch ambiguity to resolve first here). The +backend itself only ever calls `encode` with an Order packet (via +`tcp::encode_order`) and `decode::` (via `udp::decode_datagram`) - +that direction restriction lives at the transport layer, not here. **Key functions:** -- `encode(order, index)` - Encode an Order packet into bytes -- `decode(bytes, index)` - Decode a Data packet from bytes +- `encode(packet, index)` - Encode a Data or Order packet into bytes (`Kind` inferred from `packet`'s type) +- `decode::(bytes, index)` - Decode bytes into a Data or Order packet + +#### `message.rs` + +Decodes free-text log messages from boards over TCP (decode only — in +production this only ever travels board → backend). `encode` also +exists, but purely for test symmetry; nothing in the real backend calls +it. + +Unlike `data_order.rs`, a TCP dispatcher needs this frame's leading id +*before* it even knows to call this file (to tell a message apart from +a protection) — so, same as `protection.rs`, `id` is `Option`: +`Some` if the caller already read it (and `reader` starts right after +the id), `None` to have `decode` read it itself. Either way, `id` is +resolved against `index` to confirm it's actually a declared +`PacketKind::Message` (`UnknownId`/`WrongKind` otherwise) — but unlike +`protection.rs`, the severity itself is never stored on the decoded +`MessagePacket`; it's metadata about the id, not about this particular +instance, so look it up again via `index.packet(id)` if it's needed. -#### `message.rs` ⚠ Stub +**Key functions:** +- `decode(reader, id: Option, index)` - Decode a message frame, resolving its id itself if not given one +- `encode(packet, index)` - Test-only: encode a complete `MessagePacket` frame, id included + +#### `protection.rs` -Decodes free-text log messages from boards over TCP. Not yet implemented. +Decodes protection trigger events from boards over TCP (decode only — +in production this only ever travels board → backend). `encode` also +exists, but purely for test symmetry; nothing in the real backend calls +it. -#### `protection.rs` ⚠ Stub +Same `Option` pattern as `message.rs`, for the same reason: a TCP +dispatcher needs the leading id first to tell a protection apart from a +message. `compound_id: Option` - `Some` if the caller already +read it, `None` to have `decode` read it itself off `reader`'s first 2 +bytes. -Decodes protection trigger events from boards over TCP. Not yet implemented. +**Key functions:** +- `decode(reader, compound_id: Option, index)` - Decode a protection frame, resolving its id itself if not given one +- `encode(packet, index)` - Test-only: encode a complete `ProtectionPacket` frame, id included ### `tcp.rs` - TCP Transport Framing ⚠ Partial @@ -128,8 +181,8 @@ Handles the shared UDP socket for periodic telemetry. UDP datagrams are complete |-------------|-----------|-----------|--------| | Data (telemetry) | Board → Backend | UDP | ✓ Implemented | | Order (command) | Backend → Board | TCP | ✓ Implemented | -| Message (log) | Board → Backend | TCP | ⚠ Stub | -| Protection (event) | Board → Backend | TCP | ⚠ Stub | +| Message (log) | Board → Backend | TCP | ✓ Implemented (decode is the only real direction; `encode` is test-only) | +| Protection (event) | Board → Backend | TCP | ✓ Implemented (decode is the only real direction; `encode` is test-only) | ## Implementation Status @@ -137,19 +190,20 @@ Handles the shared UDP socket for periodic telemetry. UDP datagrams are complete - ✅ **Order packets** - Full encode/decode with tests - ✅ **Wire-level numeric types** - All numeric kinds supported with tests - ✅ **Wire-level enum types** - Full encode/decode with tests -- ⚠️ **Wire-level boolean types** - Stub (awaiting firmware confirmation) -- ⚠️ **Message packets** - Stub (decode not implemented) -- ⚠️ **Protection packets** - Stub (decode not implemented) +- ✅ **Wire-level boolean types** - Single byte, confirmed with firmware +- ✅ **Message packets** - decode implemented, with tests (encode exists for test symmetry only) +- ✅ **Protection packets** - decode implemented, with tests (encode exists for test symmetry only) - ⚠️ **TCP framing** - Partial (decode_next not implemented) ## Testing The module includes comprehensive unit tests for: -- Wire-level encoding/decoding for all numeric types -- Enum encoding/decoding with boundary checks -- Order packet encoding with field validation -- Data packet decoding with error handling -- Error propagation for unknown IDs, wrong kinds, and type mismatches +- Wire-level encoding/decoding for all numeric, boolean and enum types +- Order/Data packet encoding and decoding, including round trips +- Message/Protection packet decoding (timestamps, strings, values) and + their test-only encoding, including round trips +- Error propagation for unknown IDs, wrong kinds, type mismatches, + unterminated/invalid strings, and out-of-range values Run tests with: ```bash diff --git a/backend/crates/core/src/protocol/error.rs b/backend/crates/core/src/protocol/error.rs index 1ffd3b638..b08a065a6 100644 --- a/backend/crates/core/src/protocol/error.rs +++ b/backend/crates/core/src/protocol/error.rs @@ -36,6 +36,10 @@ pub enum DecodeError { max: usize, }, + /// A free-text field's bytes weren't valid UTF-8. + #[error("string field wasn't valid UTF-8: {0:?}")] + InvalidUtf8(Vec), + /// A looked-up packet exists, but isn't the kind this function expects /// (e.g. `packet::data::decode` found an id that resolves to an /// `Order`). @@ -65,6 +69,7 @@ impl PartialEq for DecodeError { }, ) => a_index == b_index && a_options == b_options, (Self::UnterminatedString { max: a }, Self::UnterminatedString { max: b }) => a == b, + (Self::InvalidUtf8(a), Self::InvalidUtf8(b)) => a == b, (Self::WrongKind { id: a }, Self::WrongKind { id: b }) => a == b, _ => false, } @@ -114,4 +119,17 @@ pub enum EncodeError { /// The packet whose kind didn't match. id: AdjId, }, + + /// A string field's content plus its terminator wouldn't fit in the + /// wire format's maximum length. + #[error("string content plus its terminator doesn't fit in {max} byte(s)")] + StringTooLong { + /// The field's maximum length, terminator included. + max: usize, + }, + + /// A string field contains an embedded NUL byte, which would be + /// misread as an early terminator on the wire. + #[error("string contains an embedded NUL byte")] + EmbeddedNulByte, } diff --git a/backend/crates/core/src/protocol/packet.rs b/backend/crates/core/src/protocol/packet.rs index 7f357df8f..11b2847a8 100644 --- a/backend/crates/core/src/protocol/packet.rs +++ b/backend/crates/core/src/protocol/packet.rs @@ -1,10 +1,19 @@ //! Encode/decode for one specific kind of packet, independent of which //! transport carries it — that mapping lives in [`super::tcp`]/ -//! [`super::udp`], which are thin wrappers around these. Each kind only -//! implements whichever direction it actually needs: a `Data` packet is -//! only ever received (over UDP), an `Order` only ever sent (over TCP), -//! so there's no `encode` for the former or `decode` for the latter. +//! [`super::udp`], which are thin wrappers around these. +//! +//! [`data_order`]'s `encode`/`decode` are generic over `Kind` +//! ([`crate::model::KindTag`]), so they work for both `Data` and `Order` +//! alike; the backend itself only ever exercises one direction per kind +//! (an order is only ever sent, data only ever received), but that's a +//! restriction `tcp`/`udp` apply, not something baked into the codec. +//! +//! [`message`]/[`protection`] are genuinely one-directional in +//! production — a board only ever sends these, never receives them — +//! but both also expose an `encode`, purely so tests can build +//! well-formed frames without hand-written byte arrays; see each +//! module's own doc comment. +pub mod data_order; pub mod message; pub mod protection; -pub mod data_order; diff --git a/backend/crates/core/src/protocol/packet/README.md b/backend/crates/core/src/protocol/packet/README.md new file mode 100644 index 000000000..fce1586c9 --- /dev/null +++ b/backend/crates/core/src/protocol/packet/README.md @@ -0,0 +1,90 @@ +# `packet/` — Per-Packet-Kind Codecs + +Each file here owns **all** the byte-level parsing for one packet kind — +how many bytes a field takes, in what order, what terminates a string, +what the leading id means. That parsing never gets split out into +`tcp.rs`/`udp.rs` (the transport layer) or anywhere else. A transport +module is only ever allowed to do the one thing it structurally has no +choice about — see "The dispatcher's one unavoidable read" below — and +then hands the rest straight to one of these files. + +## `data_order.rs` + +Self-contained both ways: `encode`/`decode` always read/write the +leading 2-byte id themselves, since there's no dispatch ambiguity to +resolve first — a UDP datagram is unambiguously `Data`, and an order is +only ever something the backend already decided to send. Generic over +`Kind` (`model::KindTag`), written once for both `Data` and `Order` — +see its own module doc and `model/README.md`'s §4.2 for why. + +## `message.rs` / `protection.rs` + +These two are different: over TCP, a `Protection` frame and a `Message` +frame share the same leading 16-bit id space, so **something** has to +read that id before it even knows which of the two decoders to call. +That something is `tcp::decode_next` (still unimplemented). To keep that +reality from leaking actual decoding logic into `tcp.rs`, both files +take their id as `Option` — the exact same shape: + +```rust +// protection.rs +pub fn decode(reader: impl Read, compound_id: Option, index: &Index) -> Result; +pub fn encode(packet: &ProtectionPacket, index: &Index) -> Result, EncodeError>; + +// message.rs +pub fn decode(reader: impl Read, id: Option, index: &Index) -> Result; +pub fn encode(packet: &MessagePacket, index: &Index) -> Result, EncodeError>; +``` + +- **`Some(known_value)`** — the caller already read it, typically + because it had to read the leading id anyway to decide which of these + two functions to call in the first place. In this case `reader` must + already be positioned *right after* the id (byte 2 onward). +- **`None`** — the caller doesn't know it and isn't going to try. In + this case `reader` must start at byte 0 of the frame, id included, and + `decode` reads those 2 bytes itself. Either way, the id is then + resolved against `index` — `index.packet(id)` + matching + `PacketKind::Protection`/`PacketKind::Message` — to confirm it's + actually the declared kind (`UnknownId`/`WrongKind` otherwise). A + message's severity is just another `PacketDef` by the time it gets + here (see `index.rs`'s own docs) — there's no separate lookup for it. + +One real difference between the two: `ProtectionPacket` stores its +`id` *and* the triggering `value` (which needs the watched measurement's +wire type, from `PacketKind::Protection(measurement)`, to decode at +all). `MessagePacket` only stores `id` — its severity is metadata +*about* that id, not part of the frame's own byte layout, so `decode` +only uses `PacketKind::Message(level)` to confirm the kind and discards +`level` immediately; nothing about `timestamp`/`origin`/`message`'s +bytes depends on which severity it is. Look the severity up again via +`index.packet(id)` if it's needed later — it's never stored redundantly +on the decoded instance. + +Either way, **every byte of this frame is parsed inside the file that +owns that packet kind** — `tcp.rs` never touches a timestamp, a `resv` +byte, a measurement's wire width, or a NUL-terminated string. `encode` +always writes the leading id back out too (from `packet.id`, after +confirming via `index` it resolves to the right kind), so its output is +a complete, self-contained frame — feed it straight into +`decode(reader, None, index)` and get the same packet back; that's +exactly what each file's round-trip test does. + +### The dispatcher's one unavoidable read + +`tcp::decode_next` still has to read the raw 2-byte id itself once, to +decide *which* of `protection::decode`/`message::decode` to call — there +is no way around this for a non-seekable stream: once those bytes are +consumed, there's no handing them to the other function's `None` path +instead. That single mechanical "read a `u16`" is the one piece of +byte-handling that's expected to exist in `tcp.rs`. It is not decoding — +nothing is validated or interpreted by it beyond "is the top bit of +`AdjId::protection_position()` set" — and its result is immediately +handed to the matching function as `Some(id)`, which then resolves it +against `index` itself and does everything else. + +## Tests + +Every file's test module proves both `Some` and `None` work, plus a +round trip through its own `encode`/`decode` (`protection.rs`, +`message.rs`) or through `encode::`/`decode::` +(`data_order.rs`). See each file's own tests for the exact byte layouts. diff --git a/backend/crates/core/src/protocol/packet/message.rs b/backend/crates/core/src/protocol/packet/message.rs index 88f70bd9c..eb9f1986b 100644 --- a/backend/crates/core/src/protocol/packet/message.rs +++ b/backend/crates/core/src/protocol/packet/message.rs @@ -1,16 +1,453 @@ //! Decodes a `Message` packet: a board's free-text log line. Only ever -//! received, over TCP. +//! received, over TCP. Also provides `encode`, purely so tests can build +//! well-formed frames without hand-written byte arrays — nothing in the +//! real backend calls it, since a message never travels backend -> board. +//! +//! Wire structure (whole frame, including the leading id): +//! ```text +//! | byte(s) | 0-1 | 2 | 3 | 4 | 5 | 6.. | .. | +//! |---------|-----|------|-----|-----|--------|-----------|-----------| +//! | field | id | hora | min | seg | subseg | origin\0 | message\0 | +//! ``` +//! `id` (2 bytes) is normally read by a TCP dispatcher before it even +//! knows to call [`decode`] (it needs the id first, to decide this is a +//! message and not a protection) — when that's the case, pass it as +//! `Some`, and `reader` should start right at byte 2 above. Otherwise +//! pass `None`: `reader` should then start at byte 0, id included, and +//! `decode` reads it itself — all of this frame's byte parsing stays in +//! this file either way, never split out into whatever dispatches here. +//! Unlike [`super::protection`], there's no `resv` padding — the +//! timestamp is followed directly by `origin`, a NUL-terminated string +//! of at most `ORIGIN_MAX` bytes (terminator included), then `message`, +//! at most `MESSAGE_MAX` bytes the same way. Both are variable-length — +//! there's no fixed byte range for either. +//! +//! Unlike [`super::protection`] too, [`MessagePacket`] doesn't carry its +//! own severity — `id` is resolved against `index` to confirm it's +//! actually a declared [`crate::model::PacketKind::Message`] (so a +//! `WrongKind`/`UnknownId` frame is rejected), but the severity itself +//! is never stored redundantly on the decoded instance; look it up via +//! `index.packet(id)` again if it's needed. -use crate::model::{MessageLevel, MessagePacket}; -use crate::protocol::DecodeError; +use crate::model::{AdjId, MessagePacket, PacketKind, ShortTimestamp}; +use crate::protocol::{DecodeError, EncodeError, Index}; use std::io::Read; -/// Decodes a message frame's remaining bytes, given the frame's -/// already-resolved severity level (`tcp::decode_next`'s job). -pub fn decode(reader: impl Read, level: MessageLevel) -> Result { - let _ = (reader, level); - todo!( - "read the timestamp, then the null-terminated `origin` (max 48 \ - bytes) and `message` (max 320 bytes) strings" - ) +// `origin`/`message` max lengths, content + NUL terminator included +// (docu_backend/Comunicaciones_Reunion01.qmd, lines 207-237). +const ORIGIN_MAX: usize = 48; +const MESSAGE_MAX: usize = 320; + +/// Decodes a message frame, resolving its id against `index` to confirm +/// it's actually a declared message. +/// +/// `id`: `Some` if the caller already read it (see this module's doc +/// comment); `None` to have `decode` read it itself off `reader`'s first +/// 2 bytes. +pub fn decode( + mut reader: impl Read, + id: Option, + index: &Index, +) -> Result { + let id = match id { + Some(id) => id, + None => read_id(&mut reader)?, + }; + + // Look up the packet definition for this id, and ensure it's a + // message packet. If not, the frame is malformed and we can't decode it. + let packet_def = index.packet(id).ok_or(DecodeError::UnknownId(id))?; + + let PacketKind::Message(_) = &packet_def.kind else { + return Err(DecodeError::WrongKind { id }); + }; + + let mut header = [0u8; 4]; + reader.read_exact(&mut header)?; + let timestamp = ShortTimestamp { + hour: header[0], + minute: header[1], + second: header[2], + subsecond: header[3], + }; + + let origin = read_null_terminated_string(&mut reader, ORIGIN_MAX)?; + let message = read_null_terminated_string(&mut reader, MESSAGE_MAX)?; + + Ok(MessagePacket { + id, + timestamp, + origin, + message, + }) +} + +/// Reads a raw little-endian 16-bit id off the front of `reader`. The +/// one piece of byte parsing [`decode`]/[`encode`] share, so it only +/// lives here once instead of wherever else might need an `AdjId`. +fn read_id(reader: &mut impl Read) -> Result { + let mut bytes = [0u8; 2]; + reader.read_exact(&mut bytes)?; + Ok(AdjId(u16::from_le_bytes(bytes))) +} + +/// Reads bytes up to the first `0x00` (exclusive) or `max` bytes total, +/// whichever comes first — [`DecodeError::UnterminatedString`] if no +/// terminator shows up within `max` bytes. +fn read_null_terminated_string(reader: &mut impl Read, max: usize) -> Result { + // Byte by byte via `read_exact`, not `.bytes()` — that iterator warns + // under clippy for being unbuffered, and `reader` here can be any + // `impl Read`, not necessarily a buffered one. + let mut bytes = Vec::new(); + for _ in 0..max { + let mut byte = [0u8; 1]; + reader.read_exact(&mut byte)?; + if byte[0] == 0 { + return String::from_utf8(bytes).map_err(|e| DecodeError::InvalidUtf8(e.into_bytes())); + } + bytes.push(byte[0]); + } + Err(DecodeError::UnterminatedString { max }) +} + +/// Encodes a [`MessagePacket`] back into the bytes [`decode`] expects — +/// a complete, self-contained frame, leading id included. +/// +/// Nothing in the real backend calls this — per the ADJ spec, message +/// packets only ever travel board -> backend. This exists purely so +/// tests can build well-formed frames without hand-written byte arrays, +/// and to prove `decode` recovers exactly what was encoded. +pub fn encode(packet: &MessagePacket, index: &Index) -> Result, EncodeError> { + let packet_def = index + .packet(packet.id) + .ok_or(EncodeError::UnknownId(packet.id))?; + + let PacketKind::Message(_) = &packet_def.kind else { + return Err(EncodeError::WrongKind { id: packet.id }); + }; + + let mut bytes = packet.id.0.to_le_bytes().to_vec(); + bytes.extend([ + packet.timestamp.hour, + packet.timestamp.minute, + packet.timestamp.second, + packet.timestamp.subsecond, + ]); + + write_null_terminated_string(&mut bytes, &packet.origin, ORIGIN_MAX)?; + write_null_terminated_string(&mut bytes, &packet.message, MESSAGE_MAX)?; + + Ok(bytes) +} + +/// Appends `value` to `bytes` as a NUL-terminated string, erroring if it +/// can't be represented that way: an embedded `\0` would be misread as +/// an early terminator, and the content plus its terminator must still +/// fit within `max` bytes. +fn write_null_terminated_string( + bytes: &mut Vec, + value: &str, + max: usize, +) -> Result<(), EncodeError> { + if value.contains('\0') { + return Err(EncodeError::EmbeddedNulByte); + } + if value.len() >= max { + return Err(EncodeError::StringTooLong { max }); + } + + bytes.extend_from_slice(value.as_bytes()); + bytes.push(0); + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::model::{Board, BoardId, MacAddress, MessageLevel, PacketDef, PodData}; + use std::collections::HashMap; + use std::io::Cursor; + use std::net::IpAddr; + + /// Builds an `Index` declaring one message severity: `id` as + /// `MessageLevel::Fault`, exactly as `protocol::Index::new` would + /// synthesize it from a loaded ADJ's `message_levels`. + fn index_with_message(id: AdjId, level: MessageLevel) -> Index { + let message_levels = HashMap::from([(id, level)]); + Index::new(&PodData::default(), Some(&message_levels)) + } + + #[test] + fn decodes_timestamp_and_both_strings() { + let index = index_with_message(AdjId(11), MessageLevel::Warning); + let mut bytes = vec![12, 30, 5, 0]; // hour, minute, second, subsecond + bytes.extend(b"main.c"); + bytes.push(0); + bytes.extend(b"something went wrong"); + bytes.push(0); + + let Ok(packet) = decode(Cursor::new(bytes), Some(AdjId(11)), &index) else { + unreachable!("decoding a well-formed message frame should succeed"); + }; + + assert_eq!(packet.id, AdjId(11)); + assert_eq!(packet.timestamp.hour, 12); + assert_eq!(packet.timestamp.minute, 30); + assert_eq!(packet.timestamp.second, 5); + assert_eq!(packet.origin, "main.c"); + assert_eq!(packet.message, "something went wrong"); + } + + #[test] + fn decode_treats_a_leading_terminator_as_an_empty_string() { + let index = index_with_message(AdjId(12), MessageLevel::Info); + let mut bytes = vec![0, 0, 0, 0]; + bytes.push(0); // origin: empty + bytes.push(0); // message: empty + + let Ok(packet) = decode(Cursor::new(bytes), Some(AdjId(12)), &index) else { + unreachable!("decoding a well-formed message frame should succeed"); + }; + + assert_eq!(packet.origin, ""); + assert_eq!(packet.message, ""); + } + + #[test] + fn decode_fails_when_origin_has_no_terminator_within_max() { + let index = index_with_message(AdjId(10), MessageLevel::Fault); + let mut bytes = vec![0, 0, 0, 0]; + bytes.extend(vec![b'a'; ORIGIN_MAX]); // no terminator anywhere + + let Err(err) = decode(Cursor::new(bytes), Some(AdjId(10)), &index) else { + unreachable!("decoding an unterminated origin should fail"); + }; + assert_eq!(err, DecodeError::UnterminatedString { max: ORIGIN_MAX }); + } + + #[test] + fn decode_fails_when_message_has_no_terminator_within_max() { + let index = index_with_message(AdjId(13), MessageLevel::Panic); + let mut bytes = vec![0, 0, 0, 0]; + bytes.push(0); // origin: empty, terminated + bytes.extend(vec![b'a'; MESSAGE_MAX]); // message: no terminator + + let Err(err) = decode(Cursor::new(bytes), Some(AdjId(13)), &index) else { + unreachable!("decoding an unterminated message should fail"); + }; + assert_eq!(err, DecodeError::UnterminatedString { max: MESSAGE_MAX }); + } + + #[test] + fn decode_fails_on_invalid_utf8() { + let index = index_with_message(AdjId(12), MessageLevel::Info); + let mut bytes = vec![0, 0, 0, 0]; + bytes.push(0x80); // lone continuation byte: not valid UTF-8 on its own + bytes.push(0); + + let Err(err) = decode(Cursor::new(bytes), Some(AdjId(12)), &index) else { + unreachable!("decoding invalid UTF-8 should fail"); + }; + assert_eq!(err, DecodeError::InvalidUtf8(vec![0x80])); + } + + #[test] + fn decode_fails_on_truncated_header() { + let index = index_with_message(AdjId(12), MessageLevel::Info); + let Err(err) = decode(Cursor::new(vec![0, 0]), Some(AdjId(12)), &index) else { + unreachable!("decoding a truncated header should fail"); + }; + assert!(matches!(err, DecodeError::Io(_))); + } + + #[test] + fn decode_reads_the_id_itself_when_not_given_one() { + let index = index_with_message(AdjId(11), MessageLevel::Warning); + let mut bytes = AdjId(11).0.to_le_bytes().to_vec(); + bytes.extend([12, 30, 5, 0]); // hour, minute, second, subsecond + bytes.push(0); // origin: empty + bytes.push(0); // message: empty + + let Ok(packet) = decode(Cursor::new(bytes), None, &index) else { + unreachable!("decoding a well-formed message frame should succeed"); + }; + + assert_eq!(packet.id, AdjId(11)); + } + + #[test] + fn decode_fails_on_an_unknown_id() { + let index = index_with_message(AdjId(11), MessageLevel::Warning); + let bytes = 9999u16.to_le_bytes().to_vec(); + + let Err(err) = decode(Cursor::new(bytes), None, &index) else { + unreachable!("decoding an unknown message id should fail"); + }; + assert_eq!(err, DecodeError::UnknownId(AdjId(9999))); + } + + #[test] + fn decode_fails_when_the_id_resolves_to_a_non_message_packet() { + let data_id = AdjId(2000); + let packet = PacketDef { + id: data_id, + board: BoardId(1), + name: "bcu_data".to_string(), + kind: PacketKind::Data(vec![]), + }; + let board = Board { + id: BoardId(1), + name: "BCU".to_string(), + ip: IpAddr::from([127, 0, 0, 1]), + mac: MacAddress([0; 6]), + packets: HashMap::from([(packet.id, packet)]), + }; + let pod_data = PodData { + boards: HashMap::from([(board.id, board)]), + }; + let index = Index::new(&pod_data, None); + + let bytes = data_id.0.to_le_bytes().to_vec(); + let Err(err) = decode(Cursor::new(bytes), None, &index) else { + unreachable!("decoding an id that resolves to a Data packet should fail"); + }; + assert_eq!(err, DecodeError::WrongKind { id: data_id }); + } + + // --- ENCODE TESTS --- + + #[test] + fn encode_then_decode_round_trips_timestamp_and_strings() { + let index = index_with_message(AdjId(10), MessageLevel::Fault); + let original = MessagePacket { + id: AdjId(10), + timestamp: ShortTimestamp { + hour: 23, + minute: 59, + second: 58, + subsecond: 200, + }, + origin: "board/src/main.c".to_string(), + message: "overcurrent detected".to_string(), + }; + + let Ok(bytes) = encode(&original, &index) else { + unreachable!("encoding a well-formed message packet should succeed"); + }; + // `encode` writes the id too, so `decode` can read it back itself — + // proves the full frame round-trips, not just the body. + let Ok(decoded) = decode(Cursor::new(bytes), None, &index) else { + unreachable!("decoding what we just encoded should succeed"); + }; + + assert_eq!(decoded, original); + } + + #[test] + fn encode_fails_on_unknown_id() { + let index = index_with_message(AdjId(10), MessageLevel::Fault); + let packet = MessagePacket { + id: AdjId(9999), + timestamp: ShortTimestamp { + hour: 0, + minute: 0, + second: 0, + subsecond: 0, + }, + origin: String::new(), + message: String::new(), + }; + + let Err(err) = encode(&packet, &index) else { + unreachable!("encoding an unknown id should fail"); + }; + assert_eq!(err, EncodeError::UnknownId(AdjId(9999))); + } + + #[test] + fn encode_fails_on_wrong_kind() { + let data_id = AdjId(2000); + let packet_def = PacketDef { + id: data_id, + board: BoardId(1), + name: "bcu_data".to_string(), + kind: PacketKind::Data(vec![]), + }; + let board = Board { + id: BoardId(1), + name: "BCU".to_string(), + ip: IpAddr::from([127, 0, 0, 1]), + mac: MacAddress([0; 6]), + packets: HashMap::from([(packet_def.id, packet_def)]), + }; + let pod_data = PodData { + boards: HashMap::from([(board.id, board)]), + }; + let index = Index::new(&pod_data, None); + + let packet = MessagePacket { + id: data_id, + timestamp: ShortTimestamp { + hour: 0, + minute: 0, + second: 0, + subsecond: 0, + }, + origin: String::new(), + message: String::new(), + }; + + let Err(err) = encode(&packet, &index) else { + unreachable!("encoding into a non-message packet's id should fail"); + }; + assert_eq!(err, EncodeError::WrongKind { id: data_id }); + } + + #[test] + fn encode_rejects_a_too_long_origin() { + let index = index_with_message(AdjId(12), MessageLevel::Info); + let packet = MessagePacket { + id: AdjId(12), + timestamp: ShortTimestamp { + hour: 0, + minute: 0, + second: 0, + subsecond: 0, + }, + origin: "a".repeat(ORIGIN_MAX), + message: String::new(), + }; + + let Err(err) = encode(&packet, &index) else { + unreachable!("encoding an origin with no room for its terminator should fail"); + }; + assert_eq!(err, EncodeError::StringTooLong { max: ORIGIN_MAX }); + + let fits = MessagePacket { + origin: "a".repeat(ORIGIN_MAX - 1), + ..packet + }; + assert!(encode(&fits, &index).is_ok()); + } + + #[test] + fn encode_rejects_an_embedded_nul_byte() { + let index = index_with_message(AdjId(12), MessageLevel::Info); + let packet = MessagePacket { + id: AdjId(12), + timestamp: ShortTimestamp { + hour: 0, + minute: 0, + second: 0, + subsecond: 0, + }, + origin: "ab\0cd".to_string(), + message: String::new(), + }; + + let Err(err) = encode(&packet, &index) else { + unreachable!("encoding a string with an embedded NUL byte should fail"); + }; + assert_eq!(err, EncodeError::EmbeddedNulByte); + } } From 2a11b67e0bd7f83905851e71e8cedd54be027828 Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Tue, 13 Oct 2026 00:05:47 +0200 Subject: [PATCH 089/225] fix(backend, protocol): remove duplicated function --- backend/crates/core/src/protocol/packet.rs | 17 +++++++++++++++++ .../crates/core/src/protocol/packet/message.rs | 11 +---------- .../core/src/protocol/packet/protection.rs | 11 +---------- 3 files changed, 19 insertions(+), 20 deletions(-) diff --git a/backend/crates/core/src/protocol/packet.rs b/backend/crates/core/src/protocol/packet.rs index 11b2847a8..d0f49d3b8 100644 --- a/backend/crates/core/src/protocol/packet.rs +++ b/backend/crates/core/src/protocol/packet.rs @@ -17,3 +17,20 @@ pub mod data_order; pub mod message; pub mod protection; + +use crate::model::AdjId; +use crate::protocol::DecodeError; +use std::io::Read; + +/// Reads a raw little-endian 16-bit id off the front of `reader`. +/// +/// Shared by [`message`]/[`protection`] — the only two kinds whose +/// `decode` ever needs to read its own leading id, when the caller +/// doesn't already know it (see each module's own doc comment on why). +/// [`data_order`] doesn't need this: it reads its id a different way, +/// straight out of an in-memory byte slice, never a `Read` stream. +fn read_id(reader: &mut impl Read) -> Result { + let mut bytes = [0u8; 2]; + reader.read_exact(&mut bytes)?; + Ok(AdjId(u16::from_le_bytes(bytes))) +} diff --git a/backend/crates/core/src/protocol/packet/message.rs b/backend/crates/core/src/protocol/packet/message.rs index eb9f1986b..b1b776a62 100644 --- a/backend/crates/core/src/protocol/packet/message.rs +++ b/backend/crates/core/src/protocol/packet/message.rs @@ -51,7 +51,7 @@ pub fn decode( ) -> Result { let id = match id { Some(id) => id, - None => read_id(&mut reader)?, + None => super::read_id(&mut reader)?, }; // Look up the packet definition for this id, and ensure it's a @@ -82,15 +82,6 @@ pub fn decode( }) } -/// Reads a raw little-endian 16-bit id off the front of `reader`. The -/// one piece of byte parsing [`decode`]/[`encode`] share, so it only -/// lives here once instead of wherever else might need an `AdjId`. -fn read_id(reader: &mut impl Read) -> Result { - let mut bytes = [0u8; 2]; - reader.read_exact(&mut bytes)?; - Ok(AdjId(u16::from_le_bytes(bytes))) -} - /// Reads bytes up to the first `0x00` (exclusive) or `max` bytes total, /// whichever comes first — [`DecodeError::UnterminatedString`] if no /// terminator shows up within `max` bytes. diff --git a/backend/crates/core/src/protocol/packet/protection.rs b/backend/crates/core/src/protocol/packet/protection.rs index 29d171356..fdb36768d 100644 --- a/backend/crates/core/src/protocol/packet/protection.rs +++ b/backend/crates/core/src/protocol/packet/protection.rs @@ -39,7 +39,7 @@ pub fn decode( ) -> Result { let compound_id = match compound_id { Some(id) => id, - None => read_id(&mut reader)?, + None => super::read_id(&mut reader)?, }; // Look up the packet definition for this compound id, and ensure it's a @@ -76,15 +76,6 @@ pub fn decode( }) } -/// Reads a raw little-endian 16-bit id off the front of `reader`. The -/// one piece of byte parsing [`decode`]/[`encode`] share, so it only -/// lives here once instead of wherever else might need an `AdjId`. -fn read_id(reader: &mut impl Read) -> Result { - let mut bytes = [0u8; 2]; - reader.read_exact(&mut bytes)?; - Ok(AdjId(u16::from_le_bytes(bytes))) -} - /// Encodes a [`ProtectionPacket`] back into the bytes [`decode`] expects /// — a complete, self-contained frame, leading id included. /// From 80d34b3d19569b1bcf792be6dba0c46f52b98bea Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Tue, 13 Oct 2026 00:19:37 +0200 Subject: [PATCH 090/225] feat(backend, protocol): tcp decode --- backend/crates/core/src/protocol/README.md | 10 +- backend/crates/core/src/protocol/packet.rs | 13 +- .../crates/core/src/protocol/packet/README.md | 20 ++- backend/crates/core/src/protocol/tcp.rs | 141 ++++++++++++++++-- 4 files changed, 154 insertions(+), 30 deletions(-) diff --git a/backend/crates/core/src/protocol/README.md b/backend/crates/core/src/protocol/README.md index a62b38c26..400359608 100644 --- a/backend/crates/core/src/protocol/README.md +++ b/backend/crates/core/src/protocol/README.md @@ -32,7 +32,7 @@ protocol/ │ ├── data_order.rs # Data (telemetry) & Order (command) packets │ ├── message.rs # Free-text log message packets │ └── protection.rs # Protection trigger packets -├── tcp.rs # TCP transport framing (stub) +├── tcp.rs # TCP transport framing └── udp.rs # UDP transport framing ``` @@ -154,18 +154,20 @@ bytes. - `decode(reader, compound_id: Option, index)` - Decode a protection frame, resolving its id itself if not given one - `encode(packet, index)` - Test-only: encode a complete `ProtectionPacket` frame, id included -### `tcp.rs` - TCP Transport Framing ⚠ Partial +### `tcp.rs` - TCP Transport Framing Handles the dedicated TCP connection to each board. A TCP connection carries: - Protection events (board → backend) - Free-text messages (board → backend) - Order commands (backend → board) +`decode_next` reads the frame's leading 16-bit id itself (via `packet::read_id`, `pub(super)` so `tcp` — a sibling of `packet`, not a descendant — can reach it), then dispatches purely on the raw id: `id.0 >= 8192` (`1 << 13` — a protection's compound id always has its high 3 bits set, see `AdjId`'s own docs) goes to `packet::protection::decode(reader, Some(id), index)`, anything below that to `packet::message::decode(reader, Some(id), index)`. Neither branch does its own lookup first — each `decode` already resolves `UnknownId`/`WrongKind` against `index` itself. + **Key types:** - `TcpFrame` - Enum of frames that can be received over TCP (Protection, Message) **Key functions:** -- `decode_next(reader, index)` - ⚠ Stub - Decode the next frame from a TCP stream +- `decode_next(reader, index)` - ✓ Implemented - Decode the next frame from a TCP stream - `encode_order(order, index)` - ✓ Implemented - Encode an order for sending ### `udp.rs` - UDP Transport Framing @@ -193,7 +195,7 @@ Handles the shared UDP socket for periodic telemetry. UDP datagrams are complete - ✅ **Wire-level boolean types** - Single byte, confirmed with firmware - ✅ **Message packets** - decode implemented, with tests (encode exists for test symmetry only) - ✅ **Protection packets** - decode implemented, with tests (encode exists for test symmetry only) -- ⚠️ **TCP framing** - Partial (decode_next not implemented) +- ✅ **TCP framing** - `decode_next` implemented and tested (dispatches to protection/message by `id.0 >= 8192`) ## Testing diff --git a/backend/crates/core/src/protocol/packet.rs b/backend/crates/core/src/protocol/packet.rs index d0f49d3b8..df7842292 100644 --- a/backend/crates/core/src/protocol/packet.rs +++ b/backend/crates/core/src/protocol/packet.rs @@ -26,10 +26,15 @@ use std::io::Read; /// /// Shared by [`message`]/[`protection`] — the only two kinds whose /// `decode` ever needs to read its own leading id, when the caller -/// doesn't already know it (see each module's own doc comment on why). -/// [`data_order`] doesn't need this: it reads its id a different way, -/// straight out of an in-memory byte slice, never a `Read` stream. -fn read_id(reader: &mut impl Read) -> Result { +/// doesn't already know it (see each module's own doc comment on why) — +/// and by [`super::tcp::decode_next`], which needs the id *before* it +/// can even decide which of the two to call. `pub(super)` (visible to +/// `protocol` and everything under it) rather than private, for that +/// last caller: `tcp` is `packet`'s sibling, not its descendant, so +/// private wouldn't reach it. [`data_order`] doesn't need this: it reads +/// its id a different way, straight out of an in-memory byte slice, +/// never a `Read` stream. +pub(super) fn read_id(reader: &mut impl Read) -> Result { let mut bytes = [0u8; 2]; reader.read_exact(&mut bytes)?; Ok(AdjId(u16::from_le_bytes(bytes))) diff --git a/backend/crates/core/src/protocol/packet/README.md b/backend/crates/core/src/protocol/packet/README.md index fce1586c9..668e8532b 100644 --- a/backend/crates/core/src/protocol/packet/README.md +++ b/backend/crates/core/src/protocol/packet/README.md @@ -22,9 +22,9 @@ see its own module doc and `model/README.md`'s §4.2 for why. These two are different: over TCP, a `Protection` frame and a `Message` frame share the same leading 16-bit id space, so **something** has to read that id before it even knows which of the two decoders to call. -That something is `tcp::decode_next` (still unimplemented). To keep that -reality from leaking actual decoding logic into `tcp.rs`, both files -take their id as `Option` — the exact same shape: +That something is `tcp::decode_next`. To keep that reality from leaking +actual decoding logic into `tcp.rs`, both files take their id as +`Option` — the exact same shape: ```rust // protection.rs @@ -76,11 +76,15 @@ decide *which* of `protection::decode`/`message::decode` to call — there is no way around this for a non-seekable stream: once those bytes are consumed, there's no handing them to the other function's `None` path instead. That single mechanical "read a `u16`" is the one piece of -byte-handling that's expected to exist in `tcp.rs`. It is not decoding — -nothing is validated or interpreted by it beyond "is the top bit of -`AdjId::protection_position()` set" — and its result is immediately -handed to the matching function as `Some(id)`, which then resolves it -against `index` itself and does everything else. +byte-handling that's expected to exist in `tcp.rs` — it calls the exact +same private `read_id` helper `protection.rs`/`message.rs` use for their +own `None` path (defined once in `packet.rs`, `pub(super)` so `tcp.rs` +can reach it too, rather than duplicated a third time). It is not +decoding — nothing is validated or interpreted by it beyond a single +`id.0 >= 8192` comparison (a protection's compound id always has its +high 3 bits set, see `AdjId`'s own docs) — and its result is +immediately handed to the matching function as `Some(id)`, which then +resolves it against `index` itself and does everything else. ## Tests diff --git a/backend/crates/core/src/protocol/tcp.rs b/backend/crates/core/src/protocol/tcp.rs index 9d4169087..a2d645944 100644 --- a/backend/crates/core/src/protocol/tcp.rs +++ b/backend/crates/core/src/protocol/tcp.rs @@ -26,23 +26,136 @@ pub enum TcpFrame { /// Reads and decodes the next complete frame from `reader`, resolving /// field shapes against `index`. /// -/// Reads the frame's leading 16-bit id first, then decides which of -/// [`super::packet::protection::decode`] ([`crate::model::AdjId::protection_position`] -/// is non-zero) or [`super::packet::message::decode`] (the id matches one -/// of `general_info.json`'s `message_ids`) to hand the rest of the frame -/// to, wrapping the result in the matching [`TcpFrame`] variant. -pub fn decode_next(reader: impl Read, index: &Index) -> Result { - let _ = (reader, index); - todo!( - "read the leading 16-bit id; if its AdjId::protection_position() is \ - non-zero, call packet::protection::decode; otherwise resolve it \ - against general_info.json's message_ids (not yet reachable from \ - `Index` — needs AdjInfo too) and call packet::message::decode; \ - wrap either result in the matching TcpFrame variant" - ) +/// Reads the frame's leading 16-bit id first — the one piece of byte +/// handling this function does itself, since it has no way to decide +/// which of [`super::packet::protection::decode`]/ +/// [`super::packet::message::decode`] to call otherwise (see +/// `packet/README.md`'s "dispatcher's one unavoidable read"). A +/// protection's compound id always has its high 3 bits set to a nonzero +/// position (see [`crate::model::AdjId`]'s own docs on its ranges), so +/// `id.0 >= 8192` (`1 << 13`) is a protection; anything below that hands +/// off to `message::decode` instead — `message::decode` resolves it +/// against `index` itself (`UnknownId`/`WrongKind` if it isn't actually +/// a declared message), so there's no separate lookup to do here first. +/// Either call's result is wrapped in the matching [`TcpFrame`] variant. +pub fn decode_next(mut reader: impl Read, index: &Index) -> Result { + let id = packet::read_id(&mut reader)?; + + if id.0 >= 8192 { + let protection = packet::protection::decode(reader, Some(id), index)?; + Ok(TcpFrame::Protection(protection)) + } else { + let message = packet::message::decode(reader, Some(id), index)?; + Ok(TcpFrame::Message(message)) + } } /// Encodes `order` into the bytes to write to the board's connection. pub fn encode_order(order: &OrderPacket, index: &Index) -> Result, EncodeError> { packet::data_order::encode(order, index) } + +#[cfg(test)] +mod tests { + use super::*; + use crate::model::{ + AdjId, Board, BoardId, MacAddress, Measurement, MeasurementKind, MessageLevel, NumericKind, + PacketDef, PacketKind, PodData, ShortTimestamp, Value, + }; + use std::collections::HashMap; + use std::io::Cursor; + use std::net::IpAddr; + + /// A board with one protection (position 1 on measurement 100, wire + /// type `U8`) and one declared message severity (`id` 10 = `Fault`). + fn sample_index() -> Index { + let measurement = Measurement { + id: AdjId(100), + alias: "temp".to_string(), + name: "Temp".to_string(), + display_units: String::new(), + kind: MeasurementKind::Numeric { + wire_type: NumericKind::U8, + }, + protections: vec![], + }; + let compound_id = AdjId((1u16 << 13) | measurement.id.0); + let packet_def = PacketDef { + id: compound_id, + board: BoardId(1), + name: "temp_protection".to_string(), + kind: PacketKind::Protection(measurement), + }; + let board = Board { + id: BoardId(1), + name: "MOCK".to_string(), + ip: IpAddr::from([127, 0, 0, 1]), + mac: MacAddress([0; 6]), + packets: HashMap::from([(packet_def.id, packet_def)]), + }; + let pod_data = PodData { + boards: HashMap::from([(board.id, board)]), + }; + let message_levels = HashMap::from([(AdjId(10), MessageLevel::Fault)]); + Index::new(&pod_data, Some(&message_levels)) + } + + #[test] + fn decode_next_dispatches_a_protection_frame() { + let index = sample_index(); + let compound_id = AdjId((1u16 << 13) | 100); + + let mut bytes = compound_id.0.to_le_bytes().to_vec(); + bytes.extend([12, 30, 5, 0, 0, 0]); // hora, min, seg, subseg, resv(2) + bytes.push(42); // value, U8 + + let Ok(frame) = decode_next(Cursor::new(bytes), &index) else { + unreachable!("decoding a well-formed protection frame should succeed"); + }; + + let TcpFrame::Protection(protection) = frame else { + unreachable!("a non-zero protection_position should dispatch to Protection"); + }; + assert_eq!(protection.id, compound_id); + assert_eq!(protection.value, Value::Number(42.0)); + } + + #[test] + fn decode_next_dispatches_a_message_frame() { + let index = sample_index(); + + let mut bytes = AdjId(10).0.to_le_bytes().to_vec(); + bytes.extend([1, 2, 3, 4]); // hora, min, seg, subseg + bytes.push(0); // origin: empty + bytes.push(0); // message: empty + + let Ok(frame) = decode_next(Cursor::new(bytes), &index) else { + unreachable!("decoding a well-formed message frame should succeed"); + }; + + let TcpFrame::Message(message) = frame else { + unreachable!("a zero protection_position should dispatch to Message"); + }; + assert_eq!(message.id, AdjId(10)); + assert_eq!( + message.timestamp, + ShortTimestamp { + hour: 1, + minute: 2, + second: 3, + subsecond: 4, + } + ); + } + + #[test] + fn decode_next_propagates_an_unknown_message_id() { + let index = sample_index(); + let bytes = 9999u16.to_le_bytes().to_vec(); + + let Err(err) = decode_next(Cursor::new(bytes), &index) else { + unreachable!("decoding an id that's neither a protection nor a message should fail"); + }; + assert_eq!(err, DecodeError::UnknownId(AdjId(9999))); + } +} From 8d7b6b52337ad91420375f710886d4ec3564ef3b Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Tue, 13 Oct 2026 14:15:12 +0200 Subject: [PATCH 091/225] refactor(backend): change PacketKind for Pakcet .type --- backend/crates/core/src/adj/README.md | 4 +- backend/crates/core/src/adj/raw/loader.rs | 34 ++++----- backend/crates/core/src/adj/raw/types.rs | 6 +- backend/crates/core/src/model.rs | 6 +- backend/crates/core/src/model/README.md | 30 ++++---- backend/crates/core/src/model/board.rs | 26 +++---- backend/crates/core/src/model/packet.rs | 36 ++++----- backend/crates/core/src/protocol.rs | 2 +- backend/crates/core/src/protocol/README.md | 18 ++--- backend/crates/core/src/protocol/error.rs | 18 ++--- backend/crates/core/src/protocol/index.rs | 13 ++-- backend/crates/core/src/protocol/packet.rs | 12 +-- .../crates/core/src/protocol/packet/README.md | 18 ++--- .../core/src/protocol/packet/data_order.rs | 76 +++++++++---------- .../core/src/protocol/packet/message.rs | 28 +++---- .../core/src/protocol/packet/protection.rs | 26 +++---- backend/crates/core/src/protocol/tcp.rs | 11 +-- 17 files changed, 183 insertions(+), 181 deletions(-) diff --git a/backend/crates/core/src/adj/README.md b/backend/crates/core/src/adj/README.md index 815cbb6e1..c167bdfbc 100644 --- a/backend/crates/core/src/adj/README.md +++ b/backend/crates/core/src/adj/README.md @@ -67,7 +67,7 @@ doesn't hardcode `"fault"`/`"warning"`/`"info"`/`"panic"` itself. `Option<&HashMap>` — `None` for callers with no `AdjInfo` at all (most tests in this crate, which only build a bare `PodData`) — and, for each entry, synthesizes a -`PacketDef { kind: PacketKind::Message(level), board: BoardId(0), .. }` +`PacketDef { packet_type: PacketType::Message(level), board: BoardId(0), .. }` into the very same `AdjId -> PacketDef` table every other packet lives in. `BoardId(0)` (reserved, not validated — see `AdjId`/`BoardId`'s own docs) because a severity isn't owned by any one board — any board's @@ -89,4 +89,4 @@ The `Adj` object enforces a clear architectural boundary between **vehicle topol The raw deserialization types and the loader logic live isolated inside `raw`[cite: 2]. This enables non-station tools (such as bus sniffers, test runners, or simulators) to parse and ingest ADJ directories without dragging along application-level UI or station state logic. ### 3. Unified Packet Map (`packets`) -Protections defined under measurements are materialized during loading as first-class `PacketKind::Protection(Measurement)` packets alongside the explicit data, order and message packets declared in `packets.json`. Downstream networking layers can route and handle every wire event uniformly via `Board::packets` without needing specialized traversal logic for nested measurement alarms. `packets.json` itself never declares a `"type": "protection"` entry directly — that shape only exists synthesized, one per protection a measurement declares, never as a free-standing declaration with its own arbitrary variable list. \ No newline at end of file +Protections defined under measurements are materialized during loading as first-class `PacketType::Protection(Measurement)` packets alongside the explicit data, order and message packets declared in `packets.json`. Downstream networking layers can route and handle every wire event uniformly via `Board::packets` without needing specialized traversal logic for nested measurement alarms. `packets.json` itself never declares a `"type": "protection"` entry directly — that shape only exists synthesized, one per protection a measurement declares, never as a free-standing declaration with its own arbitrary variable list. \ No newline at end of file diff --git a/backend/crates/core/src/adj/raw/loader.rs b/backend/crates/core/src/adj/raw/loader.rs index 53390d252..32216fc2b 100644 --- a/backend/crates/core/src/adj/raw/loader.rs +++ b/backend/crates/core/src/adj/raw/loader.rs @@ -4,7 +4,7 @@ use super::types::{RawBoard, RawGeneralInfo, RawMeasurement, RawPacket}; use crate::adj::error::LoadError; use crate::adj::{Adj, AdjInfo}; use crate::model::{ - AdjId, Board, BoardId, MacAddress, Measurement, MessageLevel, PacketDef, PacketKind, PodData, + AdjId, Board, BoardId, MacAddress, Measurement, MessageLevel, PacketDef, PacketType, PodData, }; use serde::de::DeserializeOwned; use std::collections::HashMap; @@ -82,7 +82,7 @@ pub(crate) fn load_board(root: &Path, name: &str, rel_path: &str) -> Result, ) -> Result { - let kind = match raw.kind.as_str() { - "data" => PacketKind::Data(resolve_measurements( + let packet_type = match raw.packet_type.as_str() { + "data" => PacketType::Data(resolve_measurements( board, &raw.name, &raw.variables, measurements, )?), - "order" => PacketKind::Order(resolve_measurements( + "order" => PacketType::Order(resolve_measurements( board, &raw.name, &raw.variables, @@ -147,7 +147,7 @@ fn build_packet_def( // severities (`"fault"`/`"warning"`/`"info"`/`"panic"`) — that's // the only way a `"message"`-type packet in `packets.json` says // which severity it is; nothing else in its JSON shape does. - "message" => PacketKind::Message(MessageLevel::from_name(&raw.name).ok_or_else(|| { + "message" => PacketType::Message(MessageLevel::from_name(&raw.name).ok_or_else(|| { LoadError::UnknownMessageSeverity { board: board.to_string(), name: raw.name.clone(), @@ -166,7 +166,7 @@ fn build_packet_def( id: AdjId(raw.id), board: board_id, name: raw.name, - kind, + packet_type, }) } @@ -217,7 +217,7 @@ fn parse_mac(raw: &str) -> Option { mod tests { use super::*; use crate::adj::ProtectionTypeInfo; - use crate::model::{PacketKind, Port, ProtectionKind, Severity}; + use crate::model::{PacketType, Port, ProtectionKind, Severity}; use std::path::Path; use std::time::Duration; @@ -249,7 +249,7 @@ mod tests { fn build_packet_def_rejects_unknown_packet_type() { let raw = RawPacket { id: 1, - kind: "status".to_string(), + packet_type: "status".to_string(), name: "Status".to_string(), variables: vec![], }; @@ -263,7 +263,7 @@ mod tests { fn build_packet_def_rejects_unknown_alias() { let raw = RawPacket { id: 1, - kind: "data".to_string(), + packet_type: "data".to_string(), name: "Status".to_string(), variables: vec!["missing".to_string()], }; @@ -277,21 +277,21 @@ mod tests { fn build_packet_def_resolves_a_message_packets_severity_from_its_name() { let raw = RawPacket { id: 2, - kind: "message".to_string(), + packet_type: "message".to_string(), name: "fault".to_string(), variables: vec![], }; let Ok(packet) = build_packet_def("VCU", BoardId(3), raw, &HashMap::new()) else { unreachable!("\"fault\" is a known message severity"); }; - assert_eq!(packet.kind, PacketKind::Message(MessageLevel::Fault)); + assert_eq!(packet.packet_type, PacketType::Message(MessageLevel::Fault)); } #[test] fn build_packet_def_rejects_a_message_whose_name_isnt_a_severity() { let raw = RawPacket { id: 2, - kind: "message".to_string(), + packet_type: "message".to_string(), name: "not_a_severity".to_string(), variables: vec![], }; @@ -326,14 +326,14 @@ mod tests { let Some(order) = vcu.packets.get(&AdjId(600)) else { unreachable!("VCU should have order 600"); }; - let PacketKind::Order(_) = &order.kind else { + let PacketType::Order(_) = &order.packet_type else { unreachable!("order 600 should be an Order"); }; assert_eq!(order.board, BoardId(3)); let Some(data) = vcu.packets.get(&AdjId(625)) else { unreachable!("VCU should have data packet 625"); }; - let PacketKind::Data(_) = &data.kind else { + let PacketType::Data(_) = &data.packet_type else { unreachable!("data packet 625 should be Data"); }; @@ -343,7 +343,7 @@ mod tests { let Some(protected) = pcu .packets .values() - .flat_map(|p| p.kind.measurements()) + .flat_map(|p| p.packet_type.measurements()) .find(|m| !m.protections.is_empty()) else { unreachable!("PCU should have a measurement with a protection"); @@ -375,7 +375,7 @@ mod tests { let Some(protection_packet) = pcu.packets.get(&AdjId((1u16 << 13) | protected.id.0)) else { unreachable!("PCU should have a synthetic protection packet"); }; - let PacketKind::Protection(measurement) = &protection_packet.kind else { + let PacketType::Protection(measurement) = &protection_packet.packet_type else { unreachable!("protection_packet should be a Protection"); }; assert_eq!(measurement, protected); diff --git a/backend/crates/core/src/adj/raw/types.rs b/backend/crates/core/src/adj/raw/types.rs index 3942a3bc7..bac40de9f 100644 --- a/backend/crates/core/src/adj/raw/types.rs +++ b/backend/crates/core/src/adj/raw/types.rs @@ -79,7 +79,7 @@ fn default_fault() -> bool { pub(crate) struct RawPacket { pub(crate) id: u16, #[serde(rename = "type")] - pub(crate) kind: String, + pub(crate) packet_type: String, pub(crate) name: String, #[serde(default)] pub(crate) variables: Vec, @@ -306,7 +306,7 @@ fn parse_duration(text: &str) -> Result { mod tests { use super::*; use crate::adj::raw::loader::load_board; - use crate::model::PacketKind; + use crate::model::PacketType; use std::net::IpAddr; fn raw_protection( @@ -623,7 +623,7 @@ mod tests { let protection_count = board .packets .values() - .filter(|p| matches!(p.kind, PacketKind::Protection(_))) + .filter(|p| matches!(p.packet_type, PacketType::Protection(_))) .count(); assert_eq!( protection_count, 2, diff --git a/backend/crates/core/src/model.rs b/backend/crates/core/src/model.rs index 04f933cb3..75cdb319e 100644 --- a/backend/crates/core/src/model.rs +++ b/backend/crates/core/src/model.rs @@ -17,12 +17,12 @@ mod packet; mod protections; mod value; -pub use board::{Board, PacketDef, PacketKind, PodData}; +pub use board::{Board, PacketDef, PacketType, PodData}; pub use id::{AdjId, BoardId, MacAddress, Port}; pub use measurement::{Measurement, MeasurementKind, NumericKind, Range}; pub use packet::{ - Data, DataOrderPacket, DataPacket, KindTag, MessageLevel, MessagePacket, Order, OrderPacket, - Packet, ProtectionPacket, ShortTimestamp, + Data, DataOrderPacket, DataPacket, MessageLevel, MessagePacket, Order, OrderPacket, Packet, + PacketTypeTag, ProtectionPacket, ShortTimestamp, }; pub use protections::{Protection, ProtectionKind, Severity}; pub use value::Value; diff --git a/backend/crates/core/src/model/README.md b/backend/crates/core/src/model/README.md index eaa09367e..20db8642d 100644 --- a/backend/crates/core/src/model/README.md +++ b/backend/crates/core/src/model/README.md @@ -6,8 +6,8 @@ This module is meant to store and organize all the different structs, enums and ## 1. `board.rs` All structs and enums needed for the Pod can be found defined in this file. -### 1.1 `PacketKind` -Enum used to define what kind of packet a `PacketDef` declares. Not every kind carries the same shape, so each variant holds whatever measurement data is actually meaningful for it, instead of every packet being forced through one shared field. +### 1.1 `PacketType` +Enum used to define what type of packet a `PacketDef` declares. Not every type carries the same shape, so each variant holds whatever measurement data is actually meaningful for it, instead of every packet being forced through one shared field. #### `Data(Vec)` Telemetry sent by a board: one value per measurement, decoded positionally in this order. @@ -16,9 +16,9 @@ The single measurement one of a board's declared protections watches. Always exa #### `Order(Vec)` An order sent to a board. Many orders take no parameters at all, so this can be empty. #### `Message(MessageLevel)` -A free-text log line of this severity. Never carries measurement data — the severity is the only thing that tells one `Message` `PacketDef` apart from another. Lives here, on `PacketKind`, rather than as a separate field on `PacketDef`: a message's severity is as much part of "what kind of packet is this" as a `Data` packet's measurement list is. +A free-text log line of this severity. Never carries measurement data — the severity is the only thing that tells one `Message` `PacketDef` apart from another. Lives here, on `PacketType`, rather than as a separate field on `PacketDef`: a message's severity is as much part of "what type of packet is this" as a `Data` packet's measurement list is. -`PacketKind` also exposes a `measurements()` method that flattens any variant into a `&[Measurement]` slice, for code that just wants every measurement a packet references regardless of its kind. +`PacketType` also exposes a `measurements()` method that flattens any variant into a `&[Measurement]` slice, for code that just wants every measurement a packet references regardless of its type. ### 1.2 `PacketDef` Struct used to define the structure of a packet a board can send or recieve. @@ -29,8 +29,8 @@ ID of a packet, using the AdjId type which is a u16. Structure of ID is defined The owning board's `BoardId`. Carried here too (not just reachable through the owning `Board`) so anything holding just a `&PacketDef` — e.g. a lookup table indexed by `AdjId` — knows which board it belongs to without a separate index back to it. #### `name` Human-readable String shown to the user to identify packet. -#### `kind` -`PacketKind` enum: both what kind of packet this is, and the measurement shape — if any — specific to that kind. +#### `packet_type` +`PacketType` enum: both what type of packet this is, and the measurement shape — if any — specific to that type. ### 1.3 `Board` Struct used to identify a single board in the vehicle. @@ -139,16 +139,16 @@ pub struct DataOrderPacket { #### `Data` / `Order` Two empty marker structs — the only two types `Kind` is ever instantiated with. Neither is ever actually constructed; they only ever appear as a type argument. That's what makes the whole thing *phantom*: the type parameter has no representation in the compiled struct, it's erased after type-checking, the same way `id.rs` (§2) uses distinct `AdjId`/`BoardId` types so the compiler won't confuse two different kinds of `u16`. -#### `KindTag` -The compiler erases `Kind` after type-checking, so nothing at runtime can look at a `DataOrderPacket` and ask "is this actually a `Data` one?" — `KindTag` is how code that's generic over `Kind` answers that anyway, by asking the question of the *type* instead of the *value*: +#### `PacketTypeTag` +The compiler erases `Kind` after type-checking, so nothing at runtime can look at a `DataOrderPacket` and ask "is this actually a `Data` one?" — `PacketTypeTag` is how code that's generic over `Kind` answers that anyway, by asking the question of the *type* instead of the *value*: ```rust -pub trait KindTag { - fn matches(kind: &PacketKind) -> bool; +pub trait PacketTypeTag { + fn matches(packet_type: &PacketType) -> bool; } ``` -`Data`/`Order` each implement it by checking which `PacketKind` (§1.1) variant they stand for (`matches!(kind, PacketKind::Data(_))` / `PacketKind::Order(_)`). This is the only thing `KindTag` decides — once a `PacketDef`'s kind is confirmed to match, the actual measurement list still comes from the existing `PacketKind::measurements()` (§1.1), not from `KindTag` itself. +`Data`/`Order` each implement it by checking which `PacketType` (§1.1) variant they stand for (`matches!(packet_type, PacketType::Data(_))` / `PacketType::Order(_)`). This is the only thing `PacketTypeTag` decides — once a `PacketDef`'s type is confirmed to match, the actual measurement list still comes from the existing `PacketType::measurements()` (§1.1), not from `PacketTypeTag` itself. -`protocol::packet::data_order`'s `encode`/`decode` use this to be generic over `Kind`: written once, they work for both `DataPacket` and `OrderPacket` instead of needing a near-duplicate pair of functions per kind. +`protocol::packet::data_order`'s `encode`/`decode` use this to be generic over `Kind`: written once, they work for both `DataPacket` and `OrderPacket` instead of needing a near-duplicate pair of functions per type. #### `DataPacket` / `OrderPacket` ```rust @@ -157,9 +157,9 @@ pub type OrderPacket = DataOrderPacket; ``` Now genuinely different types: a function that takes an `OrderPacket` cannot be called with a `DataPacket`, even though both just wrap the same `(AdjId, Vec)` underneath — the mix-up is a compile error instead of a bug waiting to happen. `DataOrderPacket`'s own doc comment has a `compile_fail` doctest proving exactly that (run by `cargo test`, like any other doctest). -`DataPacket` holds the decoded values of the measurements a board just sent — positional, not individually tagged with their measurement ID, just written in the order their `Measurement`s appear in this packet's `PacketKind::Data` list. +`DataPacket` holds the decoded values of the measurements a board just sent — positional, not individually tagged with their measurement ID, just written in the order their `Measurement`s appear in this packet's `PacketType::Data` list. -`OrderPacket` holds an order sent from the backend to a board — positional the same way, matching `PacketKind::Order`'s measurement list. +`OrderPacket` holds an order sent from the backend to a board — positional the same way, matching `PacketType::Order`'s measurement list. #### `id` Which packet/order definition this is an instance of (`AdjId`). @@ -199,7 +199,7 @@ This is deliberately where the name↔severity association lives — in `model`, A free-text message sent by a board. #### `id` -The wire id this message was sent under — one of the severities declared in `general_info.json`'s `message_ids`. Not a `MessageLevel` directly, the same way `ProtectionPacket::id` isn't a `Protection`: resolving it to a severity means looking it up (`PacketKind::Message`/`protocol::Index`), not storing a second, redundant copy of it here. +The wire id this message was sent under — one of the severities declared in `general_info.json`'s `message_ids`. Not a `MessageLevel` directly, the same way `ProtectionPacket::id` isn't a `Protection`: resolving it to a severity means looking it up (`PacketType::Message`/`protocol::Index`), not storing a second, redundant copy of it here. #### `timestamp` When the message was sent (`ShortTimestamp`). #### `origin` diff --git a/backend/crates/core/src/model/board.rs b/backend/crates/core/src/model/board.rs index b00e3a82c..2dc56b6b7 100644 --- a/backend/crates/core/src/model/board.rs +++ b/backend/crates/core/src/model/board.rs @@ -14,13 +14,13 @@ use super::{AdjId, BoardId, MacAddress, Measurement, MessageLevel}; use std::collections::HashMap; use std::net::IpAddr; -/// What kind of packet a [`PacketDef`] declares, carrying whatever -/// measurement shape — if any — is specific to that kind. Not every kind +/// What type of packet a [`PacketDef`] declares, carrying whatever +/// measurement shape — if any — is specific to that type. Not every type /// has measurements, so this says so in the type instead of forcing every /// [`PacketDef`] through one shared `measurements: Vec` field /// regardless of whether that's meaningful for it. #[derive(Debug, Clone, PartialEq)] -pub enum PacketKind { +pub enum PacketType { /// A board's periodic telemetry: one value per measurement, decoded /// positionally in this order. Data(Vec), @@ -35,15 +35,15 @@ pub enum PacketKind { Message(MessageLevel), } -impl PacketKind { - /// Every measurement this packet's kind references, flattened — for - /// code that doesn't care which kind this is, just what measurements +impl PacketType { + /// Every measurement this packet's type references, flattened — for + /// code that doesn't care which type this is, just what measurements /// it touches. pub fn measurements(&self) -> &[Measurement] { match self { - PacketKind::Data(measurements) | PacketKind::Order(measurements) => measurements, - PacketKind::Protection(measurement) => std::slice::from_ref(measurement), - PacketKind::Message(_) => &[], + PacketType::Data(measurements) | PacketType::Order(measurements) => measurements, + PacketType::Protection(measurement) => std::slice::from_ref(measurement), + PacketType::Message(_) => &[], } } } @@ -66,8 +66,8 @@ pub struct PacketDef { /// The human-readable name shown to the user. pub name: String, /// Whether this is data, order, protection or message — and the - /// measurement shape specific to that kind, if any. - pub kind: PacketKind, + /// measurement shape specific to that type, if any. + pub packet_type: PacketType, } /// A single board of the vehicle, as defined by the ADJ. @@ -132,7 +132,7 @@ mod tests { id: AdjId(1000), board: BoardId(1), name: "bcu_data".to_string(), - kind: PacketKind::Data(vec![sample_measurement()]), + packet_type: PacketType::Data(vec![sample_measurement()]), }, )]), }; @@ -141,7 +141,7 @@ mod tests { let Some(packet) = board.packets.get(&AdjId(1000)) else { unreachable!("the packet we just inserted should be there"); }; - let PacketKind::Data(measurements) = &packet.kind else { + let PacketType::Data(measurements) = &packet.packet_type else { unreachable!("packet should be Data"); }; assert_eq!(measurements.len(), 1); diff --git a/backend/crates/core/src/model/packet.rs b/backend/crates/core/src/model/packet.rs index 948d77834..c3dda408d 100644 --- a/backend/crates/core/src/model/packet.rs +++ b/backend/crates/core/src/model/packet.rs @@ -6,7 +6,7 @@ //! packet or a protection *can* look like, or [`super::PacketDef`], which //! describes a whole packet. -use super::{AdjId, PacketKind, Value}; +use super::{AdjId, PacketType, Value}; use std::marker::PhantomData; /// A short timestamp carrying only the time of day: hour, minute, second @@ -48,30 +48,30 @@ pub struct Data; pub struct Order; /// Bridges a [`DataOrderPacket`]'s phantom `Kind` to the runtime -/// [`PacketKind`] variant it stands for. +/// [`PacketType`] variant it stands for. /// /// `protocol::packet::data_order`'s `encode`/`decode` are generic over /// `Kind`: they're written once and work for both [`Data`] and [`Order`], -/// instead of needing a near-identical copy per kind. This trait is the +/// instead of needing a near-identical copy per type. This trait is the /// one yes/no question that generic code can't answer on its own — -/// "is this `PacketDef`'s kind actually the one I was asked to +/// "is this `PacketDef`'s type actually the one I was asked to /// encode/decode?" — everything after that (pulling out the -/// measurements) is already handled by [`PacketKind::measurements`], -/// kind-agnostic, so there's no need to redo that here. -pub trait KindTag { - /// Whether `kind` is the variant this `Kind` stands for. - fn matches(kind: &PacketKind) -> bool; +/// measurements) is already handled by [`PacketType::measurements`], +/// type-agnostic, so there's no need to redo that here. +pub trait PacketTypeTag { + /// Whether `packet_type` is the variant this `Kind` stands for. + fn matches(packet_type: &PacketType) -> bool; } -impl KindTag for Data { - fn matches(kind: &PacketKind) -> bool { - matches!(kind, PacketKind::Data(_)) +impl PacketTypeTag for Data { + fn matches(packet_type: &PacketType) -> bool { + matches!(packet_type, PacketType::Data(_)) } } -impl KindTag for Order { - fn matches(kind: &PacketKind) -> bool { - matches!(kind, PacketKind::Order(_)) +impl PacketTypeTag for Order { + fn matches(packet_type: &PacketType) -> bool { + matches!(packet_type, PacketType::Order(_)) } } @@ -81,7 +81,7 @@ impl KindTag for Order { /// The wire protocol is positional: values are not individually tagged /// with their measurement's id, just written back to back in the order /// their [`super::Measurement`]s appear in this packet's -/// [`super::PacketKind::Data`] list. `values[i]` is the decoded value of +/// [`super::PacketType::Data`] list. `values[i]` is the decoded value of /// that list's `i`-th measurement — matching them up by position is /// `protocol`'s job, this type just holds the result in that same order. /// @@ -110,7 +110,7 @@ pub struct DataOrderPacket { /// The packet's id. pub id: AdjId, /// Each measurement's decoded value, in the same order as the - /// matching [`super::PacketKind::Data`]/[`super::PacketKind::Order`] + /// matching [`super::PacketType::Data`]/[`super::PacketType::Order`] /// list. pub values: Vec, _marker: PhantomData, @@ -219,7 +219,7 @@ pub struct MessagePacket { /// Not a [`MessageLevel`] directly, the same way [`ProtectionPacket::id`] /// isn't a [`super::Protection`]: this is what was actually on the /// wire, and resolving it to a severity means looking it up (see - /// [`PacketKind::Message`]/[`crate::protocol::Index`]), not storing + /// [`PacketType::Message`]/[`crate::protocol::Index`]), not storing /// a second, redundant copy of it here. pub id: AdjId, /// When it was sent. diff --git a/backend/crates/core/src/protocol.rs b/backend/crates/core/src/protocol.rs index 4ee7cfdd1..e89fe6064 100644 --- a/backend/crates/core/src/protocol.rs +++ b/backend/crates/core/src/protocol.rs @@ -11,7 +11,7 @@ //! compiler enforces the separation the ADJ itself draws between what //! travels over which transport, not runtime convention. `tcp`/`udp` //! themselves are thin wrappers around [`crate::protocol::packet`], which -//! does the actual per-packet-kind work independent of transport. +//! does the actual per-packet-type work independent of transport. mod error; mod index; diff --git a/backend/crates/core/src/protocol/README.md b/backend/crates/core/src/protocol/README.md index 400359608..f107da5d2 100644 --- a/backend/crates/core/src/protocol/README.md +++ b/backend/crates/core/src/protocol/README.md @@ -42,7 +42,7 @@ protocol/ Provides a fast lookup table from packet IDs (`AdjId`) to their declarations (`PacketDef`). Built once from loaded ADJ configuration data (`PodData`), it owns cloned copies of packet definitions so it can be shared across async tasks via `Arc`. -A message severity is not a separate lookup bolted onto `Index` — it's just another `PacketDef`. `Index::new(pod_data, message_levels)` takes `message_levels` as `Option<&HashMap>` (an ADJ's `adj::AdjInfo::message_levels` — `None` for callers with no `AdjInfo` at all, e.g. most tests here) and, for each entry, synthesizes a `PacketDef { kind: PacketKind::Message(level), board: BoardId(0), .. }` into the very same `AdjId -> PacketDef` table as every board's own packets. `BoardId(0)` (reserved, not validated — see `AdjId`/`BoardId`'s own docs) because a severity isn't owned by any one board. Resolving a message is then `Index::packet(id)` + matching `PacketKind::Message(level)`, exactly like `packet::protection` already does for `PacketKind::Protection`. +A message severity is not a separate lookup bolted onto `Index` — it's just another `PacketDef`. `Index::new(pod_data, message_levels)` takes `message_levels` as `Option<&HashMap>` (an ADJ's `adj::AdjInfo::message_levels` — `None` for callers with no `AdjInfo` at all, e.g. most tests here) and, for each entry, synthesizes a `PacketDef { packet_type: PacketType::Message(level), board: BoardId(0), .. }` into the very same `AdjId -> PacketDef` table as every board's own packets. `BoardId(0)` (reserved, not validated — see `AdjId`/`BoardId`'s own docs) because a severity isn't owned by any one board. Resolving a message is then `Index::packet(id)` + matching `PacketType::Message(level)`, exactly like `packet::protection` already does for `PacketType::Protection`. **Key types:** - `Index` - HashMap-based lookup from `AdjId` to `PacketDef` (synthesized `Message` entries included) @@ -63,14 +63,14 @@ Defines errors that can occur during packet encoding and decoding. - `InvalidEnumValue` - Enum index out of range - `UnterminatedString` - String field not null-terminated - `InvalidUtf8` - String field's bytes weren't valid UTF-8 - - `WrongKind` - Packet exists but isn't expected kind + - `WrongPacketType` - Packet exists but isn't expected type - `EncodeError` - Errors when converting packets to bytes - `UnknownId` - No packet declared with this ID - `WrongFieldCount` - Missing or extra fields in order - `TypeMismatch` - Value doesn't match declared type - `OutOfRange` - Numeric value doesn't fit wire type - - `WrongKind` - Packet exists but isn't expected kind + - `WrongPacketType` - Packet exists but isn't expected type - `StringTooLong` - String field + terminator doesn't fit the max length - `EmbeddedNulByte` - String field contains a `\0` byte @@ -90,16 +90,16 @@ Handles conversion between raw bytes and `Value` types for individual measuremen ### `packet/` - Packet-Level Encoding/Decoding -Contains per-packet-kind encoding and decoding logic, independent of +Contains per-packet-type encoding and decoding logic, independent of transport. **Hard rule for this directory: all byte-level parsing for a -packet kind lives in its own file here, never in `tcp.rs`/`udp.rs`.** +packet type lives in its own file here, never in `tcp.rs`/`udp.rs`.** See **[`packet/README.md`](packet/README.md)** for the full design rationale (the `Option` pattern below, and exactly what `tcp.rs` is and isn't allowed to do). #### `data_order.rs` -Handles the positional Data/Order wire shape shared by both packet kinds +Handles the positional Data/Order wire shape shared by both packet types (see `model::DataOrderPacket`'s phantom `Kind`). `encode`/`decode` are generic over `Kind`, written once for both: - **Order packets** (commands sent to boards) - sent over TCP @@ -128,7 +128,7 @@ a protection) — so, same as `protection.rs`, `id` is `Option`: `Some` if the caller already read it (and `reader` starts right after the id), `None` to have `decode` read it itself. Either way, `id` is resolved against `index` to confirm it's actually a declared -`PacketKind::Message` (`UnknownId`/`WrongKind` otherwise) — but unlike +`PacketType::Message` (`UnknownId`/`WrongPacketType` otherwise) — but unlike `protection.rs`, the severity itself is never stored on the decoded `MessagePacket`; it's metadata about the id, not about this particular instance, so look it up again via `index.packet(id)` if it's needed. @@ -161,7 +161,7 @@ Handles the dedicated TCP connection to each board. A TCP connection carries: - Free-text messages (board → backend) - Order commands (backend → board) -`decode_next` reads the frame's leading 16-bit id itself (via `packet::read_id`, `pub(super)` so `tcp` — a sibling of `packet`, not a descendant — can reach it), then dispatches purely on the raw id: `id.0 >= 8192` (`1 << 13` — a protection's compound id always has its high 3 bits set, see `AdjId`'s own docs) goes to `packet::protection::decode(reader, Some(id), index)`, anything below that to `packet::message::decode(reader, Some(id), index)`. Neither branch does its own lookup first — each `decode` already resolves `UnknownId`/`WrongKind` against `index` itself. +`decode_next` reads the frame's leading 16-bit id itself (via `packet::read_id`, `pub(super)` so `tcp` — a sibling of `packet`, not a descendant — can reach it), then dispatches purely on the raw id: `id.0 >= 8192` (`1 << 13` — a protection's compound id always has its high 3 bits set, see `AdjId`'s own docs) goes to `packet::protection::decode(reader, Some(id), index)`, anything below that to `packet::message::decode(reader, Some(id), index)`. Neither branch does its own lookup first — each `decode` already resolves `UnknownId`/`WrongPacketType` against `index` itself. **Key types:** - `TcpFrame` - Enum of frames that can be received over TCP (Protection, Message) @@ -204,7 +204,7 @@ The module includes comprehensive unit tests for: - Order/Data packet encoding and decoding, including round trips - Message/Protection packet decoding (timestamps, strings, values) and their test-only encoding, including round trips -- Error propagation for unknown IDs, wrong kinds, type mismatches, +- Error propagation for unknown IDs, wrong packet types, type mismatches, unterminated/invalid strings, and out-of-range values Run tests with: diff --git a/backend/crates/core/src/protocol/error.rs b/backend/crates/core/src/protocol/error.rs index b08a065a6..b6de39dea 100644 --- a/backend/crates/core/src/protocol/error.rs +++ b/backend/crates/core/src/protocol/error.rs @@ -40,12 +40,12 @@ pub enum DecodeError { #[error("string field wasn't valid UTF-8: {0:?}")] InvalidUtf8(Vec), - /// A looked-up packet exists, but isn't the kind this function expects + /// A looked-up packet exists, but isn't the type this function expects /// (e.g. `packet::data::decode` found an id that resolves to an /// `Order`). - #[error("packet {id:?} isn't the expected kind")] - WrongKind { - /// The packet whose kind didn't match. + #[error("packet {id:?} isn't the expected type")] + WrongPacketType { + /// The packet whose type didn't match. id: AdjId, }, } @@ -70,7 +70,7 @@ impl PartialEq for DecodeError { ) => a_index == b_index && a_options == b_options, (Self::UnterminatedString { max: a }, Self::UnterminatedString { max: b }) => a == b, (Self::InvalidUtf8(a), Self::InvalidUtf8(b)) => a == b, - (Self::WrongKind { id: a }, Self::WrongKind { id: b }) => a == b, + (Self::WrongPacketType { id: a }, Self::WrongPacketType { id: b }) => a == b, _ => false, } } @@ -111,12 +111,12 @@ pub enum EncodeError { max: f64, }, - /// A looked-up packet exists, but isn't the kind this function expects + /// A looked-up packet exists, but isn't the type this function expects /// (e.g. `packet::order::encode` found an id that resolves to a /// `Data` packet). - #[error("packet {id:?} isn't the expected kind")] - WrongKind { - /// The packet whose kind didn't match. + #[error("packet {id:?} isn't the expected type")] + WrongPacketType { + /// The packet whose type didn't match. id: AdjId, }, diff --git a/backend/crates/core/src/protocol/index.rs b/backend/crates/core/src/protocol/index.rs index 117802a3a..0f9d5a5bd 100644 --- a/backend/crates/core/src/protocol/index.rs +++ b/backend/crates/core/src/protocol/index.rs @@ -1,6 +1,6 @@ //! The `id -> PacketDef` lookup `tcp`/`udp` decode against. -use crate::model::{AdjId, BoardId, MessageLevel, PacketDef, PacketKind, PodData}; +use crate::model::{AdjId, BoardId, MessageLevel, PacketDef, PacketType, PodData}; use std::collections::HashMap; /// A lookup table from a packet's [`AdjId`] to its declaration, built once @@ -49,7 +49,7 @@ impl Index { id, board: BoardId(0), name: level.name().to_string(), - kind: PacketKind::Message(level), + packet_type: PacketType::Message(level), }, ); } @@ -60,7 +60,8 @@ impl Index { /// Looks up a packet's declaration by id — a message severity /// resolves through here too, as a synthesized `PacketDef` with - /// `kind: PacketKind::Message(level)`; see this type's doc comment. + /// `packet_type: PacketType::Message(level)`; see this type's doc + /// comment. pub fn packet(&self, id: AdjId) -> Option<&PacketDef> { self.by_id.get(&id) } @@ -69,7 +70,7 @@ impl Index { #[cfg(test)] mod tests { use super::*; - use crate::model::{Board, BoardId, MacAddress, PacketKind}; + use crate::model::{Board, BoardId, MacAddress, PacketType}; use std::net::IpAddr; fn sample_pod_data() -> PodData { @@ -77,7 +78,7 @@ mod tests { id: AdjId(1000), board: BoardId(1), name: "bcu_data".to_string(), - kind: PacketKind::Data(vec![]), + packet_type: PacketType::Data(vec![]), }; let board = Board { id: BoardId(1), @@ -114,7 +115,7 @@ mod tests { let Some(packet) = index.packet(AdjId(2)) else { unreachable!("the \"fault\" severity was declared at id 2"); }; - assert_eq!(packet.kind, PacketKind::Message(MessageLevel::Fault)); + assert_eq!(packet.packet_type, PacketType::Message(MessageLevel::Fault)); assert_eq!(packet.board, BoardId(0)); } diff --git a/backend/crates/core/src/protocol/packet.rs b/backend/crates/core/src/protocol/packet.rs index df7842292..3e061e44d 100644 --- a/backend/crates/core/src/protocol/packet.rs +++ b/backend/crates/core/src/protocol/packet.rs @@ -1,12 +1,12 @@ -//! Encode/decode for one specific kind of packet, independent of which +//! Encode/decode for one specific type of packet, independent of which //! transport carries it — that mapping lives in [`super::tcp`]/ //! [`super::udp`], which are thin wrappers around these. //! //! [`data_order`]'s `encode`/`decode` are generic over `Kind` -//! ([`crate::model::KindTag`]), so they work for both `Data` and `Order` -//! alike; the backend itself only ever exercises one direction per kind -//! (an order is only ever sent, data only ever received), but that's a -//! restriction `tcp`/`udp` apply, not something baked into the codec. +//! ([`crate::model::PacketTypeTag`]), so they work for both `Data` and +//! `Order` alike; the backend itself only ever exercises one direction per +//! type (an order is only ever sent, data only ever received), but that's +//! a restriction `tcp`/`udp` apply, not something baked into the codec. //! //! [`message`]/[`protection`] are genuinely one-directional in //! production — a board only ever sends these, never receives them — @@ -24,7 +24,7 @@ use std::io::Read; /// Reads a raw little-endian 16-bit id off the front of `reader`. /// -/// Shared by [`message`]/[`protection`] — the only two kinds whose +/// Shared by [`message`]/[`protection`] — the only two types whose /// `decode` ever needs to read its own leading id, when the caller /// doesn't already know it (see each module's own doc comment on why) — /// and by [`super::tcp::decode_next`], which needs the id *before* it diff --git a/backend/crates/core/src/protocol/packet/README.md b/backend/crates/core/src/protocol/packet/README.md index 668e8532b..b55d7556b 100644 --- a/backend/crates/core/src/protocol/packet/README.md +++ b/backend/crates/core/src/protocol/packet/README.md @@ -1,6 +1,6 @@ -# `packet/` — Per-Packet-Kind Codecs +# `packet/` — Per-Packet-Type Codecs -Each file here owns **all** the byte-level parsing for one packet kind — +Each file here owns **all** the byte-level parsing for one packet type — how many bytes a field takes, in what order, what terminates a string, what the leading id means. That parsing never gets split out into `tcp.rs`/`udp.rs` (the transport layer) or anywhere else. A transport @@ -14,7 +14,7 @@ Self-contained both ways: `encode`/`decode` always read/write the leading 2-byte id themselves, since there's no dispatch ambiguity to resolve first — a UDP datagram is unambiguously `Data`, and an order is only ever something the backend already decided to send. Generic over -`Kind` (`model::KindTag`), written once for both `Data` and `Order` — +`Kind` (`model::PacketTypeTag`), written once for both `Data` and `Order` — see its own module doc and `model/README.md`'s §4.2 for why. ## `message.rs` / `protection.rs` @@ -44,27 +44,27 @@ pub fn encode(packet: &MessagePacket, index: &Index) -> Result, EncodeEr this case `reader` must start at byte 0 of the frame, id included, and `decode` reads those 2 bytes itself. Either way, the id is then resolved against `index` — `index.packet(id)` + matching - `PacketKind::Protection`/`PacketKind::Message` — to confirm it's - actually the declared kind (`UnknownId`/`WrongKind` otherwise). A + `PacketType::Protection`/`PacketType::Message` — to confirm it's + actually the declared type (`UnknownId`/`WrongPacketType` otherwise). A message's severity is just another `PacketDef` by the time it gets here (see `index.rs`'s own docs) — there's no separate lookup for it. One real difference between the two: `ProtectionPacket` stores its `id` *and* the triggering `value` (which needs the watched measurement's -wire type, from `PacketKind::Protection(measurement)`, to decode at +wire type, from `PacketType::Protection(measurement)`, to decode at all). `MessagePacket` only stores `id` — its severity is metadata *about* that id, not part of the frame's own byte layout, so `decode` -only uses `PacketKind::Message(level)` to confirm the kind and discards +only uses `PacketType::Message(level)` to confirm the type and discards `level` immediately; nothing about `timestamp`/`origin`/`message`'s bytes depends on which severity it is. Look the severity up again via `index.packet(id)` if it's needed later — it's never stored redundantly on the decoded instance. Either way, **every byte of this frame is parsed inside the file that -owns that packet kind** — `tcp.rs` never touches a timestamp, a `resv` +owns that packet type** — `tcp.rs` never touches a timestamp, a `resv` byte, a measurement's wire width, or a NUL-terminated string. `encode` always writes the leading id back out too (from `packet.id`, after -confirming via `index` it resolves to the right kind), so its output is +confirming via `index` it resolves to the right type), so its output is a complete, self-contained frame — feed it straight into `decode(reader, None, index)` and get the same packet back; that's exactly what each file's round-trip test does. diff --git a/backend/crates/core/src/protocol/packet/data_order.rs b/backend/crates/core/src/protocol/packet/data_order.rs index c01971d35..caca99161 100644 --- a/backend/crates/core/src/protocol/packet/data_order.rs +++ b/backend/crates/core/src/protocol/packet/data_order.rs @@ -3,21 +3,21 @@ //! shape under a phantom `Kind`. //! //! [`encode`]/[`decode`] are generic over that `Kind` via -//! [`crate::model::KindTag`], so they're written once and work for either -//! [`crate::model::Data`] or [`crate::model::Order`] — the backend itself -//! only ever calls `encode::` (via [`super::super::tcp`]) and -//! `decode::` (via [`super::super::udp`]), but that restriction -//! lives at the transport layer, not here. [`crate::model::KindTag`] only -//! answers whether a `PacketDef`'s kind matches `Kind` at all; the actual -//! measurement list comes from [`crate::model::PacketKind::measurements`] -//! either way. - -use crate::model::{AdjId, DataOrderPacket, KindTag}; +//! [`crate::model::PacketTypeTag`], so they're written once and work for +//! either [`crate::model::Data`] or [`crate::model::Order`] — the backend +//! itself only ever calls `encode::` (via [`super::super::tcp`]) +//! and `decode::` (via [`super::super::udp`]), but that restriction +//! lives at the transport layer, not here. [`crate::model::PacketTypeTag`] +//! only answers whether a `PacketDef`'s type matches `Kind` at all; the +//! actual measurement list comes from +//! [`crate::model::PacketType::measurements`] either way. + +use crate::model::{AdjId, DataOrderPacket, PacketTypeTag}; use crate::protocol::{DecodeError, EncodeError, Index, wire}; /// Encodes `packet` into the bytes to write to a board's connection, /// resolving its field shapes against `index`. -pub fn encode( +pub fn encode( packet: &DataOrderPacket, index: &Index, ) -> Result, EncodeError> { @@ -26,13 +26,13 @@ pub fn encode( .packet(packet.id) .ok_or(EncodeError::UnknownId(packet.id))?; - // Check that the packet is an order or data, as expected by the generic KindTag - if !Kind::matches(&packet_def.kind) { - return Err(EncodeError::WrongKind { id: packet.id }); + // Check that the packet is an order or data, as expected by the generic PacketTypeTag + if !Kind::matches(&packet_def.packet_type) { + return Err(EncodeError::WrongPacketType { id: packet.id }); } // Get the measurements for this packet - let measurements = packet_def.kind.measurements(); + let measurements = packet_def.packet_type.measurements(); // Check that the number of values that we want to encode matches the number of measurements in the packet definition if packet.values.len() != measurements.len() { @@ -60,7 +60,7 @@ pub fn encode( /// Decodes a complete, already-delimited buffer into a /// [`DataOrderPacket`], resolving its field shapes against `index`. -pub fn decode( +pub fn decode( bytes: &[u8], index: &Index, ) -> Result, DecodeError> { @@ -80,12 +80,12 @@ pub fn decode( // Look up the packet definition for this id if not found return an UnknownId error let packet_def = index.packet(adj_id).ok_or(DecodeError::UnknownId(adj_id))?; - // Check that the packet is an order or data, as expected by the generic KindTag - if !Kind::matches(&packet_def.kind) { - return Err(DecodeError::WrongKind { id: adj_id }); + // Check that the packet is an order or data, as expected by the generic PacketTypeTag + if !Kind::matches(&packet_def.packet_type) { + return Err(DecodeError::WrongPacketType { id: adj_id }); } // Get the measurements for this packet - let measurements = packet_def.kind.measurements(); + let measurements = packet_def.packet_type.measurements(); // Prepare a vector to hold the decoded values and a pointer to track the current position in the byte slice let mut values = Vec::with_capacity(measurements.len()); @@ -117,7 +117,7 @@ mod tests { use super::*; use crate::model::{ Board, BoardId, Data, DataPacket, MacAddress, Measurement, MeasurementKind, NumericKind, - Order, OrderPacket, PacketDef, PacketKind, PodData, Value, + Order, OrderPacket, PacketDef, PacketType, PodData, Value, }; use std::collections::HashMap; use std::net::IpAddr; @@ -135,12 +135,12 @@ mod tests { } } - fn sample_packet_def(id: AdjId, kind: PacketKind) -> PacketDef { + fn sample_packet_def(id: AdjId, packet_type: PacketType) -> PacketDef { PacketDef { id, board: BoardId(1), name: "TestPacket".into(), - kind, + packet_type, } } @@ -166,7 +166,7 @@ mod tests { let order_id = AdjId(1001); let packet_def = sample_packet_def( order_id, - PacketKind::Order(vec![ + PacketType::Order(vec![ sample_measurement( 1, MeasurementKind::Numeric { @@ -208,17 +208,17 @@ mod tests { } #[test] - fn encode_fails_on_wrong_kind() { + fn encode_fails_on_wrong_packet_type() { let data_id = AdjId(2001); - let packet_def = sample_packet_def(data_id, PacketKind::Data(vec![])); + let packet_def = sample_packet_def(data_id, PacketType::Data(vec![])); let index = make_test_index(vec![packet_def]); let packet = OrderPacket::new(data_id, vec![]); let Err(err) = encode(&packet, &index) else { - unreachable!("encoding the wrong packet kind should fail"); + unreachable!("encoding the wrong packet type should fail"); }; - assert_eq!(err, EncodeError::WrongKind { id: data_id }); + assert_eq!(err, EncodeError::WrongPacketType { id: data_id }); } #[test] @@ -226,7 +226,7 @@ mod tests { let order_id = AdjId(1002); let packet_def = sample_packet_def( order_id, - PacketKind::Order(vec![ + PacketType::Order(vec![ sample_measurement( 1, MeasurementKind::Numeric { @@ -264,7 +264,7 @@ mod tests { let data_id = AdjId(3001); let packet_def = sample_packet_def( data_id, - PacketKind::Data(vec![ + PacketType::Data(vec![ sample_measurement( 1, MeasurementKind::Numeric { @@ -312,7 +312,7 @@ mod tests { let data_id = AdjId(3002); let packet_def = sample_packet_def( data_id, - PacketKind::Data(vec![sample_measurement( + PacketType::Data(vec![sample_measurement( 1, MeasurementKind::Numeric { wire_type: NumericKind::U32, @@ -341,17 +341,17 @@ mod tests { } #[test] - fn decode_fails_on_wrong_kind() { + fn decode_fails_on_wrong_packet_type() { let order_id = AdjId(4001); - let packet_def = sample_packet_def(order_id, PacketKind::Order(vec![])); + let packet_def = sample_packet_def(order_id, PacketType::Order(vec![])); let index = make_test_index(vec![packet_def]); let raw_bytes = [0xA1, 0x0F]; let Err(err) = decode::(&raw_bytes, &index) else { - unreachable!("decoding the wrong packet kind should fail"); + unreachable!("decoding the wrong packet type should fail"); }; - assert_eq!(err, DecodeError::WrongKind { id: order_id }); + assert_eq!(err, DecodeError::WrongPacketType { id: order_id }); } // --- ROUND-TRIP TESTS --- @@ -359,7 +359,7 @@ mod tests { // `encode`/`decode` are generic over `Kind`, so the same `PacketDef` // works for both directions here — that genericity is the whole // point of giving `DataOrderPacket` a phantom `Kind` in the first - // place, instead of writing one hardcoded pair of functions per kind. + // place, instead of writing one hardcoded pair of functions per type. // // Enum fields are left out of both: `encode_enum` takes an // already-selected index (`Value::Number`) but `decode_enum` returns @@ -389,7 +389,7 @@ mod tests { let id = AdjId(6001); let index = make_test_index(vec![sample_packet_def( id, - PacketKind::Order(numeric_measurements()), + PacketType::Order(numeric_measurements()), )]); let original = OrderPacket::new(id, vec![Value::Number(1234.0), Value::Number(-5.0)]); @@ -409,7 +409,7 @@ mod tests { let id = AdjId(6002); let index = make_test_index(vec![sample_packet_def( id, - PacketKind::Data(numeric_measurements()), + PacketType::Data(numeric_measurements()), )]); let original = DataPacket::new(id, vec![Value::Number(42.0), Value::Number(-1.0)]); diff --git a/backend/crates/core/src/protocol/packet/message.rs b/backend/crates/core/src/protocol/packet/message.rs index b1b776a62..ec20e16e3 100644 --- a/backend/crates/core/src/protocol/packet/message.rs +++ b/backend/crates/core/src/protocol/packet/message.rs @@ -24,12 +24,12 @@ //! //! Unlike [`super::protection`] too, [`MessagePacket`] doesn't carry its //! own severity — `id` is resolved against `index` to confirm it's -//! actually a declared [`crate::model::PacketKind::Message`] (so a -//! `WrongKind`/`UnknownId` frame is rejected), but the severity itself -//! is never stored redundantly on the decoded instance; look it up via -//! `index.packet(id)` again if it's needed. +//! actually a declared [`crate::model::PacketType::Message`] (so a +//! `WrongPacketType`/`UnknownId` frame is rejected), but the severity +//! itself is never stored redundantly on the decoded instance; look it up +//! via `index.packet(id)` again if it's needed. -use crate::model::{AdjId, MessagePacket, PacketKind, ShortTimestamp}; +use crate::model::{AdjId, MessagePacket, PacketType, ShortTimestamp}; use crate::protocol::{DecodeError, EncodeError, Index}; use std::io::Read; @@ -58,8 +58,8 @@ pub fn decode( // message packet. If not, the frame is malformed and we can't decode it. let packet_def = index.packet(id).ok_or(DecodeError::UnknownId(id))?; - let PacketKind::Message(_) = &packet_def.kind else { - return Err(DecodeError::WrongKind { id }); + let PacketType::Message(_) = &packet_def.packet_type else { + return Err(DecodeError::WrongPacketType { id }); }; let mut header = [0u8; 4]; @@ -113,8 +113,8 @@ pub fn encode(packet: &MessagePacket, index: &Index) -> Result, EncodeEr .packet(packet.id) .ok_or(EncodeError::UnknownId(packet.id))?; - let PacketKind::Message(_) = &packet_def.kind else { - return Err(EncodeError::WrongKind { id: packet.id }); + let PacketType::Message(_) = &packet_def.packet_type else { + return Err(EncodeError::WrongPacketType { id: packet.id }); }; let mut bytes = packet.id.0.to_le_bytes().to_vec(); @@ -284,7 +284,7 @@ mod tests { id: data_id, board: BoardId(1), name: "bcu_data".to_string(), - kind: PacketKind::Data(vec![]), + packet_type: PacketType::Data(vec![]), }; let board = Board { id: BoardId(1), @@ -302,7 +302,7 @@ mod tests { let Err(err) = decode(Cursor::new(bytes), None, &index) else { unreachable!("decoding an id that resolves to a Data packet should fail"); }; - assert_eq!(err, DecodeError::WrongKind { id: data_id }); + assert_eq!(err, DecodeError::WrongPacketType { id: data_id }); } // --- ENCODE TESTS --- @@ -356,13 +356,13 @@ mod tests { } #[test] - fn encode_fails_on_wrong_kind() { + fn encode_fails_on_wrong_packet_type() { let data_id = AdjId(2000); let packet_def = PacketDef { id: data_id, board: BoardId(1), name: "bcu_data".to_string(), - kind: PacketKind::Data(vec![]), + packet_type: PacketType::Data(vec![]), }; let board = Board { id: BoardId(1), @@ -391,7 +391,7 @@ mod tests { let Err(err) = encode(&packet, &index) else { unreachable!("encoding into a non-message packet's id should fail"); }; - assert_eq!(err, EncodeError::WrongKind { id: data_id }); + assert_eq!(err, EncodeError::WrongPacketType { id: data_id }); } #[test] diff --git a/backend/crates/core/src/protocol/packet/protection.rs b/backend/crates/core/src/protocol/packet/protection.rs index fdb36768d..d3a4e1e4e 100644 --- a/backend/crates/core/src/protocol/packet/protection.rs +++ b/backend/crates/core/src/protocol/packet/protection.rs @@ -22,7 +22,7 @@ //! [`crate::protocol::wire::byte_width`] says for the watched //! measurement's kind — not fixed, unlike every other field here. -use crate::model::{AdjId, PacketKind, ProtectionPacket, ShortTimestamp}; +use crate::model::{AdjId, PacketType, ProtectionPacket, ShortTimestamp}; use crate::protocol::{DecodeError, EncodeError, Index, wire}; use std::io::Read; @@ -48,8 +48,8 @@ pub fn decode( .packet(compound_id) .ok_or(DecodeError::UnknownId(compound_id))?; - let PacketKind::Protection(measurement) = &packet_def.kind else { - return Err(DecodeError::WrongKind { id: compound_id }); + let PacketType::Protection(measurement) = &packet_def.packet_type else { + return Err(DecodeError::WrongPacketType { id: compound_id }); }; // `hora`/`min`/`seg`/`subseg` (1 byte each), then 2 bytes of `resv` @@ -88,8 +88,8 @@ pub fn encode(packet: &ProtectionPacket, index: &Index) -> Result, Encod .packet(packet.id) .ok_or(EncodeError::UnknownId(packet.id))?; - let PacketKind::Protection(measurement) = &packet_def.kind else { - return Err(EncodeError::WrongKind { id: packet.id }); + let PacketType::Protection(measurement) = &packet_def.packet_type else { + return Err(EncodeError::WrongPacketType { id: packet.id }); }; let mut bytes = packet.id.0.to_le_bytes().to_vec(); @@ -136,7 +136,7 @@ mod tests { id: compound_id, board: BoardId(1), name: "mock_protection".to_string(), - kind: PacketKind::Protection(measurement), + packet_type: PacketType::Protection(measurement), }; let board = Board { id: BoardId(1), @@ -219,7 +219,7 @@ mod tests { } #[test] - fn a_non_protection_packet_at_that_id_is_the_wrong_kind() { + fn a_non_protection_packet_at_that_id_is_the_wrong_packet_type() { let measurement = sample_measurement( 200, MeasurementKind::Numeric { @@ -231,7 +231,7 @@ mod tests { id: compound_id, board: BoardId(1), name: "mock_data".to_string(), - kind: PacketKind::Data(vec![measurement]), + packet_type: PacketType::Data(vec![measurement]), }; let board = Board { id: BoardId(1), @@ -247,7 +247,7 @@ mod tests { assert!(matches!( decode(Cursor::new(vec![]), Some(compound_id), &index), - Err(DecodeError::WrongKind { id }) if id == compound_id + Err(DecodeError::WrongPacketType { id }) if id == compound_id )); } @@ -364,7 +364,7 @@ mod tests { } #[test] - fn encode_fails_on_wrong_kind() { + fn encode_fails_on_wrong_packet_type() { let measurement = sample_measurement( 200, MeasurementKind::Numeric { @@ -376,7 +376,7 @@ mod tests { id: compound_id, board: BoardId(1), name: "mock_data".to_string(), - kind: PacketKind::Data(vec![measurement]), + packet_type: PacketType::Data(vec![measurement]), }; let board = Board { id: BoardId(1), @@ -402,9 +402,9 @@ mod tests { }; let Err(err) = encode(&packet, &index) else { - unreachable!("encoding the wrong packet kind should fail"); + unreachable!("encoding the wrong packet type should fail"); }; - assert_eq!(err, EncodeError::WrongKind { id: compound_id }); + assert_eq!(err, EncodeError::WrongPacketType { id: compound_id }); } #[test] diff --git a/backend/crates/core/src/protocol/tcp.rs b/backend/crates/core/src/protocol/tcp.rs index a2d645944..d4becf3fb 100644 --- a/backend/crates/core/src/protocol/tcp.rs +++ b/backend/crates/core/src/protocol/tcp.rs @@ -3,7 +3,7 @@ //! orders to it. Never a `Data` packet — see the module doc on //! [`super`]. //! -//! Both functions here are thin: the actual per-kind decoding lives in +//! Both functions here are thin: the actual per-type decoding lives in //! [`super::packet::protection`]/[`super::packet::message`]/ //! [`super::packet::data_order`], independent of TCP. This module only adds //! the transport-level guarantee — [`decode_next`] can only ever return @@ -35,8 +35,9 @@ pub enum TcpFrame { /// position (see [`crate::model::AdjId`]'s own docs on its ranges), so /// `id.0 >= 8192` (`1 << 13`) is a protection; anything below that hands /// off to `message::decode` instead — `message::decode` resolves it -/// against `index` itself (`UnknownId`/`WrongKind` if it isn't actually -/// a declared message), so there's no separate lookup to do here first. +/// against `index` itself (`UnknownId`/`WrongPacketType` if it isn't +/// actually a declared message), so there's no separate lookup to do here +/// first. /// Either call's result is wrapped in the matching [`TcpFrame`] variant. pub fn decode_next(mut reader: impl Read, index: &Index) -> Result { let id = packet::read_id(&mut reader)?; @@ -60,7 +61,7 @@ mod tests { use super::*; use crate::model::{ AdjId, Board, BoardId, MacAddress, Measurement, MeasurementKind, MessageLevel, NumericKind, - PacketDef, PacketKind, PodData, ShortTimestamp, Value, + PacketDef, PacketType, PodData, ShortTimestamp, Value, }; use std::collections::HashMap; use std::io::Cursor; @@ -84,7 +85,7 @@ mod tests { id: compound_id, board: BoardId(1), name: "temp_protection".to_string(), - kind: PacketKind::Protection(measurement), + packet_type: PacketType::Protection(measurement), }; let board = Board { id: BoardId(1), From f5821af746ecd441fe1835dd199737be93249037 Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Wed, 14 Oct 2026 18:33:26 +0200 Subject: [PATCH 092/225] refactor(backend, git): separete errors in specific file --- backend/crates/core/src/git.rs | 69 +----------- backend/crates/core/src/git/clone.rs | 39 ++----- backend/crates/core/src/git/error.rs | 121 ++++++++++++++++++++++ backend/crates/core/src/git/repository.rs | 33 +----- 4 files changed, 134 insertions(+), 128 deletions(-) create mode 100644 backend/crates/core/src/git/error.rs diff --git a/backend/crates/core/src/git.rs b/backend/crates/core/src/git.rs index 46c854cef..3418342c0 100644 --- a/backend/crates/core/src/git.rs +++ b/backend/crates/core/src/git.rs @@ -1,72 +1,11 @@ //! Blocking Git helpers for ADJ, an application-owned, replaceable data cache. mod clone; +mod error; mod repository; mod update; -pub use clone::CloneError; -pub use repository::{RepositoryError, branch_exists, list_remote_branches, open_repo}; +pub use error::{CloneError, GitError, RepositoryError}; +pub use repository::{branch_exists, list_remote_branches, open_repo}; +pub(crate) use update::unwrap_repo_path; pub use update::update_adj; - -/// Errors produced while reading, downloading, or replacing the ADJ cache. -/// -/// Five categories identify the failed operation and preserve its underlying -/// error as [`std::error::Error::source`]. [`RepositoryError`] and [`CloneError`] -/// retain concrete `gix` causes and are boxed to keep this enum small. -/// -/// A failed connectivity probe is not itself an error when cached ADJ exists. -/// If no cache exists, the operation returns [`GitError::UnavailableOffline`]. -#[derive(Debug, thiserror::Error)] -pub enum GitError { - /// Resolving, inspecting, or preparing the cache directory failed. - #[error("ADJ path operation failed: {0}")] - Path(#[source] std::io::Error), - - /// Opening the repository, reading HEAD, or querying local or remote refs failed. - /// A branch missing from a successful remote listing is not an error. - #[error("ADJ repository operation failed: {0}")] - Repository(#[source] Box), - - /// Preparing, downloading, or checking out the requested branch failed. - /// - /// This can indicate a network, configuration, or remote-reference failure; - /// it does not necessarily mean that internet connectivity is unavailable. - #[error("ADJ clone failed: {0}")] - Clone(#[source] Box), - - /// Moving the old cache aside or installing the new checkout failed. - /// - /// When restoration also fails, `rollback` holds its error and the preserved - /// backup's location. Otherwise, the old cache was restored or never moved. - #[error( - "ADJ cache replacement failed: {source}{recovery}", - recovery = .rollback.as_ref().map(|(error, path)| { - format!("; rollback failed: {error}; backup kept at {}", path.display()) - }).unwrap_or_default() - )] - Replacement { - /// The original error moving the old cache or installing the new checkout. - #[source] - source: std::io::Error, - /// Restoration error and preserved backup path, if rollback failed. - rollback: Option<(std::io::Error, std::path::PathBuf)>, - }, - - /// The connectivity probe failed and no local ADJ cache was available. - #[error("ADJ is not available locally and cannot be downloaded")] - UnavailableOffline, -} - -// Convert repository errors for '?' propagation, boxing the concrete error to keep GitError small. -impl From for GitError { - fn from(error: RepositoryError) -> Self { - Self::Repository(Box::new(error)) - } -} - -// Convert clone errors for '?' propagation, boxing the concrete error to keep GitError small. -impl From for GitError { - fn from(error: CloneError) -> Self { - Self::Clone(Box::new(error)) - } -} diff --git a/backend/crates/core/src/git/clone.rs b/backend/crates/core/src/git/clone.rs index 006f127ab..bccc73c9f 100644 --- a/backend/crates/core/src/git/clone.rs +++ b/backend/crates/core/src/git/clone.rs @@ -1,38 +1,13 @@ -use super::{GitError, update::get_commit_hash}; +use super::{ + error::{CloneError, GitError}, + update::get_commit_hash, +}; use gix::Repository; use std::{fs, path::Path, sync::atomic::AtomicBool}; use tracing::{debug, info, instrument, warn}; const GIT_REMOTE: &str = "origin"; -/// Concrete clone failures wrapped by [`GitError::Clone`]. -/// -/// Preparation, name validation, fetching, and checkout expose different `gix` -/// error types. These variants retain each original error as their source. -#[derive(Debug, thiserror::Error)] -pub enum CloneError { - /// Clone preparation failed before downloading repository data. - #[error("clone preparation failed: {0}")] - Prepare(#[from] gix::clone::Error), - - /// The configured remote name was invalid. - #[error("remote name is invalid: {0}")] - RemoteName(#[from] gix::remote::name::Error), - - /// The requested branch name was not a valid Git reference name. - #[error("branch name is invalid: {0}")] - BranchName(#[from] gix::validate::reference::name::Error), - - /// Fetching failed, including a missing requested branch. - /// This can indicate network, configuration, or remote-reference failures. - #[error("fetch failed: {0}")] - Fetch(#[from] gix::clone::fetch::Error), - - /// Downloaded data could not be checked out into the working tree. - #[error("checkout failed: {0}")] - Checkout(#[from] gix::clone::checkout::main_worktree::Error), -} - // Fetch and check out the requested branch instead of switching an existing repo. #[instrument(level = "debug", skip(url))] fn git_clone(path: &Path, branch: &str, url: &str) -> Result { @@ -171,7 +146,8 @@ mod tests { // Verify branch selection, newer commits, and removal of stale cache files. #[test] - fn clones_and_replaces_with_requested_branch() -> Result<(), Box> { + fn clones_and_replaces_with_requested_branch() + -> Result<(), Box> { let temp = tempfile::tempdir()?; let source = temp.path().join("source"); let cache = temp.path().join("cache").join("adj"); @@ -210,7 +186,8 @@ mod tests { // Verify clone failures preserve cached ADJ and leave no staging debris. #[test] - fn failed_clone_preserves_existing_cache() -> Result<(), Box> { + fn failed_clone_preserves_existing_cache() + -> Result<(), Box> { let temp = tempfile::tempdir()?; let source = temp.path().join("source"); let cache = temp.path().join("adj"); diff --git a/backend/crates/core/src/git/error.rs b/backend/crates/core/src/git/error.rs new file mode 100644 index 000000000..ec3c3f69b --- /dev/null +++ b/backend/crates/core/src/git/error.rs @@ -0,0 +1,121 @@ +/// Errors produced while reading, downloading, or replacing the ADJ cache. +/// +/// Five categories identify the failed operation and preserve its underlying +/// error as [`std::error::Error::source`]. [`RepositoryError`] and [`CloneError`] +/// retain concrete `gix` causes and are boxed to keep this enum small. +/// +/// A failed connectivity probe is not itself an error when cached ADJ exists. +/// If no cache exists, the operation returns [`GitError::UnavailableOffline`]. +#[derive(Debug, thiserror::Error)] +pub enum GitError { + /// Resolving, inspecting, or preparing the cache directory failed. + #[error("ADJ path operation failed: {0}")] + Path(#[source] std::io::Error), + + /// Opening the repository, reading HEAD, or querying local or remote refs failed. + /// A branch missing from a successful remote listing is not an error. + #[error("ADJ repository operation failed: {0}")] + Repository(#[source] Box), + + /// Preparing, downloading, or checking out the requested branch failed. + /// + /// This can indicate a network, configuration, or remote-reference failure; + /// it does not necessarily mean that internet connectivity is unavailable. + #[error("ADJ clone failed: {0}")] + Clone(#[source] Box), + + /// Moving the old cache aside or installing the new checkout failed. + /// + /// When restoration also fails, `rollback` holds its error and the preserved + /// backup's location. Otherwise, the old cache was restored or never moved. + #[error( + "ADJ cache replacement failed: {source}{recovery}", + recovery = .rollback.as_ref().map(|(error, path)| { + format!("; rollback failed: {error}; backup kept at {}", path.display()) + }).unwrap_or_default() + )] + Replacement { + /// The original error moving the old cache or installing the new checkout. + #[source] + source: std::io::Error, + /// Restoration error and preserved backup path, if rollback failed. + rollback: Option<(std::io::Error, std::path::PathBuf)>, + }, + + /// The connectivity probe failed and no local ADJ cache was available. + #[error("ADJ is not available locally and cannot be downloaded")] + UnavailableOffline, +} + +// Convert repository errors for '?' propagation, boxing the concrete error to keep GitError small. +impl From for GitError { + fn from(error: RepositoryError) -> Self { + Self::Repository(Box::new(error)) + } +} + +// Convert clone errors for '?' propagation, boxing the concrete error to keep GitError small. +impl From for GitError { + fn from(error: CloneError) -> Self { + Self::Clone(Box::new(error)) + } +} + +/// Concrete clone failures wrapped by [`GitError::Clone`]. +/// +/// Preparation, name validation, fetching, and checkout expose different `gix` +/// error types. These variants retain each original error as their source. +#[derive(Debug, thiserror::Error)] +pub enum CloneError { + /// Clone preparation failed before downloading repository data. + #[error("clone preparation failed: {0}")] + Prepare(#[from] gix::clone::Error), + + /// The configured remote name was invalid. + #[error("remote name is invalid: {0}")] + RemoteName(#[from] gix::remote::name::Error), + + /// The requested branch name was not a valid Git reference name. + #[error("branch name is invalid: {0}")] + BranchName(#[from] gix::validate::reference::name::Error), + + /// Fetching failed, including a missing requested branch. + /// This can indicate network, configuration, or remote-reference failures. + #[error("fetch failed: {0}")] + Fetch(#[from] gix::clone::fetch::Error), + + /// Downloaded data could not be checked out into the working tree. + #[error("checkout failed: {0}")] + Checkout(#[from] gix::clone::checkout::main_worktree::Error), +} + +/// Concrete repository failures wrapped by [`GitError::Repository`]. +/// +/// Variants identify local reads or remote-reference queries and preserve the +/// original `gix` error as their source. +#[derive(Debug, thiserror::Error)] +pub enum RepositoryError { + /// An existing repository could not be opened or validated. + #[error("repository could not be opened: {0}")] + Open(#[from] gix::open::Error), + + /// HEAD could not be resolved to a commit ID, including an unborn HEAD. + #[error("HEAD could not be resolved: {0}")] + Head(#[from] gix::reference::head_id::Error), + + /// No default fetch remote could be determined, including ambiguous configurations. + #[error("no default fetch remote could be determined")] + NoDefaultRemote, + + /// The selected default remote could not be loaded from repository configuration. + #[error("default fetch remote could not be loaded: {0}")] + FindDefaultRemote(#[from] gix::remote::find::existing::Error), + + /// A transport connection to the selected remote could not be prepared. + #[error("remote connection failed: {0}")] + RemoteConnect(#[from] gix::remote::connect::Error), + + /// The remote handshake or query of advertised references failed. + #[error("remote reference query failed: {0}")] + RemoteRefMap(#[from] gix::remote::ref_map::Error), +} diff --git a/backend/crates/core/src/git/repository.rs b/backend/crates/core/src/git/repository.rs index eeb8b2ff6..cd8d83b1a 100644 --- a/backend/crates/core/src/git/repository.rs +++ b/backend/crates/core/src/git/repository.rs @@ -1,39 +1,8 @@ -use super::{GitError, update::unwrap_repo_path}; +use super::{error::{RepositoryError, GitError}, update::unwrap_repo_path}; use gix::Repository; use std::path::PathBuf; use tracing::{debug, instrument}; -/// Concrete repository failures wrapped by [`GitError::Repository`]. -/// -/// Variants identify local reads or remote-reference queries and preserve the -/// original `gix` error as their source. -#[derive(Debug, thiserror::Error)] -pub enum RepositoryError { - /// An existing repository could not be opened or validated. - #[error("repository could not be opened: {0}")] - Open(#[from] gix::open::Error), - - /// HEAD could not be resolved to a commit ID, including an unborn HEAD. - #[error("HEAD could not be resolved: {0}")] - Head(#[from] gix::reference::head_id::Error), - - /// No default fetch remote could be determined, including ambiguous configurations. - #[error("no default fetch remote could be determined")] - NoDefaultRemote, - - /// The selected default remote could not be loaded from repository configuration. - #[error("default fetch remote could not be loaded: {0}")] - FindDefaultRemote(#[from] gix::remote::find::existing::Error), - - /// A transport connection to the selected remote could not be prepared. - #[error("remote connection failed: {0}")] - RemoteConnect(#[from] gix::remote::connect::Error), - - /// The remote handshake or query of advertised references failed. - #[error("remote reference query failed: {0}")] - RemoteRefMap(#[from] gix::remote::ref_map::Error), -} - /// Opens an existing repository without fetching or changing its checkout. /// /// `path` is the repository directory. If omitted, it defaults to From 791cad7f6b892d24999388da6689389abbd79d4f Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Wed, 14 Oct 2026 18:43:37 +0200 Subject: [PATCH 093/225] feat(backend, adj): implement auto_adj() and create new LoadError for it --- backend/crates/core/src/adj.rs | 48 +++++++++++++++++++++-- backend/crates/core/src/adj/error.rs | 12 +++++- backend/crates/core/src/git/repository.rs | 5 ++- 3 files changed, 58 insertions(+), 7 deletions(-) diff --git a/backend/crates/core/src/adj.rs b/backend/crates/core/src/adj.rs index 839f4fa4a..91179897a 100644 --- a/backend/crates/core/src/adj.rs +++ b/backend/crates/core/src/adj.rs @@ -2,23 +2,35 @@ //! [`crate::model::PodData`], plus backend-session metadata not modeled as //! vehicle data ([`crate::adj::AdjInfo`]). //! -//! Loading (and if `git` feature is enabled also downloading) is not specific to `station`: a sniffer, a -//! simulator, or any other tool that reads an ADJ needs exactly the same -//! parsing. Scope for this iteration: no `sockets.json`, no +//! [`load_from_dir`] loads an existing ADJ directory. With the `git` feature +//! enabled, `auto_adj` updates the ADJ repository before loading its data +//! and returns the checked-out commit hash. +//! +//! Loading is not specific to `station`: a sniffer, a simulator, or any +//! other tool that reads an ADJ needs exactly the same parsing. +//! +//! Scope for this iteration: no `sockets.json`, no //! `period`/`period_type`/`socket` packet fields (matches //! [`crate::model::PacketDef`]'s own omission), and no schema validation //! (`adj::validate` is a separate, deliberately out-of-scope concern for -//! now) — this module only surfaces structural errors it cannot avoid, +//! now). This module only surfaces structural errors it cannot avoid, //! e.g. a packet referencing a measurement alias that doesn't exist. mod error; mod info; mod raw; +#[cfg(feature = "git")] +use std::path::PathBuf; +#[cfg(feature = "git")] +use tracing::{info, instrument}; + pub use error::{LoadError, MeasurementError, ProtectionError}; pub use info::{AdjInfo, ProtectionTypeInfo}; pub use raw::load_from_dir; +#[cfg(feature = "git")] +use crate::git::{unwrap_repo_path, update_adj}; use crate::model::PodData; /// The result of loading an ADJ: the vehicle's data (as [`crate::model`] @@ -31,3 +43,31 @@ pub struct Adj { /// Backend-session metadata from `general_info.json`. pub info: AdjInfo, } + +/// Updates the ADJ repository, loads its data, and returns its full commit hash. +/// +/// `path` identifies the repository directory, not its parent. If omitted, +/// the platform's user cache directory is used. +/// +/// Online, the repository is replaced and local edits and commits are discarded. +/// Offline, the current cached checkout is loaded without switching branches, +/// so it may differ from `branch`. Clone failures do not fall back to the cache. +/// +/// This performs blocking network and filesystem operations. Call during startup, +/// before readers use ADJ, with only one updater at a time. +/// +/// # Errors +/// +/// Returns [`LoadError::Git`] if path resolution or the update fails. +/// Other variants report failures loading the checked-out ADJ data. +/// Loading failures do not restore the previous cache. +#[cfg(feature = "git")] +#[instrument(level = "debug")] +pub fn auto_adj(path: Option, branch: &str) -> Result<(Adj, String), LoadError> { + let repo_path = unwrap_repo_path(path)?; + let hash = update_adj(Some(repo_path.clone()), branch)?; + let adj = load_from_dir(&repo_path)?; + + info!(path = ?repo_path, %hash, "ADJ loaded"); + Ok((adj, hash)) +} diff --git a/backend/crates/core/src/adj/error.rs b/backend/crates/core/src/adj/error.rs index 2f6d31764..957c3a662 100644 --- a/backend/crates/core/src/adj/error.rs +++ b/backend/crates/core/src/adj/error.rs @@ -1,4 +1,4 @@ -//! Errors produced while loading an ADJ. +//! Errors produced while acquiring or loading an ADJ. //! //! Layered on purpose: [`LoadError`] is the only public error type here — //! the one a composition root's own aggregate error would `#[from]`-chain @@ -10,7 +10,10 @@ use std::net::AddrParseError; use std::path::PathBuf; -/// An error produced while loading an ADJ directory into an [`crate::adj::Adj`]. +#[cfg(feature = "git")] +use crate::git::GitError; + +/// An error produced while acquiring or loading an [`crate::adj::Adj`]. #[derive(Debug, thiserror::Error)] pub enum LoadError { /// Couldn't read a file. @@ -108,6 +111,11 @@ pub enum LoadError { #[source] source: MeasurementError, }, + + /// Couldn't resolve the ADJ repository path or update its checkout. + #[cfg(feature = "git")] + #[error("couldn't prepare ADJ repository: {0}")] + Git(#[from] GitError), } /// An error converting a raw measurement into [`crate::model::Measurement`]. diff --git a/backend/crates/core/src/git/repository.rs b/backend/crates/core/src/git/repository.rs index cd8d83b1a..22e16b294 100644 --- a/backend/crates/core/src/git/repository.rs +++ b/backend/crates/core/src/git/repository.rs @@ -1,4 +1,7 @@ -use super::{error::{RepositoryError, GitError}, update::unwrap_repo_path}; +use super::{ + error::{GitError, RepositoryError}, + update::unwrap_repo_path, +}; use gix::Repository; use std::path::PathBuf; use tracing::{debug, instrument}; From c6679ce1a96cd71a7495f7bd5900e04b82a2a151 Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Sun, 18 Oct 2026 22:21:23 +0200 Subject: [PATCH 094/225] wip: net --- backend/crates/core/src/lib.rs | 11 +- backend/crates/core/src/net.rs | 45 ++++ backend/crates/core/src/net/README.md | 175 ++++++++++++ backend/crates/core/src/net/error.rs | 28 ++ backend/crates/core/src/net/report.rs | 367 +++++++++++++++++++++++++ backend/crates/core/src/net/tcp.rs | 375 ++++++++++++++++++++++++++ backend/crates/core/src/net/udp.rs | 217 +++++++++++++++ 7 files changed, 1215 insertions(+), 3 deletions(-) create mode 100644 backend/crates/core/src/net.rs create mode 100644 backend/crates/core/src/net/README.md create mode 100644 backend/crates/core/src/net/error.rs create mode 100644 backend/crates/core/src/net/report.rs create mode 100644 backend/crates/core/src/net/tcp.rs create mode 100644 backend/crates/core/src/net/udp.rs diff --git a/backend/crates/core/src/lib.rs b/backend/crates/core/src/lib.rs index fb8d888bf..573dd787e 100644 --- a/backend/crates/core/src/lib.rs +++ b/backend/crates/core/src/lib.rs @@ -2,12 +2,12 @@ pub mod hello_world; -/// NTP server -#[cfg(feature = "ntp")] -pub mod ntp; /// Basic domain types: identifiers, values, measurements, protections, /// packets and boards. pub mod model; +/// NTP server +#[cfg(feature = "ntp")] +pub mod ntp; /// Parses an ADJ (Architecture Description JSON) directory into /// [`model::PodData`], plus backend-session metadata not modeled as @@ -18,3 +18,8 @@ pub mod adj; /// [`adj`] declares as the schema. See [`protocol::wire`], /// [`protocol::tcp`], [`protocol::udp`]. pub mod protocol; + +/// Owns the real tokio sockets and reports what arrives on them, calling +/// into [`protocol`] to decode. See [`net::tcp`], [`net::udp`]. +#[cfg(feature = "net")] +pub mod net; diff --git a/backend/crates/core/src/net.rs b/backend/crates/core/src/net.rs new file mode 100644 index 000000000..ff2824e13 --- /dev/null +++ b/backend/crates/core/src/net.rs @@ -0,0 +1,45 @@ +//! Real sockets, on top of tokio (feature `net`). +//! +//! Two submodules do the actual I/O: [`crate::net::tcp`], a client that +//! keeps one task per board and recovers frames out of a byte stream, +//! and [`crate::net::udp`], a single shared receive-only socket. This module opens nothing. It defines only what +//! both of them need to agree on: [`crate::net::Event`] (what happened on +//! a link, carried by a [`crate::net::Notification`]) and +//! [`crate::net::Reporter`] (the two sinks they report through — one for +//! notifications, one for errors). +//! +//! Everything that reaches a [`crate::net::Reporter`] has already been +//! decoded by [`crate::protocol`], which this module layers on top of: +//! `protocol` turns bytes into packets and never touches a socket, `net` +//! owns the socket and calls into it. A sniffer or a simulator can use +//! `protocol` on its own, against a capture, without any of this. +//! +//! # Identity +//! +//! Everything that travels down the notification channel carries its +//! board: [`crate::net::Notification`] holds a +//! [`crate::model::BoardId`] next to the timestamp, whatever the event +//! is. No consumer ever has to go and look up whose packet it just got. +//! +//! It is never a second source of truth, though — it is resolved from +//! what the ADJ already says, once, here. A TCP task was spawned for one +//! board and knows it without asking; [`crate::net::udp`] resolves it +//! from the decoded packet's id through [`crate::protocol::Index`] (every +//! [`crate::model::PacketDef`] carries its `board`), which is one +//! `HashMap` lookup per datagram instead of one per consumer downstream. +//! +//! A board id is all the identity there is: one connection per board, and +//! one shared socket for UDP, so nothing needs telling apart beyond it. +//! +//! Addresses are for the operator, not for the domain types: they show +//! up interpolated in each submodule's error messages (`tcp::Error`, +//! `udp::Error`), which is where somebody actually reads them. + +mod error; +mod report; + +pub mod tcp; +pub mod udp; + +pub use error::Error; +pub use report::{Closed, ErrorReport, Event, Notification, Reporter, Sinks}; diff --git a/backend/crates/core/src/net/README.md b/backend/crates/core/src/net/README.md new file mode 100644 index 000000000..f5f9cd5f3 --- /dev/null +++ b/backend/crates/core/src/net/README.md @@ -0,0 +1,175 @@ +# `net` — Real Sockets (feature `net`) + +Owns the actual tokio sockets. `protocol` turns bytes into packets and never +touches a socket; `net` owns the socket and calls into `protocol`. Nothing above +`net` (WebSocket, disk, aggregation) is known here. + +Two submodules do the I/O, and **this directory's shared part opens nothing**: + +``` +net/ +├── net.rs # module root: docs and re-exports +├── report.rs # Event, Notification, ErrorReport, Reporter — what is reported +├── error.rs # Error — aggregates tcp::Error / udp::Error, nothing else +├── tcp.rs # the TCP client (not written yet: error type + contract) +└── udp.rs # the shared UDP socket (not written yet: error type + contract) +``` + +## The shared part + +### Identity: the board travels with everything + +Every notification carries its board, whatever the event: + +```rust +Notification { board: BoardId, at: SystemTime, event: Event } +``` + +It is never a second source of truth, though — it is resolved from what the ADJ +already says, once, inside `net`. A TCP task was spawned for one board and knows +it without asking; `udp` resolves it from the decoded packet's id through `Index` +(every `PacketDef` carries its `board`), which is one `HashMap` lookup per +datagram instead of one per consumer downstream. + +And the board is all the identity there is: one connection per board, one shared +socket for UDP, so nothing needs telling apart beyond it. + +Addresses are for the operator, not for the domain types: they show up +interpolated in `tcp::Error`/`udp::Error` messages, which is where somebody +actually reads them. + +### `Event` and `Notification` — what happened, and when + +```rust +enum Event { + Connected, // TCP only + Disconnected, // TCP only + Received(model::Packet), +} +``` + +`Event::Received` leans on the existing `model::Packet` umbrella +(`Data | Order | Protection | Message`) rather than repeating that split with one +variant per packet type. Its `Order` variant is never produced while receiving — +it is there for an eventual "the order really did go out on the wire" report, +which only `net` can make. + +`board` and `at` sit in the envelope rather than inside the variants so that +**everything** that travels down the channel carries them, and so a notification +**cannot be built without a timestamp**. `Reporter::notify` is the only thing that +stamps it. That +matters: a queue adds delay under load, so a date taken when the record is +*written* would be wrong by exactly that delay, precisely when the data matters +most. It is also the only full date a record can have — the board clock on +protections and messages (`ShortTimestamp`) is a time of day with no date. + +### `Reporter` — the two sinks + +```rust +let (reporter, sinks) = Reporter::channels(notifications, errors); + +reporter.notify(board, event).await?; // notification channel +reporter.report(tcp_or_udp_error).await?; // error channel +``` + +Cloneable, and meant to be cloned: one copy per TCP connection task, one for the +UDP loop, all feeding the same two channels. + +Two channels, not one, because the rules differ. **A notification is never +dropped**: `notify` waits when the channel is full, so the backpressure reaches +the read loop and the kernel's receive buffer becomes the only place anything can +be lost — and whatever is lost there is lost *before* being decoded, so +"everything decoded gets through" stays literally true. An error is rare enough +that it can afford to queue behind telemetry. + +`ErrorReport` carries **no board**, unlike a notification: the identity of what +failed lives inside the `Error` variant, which is the only place that always has +it. A datagram that fails to decode resolves to no board at all — its id is not in +the ADJ, so there is no `PacketDef` to ask — and all that can be said about it is +the address it came from, which is what `udp::Error::Decode` holds. + +### `Error` — aggregation only + +`net::Error` adds no identity and no message of its own; both variants are +`#[error(transparent)]`, so `to_string()` is the submodule's own message with its +identity already interpolated, and `source()` still reaches the original +`io::Error` or `DecodeError`. Each submodule owns its error type and puts the +board or address **inside the variant** — the Go backend lost exactly +that when an error crossed its channel. `is_fatal()`, if needed, belongs to each +submodule's own error: nobody outside knows which of its variants are fatal. + +## The contract for the two submodules + +| | `tcp` | `udp` | +|---|---|---| +| Entry point | `spawn(Config, Arc, Reporter) -> Handles` | `spawn(Config, Arc, Reporter) -> Result, Error>` (binds first) | +| Inputs | its `Config` (boards, timeouts, backoff, keep-alive) | its `Config` (bind address, `SO_RCVBUF`) | +| Role | client only; one connection per board, one task each | one shared socket, receive-only, one task | +| Framing | buffer + `&mut Cursor` + advance by `cursor.position()`; bail out past 374 bytes | none — `recv_from` delivers a whole datagram into a reused 64 KiB buffer | +| Writing | yes (orders, keep-alive); a single writer task per connection | no | +| On a decode error | report it; **fatal**, and close/reopen the connection (the stream cannot be resynchronised) | report it; **fatal**, and keep receiving | +| `Connected`/`Disconnected` | per board | never | +| Fault | writes it: `Handles::propagate_fault()`, id 0 to every board | cannot write; only reports | + +Both take the same two things besides their own `Config`: an `Arc` — the +only part of the ADJ `net` needs, owned by `station` and read-only here — and a +`Reporter`. Neither reads a config file, and neither reads the ADJ itself: the +addresses `tcp` connects to are resolved by `station` and arrive in `Config`, +which is also what lets a test point it at a fake peer. + +`net` never decides to fault the pod, but `tcp` is what can write one: `station` +reads `is_fatal()` and calls `Handles::propagate_fault()`, which puts the order +with id 0 into every board's writer channel (the Go backend's `SendFault`). A +*received* packet with id 0 is the same action requested by a board, and +`station` answers it the same way. + +Three rules both follow: + +1. The timestamp comes from `Reporter`, never by hand. +2. Decode and report, nothing else — no disk, no WebSocket, no aggregation. +3. What to do about an error is decided locally; only the report goes up. + +### What "fatal" means + +`tcp::Error::is_fatal`/`udp::Error::is_fatal` are about the **pod**, not about +this process: it means the pod has to be sent to fault, and the backend +**stays up** — still reading, still serving the frontend, still recording — so the +operator can see why. Nothing in `net` ever calls `std::process::exit`. + +Only a decode failure is fatal, on either transport, and this is a deliberate +departure from Go. Nothing corrupts a frame or a datagram in flight (both +transports checksum, TCP retransmits, and the pod's network does not fragment), so +something that will not decode means the loaded ADJ does not describe what the +firmware is sending — which reconnecting cannot fix. A failed connect or write is +*not* fatal: that is what the backoff is for. + +`net` never raises the fault itself — neither transport does. It logs, it reports, +and `is_fatal()` is the classification whoever consumes the error channel acts on. +That is deliberate: a mismatched ADJ fails on every frame that follows, thousands +a second, so the fault has to be broadcast **once**, and the guard for that lives +in one place instead of one per transport. + +## Why TCP needs a buffer and UDP does not + +TCP is a byte stream and preserves no write boundaries, so one read can deliver +half a frame or two frames glued together — both are normal, and the glued case is +the frequent one. Our frames carry no length prefix: a protection's length is +fixed but derivable only from the ADJ (`2 + 4 + 2 + the watched measurement's wire +width`), and a message ends at the second NUL byte of its two variable-length +strings. So a frame's end is never known in advance, only deduced by parsing it — +which is why the loop tries, and retries with more bytes when it fails. + +The Go backend never faced this because it read straight off the connection, where +a blocking read simply waits mid-frame. That state has to live somewhere: in Go it +lived in the blocked goroutine's stack, and here it lives in an explicit buffer — +which is also what lets `protocol` stay synchronous and socket-free, reusable by a +sniffer against a capture. + +UDP has none of it: the kernel hands over a whole datagram or nothing. + +## Open questions + +- Who raises the fault on `is_fatal()`, and where its "only once" guard lives. + Not in `net`: both transports only report. +- Whether an order's write is reported back as + `Event::Received(Packet::Order(..))`, or `station` just assumes it went out. diff --git a/backend/crates/core/src/net/error.rs b/backend/crates/core/src/net/error.rs new file mode 100644 index 000000000..64109a954 --- /dev/null +++ b/backend/crates/core/src/net/error.rs @@ -0,0 +1,28 @@ +//! The one error type an [`super::ErrorReport`] can carry. + +use super::{tcp, udp}; + +/// Anything that went wrong in `net`. +/// +/// Aggregation only: this enum adds no identity and no message of its +/// own. Each submodule owns its own error type and puts the identity of +/// whatever failed — the board, or the peer address — +/// *inside* the variant, not just in its text, so that the identity +/// survives being sent down a channel. The Go backend lost it exactly +/// there: the log line before the send had the board, the error value +/// that travelled did not. +/// +/// Both variants are `#[error(transparent)]`, so `to_string()` on this +/// enum is the submodule's own message, identity interpolated and all — +/// which is what gets shown to the operator — and `source()` still walks +/// down to the original `io::Error` or +/// [`crate::protocol::DecodeError`]. +#[derive(Debug, thiserror::Error)] +pub enum Error { + /// On a board's TCP connection. + #[error(transparent)] + Tcp(#[from] tcp::Error), + /// On the shared UDP socket. + #[error(transparent)] + Udp(#[from] udp::Error), +} diff --git a/backend/crates/core/src/net/report.rs b/backend/crates/core/src/net/report.rs new file mode 100644 index 000000000..35f7dc16c --- /dev/null +++ b/backend/crates/core/src/net/report.rs @@ -0,0 +1,367 @@ +//! What [`super::tcp`]/[`super::udp`] report, and the sinks they report +//! through. +//! +//! Two separate channels, both bounded. Notifications +//! ([`Notification`]) carry everything that happened on a link, errors +//! ([`ErrorReport`]) everything that went wrong. They are separate +//! because their rules differ: a notification must never be dropped, +//! while an error is rare enough that it can afford to wait behind a +//! queue of telemetry. +//! +//! Both sinks apply backpressure rather than dropping: see +//! [`Reporter::notify`]. + +use super::Error; +use crate::model::{BoardId, Packet}; +use std::time::SystemTime; +use tokio::sync::mpsc; + +/// Something that happened on a link: which board it concerns, when, +/// and what. +/// +/// Both `board` and `at` live in this envelope rather than inside the +/// variants of [`Event`], so that **everything** that travels down the +/// channel carries them — there is no event whose board the consumer has +/// to go and look up, and none that can be built without a timestamp. +/// [`Reporter::notify`] is the only thing that stamps `at`. +#[derive(Debug)] +pub struct Notification { + /// The board this concerns. + /// + /// Always known by the time anything is reported: a TCP task was + /// spawned for one board and knows it without asking, and [`super::udp`] + /// resolves it from the decoded packet's id through + /// [`crate::protocol::Index`] — `index.packet(id)` gives a + /// [`crate::model::PacketDef`], which carries its `board` — so that a + /// notification looks the same whichever transport brought it. + pub board: BoardId, + /// The instant the bytes came off the socket. + /// + /// Stamped when the event is reported, never by whoever writes it to + /// disk later: a queue adds delay under load, so a date taken at + /// write time would be wrong by exactly that delay, at exactly the + /// moment the data matters most. The frames that carry a board clock + /// of their own ([`crate::model::ShortTimestamp`], on protections and + /// messages) only carry a time of day, with no date, so this is also + /// the only full date a record can have. + pub at: SystemTime, + /// What happened. + pub event: Event, +} + +/// Something that went wrong, and when. +/// +/// Carries no identity of its own: whose failure it was travels inside +/// the [`Error`]'s own variant, which is the only place that always has +/// it. A datagram that fails to decode, for instance, resolves to no +/// board at all — its id is not in the ADJ, so there is no +/// [`crate::model::PacketDef`] to ask — and all that can be said about +/// it is the address it came from, which is exactly what +/// [`super::udp::Error::Decode`] holds. +#[derive(Debug)] +pub struct ErrorReport { + /// The instant the failure was reported, on the same clock as + /// [`Notification::at`]. + pub at: SystemTime, + /// What went wrong, identity included. + pub error: Error, +} + +/// What happened on a link. +#[derive(Debug)] +pub enum Event { + /// The board's connection came up, and it can now be talked to. + /// Which board is in the [`Notification`] around this, which is all + /// the identity there is: one connection per board. + /// + /// TCP only: there is nothing to connect in UDP, whose socket is + /// bound once and belongs to no single board. + Connected, + /// The board's connection went down, whatever the reason. If the + /// cause was worth reporting, it already went out as an + /// [`ErrorReport`] — but on the other channel, so nothing orders the + /// two against each other. + /// + /// TCP only, same as [`Event::Connected`]. + Disconnected, + /// A packet arrived and was decoded. Whose it is, is in the + /// [`Notification`] around it. + /// + /// [`Packet`] is the whole umbrella, so this one variant covers data, + /// protections and messages alike, with no second enum repeating that + /// split. Its [`Packet::Order`] variant is never produced while + /// receiving; it is what an eventual "the order really did go out on + /// the wire" report would use, which only `net` is in a position to + /// make. + Received(Packet), +} + +/// The receiving ends of a [`Reporter`]'s two channels, handed to +/// whoever consumes them (`station`). +#[derive(Debug)] +pub struct Sinks { + /// Everything that happened, in the order it happened. + pub notifications: mpsc::Receiver, + /// Everything that went wrong. + pub errors: mpsc::Receiver, +} + +/// The sinks [`super::tcp`] and [`super::udp`] report through. +/// +/// Cloneable, and meant to be cloned: every task gets its own copy — one +/// per TCP connection, one for the UDP loop — and they all feed the same +/// two channels. +#[derive(Debug, Clone)] +pub struct Reporter { + notifications: mpsc::Sender, + errors: mpsc::Sender, +} + +/// The consumer is gone, so there is nobody left to report to. +/// +/// The only failure either sink has, and a signal to stop rather than +/// something to retry. +#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)] +#[error("the receiving end is gone")] +pub struct Closed; + +impl Reporter { + /// Builds both channels with the given capacities, and returns the + /// sending half to hand to the submodules plus the receiving halves + /// to hand to the consumer. + /// + /// Both are bounded on purpose: see [`Reporter::notify`] for what + /// happens when the notification channel fills up. + pub fn channels(notifications: usize, errors: usize) -> (Self, Sinks) { + let (notification_tx, notification_rx) = mpsc::channel(notifications); + let (error_tx, error_rx) = mpsc::channel(errors); + + ( + Self { + notifications: notification_tx, + errors: error_tx, + }, + Sinks { + notifications: notification_rx, + errors: error_rx, + }, + ) + } + + /// Stamps the instant and queues `event`. + /// + /// **Waits** if the channel is full, rather than dropping anything: + /// a packet that has already been decoded always reaches the + /// consumer. What that costs is backpressure — the wait reaches back + /// to the read loop, which stops reading, and the kernel's own + /// receive buffer becomes the only place anything can be lost. That + /// is deliberate: whatever is dropped there is dropped *before* being + /// decoded, so "everything decoded gets through" stays literally + /// true. + /// + /// The instant is taken before the wait, not after, so a full queue + /// delays the notification without distorting its timestamp. + pub async fn notify(&self, board: BoardId, event: Event) -> Result<(), Closed> { + let notification = Notification { + board, + at: SystemTime::now(), + event, + }; + + self.notifications + .send(notification) + .await + .map_err(|_| Closed) + } + + /// Stamps the instant and queues an error, on the error channel. + /// + /// Takes anything that converts into [`Error`], so a submodule + /// reports its own error type directly: + /// `reporter.report(tcp::Error::Connect { .. }).await`. + /// + /// Reporting is not deciding: by the time an error gets here its + /// submodule has already done whatever it was going to do about it + /// (reconnect, carry on with the next datagram), and has already + /// logged it through `tracing`. This channel is only for telling the + /// operator, through the frontend. + pub async fn report(&self, error: impl Into) -> Result<(), Closed> { + let report = ErrorReport { + at: SystemTime::now(), + error: error.into(), + }; + + self.errors.send(report).await.map_err(|_| Closed) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::model::{AdjId, DataPacket}; + use crate::net::udp; + use std::net::{IpAddr, SocketAddr}; + use std::time::Duration; + + fn a_packet() -> Event { + Event::Received(Packet::Data(DataPacket::new(AdjId(1000), vec![]))) + } + + fn an_error() -> udp::Error { + udp::Error::Recv { + source: std::io::Error::from(std::io::ErrorKind::ConnectionReset), + } + } + + #[tokio::test] + async fn a_notification_arrives_stamped() { + let (reporter, mut sinks) = Reporter::channels(4, 4); + + let before = SystemTime::now(); + let Ok(()) = reporter.notify(BoardId(3), a_packet()).await else { + unreachable!("the receiver is still alive"); + }; + let after = SystemTime::now(); + + let Some(notification) = sinks.notifications.recv().await else { + unreachable!("exactly one notification was sent"); + }; + assert!(notification.at >= before && notification.at <= after); + assert_eq!( + notification.board, + BoardId(3), + "the board travels with every notification, received packets included" + ); + } + + #[tokio::test] + async fn a_connection_event_names_its_board() { + let (reporter, mut sinks) = Reporter::channels(4, 4); + + // The one identity that cannot be derived from a packet: there is + // no packet here at all. + let Ok(()) = reporter.notify(BoardId(3), Event::Disconnected).await else { + unreachable!("the receiver is still alive"); + }; + + let Some(notification) = sinks.notifications.recv().await else { + unreachable!("exactly one notification was sent"); + }; + // The board is the whole identity: one connection per board. + assert_eq!(notification.board, BoardId(3)); + let Event::Disconnected = notification.event else { + unreachable!("a disconnection should arrive as Event::Disconnected"); + }; + } + + #[tokio::test] + async fn a_full_channel_makes_the_reporter_wait_instead_of_dropping() { + let (reporter, mut sinks) = Reporter::channels(1, 1); + + // Fill the single slot, then start a second report that cannot + // fit yet. + let Ok(()) = reporter.notify(BoardId(3), a_packet()).await else { + unreachable!("the first one fits"); + }; + let blocked = tokio::spawn({ + let reporter = reporter.clone(); + async move { reporter.notify(BoardId(3), a_packet()).await } + }); + + // It is still waiting: nothing was dropped, and nothing got + // through either. + tokio::time::sleep(Duration::from_millis(50)).await; + assert!( + !blocked.is_finished(), + "the second report should be waiting" + ); + + // Draining one slot lets it through, so both are delivered. + let Some(_first) = sinks.notifications.recv().await else { + unreachable!("the first notification was sent"); + }; + let Ok(Ok(())) = blocked.await else { + unreachable!("once a slot frees up, the second one goes through"); + }; + let Some(_second) = sinks.notifications.recv().await else { + unreachable!("the second notification went through"); + }; + } + + #[tokio::test] + async fn waiting_on_a_full_channel_does_not_delay_the_timestamp() { + let (reporter, mut sinks) = Reporter::channels(1, 1); + + let Ok(()) = reporter.notify(BoardId(3), a_packet()).await else { + unreachable!("the first one fits"); + }; + let blocked = tokio::spawn({ + let reporter = reporter.clone(); + async move { reporter.notify(BoardId(3), a_packet()).await } + }); + + // Let the second report sit in the queue for a while before + // anything drains it. + tokio::time::sleep(Duration::from_millis(50)).await; + let after_the_wait = SystemTime::now(); + + let Some(_first) = sinks.notifications.recv().await else { + unreachable!("the first notification was sent"); + }; + let Ok(Ok(())) = blocked.await else { + unreachable!("the second one goes through once there is room"); + }; + let Some(second) = sinks.notifications.recv().await else { + unreachable!("the second notification went through"); + }; + + // Stamped when it was reported, not when it finally fit. + assert!( + second.at <= after_the_wait, + "the timestamp should predate the end of the wait" + ); + } + + #[tokio::test] + async fn an_error_arrives_on_its_own_channel() { + let (reporter, mut sinks) = Reporter::channels(4, 4); + + let Ok(()) = reporter.report(an_error()).await else { + unreachable!("the receiver is still alive"); + }; + + let Some(report) = sinks.errors.recv().await else { + unreachable!("exactly one error was reported"); + }; + let Error::Udp(udp::Error::Recv { .. }) = report.error else { + unreachable!("a udp error should arrive as Error::Udp"); + }; + // Nothing reached the notification channel. + assert!(sinks.notifications.try_recv().is_err()); + } + + #[test] + fn a_udp_decode_error_keeps_the_address_it_cannot_resolve_to_a_board() { + let addr = SocketAddr::new(IpAddr::from([192, 168, 1, 3]), 50400); + let error = udp::Error::Decode { + from: addr, + source: crate::protocol::DecodeError::UnknownId(AdjId(9999)), + }; + + // The whole reason an error report carries no board: this one has + // an address, and no board to attribute it to. + let Error::Udp(udp::Error::Decode { from, .. }) = Error::from(error) else { + unreachable!("a decode error should convert into Error::Udp"); + }; + assert_eq!(from, addr); + } + + #[tokio::test] + async fn reporting_once_the_consumer_is_gone_says_so() { + let (reporter, sinks) = Reporter::channels(4, 4); + drop(sinks); + + assert_eq!(reporter.notify(BoardId(3), a_packet()).await, Err(Closed)); + assert_eq!(reporter.report(an_error()).await, Err(Closed)); + } +} diff --git a/backend/crates/core/src/net/tcp.rs b/backend/crates/core/src/net/tcp.rs new file mode 100644 index 000000000..297923dc1 --- /dev/null +++ b/backend/crates/core/src/net/tcp.rs @@ -0,0 +1,375 @@ +//! The TCP client: one connection per board, one task each. +//! +//! **Not written yet.** This file currently holds only the error type +//! [`super::Error`] aggregates, plus the contract below, so that the rest +//! of `net` compiles and whoever implements this module knows what the +//! shared part expects of it. See [`super`] and `net/README.md`. +//! +//! # What this module is +//! +//! The backend is the **client**: it connects out to each board's +//! `TCP_SERVER` port, and never listens. One connection per board, each +//! one its own task with its own framing buffer and its own reconnection +//! state. That connection carries protections and messages inbound, and +//! orders and the keep-alive outbound. +//! +//! # Entry point +//! +//! [`spawn`], taking [`Config`], an `Arc` and a +//! [`super::Reporter`], and returning [`Handles`] — the API is written +//! out below, with its reasoning on the items themselves. One call opens +//! **every** connection: one task per entry in [`Config::boards`], so the +//! per-board bookkeeping stays here and `station` only ever asks for +//! "write this to that board". +//! +//! # Contract +//! +//! - **Framing is this module's job.** TCP is a byte stream: a frame can +//! arrive split across reads, and two frames can arrive glued together +//! in one read — both are normal, and the second is the common case. +//! So: accumulate into a per-connection buffer, run +//! [`crate::protocol::tcp::decode_next`] against a `&mut Cursor` over +//! it, and on success advance the buffer by `cursor.position()`. Never +//! consume from the buffer unless a frame parsed in full, or the stream +//! is permanently misaligned. A failed parse means "not enough bytes +//! yet"; the one safeguard is that no frame can exceed 374 bytes +//! (`2 + 4 + 48 + 320`), so a buffer that grows past that without +//! yielding a frame is out of step rather than waiting, and the +//! connection should be dropped and reopened. +//! - **One writer task per connection.** Orders, the keep-alive and the +//! fault all share the socket, so a single task must own the write +//! half, or two half-written frames can interleave on the wire. That +//! task is what [`super::Reporter`]-side callers reach through the +//! board's channel in `Handles`. +//! - **Be ready to be told to propagate the fault.** `station` is what +//! decides (it is the one consuming the error channel and reading +//! [`Error::is_fatal`]); this module is what can actually write, so it +//! exposes `Handles::propagate_fault`, which puts **the order with id +//! 0** — the fault, same as the Go backend's `SendFault` — into every +//! board's writer channel at once, bounded by `write_timeout` per +//! write. It reports back which boards it could not reach instead of +//! collapsing them into one opaque error, since a fault that only +//! half-landed is exactly what the operator has to know. The same path +//! covers the other case the Go backend had under `propagate_fault`: a +//! *received* packet with id 0 is a board announcing a fault, and +//! `station` answers it by calling this, so that logic does not have to +//! exist twice. +//! - Reconnection with exponential backoff and unlimited retries, the +//! OS-level keep-alive disabled (there is an application-level one), +//! `linger = 0` so a dropped connection frees its fixed local port +//! immediately instead of sitting in `TIME_WAIT`. +//! - Report through [`super::Reporter`] only: [`super::Event::Connected`] +//! and [`super::Event::Disconnected`] per connection, +//! [`super::Event::Received`] per frame, and [`Error`] on the error +//! channel. Never stamp a timestamp by hand — [`super::Reporter::notify`] +//! does it. Never touch disk, WebSocket or aggregation. +//! - **A decode failure is fatal**: see [`Error::is_fatal`]. Log it and +//! report it on the error channel — and that is all this module does +//! about it. Sending the pod to fault is not `net`'s call to make: +//! whoever consumes the error channel reads [`Error::is_fatal`] and +//! decides, which also keeps the "fault once" guard in one place +//! instead of one per transport. The stream cannot be resynchronised +//! mid-frame, though, so this module does close the connection and let +//! the reconnection loop reopen it — reconnecting will not fix a +//! mismatched ADJ, so expect the same frame to fail again. +//! - Everything else is decided here, locally: a failed connect or write +//! is what the backoff is for, and only the report goes up. + +use super::Reporter; +use crate::model::{AdjId, BoardId, OrderPacket}; +use crate::protocol::{DecodeError, Index}; +use std::net::SocketAddr; +use std::sync::Arc; +use std::time::Duration; + +/// One board to keep a connection to. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct BoardLink { + /// Whose connection this is. Every report about it names this board, + /// which is the whole identity of a link. + pub board: BoardId, + /// Where to connect: the board's `ip` + its `ports["TCP_SERVER"]`. + pub addr: SocketAddr, + /// The fixed local port to bind the client side to (`TCP_CLIENT + i` + /// in the Go backend). Being fixed is why `linger = 0` matters: a + /// dropped connection must not leave this port in `TIME_WAIT`. + pub local_port: u16, +} + +/// How long to wait between reconnection attempts. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Backoff { + /// The first wait after a connection fails or drops. + pub initial: Duration, + /// The ceiling the doubling stops at. Retries are unlimited: a board + /// that is not up yet is the normal state before a test, not an + /// error to give up on. + pub max: Duration, +} + +/// How to run the TCP client. +/// +/// Everything here is resolved by `station` before `net` is reached: this +/// module reads no config file, and it does not read the ADJ to find its +/// peers either. That is also what lets a test point it at a fake peer. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Config { + /// One entry per board to connect to, already filtered by what the + /// config file lists: a board the ADJ declares but the config does + /// not name gets no client at all. + pub boards: Vec, + /// Bound on each connection attempt. + pub connect_timeout: Duration, + /// What to wait between attempts. + pub backoff: Backoff, + /// Period of the application-level keep-alive this module sends on + /// its own. The OS-level keep-alive is + /// disabled precisely because this one exists. + pub keep_alive: Duration, + /// Bound on each write, so that a peer that stops reading cannot park + /// a writer task for good (1 s in the Go backend). + pub write_timeout: Duration, +} + +/// Opens a connection to every board in `config.boards`. +/// +/// One call, one task per board: the per-connection bookkeeping stays in +/// this module, and `station` only ever asks for "write this to that +/// board" through the [`Handles`] that come back. +/// +/// `adj` is the only part of the ADJ this module needs: it decodes +/// inbound frames and encodes outbound orders against it. `station` owns +/// it and hands out clones; it is read-only here, and a reload of the ADJ +/// is a new [`Index`] with new tasks, never a mutation of this one. +/// +/// Connecting is *not* done before spawning, unlike [`super::udp`]: a +/// board that is not up yet is normal, so a failed attempt is a report +/// and a retry, never a startup failure. +pub fn spawn(config: Config, adj: Arc, reporter: Reporter) -> Handles { + let _ = (config, adj, reporter); + todo!("the TCP client is not written yet: see this module's contract") +} + +/// The writing side of every connection [`spawn`] opened. +/// +/// The representation is left to the implementation — a writer channel +/// per board and the task handles — so that this file states the API and +/// nothing else. +#[derive(Debug)] +pub struct Handles {} + +impl Handles { + /// The handle for one board, or `None` if the config did not list it. + #[must_use] + pub fn board(&self, board: BoardId) -> Option<&BoardHandle> { + let _ = board; + todo!("the TCP client is not written yet: see this module's contract") + } + + /// Hands an order to the board it belongs to, resolved by its id + /// through the [`Index`]. + /// + /// Returns once the order is queued on that board's writer, not once + /// it is on the wire — the write itself is bounded by + /// [`Config::write_timeout`] and reported through [`Error::Write`]. + /// + /// # Errors + /// + /// See [`SendError`]: an id no ADJ declares, a board with no client, + /// or a connection task that is gone. + pub async fn send(&self, order: OrderPacket) -> Result<(), SendError> { + let _ = order; + todo!("the TCP client is not written yet: see this module's contract") + } + + /// Sends the fault — the order with id 0 — to every board at once. + /// + /// This module does not decide to fault the pod; `station` does, by + /// reading [`Error::is_fatal`] off the error channel. This is only + /// the one place that can actually write it, so it is where the + /// fan-out lives. A *received* packet with id 0 is a board asking for + /// the same thing, and `station` answers it by calling this, so that + /// logic does not exist twice. + /// + /// # Errors + /// + /// [`Unreachable`], naming the boards the fault did not reach rather + /// than collapsing them into one opaque failure: a fault that only + /// half landed is exactly what the operator has to be told. + pub async fn propagate_fault(&self) -> Result<(), Unreachable> { + todo!("the TCP client is not written yet: see this module's contract") + } + + /// Closes every connection and waits for its task to finish. + pub async fn shutdown(self) { + todo!("the TCP client is not written yet: see this module's contract") + } +} + +/// The writing side of one board's connection. +/// +/// The representation is left to the implementation, same as +/// [`Handles`]. +#[derive(Debug)] +pub struct BoardHandle {} + +impl BoardHandle { + /// Hands an order to this board's writer, without consulting the + /// order's id — [`Handles::send`] is what routes. + /// + /// # Errors + /// + /// [`SendError::Gone`] if this connection's task is no longer there. + pub async fn send(&self, order: OrderPacket) -> Result<(), SendError> { + let _ = order; + todo!("the TCP client is not written yet: see this module's contract") + } +} + +/// Why an order could not be handed to a writer. +/// +/// Returned to the caller, not reported through [`super::Reporter`]: it +/// says something about the order that was asked for, not about the state +/// of a connection. [`Error`] is the one that travels on the error +/// channel. +#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)] +pub enum SendError { + /// No order with this id is declared in the loaded ADJ. + #[error("no order is declared with id {0:?}")] + UnknownId(AdjId), + /// The order resolves to a board the config did not list, so no + /// client was ever opened for it. + #[error("board {0:?} has no TCP client: the config does not list it")] + NoClient(BoardId), + /// The board's connection task is no longer running. + #[error("board {0:?}: its connection task is gone")] + Gone(BoardId), +} + +/// The boards a fault broadcast did not reach. +/// +/// Never empty: a broadcast that reached everybody returns `Ok`. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +#[error("the fault did not reach these boards: {0:?}")] +pub struct Unreachable(pub Vec); + +/// Something that went wrong on a board's TCP connection. +/// +/// Every variant names its board, which is the whole identity of a link: +/// one connection per board. +#[derive(Debug, thiserror::Error)] +pub enum Error { + /// The connection could not be opened. + #[error("board {board:?}: could not connect")] + Connect { + /// The board that was being connected to. + board: BoardId, + /// The underlying I/O failure. + #[source] + source: std::io::Error, + }, + + /// A frame could not be decoded, which means the loaded ADJ does not + /// describe what the board is sending. Fatal: see + /// [`Error::is_fatal`]. + #[error("board {board:?}: could not decode a frame")] + Decode { + /// The board whose frame failed. + board: BoardId, + /// What [`crate::protocol`] said about it. + #[source] + source: DecodeError, + }, + + /// An order or a keep-alive could not be written. + #[error("board {board:?}: could not write")] + Write { + /// The board that was being written to. + board: BoardId, + /// The underlying I/O failure. + #[source] + source: std::io::Error, + }, +} + +impl Error { + /// Whether this error means the pod has to be sent to fault. + /// + /// "Fatal" is about the **pod**, not about this process: the backend + /// stays up — still reading its other connections, still serving the + /// frontend, still recording — so that whoever is operating the pod + /// can see what happened. Nothing here ever calls + /// `std::process::exit`. + /// + /// Only [`Error::Decode`] qualifies, and this is the one place where + /// the behaviour deliberately departs from the Go backend. Go treated + /// an undecodable frame as a connection that had fallen out of step, + /// and reconnecting was the remedy. But nothing corrupts a frame in + /// flight — TCP checksums and retransmits — so a frame that will not + /// decode means the loaded ADJ does not match what the firmware is + /// sending, and reopening the connection cannot fix that. The stream + /// still cannot be resynchronised mid-frame, so the connection is + /// closed and reopened anyway; what changes is that the pod is also + /// sent to fault instead of carrying on as if a retry would help. + /// + /// [`Error::Connect`] and [`Error::Write`] are not fatal: a board + /// that is not up yet, or a write that failed on a connection that + /// just dropped, is exactly what the reconnection loop with its + /// backoff is for. Losing a board for good is reported through + /// [`super::Event::Disconnected`], not through this. + pub fn is_fatal(&self) -> bool { + match self { + Error::Decode { .. } => true, + Error::Connect { .. } | Error::Write { .. } => false, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn io_error() -> std::io::Error { + std::io::Error::from(std::io::ErrorKind::ConnectionRefused) + } + + #[test] + fn a_frame_that_will_not_decode_faults_the_pod() { + let error = Error::Decode { + board: BoardId(3), + source: DecodeError::UnknownId(crate::model::AdjId(9999)), + }; + + // Not a desynchronised stream to retry: the ADJ does not match + // the firmware, and reconnecting cannot fix that. + assert!(error.is_fatal()); + } + + #[test] + fn a_board_that_is_not_up_yet_does_not_fault_the_pod() { + let connect = Error::Connect { + board: BoardId(3), + source: io_error(), + }; + let write = Error::Write { + board: BoardId(3), + source: io_error(), + }; + + // That is what the reconnection backoff is for. + assert!(!connect.is_fatal()); + assert!(!write.is_fatal()); + } + + #[test] + fn an_error_says_which_board_it_was() { + let error = Error::Write { + board: BoardId(3), + source: io_error(), + }; + + // The identity survives being formatted, which is what reaches + // the operator. + assert!(error.to_string().contains("BoardId(3)")); + } +} diff --git a/backend/crates/core/src/net/udp.rs b/backend/crates/core/src/net/udp.rs new file mode 100644 index 000000000..e8048507b --- /dev/null +++ b/backend/crates/core/src/net/udp.rs @@ -0,0 +1,217 @@ +//! The shared UDP socket: one socket, receive-only, every board's +//! telemetry. +//! +//! **Not written yet.** This file currently holds only the error type +//! [`super::Error`] aggregates, plus the contract below, so that the rest +//! of `net` compiles and whoever implements this module knows what the +//! shared part expects of it. See [`super`] and `net/README.md`. +//! +//! # What this module is +//! +//! One socket bound to the backend's own address, carrying `Data` packets +//! from every board. Nothing is ever sent from it. One task is enough: +//! there is no per-board state to keep. +//! +//! # Entry point +//! +//! [`spawn`], taking [`Config`], an `Arc` and a +//! [`super::Reporter`] — written out with its reasoning on the items +//! themselves. No handle comes back beyond the `JoinHandle`: there is no +//! writing side. +//! +//! # Contract +//! +//! - **No framing.** A datagram arrives whole or not at all, so +//! `recv_from` already delivers exactly one packet and its length — +//! none of [`super::tcp`]'s buffer applies here. Read into one reused +//! 64 KiB buffer and a datagram can never be silently truncated, +//! whatever the ADJ grows to. +//! - The loop does three things and nothing else: receive, decode with +//! [`crate::protocol::udp::decode_datagram`], report. No disk, no +//! WebSocket, no aggregation — the socket's receive buffer is where +//! packets get dropped if this task falls behind, and the kernel drops +//! them silently, so this loop stays as short as it can be. Raising +//! `SO_RCVBUF` is part of setting the socket up. +//! - [`super::Notification::board`] comes from the decoded packet's id, +//! through [`crate::protocol::Index`] — every +//! [`crate::model::PacketDef`] carries its `board` — so that a +//! notification looks the same whichever transport brought it. That is +//! one `HashMap` lookup per datagram, done here once rather than +//! repeated by every consumer downstream. +//! - **A decode failure is fatal**: see [`Error::is_fatal`]. Nothing +//! corrupts a datagram in flight — UDP checksums it and the pod's +//! network does not fragment it — so a datagram that will not decode +//! means the ADJ this backend loaded does not describe what the boards +//! are actually sending, and every datagram after it is suspect for the +//! same reason. So: log it and report it on the error channel, exactly +//! as [`super::tcp`] does — and that is all. This socket writes +//! nothing, and sending the pod to fault is not `net`'s call anyway: +//! whoever consumes the error channel reads [`Error::is_fatal`] and +//! decides, which also keeps the "fault once" guard in one place +//! rather than one per transport. Keep receiving meanwhile: a +//! mismatched ADJ fails on every datagram that follows, several +//! thousand a second, and each one is reported, not acted on. +//! - [`super::Event::Connected`]/[`super::Event::Disconnected`] are never +//! emitted: there is no connection to come up or go down. +//! - Binding happens **before** the task is spawned, so a bad address is +//! a startup failure returned to whoever is composing the backend +//! (`station::vehicle::bootstrap`), not something reported once +//! everything is already running. Hence the entry point returns +//! `Result, Error>`. + +use super::Reporter; +use crate::protocol::{DecodeError, Index}; +use std::net::SocketAddr; +use std::sync::Arc; +use tokio::task::JoinHandle; + +/// How to set the shared socket up. +/// +/// Everything here is resolved by `station` before `net` is reached: this +/// module reads no config file and no ADJ of its own. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Config { + /// Where to bind: the backend's own address, `backend_ip` + + /// `ports["UDP"]` in the ADJ's general info. + pub addr: SocketAddr, + /// `SO_RCVBUF`, in bytes. + /// + /// The only thing absorbing a stall of the receive loop, since the + /// kernel drops the tail silently once it is full: 2 MiB is about + /// 0.8 s of margin at 20 Mbit/s. + pub recv_buffer: usize, +} + +/// Binds the shared socket and spawns the receive loop. +/// +/// Binding happens here, **before** the task, so that a bad address is a +/// startup failure handed back to whoever is composing the backend rather +/// than something reported once everything is already running. +/// +/// `adj` is the only part of the ADJ this module needs: it maps a decoded +/// id to its [`crate::model::PacketDef`], for the decode itself and for +/// the `board` every [`super::Notification`] carries. `station` owns it +/// and hands out clones; it is read-only here, and a reload of the ADJ is +/// a new [`Index`] with a new task, never a mutation of this one. +/// +/// # Errors +/// +/// [`Error::Bind`] only — every later failure goes out through +/// `reporter`, since by then there is nobody left to return it to. +pub fn spawn(config: Config, adj: Arc, reporter: Reporter) -> Result, Error> { + let _ = (config, adj, reporter); + todo!("the UDP socket is not written yet: see this module's contract") +} + +/// Something that went wrong on the shared UDP socket. +/// +/// No [`crate::model::BoardId`] in any variant, on purpose: the socket +/// belongs to no board, and a datagram that fails to decode may not +/// resolve to one at all — [`Error::Decode`] carries the address it came +/// from, which is the only identity that always exists. +#[derive(Debug, thiserror::Error)] +pub enum Error { + /// The socket could not be bound, so no telemetry will arrive at all. + #[error("could not bind the shared UDP socket to {addr}")] + Bind { + /// The address it was being bound to. + addr: SocketAddr, + /// The underlying I/O failure. + #[source] + source: std::io::Error, + }, + + /// Receiving on the socket failed. + #[error("could not receive on the shared UDP socket")] + Recv { + /// The underlying I/O failure. + #[source] + source: std::io::Error, + }, + + /// A datagram could not be decoded, which means the loaded ADJ does + /// not describe what the boards are sending. Fatal: see + /// [`Error::is_fatal`]. + #[error("could not decode a datagram from {from}")] + Decode { + /// Where the datagram came from — there may be no board to + /// attribute it to. + from: SocketAddr, + /// What [`crate::protocol`] said about it. + #[source] + source: DecodeError, + }, +} + +impl Error { + /// Whether this error means the pod has to be sent to fault. + /// + /// "Fatal" is about the **pod**, not about this process: the backend + /// stays up — still reading, still serving the frontend, still + /// recording — so that whoever is operating the pod can see what + /// happened. Nothing here ever calls `std::process::exit`. + /// + /// Both runtime failures of this socket qualify, and for the same + /// reason: neither can be true of a single datagram. + /// [`Error::Decode`] means the loaded ADJ does not describe what the + /// boards are sending, and [`Error::Recv`] means the socket itself is + /// no longer usable, which is every board's telemetry gone at once. + /// Neither is something a retry fixes. + /// + /// [`Error::Bind`] never reaches this: binding happens before the + /// task is spawned, so it is a startup failure handed back to + /// whoever composes the backend. + pub fn is_fatal(&self) -> bool { + // Matched exhaustively rather than just returning `true`: a + // variant added later has to say which it is instead of + // inheriting this answer in silence. + match self { + Error::Bind { .. } | Error::Recv { .. } | Error::Decode { .. } => true, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::model::AdjId; + use std::net::IpAddr; + + fn peer() -> SocketAddr { + SocketAddr::new(IpAddr::from([192, 168, 1, 3]), 50400) + } + + #[test] + fn a_datagram_that_will_not_decode_faults_the_pod() { + let error = Error::Decode { + from: peer(), + source: DecodeError::UnknownId(AdjId(9999)), + }; + + // Nothing corrupts a datagram in flight, so this is a mismatched + // ADJ, not noise to skip over. + assert!(error.is_fatal()); + } + + #[test] + fn losing_the_socket_faults_the_pod_too() { + let error = Error::Recv { + source: std::io::Error::from(std::io::ErrorKind::ConnectionReset), + }; + + // Every board's telemetry at once. + assert!(error.is_fatal()); + } + + #[test] + fn a_decode_failure_says_where_it_came_from() { + let error = Error::Decode { + from: peer(), + source: DecodeError::UnknownId(AdjId(9999)), + }; + + // The only identity it has: there is no board to attribute an + // undeclared id to. + assert!(error.to_string().contains("192.168.1.3:50400")); + } +} From 7b98b80f9bfafd26a3f5168a3fbdcb645b21c76b Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Sun, 18 Oct 2026 22:21:59 +0200 Subject: [PATCH 095/225] wip(backend, net): upload cargo.toml --- backend/crates/core/Cargo.toml | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/backend/crates/core/Cargo.toml b/backend/crates/core/Cargo.toml index e9eabc177..0a3e434e8 100644 --- a/backend/crates/core/Cargo.toml +++ b/backend/crates/core/Cargo.toml @@ -29,7 +29,14 @@ serde.workspace = true serde_json.workspace = true thiserror.workspace = true tracing.workspace = true -tokio = { workspace = true, optional = true, features = ["macros", "rt-multi-thread"] } +# `io-util` is what `net` needs on top of the workspace's own list +# (`net`, `sync`, `time`...): `AsyncReadExt`/`AsyncWriteExt`, i.e. reading +# a TCP stream into a buffer at all. +tokio = { workspace = true, optional = true, features = [ + "macros", + "rt-multi-thread", + "io-util", +] } tracing-subscriber = { workspace = true, optional = true , features = ["env-filter", "fmt"]} tracing-appender = { workspace = true, optional = true } ntp_usg-server = { version = "5.0.0", optional = true, features = ["ipv4", "tokio"] } From c8a8c0c0af4e1b20a9eddedacd46020967a408c3 Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Sun, 18 Oct 2026 23:50:29 +0200 Subject: [PATCH 096/225] chore(backend, git): make git dependencies optional, clarify ADJ docs and create AutoAdj struct --- backend/crates/core/Cargo.toml | 6 +++--- backend/crates/core/src/adj.rs | 22 ++++++++++++++++++---- 2 files changed, 21 insertions(+), 7 deletions(-) diff --git a/backend/crates/core/Cargo.toml b/backend/crates/core/Cargo.toml index ec539f2f7..83985c825 100644 --- a/backend/crates/core/Cargo.toml +++ b/backend/crates/core/Cargo.toml @@ -15,7 +15,7 @@ ntp = ["dep:tokio", "dep:ntp_usg-server", "dep:tracing-subscriber"] # TCP/UDP transport (pulls in tokio) net = ["dep:tokio"] # ADJ download through git -git = ["dep:tempfile"] +git = ["dep:tempfile", "dep:dirs", "dep:gix"] # Packet sniffing through pcap (dependency added when the module is written) pcap = ["net"] # CSV data logger (records, sessions, subloggers) @@ -32,8 +32,8 @@ tracing.workspace = true tokio = { workspace = true, optional = true, features = ["macros", "rt-multi-thread"] } tracing-subscriber = { workspace = true, optional = true , features = ["env-filter", "fmt"]} tracing-appender = { workspace = true, optional = true } -gix = { version = "0.87.1", features = ["blocking-http-transport-reqwest-rust-tls", "blocking-network-client", "worktree-mutation"] } -dirs = "7.0.0" +gix = { version = "0.87.1", optional = true, features = ["blocking-http-transport-reqwest-rust-tls", "blocking-network-client", "worktree-mutation"] } +dirs = { version = "7.0.0", optional = true } tempfile = { version = "3.27", optional = true } ntp_usg-server = { version = "5.0.0", optional = true, features = ["ipv4", "tokio"] } diff --git a/backend/crates/core/src/adj.rs b/backend/crates/core/src/adj.rs index 91179897a..ccd420add 100644 --- a/backend/crates/core/src/adj.rs +++ b/backend/crates/core/src/adj.rs @@ -44,14 +44,28 @@ pub struct Adj { pub info: AdjInfo, } -/// Updates the ADJ repository, loads its data, and returns its full commit hash. +/// The result of [`auto_adj`]: the loaded ADJ data and the checked-out commit hash. +#[cfg(feature = "git")] +#[derive(Debug, Clone)] +pub struct AutoAdj { + /// Vehicle data + pub adj: Adj, + /// Full commit hash of the repository checkout used to load the ADJ. + pub hash: String, +} + +/// Updates the ADJ repository and returns an [`AutoAdj`] containing the loaded +/// data and the full commit hash of the checkout used to load it. /// /// `path` identifies the repository directory, not its parent. If omitted, /// the platform's user cache directory is used. /// /// Online, the repository is replaced and local edits and commits are discarded. /// Offline, the current cached checkout is loaded without switching branches, -/// so it may differ from `branch`. Clone failures do not fall back to the cache. +/// so it may differ from `branch`; `hash` is the full commit hash of its HEAD. +/// If no cached repository is available offline, or a Git operation fails, +/// returns [`LoadError::Git`] instead of an [`AutoAdj`], so no hash is returned. +/// Clone failures do not fall back to the cache. /// /// This performs blocking network and filesystem operations. Call during startup, /// before readers use ADJ, with only one updater at a time. @@ -63,11 +77,11 @@ pub struct Adj { /// Loading failures do not restore the previous cache. #[cfg(feature = "git")] #[instrument(level = "debug")] -pub fn auto_adj(path: Option, branch: &str) -> Result<(Adj, String), LoadError> { +pub fn auto_adj(path: Option, branch: &str) -> Result { let repo_path = unwrap_repo_path(path)?; let hash = update_adj(Some(repo_path.clone()), branch)?; let adj = load_from_dir(&repo_path)?; info!(path = ?repo_path, %hash, "ADJ loaded"); - Ok((adj, hash)) + Ok(AutoAdj { adj, hash }) } From 1976d336194ecc6cefd5ba7ba720ccddede49735 Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Tue, 20 Oct 2026 15:51:38 +0200 Subject: [PATCH 097/225] fix(backend, git): case where branch == "" fixed --- backend/crates/core/src/git/update.rs | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/backend/crates/core/src/git/update.rs b/backend/crates/core/src/git/update.rs index 8fa1fd1fb..ea9c32d66 100644 --- a/backend/crates/core/src/git/update.rs +++ b/backend/crates/core/src/git/update.rs @@ -35,14 +35,21 @@ const ADJ_URL: &str = "https://github.com/Hyperloop-UPV/adj.git"; pub fn update_adj(path: Option, branch: &str) -> Result { let (repo, dir) = adj_exists_repo(path)?; - if check_internet_connection() { + if check_internet_connection() && branch != "" { info!(path = ?dir, branch, "starting ADJ update"); // Release repository handles before moving the existing cache directory. drop(repo); git_replace(&dir, branch, ADJ_URL) } else if let Some(repo) = repo { - warn!(path = ?dir, requested_branch = branch, - "connectivity probe failed; using cached ADJ without switching branches"); + + if branch == "" { + warn!(path = ?dir, requested_branch = branch, + "branch not specified; using cached ADJ with current branch"); + + } else { + warn!(path = ?dir, requested_branch = branch, + "connectivity probe failed; using cached ADJ without switching branches"); + } get_commit_hash(&repo) } else { Err(GitError::UnavailableOffline) From 40047c53f79e16ecad91b364625ea5b60dd8702b Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Tue, 20 Oct 2026 18:10:04 +0200 Subject: [PATCH 098/225] docs(backend, git): update docs after fix --- backend/crates/core/src/git/README.md | 13 ++++++++++++- backend/crates/core/src/git/update.rs | 14 +++++++++----- 2 files changed, 21 insertions(+), 6 deletions(-) diff --git a/backend/crates/core/src/git/README.md b/backend/crates/core/src/git/README.md index e06a8f6fe..ef4cb55c4 100644 --- a/backend/crates/core/src/git/README.md +++ b/backend/crates/core/src/git/README.md @@ -15,7 +15,8 @@ availability. ### Online -Online updates replace the local checkout and do not preserve local edits or commits. +Online updates require a non-empty branch. They replace the local checkout and +do not preserve local edits or commits. - Shallow-clone the requested branch into a temporary directory beside ADJ. - Complete checkout and read its commit hash before touching the cache. @@ -35,6 +36,16 @@ existing cache, merge, or branch switch is needed because the checkout is replac The cached branch may differ from the requested branch when offline. +### Empty Branch + +Passing `branch = ""` skips downloading and replacing ADJ, even when online. + +- If a cached repository exists, return its current commit hash without updating + or switching branches, preserving local edits and commits. +- Otherwise, return `GitError::UnavailableOffline`, even if connectivity is available. + +The connectivity probe still runs when the branch is empty. + ## Other Helpers - `open_repo` opens the custom or default repository path. diff --git a/backend/crates/core/src/git/update.rs b/backend/crates/core/src/git/update.rs index ea9c32d66..65fe5655c 100644 --- a/backend/crates/core/src/git/update.rs +++ b/backend/crates/core/src/git/update.rs @@ -10,15 +10,19 @@ use tracing::{debug, info, instrument, warn}; const ADJ_URL: &str = "https://github.com/Hyperloop-UPV/adj.git"; -/// Downloads the requested ADJ branch, replacing the application-managed cache. +/// Updates ADJ to the requested branch or uses the existing application-managed cache. /// /// `path` is the repository directory, not its parent. If omitted, it defaults to /// `/hyperloop-control-station/adj`. `branch` selects the branch -/// to clone when the connectivity probe succeeds. +/// to clone when non-empty and the connectivity probe succeeds. /// -/// Online, local edits and commits are discarded only after a fresh checkout -/// succeeds. Offline, the current cached checkout is used without switching -/// branches, so it may differ from `branch`. Returns its full commit hash. +/// With a non-empty branch and connectivity, local edits and commits are discarded +/// only after a fresh checkout succeeds. Offline, the current cached checkout is +/// used without switching branches, so it may differ from `branch`. +/// +/// An empty `branch` ("") uses the cached checkout without updating or switching +/// branches, preserving local edits and commits regardless of connectivity. +/// The connectivity probe still runs. Returns the checked-out commit's full hash. /// /// This performs blocking network and filesystem operations. Call during startup, /// before readers use ADJ, with only one updater at a time. Replacement uses two From 7f1ad4498f7e01df20d6fe95badf648f0720d20f Mon Sep 17 00:00:00 2001 From: Gazi Al Saad Halawani Date: Sun, 8 Nov 2026 14:48:47 +0100 Subject: [PATCH 099/225] Feat(backend, net, udp): Add UDP module supporting socket binding with configurable OS-level `SO_RCVBUF` size. Implement a two-stage receive architecture using a bounded Tokio `mpsc` channel to decouple the fast network read loop from the processing path. Add robust decoding against the ADJ `Index`, with fatal error reporting for malformed datagrams or socket resets. Include a comprehensive unit test suite covering valid datagram decoding, unknown packet ID error reporting, EOF handling, and `Copy` semantics for configuration. --- backend/Cargo.lock | 1 + backend/crates/core/Cargo.toml | 5 +- backend/crates/core/src/net/udp.rs | 310 ++++++++++++++++++++++++----- 3 files changed, 269 insertions(+), 47 deletions(-) diff --git a/backend/Cargo.lock b/backend/Cargo.lock index 5f25ff681..0b5bf8656 100644 --- a/backend/Cargo.lock +++ b/backend/Cargo.lock @@ -316,6 +316,7 @@ dependencies = [ "ntp_usg-server", "serde", "serde_json", + "socket2", "thiserror", "tokio", "tracing", diff --git a/backend/crates/core/Cargo.toml b/backend/crates/core/Cargo.toml index 0a3e434e8..6daeb36de 100644 --- a/backend/crates/core/Cargo.toml +++ b/backend/crates/core/Cargo.toml @@ -12,8 +12,8 @@ repository.workspace = true default = [] # NTP server ntp = ["dep:tokio", "dep:ntp_usg-server", "dep:tracing-subscriber"] -# TCP/UDP transport (pulls in tokio) -net = ["dep:tokio"] +# TCP/UDP transport (pulls in tokio and socket2 for SO_RCVBUF) +net = ["dep:tokio", "dep:socket2"] # ADJ download through git (dependency added when the module is written) git = [] # Packet sniffing through pcap (dependency added when the module is written) @@ -37,6 +37,7 @@ tokio = { workspace = true, optional = true, features = [ "rt-multi-thread", "io-util", ] } +socket2 = { version = "0.6", optional = true } tracing-subscriber = { workspace = true, optional = true , features = ["env-filter", "fmt"]} tracing-appender = { workspace = true, optional = true } ntp_usg-server = { version = "5.0.0", optional = true, features = ["ipv4", "tokio"] } diff --git a/backend/crates/core/src/net/udp.rs b/backend/crates/core/src/net/udp.rs index e8048507b..069219dfc 100644 --- a/backend/crates/core/src/net/udp.rs +++ b/backend/crates/core/src/net/udp.rs @@ -1,16 +1,27 @@ //! The shared UDP socket: one socket, receive-only, every board's //! telemetry. //! -//! **Not written yet.** This file currently holds only the error type -//! [`super::Error`] aggregates, plus the contract below, so that the rest -//! of `net` compiles and whoever implements this module knows what the -//! shared part expects of it. See [`super`] and `net/README.md`. -//! //! # What this module is //! //! One socket bound to the backend's own address, carrying `Data` packets -//! from every board. Nothing is ever sent from it. One task is enough: -//! there is no per-board state to keep. +//! from every board. Nothing is ever sent from it. +//! +//! # Architecture: two-stage receive with bounded channel +//! +//! Boards send thousands of packets per second, sometimes in bursts that +//! overwhelm a single processing loop. To handle this, the module uses a +//! two-stage design: +//! +//! 1. **Receive loop** — a fast task that only reads datagrams from the +//! socket and pushes them into a bounded `mpsc` channel. +//! 2. **Processing loop** — drains the channel, decodes each datagram +//! using [`crate::protocol::udp::decode_datagram`], resolves the board +//! id, and reports through [`super::Reporter`]. +//! +//! The channel (`RING_CAPACITY` = 8192) absorbs bursts so the receive +//! loop stays responsive. If the channel fills, the receive loop waits for +//! space rather than dropping — the kernel socket buffer (`SO_RCVBUF`) is +//! the first line of defense, and this channel is the second. //! //! # Entry point //! @@ -26,12 +37,9 @@ //! none of [`super::tcp`]'s buffer applies here. Read into one reused //! 64 KiB buffer and a datagram can never be silently truncated, //! whatever the ADJ grows to. -//! - The loop does three things and nothing else: receive, decode with -//! [`crate::protocol::udp::decode_datagram`], report. No disk, no -//! WebSocket, no aggregation — the socket's receive buffer is where -//! packets get dropped if this task falls behind, and the kernel drops -//! them silently, so this loop stays as short as it can be. Raising -//! `SO_RCVBUF` is part of setting the socket up. +//! - The processing loop does three things and nothing else: decode with +//! [`crate::protocol::udp::decode_datagram`], resolve the board, report. +//! No disk, no WebSocket, no aggregation. //! - [`super::Notification::board`] comes from the decoded packet's id, //! through [`crate::protocol::Index`] — every //! [`crate::model::PacketDef`] carries its `board` — so that a @@ -60,10 +68,13 @@ //! `Result, Error>`. use super::Reporter; +use crate::model::Packet; use crate::protocol::{DecodeError, Index}; use std::net::SocketAddr; use std::sync::Arc; +use tokio::sync::mpsc; use tokio::task::JoinHandle; +use tracing::{error, warn}; /// How to set the shared socket up. /// @@ -82,25 +93,167 @@ pub struct Config { pub recv_buffer: usize, } -/// Binds the shared socket and spawns the receive loop. +/// A queued datagram entry: raw payload bytes and the sender's address. +#[derive(Debug)] +struct Datagram { + /// The raw datagram bytes copied from the socket receive buffer. + bytes: Box<[u8]>, + /// The sender's socket address (used for error attribution if decoding fails). + from: SocketAddr, +} + +/// Channel capacity — the number of datagrams that can be queued +/// between the fast receive loop and the decode/report path. +/// +/// Boards send thousands of packets per second. This buffer absorbs +/// bursts so the receive loop stays responsive while `SO_RCVBUF` acts +/// as the first line of defense in the OS kernel. +const RING_CAPACITY: usize = 8192; + +/// Binds the shared socket and spawns the receive and processing loops. /// /// Binding happens here, **before** the task, so that a bad address is a /// startup failure handed back to whoever is composing the backend rather /// than something reported once everything is already running. /// -/// `adj` is the only part of the ADJ this module needs: it maps a decoded -/// id to its [`crate::model::PacketDef`], for the decode itself and for -/// the `board` every [`super::Notification`] carries. `station` owns it -/// and hands out clones; it is read-only here, and a reload of the ADJ is -/// a new [`Index`] with a new task, never a mutation of this one. -/// /// # Errors /// /// [`Error::Bind`] only — every later failure goes out through /// `reporter`, since by then there is nobody left to return it to. pub fn spawn(config: Config, adj: Arc, reporter: Reporter) -> Result, Error> { - let _ = (config, adj, reporter); - todo!("the UDP socket is not written yet: see this module's contract") + // 1. Bind the UDP socket synchronously before spawning async tasks. + let socket = bind_socket(config)?; + + // 2. Create the bounded channel connecting the receive loop to the processor. + let (ring_tx, ring_rx) = mpsc::channel(RING_CAPACITY); + + let recv_reporter = reporter.clone(); + + // 3. Spawn a supervising task that runs both the receiver and processor, + // ensuring clean shutdown of the processor when the receiver exits. + let handle = tokio::spawn(async move { + let processor = tokio::spawn(process_loop(ring_rx, adj, reporter)); + receive_loop(socket, ring_tx, recv_reporter).await; + // Once receive_loop exits, `ring_tx` is dropped, causing `process_loop` + // to drain remaining items and finish. + let _ = processor.await; + }); + + Ok(handle) +} + +/// Binds a UDP socket and configures its OS-level receive buffer size (`SO_RCVBUF`). +fn bind_socket(config: Config) -> Result { + // Bind using the standard library socket first so we can configure non-blocking mode. + let std_socket = std::net::UdpSocket::bind(config.addr).map_err(|source| Error::Bind { + addr: config.addr, + source, + })?; + + // Tokio requires the underlying std socket to be in non-blocking mode. + std_socket.set_nonblocking(true).map_err(|source| Error::Bind { + addr: config.addr, + source, + })?; + + // Convert the standard socket into an async Tokio UdpSocket. + let socket = tokio::net::UdpSocket::from_std(std_socket).map_err(|source| Error::Bind { + addr: config.addr, + source, + })?; + + // Attempt to enlarge the kernel's SO_RCVBUF to handle high-frequency telemetry bursts. + let sock_ref = socket2::SockRef::from(&socket); + if let Err(e) = sock_ref.set_recv_buffer_size(config.recv_buffer) { + warn!( + %config.addr, + buffer = config.recv_buffer, + %e, + "could not set SO_RCVBUF, using system default" + ); + } + + Ok(socket) +} + +/// Fast receive loop: reads raw datagrams from the socket and pushes them into the channel. +async fn receive_loop( + socket: tokio::net::UdpSocket, + ring_tx: mpsc::Sender, + reporter: Reporter, +) { + // Allocate a single 64 KiB buffer (maximum possible UDP datagram size) + // so no incoming packet can ever be truncated. + let mut buf = vec![0u8; 64 * 1024]; + + loop { + match socket.recv_from(&mut buf).await { + Ok((len, from)) => { + // Copy only the valid bytes of this datagram into a boxed slice. + let datagram = Datagram { + bytes: buf[..len].into(), + from, + }; + + // Forward to the processing task. If the receiver dropped, exit cleanly. + if ring_tx.send(datagram).await.is_err() { + break; + } + } + Err(source) => { + // Socket-level receive failure: log, report as fatal to the backend, and stop. + let err = Error::Recv { source }; + error!(%err, "UDP receive error"); + let _ = reporter.report(err).await; + break; + } + } + } +} + +/// Processing loop: drains the channel, decodes datagrams against the ADJ `Index`, and notifies downstream. +async fn process_loop( + mut ring_rx: mpsc::Receiver, + adj: Arc, + reporter: Reporter, +) { + // Pull datagrams one by one until `ring_tx` is closed and the queue is empty. + while let Some(datagram) = ring_rx.recv().await { + let Datagram { bytes, from } = datagram; + + // Decode raw bytes into a DataPacket using the ADJ lookup index. + let packet = match crate::protocol::udp::decode_datagram(&bytes, &adj) { + Ok(p) => p, + Err(source) => { + // A decode failure indicates an ADJ mismatch; report it to the error channel + // and continue draining subsequent packets. + let error = Error::Decode { from, source }; + error!(%error, "UDP decode error"); + if reporter.report(error).await.is_err() { + break; + } + continue; + } + }; + + // Look up the packet definition to find out which board sent this packet. + let Some(packet_def) = adj.packet(packet.id) else { + warn!(id = ?packet.id, "decoded packet id not in index"); + continue; + }; + + let board = packet_def.board; + + // Broadcast the decoded telemetry packet to the event bus. + if reporter + .notify(board, super::Event::Received(Packet::Data(packet))) + .await + .is_err() + { + // Downstream event receiver closed; exit loop. + break; + } + } } /// Something that went wrong on the shared UDP socket. @@ -145,26 +298,7 @@ pub enum Error { impl Error { /// Whether this error means the pod has to be sent to fault. - /// - /// "Fatal" is about the **pod**, not about this process: the backend - /// stays up — still reading, still serving the frontend, still - /// recording — so that whoever is operating the pod can see what - /// happened. Nothing here ever calls `std::process::exit`. - /// - /// Both runtime failures of this socket qualify, and for the same - /// reason: neither can be true of a single datagram. - /// [`Error::Decode`] means the loaded ADJ does not describe what the - /// boards are sending, and [`Error::Recv`] means the socket itself is - /// no longer usable, which is every board's telemetry gone at once. - /// Neither is something a retry fixes. - /// - /// [`Error::Bind`] never reaches this: binding happens before the - /// task is spawned, so it is a startup failure handed back to - /// whoever composes the backend. pub fn is_fatal(&self) -> bool { - // Matched exhaustively rather than just returning `true`: a - // variant added later has to say which it is instead of - // inheriting this answer in silence. match self { Error::Bind { .. } | Error::Recv { .. } | Error::Decode { .. } => true, } @@ -174,9 +308,11 @@ impl Error { #[cfg(test)] mod tests { use super::*; - use crate::model::AdjId; + use crate::model::{AdjId, Board, BoardId, MacAddress, MessageLevel, PacketDef, PacketType, PodData}; + use std::collections::HashMap; use std::net::IpAddr; + /// Helper returning a dummy sender SocketAddr for tests. fn peer() -> SocketAddr { SocketAddr::new(IpAddr::from([192, 168, 1, 3]), 50400) } @@ -185,7 +321,7 @@ mod tests { fn a_datagram_that_will_not_decode_faults_the_pod() { let error = Error::Decode { from: peer(), - source: DecodeError::UnknownId(AdjId(9999)), + source: crate::protocol::DecodeError::UnknownId(AdjId(9999)), }; // Nothing corrupts a datagram in flight, so this is a mismatched @@ -207,11 +343,95 @@ mod tests { fn a_decode_failure_says_where_it_came_from() { let error = Error::Decode { from: peer(), - source: DecodeError::UnknownId(AdjId(9999)), + source: crate::protocol::DecodeError::UnknownId(AdjId(9999)), }; // The only identity it has: there is no board to attribute an // undeclared id to. assert!(error.to_string().contains("192.168.1.3:50400")); } -} + + /// Builds a minimal Index with one empty Data packet (ID 1000) on Board 1. + fn sample_index() -> Index { + let packet = PacketDef { + id: AdjId(1000), + board: BoardId(1), + name: "test_data".to_string(), + packet_type: PacketType::Message(MessageLevel::Info),// I don't know what packet type to use here + }; + let board = Board { + id: BoardId(1), + name: "TEST".to_string(), + ip: IpAddr::from([192, 168, 0, 10]), + mac: MacAddress([0; 6]), + packets: HashMap::from([(packet.id, packet)]), + }; + let pod_data = PodData { + boards: HashMap::from([(board.id, board)]), + }; + Index::new(&pod_data) // I am not sure what to do here + } + + #[test] + fn ring_capacity_is_positive() { + // Sanity: the channel must hold at least one entry. + assert!(RING_CAPACITY > 0); + } + + #[tokio::test] + async fn process_loop_reports_error_on_unknown_id() { + let (reporter, mut sinks) = Reporter::channels(16, 16); + let index = Arc::new(sample_index()); + let (ring_tx, ring_rx) = mpsc::channel(RING_CAPACITY); + + let processor = tokio::spawn(process_loop(ring_rx, index, reporter)); + + // Send a datagram with an unknown id (0xFFFF = 65535) — should trigger a decode error. + let datagram = Datagram { + bytes: vec![0xFF, 0xFF].into(), + from: peer(), + }; + ring_tx.send(datagram).await.expect("processor is alive"); + + // Drop the sender so the processor exits. + drop(ring_tx); + processor.await.expect("processor should finish"); + + // The processor should have reported a decode error. + let error_report = sinks.errors.recv().await; + assert!(error_report.is_some(), "should have reported a decode error"); + } + + #[tokio::test] + async fn process_loop_exits_when_ring_closes() { + let (reporter, sinks) = Reporter::channels(16, 16); + let index = Arc::new(sample_index()); + let (ring_tx, ring_rx) = mpsc::channel(RING_CAPACITY); + + let processor = tokio::spawn(process_loop(ring_rx, index, reporter)); + + // Send an incomplete 1-byte datagram (fails with UnexpectedEof), then close the channel. + let datagram = Datagram { + bytes: vec![0x00].into(), + from: peer(), + }; + ring_tx.send(datagram).await.expect("processor is alive"); + drop(ring_tx); + + // Wait for the processor to finish cleanly. + processor.await.expect("processor should finish cleanly"); + drop(sinks); + } + + #[test] + fn config_is_copy() { + let config = Config { + addr: SocketAddr::new(IpAddr::from([127, 0, 0, 1]), 0), + recv_buffer: 2 * 1024 * 1024, + }; + let _copy = config; + // Config is still usable after assignment — it implements Copy. + let _addr = config.addr; + let _buf = config.recv_buffer; + } +} \ No newline at end of file From 572d1c9c4a0895852c1f72981983f440603d5530 Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Tue, 10 Nov 2026 18:33:06 +0100 Subject: [PATCH 100/225] feat(backend, logger): target struvutre of logs --- backend/crates/core/src/logger/target.rs | 168 +++++++++++++++++++++++ 1 file changed, 168 insertions(+) create mode 100644 backend/crates/core/src/logger/target.rs diff --git a/backend/crates/core/src/logger/target.rs b/backend/crates/core/src/logger/target.rs new file mode 100644 index 000000000..b0deb783c --- /dev/null +++ b/backend/crates/core/src/logger/target.rs @@ -0,0 +1,168 @@ +//! The handle discipline every file in this module shares: the label +//! that names it in its errors, the poisoning after a failed write, the +//! explicit flush, and the courtesy flush on drop. +//! +//! Private, and not a trait: [`super::CsvFile`] and [`super::TextFile`] +//! differ in what they put *in* a file (columns and quoting versus +//! lines), not in how they hold one. Keeping that part here is what +//! makes "flushing is explicit, and a failed write stops the file" one +//! behaviour rather than two copies of it that can drift. + +use super::Error; +use std::fs::{self, File}; +use std::io::{BufWriter, Write}; +use std::path::Path; +use tracing::error; + +/// An open destination, plus the name it answers to in errors. +#[derive(Debug)] +pub(super) struct Target { + inner: W, // The actual file or buffer being written to. + label: String, // + poisoned: bool, // Whether a write or flush failed, so all future writes fail too. + closed: bool, // Whether the caller has called `close()`, so `Drop` doesn't flush again. + written: u64, // Total bytes written to the destination so far. + since_flush: u64, // Bytes written since the last successful flush, for the caller to decide when to flush. +} + +impl Target { + /// Takes over an already-open destination, to be called `label` in + /// any [`Error`] about it. + pub(super) fn new(inner: W, label: String) -> Self { + Self { + inner, + label, + poisoned: false, + closed: false, + written: 0, + since_flush: 0, + } + } + + /// What this destination is called in its errors. + pub(super) fn label(&self) -> &str { + &self.label + } + + /// Borrows the destination itself. + pub(super) fn get_ref(&self) -> &W { + &self.inner + } + + /// Whether an earlier write or flush failed. + pub(super) fn is_poisoned(&self) -> bool { + self.poisoned + } + + /// Every byte handed to the destination so far. + pub(super) fn bytes_written(&self) -> u64 { + self.written + } + + /// The bytes handed over since the last successful flush. + pub(super) fn bytes_since_flush(&self) -> u64 { + self.since_flush + } + + /// The error to return instead of touching a poisoned destination. + pub(super) fn poisoned_error(&self) -> Error { + Error::Poisoned { + label: self.label.clone(), + } + } + + /// Writes `bytes` in one call, poisoning the destination if it + /// fails: a write that failed halfway already left the file + /// inconsistent. + pub(super) fn write_all(&mut self, bytes: &[u8]) -> Result<(), Error> { + if self.poisoned { + return Err(self.poisoned_error()); + } + + match self.inner.write_all(bytes) { + Ok(()) => { + let bytes = bytes.len() as u64; + self.written += bytes; + self.since_flush += bytes; + Ok(()) + } + Err(source) => { + self.poisoned = true; + Err(Error::Write { + label: self.label.clone(), + source, + }) + } + } + } + + /// Flushes everything written so far. + pub(super) fn flush(&mut self) -> Result<(), Error> { + if self.poisoned { + return Err(self.poisoned_error()); + } + + match self.inner.flush() { + Ok(()) => { + self.since_flush = 0; + Ok(()) + } + Err(source) => { + self.poisoned = true; + Err(Error::Flush { + label: self.label.clone(), + source, + }) + } + } + } + + /// Flushes and marks the destination closed, so [`Drop`] neither + /// flushes again nor traces an error the caller is already getting. + pub(super) fn close(&mut self) -> Result<(), Error> { + let result = self.flush(); + self.closed = true; + result + } +} + +impl Drop for Target { + fn drop(&mut self) { + if self.closed || self.poisoned { + return; + } + + // A courtesy flush, nothing more: `Drop` can't return the error + // and the workspace lints rule out panicking, so all it can do + // is leave a trace saying this file's tail may be missing. + if let Err(source) = self.inner.flush() { + error!( + file = %self.label, + error = %source, + "file dropped without close() and its final flush failed" + ); + } + } +} + +/// Creates (or truncates) the file at `path`, creating its parent +/// directories, and wraps it in a buffer. +/// +/// The default [`BufWriter`] capacity is deliberate: a bigger buffer is +/// less I/O but more lost if the process dies before the next flush, and +/// how often to flush is a decision for whoever is writing. +pub(super) fn create_file(path: &Path) -> Result, Error> { + if let Some(parent) = path.parent() { + fs::create_dir_all(parent).map_err(|source| Error::Create { + path: path.to_path_buf(), + source, + })?; + } + + let file = File::create(path).map_err(|source| Error::Create { + path: path.to_path_buf(), + source, + })?; + + Ok(BufWriter::new(file)) +} From e19459315a5f941bd4950a729e1af07be971fd7a Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Tue, 10 Nov 2026 18:36:11 +0100 Subject: [PATCH 101/225] feat(backend, logger): errors.rs --- backend/crates/core/src/logger/error.rs | 105 ++++++++++++++++++++++++ 1 file changed, 105 insertions(+) create mode 100644 backend/crates/core/src/logger/error.rs diff --git a/backend/crates/core/src/logger/error.rs b/backend/crates/core/src/logger/error.rs new file mode 100644 index 000000000..9a68b2b11 --- /dev/null +++ b/backend/crates/core/src/logger/error.rs @@ -0,0 +1,105 @@ +//! Errors produced while writing a file. +//! +//! Every variant names the file it happened on. A bare +//! [`std::io::Error`] says what went wrong but never where, and by the +//! time it reaches whoever decides whether to keep logging, the file is +//! the only thing that makes it actionable. +//! +//! [`Error::Create`] and [`Error::Serialize`] carry a [`PathBuf`], since +//! they can only happen to a real file on disk. The rest carry a plain +//! `label`, because a [`super::CsvFile`] can wrap any +//! [`std::io::Write`] — an in-memory buffer in a test has no path, just +//! the name its caller gave it. + +use std::path::PathBuf; + +/// An error writing a file. +#[derive(Debug, thiserror::Error)] +pub enum Error { + /// Couldn't create the file, or one of its parent directories. + #[error("couldn't create {path:?}")] + Create { + /// The file that couldn't be created. + path: PathBuf, + /// The underlying I/O error. + #[source] + source: std::io::Error, + }, + + /// Couldn't write to the file. + #[error("couldn't write to {label}")] + Write { + /// The file that couldn't be written to. + label: String, + /// The underlying I/O error. + #[source] + source: std::io::Error, + }, + + /// Couldn't flush the file's buffer, so what was written since the + /// last flush may not have reached the disk. + #[error("couldn't flush {label}")] + Flush { + /// The file that couldn't be flushed. + label: String, + /// The underlying I/O error. + #[source] + source: std::io::Error, + }, + + /// A row didn't have as many fields as the file's header declares. + /// + /// Nothing was written: the row is rejected whole, instead of + /// shifting every column of the file from that point on. + #[error("{label}: row needs {expected} field(s), got {got}")] + FieldCount { + /// The file the row was meant for. + label: String, + /// How many fields the header declares. + expected: usize, + /// How many fields the row actually had. + got: usize, + }, + + /// An earlier write to this file failed, so it is no longer written + /// to at all. + /// + /// Returned instead of retrying, because a write that failed halfway + /// already left the file inconsistent — and because a failing file + /// written at telemetry rates would otherwise report the same error + /// thousands of times per second. + #[error("{label} was left in a failed state by an earlier write")] + Poisoned { + /// The file that failed earlier. + label: String, + }, + + /// Couldn't put the finished file in place of the old one. + /// + /// A JSON document is built in a temporary file next to its + /// destination and renamed over it, so this is the last step of + /// [`super::write_json`] — and the only one that can fail with the + /// new content already complete on disk, under the temporary name + /// this error reports as its source path's sibling. + #[error("couldn't put the finished file in place of {path:?}")] + Replace { + /// The destination that couldn't be replaced. + path: PathBuf, + /// The underlying I/O error. + #[source] + source: std::io::Error, + }, + + /// Couldn't serialize the value as JSON, or couldn't write the + /// serialized bytes out. + #[error("couldn't write {path:?} as JSON")] + Serialize { + /// The file being written. + path: PathBuf, + /// The underlying `serde_json` error — which wraps the I/O error + /// too, when the failure was in writing rather than in + /// serializing. + #[source] + source: serde_json::Error, + }, +} From c984babea4d199a1736e7ccf6a77f07cf67505b6 Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Tue, 10 Nov 2026 19:01:31 +0100 Subject: [PATCH 102/225] feat(backend, logger): text to write txt files --- backend/crates/core/src/logger/text.rs | 248 +++++++++++++++++++++++++ 1 file changed, 248 insertions(+) create mode 100644 backend/crates/core/src/logger/text.rs diff --git a/backend/crates/core/src/logger/text.rs b/backend/crates/core/src/logger/text.rs new file mode 100644 index 000000000..b60b663ea --- /dev/null +++ b/backend/crates/core/src/logger/text.rs @@ -0,0 +1,248 @@ +//! A plain text file, written a line at a time. + +use super::Error; +use super::target::{Target, create_file}; +use std::fs::File; +use std::io::{BufWriter, Write}; +use std::path::Path; +use tracing::debug; + +/// A text file being written to, one line at a time. +/// +/// Deliberately the same vocabulary as [`crate::logger::CsvFile`] — +/// `create`, `new`, `flush`, `close`, `get_ref`, `is_poisoned`, the same +/// [`Error`], the same poisoning after a failed write and the same +/// courtesy flush on drop — so there is nothing to relearn moving +/// between the two. +/// +/// What it does *not* have is everything that only means something for +/// columns: no header, no field count, no quoting. A line is written +/// exactly as given, with a `\n` after it, and a line that contains a +/// comma or a quote is not special in any way. That also means a text +/// file can't tell you a line came out malformed — if the content has +/// fields in it, it wants [`crate::logger::CsvFile`] instead. +/// +/// # Example +/// +/// ``` +/// use software_core::logger::TextFile; +/// +/// let mut log = TextFile::new(Vec::new(), "in memory"); +/// log.write_line("session started")?; +/// log.write_line("board LCU connected")?; +/// +/// assert_eq!(log.get_ref().as_slice(), b"session started\nboard LCU connected\n"); +/// # Ok::<(), Box>(()) +/// ``` +#[derive(Debug)] +pub struct TextFile> { + target: Target, + /// The line currently being written, reused across lines so writing + /// one allocates nothing. + buf: Vec, +} + +impl TextFile> { + /// Creates (or truncates) the file at `path`, creating its parent + /// directories. + pub fn create(path: impl AsRef) -> Result { + let path = path.as_ref(); + let file = Self::new(create_file(path)?, path.display().to_string()); + debug!(path = %path.display(), "text file created"); + Ok(file) + } +} + +impl TextFile { + /// Wraps an already-open destination. + /// + /// `label` is what this file is called in any [`Error`] it produces; + /// [`TextFile::create`] uses the path for it. + /// + /// Unlike [`crate::logger::CsvFile::new`] this can't fail: there is + /// no header to write before the caller's first line. + pub fn new(inner: W, label: impl Into) -> Self { + Self { + target: Target::new(inner, label.into()), + buf: Vec::new(), + } + } + + /// Writes `line`, followed by a `\n`. + /// + /// The line and its terminator reach the destination as a single + /// write, so a line lands whole or not at all — the same guarantee + /// a CSV row gets. + pub fn write_line(&mut self, line: &str) -> Result<(), Error> { + self.buf.clear(); + self.buf.extend_from_slice(line.as_bytes()); + self.buf.push(b'\n'); + self.target.write_all(&self.buf) + } + + /// Flushes everything written so far to the destination. + pub fn flush(&mut self) -> Result<(), Error> { + self.target.flush() + } + + /// Flushes and closes the file, reporting a failure instead of + /// swallowing it like [`Drop`] has to. + pub fn close(mut self) -> Result<(), Error> { + self.target.close() + } + + /// Borrows the destination, e.g. to read back what was written to an + /// in-memory buffer. + pub fn get_ref(&self) -> &W { + self.target.get_ref() + } + + /// Whether an earlier write or flush failed, leaving this file + /// closed to further writes. + pub fn is_poisoned(&self) -> bool { + self.target.is_poisoned() + } + + /// What this file is called in its errors: the path it was created + /// with, or the label it was given. + /// + /// Worth having beyond [`Error`]'s own text: a caller that notices a + /// file went [`TextFile::is_poisoned`] has no error in hand any more, + /// and still needs to say which file stopped. + pub fn label(&self) -> &str { + self.target.label() + } + + /// Every byte handed to the destination so far, line terminators + /// included — the file's size on disk, once flushed. + pub fn bytes_written(&self) -> u64 { + self.target.bytes_written() + } + + /// The bytes written since the last successful flush. + /// + /// This is what a flush policy is built on: "flush every so many + /// kilobytes, or every so often" is the caller's decision (see this + /// module's docs), and this saves it from keeping its own tally for + /// each of the hundreds of files it may have open. + pub fn bytes_since_flush(&self) -> u64 { + self.target.bytes_since_flush() + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::fs; + + type TestResult = Result>; + + fn written(text: &TextFile>) -> String { + String::from_utf8_lossy(text.get_ref()).into_owned() + } + + /// A destination that takes `ok_writes` writes and fails every one + /// after that — what a full disk looks like from in here. + #[derive(Debug)] + struct FailsAfter { + ok_writes: usize, + } + + impl Write for FailsAfter { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + if self.ok_writes == 0 { + return Err(std::io::Error::other("disk full")); + } + self.ok_writes -= 1; + Ok(buf.len()) + } + + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } + } + + #[test] + fn every_line_is_written_with_its_terminator() -> TestResult { + let mut text = TextFile::new(Vec::new(), "in memory"); + + text.write_line("session started")?; + text.write_line("board LCU connected")?; + + assert_eq!(written(&text), "session started\nboard LCU connected\n"); + Ok(()) + } + + #[test] + fn an_empty_line_is_just_a_terminator() -> TestResult { + let mut text = TextFile::new(Vec::new(), "in memory"); + + text.write_line("")?; + text.write_line("after the blank")?; + + assert_eq!(written(&text), "\nafter the blank\n"); + Ok(()) + } + + #[test] + fn a_line_is_written_verbatim_with_no_quoting() -> TestResult { + let mut text = TextFile::new(Vec::new(), "in memory"); + + text.write_line("LCU, bay 2: say \"hi\"")?; + + assert_eq!(written(&text), "LCU, bay 2: say \"hi\"\n"); + Ok(()) + } + + #[test] + fn a_failed_write_poisons_the_file() -> TestResult { + let mut text = TextFile::new(FailsAfter { ok_writes: 1 }, "failing"); + + text.write_line("this one gets through")?; + assert!(matches!( + text.write_line("this one doesn't"), + Err(Error::Write { .. }) + )); + assert!(text.is_poisoned()); + + assert!(matches!( + text.write_line("nor this one"), + Err(Error::Poisoned { .. }) + )); + assert!(matches!(text.flush(), Err(Error::Poisoned { .. }))); + Ok(()) + } + + #[test] + fn a_file_reports_the_name_it_answers_to_and_the_bytes_it_has_taken() -> TestResult { + let mut text = TextFile::new(Vec::new(), "in memory"); + assert_eq!(text.label(), "in memory"); + assert_eq!(text.bytes_written(), 0); + + text.write_line("session started")?; + assert_eq!(text.bytes_written(), "session started\n".len() as u64); + assert_eq!(text.bytes_since_flush(), "session started\n".len() as u64); + + text.flush()?; + assert_eq!(text.bytes_since_flush(), 0); + assert_eq!(text.bytes_written(), "session started\n".len() as u64); + Ok(()) + } + + #[test] + fn create_makes_the_parent_directories_and_close_persists_every_line() -> TestResult { + let temp = tempfile::tempdir()?; + let path = temp.path().join("session/others/session.log"); + + let mut text = TextFile::create(&path)?; + text.write_line("session started")?; + text.write_line("session stopped")?; + text.close()?; + + assert_eq!( + fs::read_to_string(&path)?, + "session started\nsession stopped\n" + ); + Ok(()) + } +} From 0ab434722b1e4c8ad2b0769e3ddb81fc10419c23 Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Tue, 10 Nov 2026 19:10:38 +0100 Subject: [PATCH 103/225] feat(backend, logger): csv --- backend/crates/core/src/logger/csv.rs | 599 ++++++++++++++++++++++++++ 1 file changed, 599 insertions(+) create mode 100644 backend/crates/core/src/logger/csv.rs diff --git a/backend/crates/core/src/logger/csv.rs b/backend/crates/core/src/logger/csv.rs new file mode 100644 index 000000000..243f55456 --- /dev/null +++ b/backend/crates/core/src/logger/csv.rs @@ -0,0 +1,599 @@ +//! A CSV file that knows its own header. + +use super::Error; +use super::target::{Target, create_file}; +use std::fmt; +use std::fs::File; +use std::io::{BufWriter, Write}; +use std::path::Path; +use tracing::debug; + +/// A CSV file being written to, one row at a time. +/// +/// Generic over its destination so the format can be exercised against +/// an in-memory buffer, but the common case is the default: a file on +/// disk behind a [`BufWriter`], built with [`CsvFile::create`]. +/// +/// Three things it guarantees, which are the reason this type exists +/// instead of a bare [`File`]: +/// +/// - **A row lands whole or not at all.** Fields are built up in a +/// buffer the file reuses, and only [`Row::end`] writes — so a row +/// rejected for having the wrong number of fields never reaches the +/// file, and a row that does reach it is a single +/// [`Write::write_all`] call. +/// - **A failed write stops the file.** The first failure that reaches +/// the file poisons it: every later call returns +/// [`Error::Poisoned`] instead of appending to something already +/// inconsistent, or repeating the same I/O error once per row. +/// - **Flushing is something you ask for.** [`CsvFile::flush`] and +/// [`CsvFile::close`] return a `Result`. [`Drop`] only does a +/// best-effort flush and traces the failure: a fatal error in the +/// backend ends in `std::process::exit`, which runs no destructor at +/// all, so a log that only flushes on drop loses its tail exactly +/// when it matters most. +/// +/// Nothing here is traced per row on purpose: at telemetry rates that +/// would be tens of thousands of events per second. Only opening a file +/// (`debug`) and a failed flush on drop (`error`) are traced. +/// +/// # Example +/// +/// ``` +/// use software_core::logger::CsvFile; +/// +/// let mut csv = CsvFile::new(Vec::new(), "in memory", &["t", "origin", "value"])?; +/// csv.row().int(1_250).text("LCU, bay 2").num(53.2).end()?; +/// +/// assert_eq!( +/// csv.get_ref().as_slice(), +/// b"t,origin,value\n1250,\"LCU, bay 2\",53.2\n", +/// ); +/// # Ok::<(), Box>(()) +/// ``` +#[derive(Debug)] +pub struct CsvFile> { + target: Target, + /// How many fields every row must have, or `None` when the file was + /// created with an empty header and there is nothing to check + /// against. + fields: Option, + /// The row currently being built, reused across rows so writing one + /// allocates nothing. + buf: Vec, +} + +impl CsvFile> { + /// Creates (or truncates) the file at `path`, creating its parent + /// directories, and writes `header` as its first line. + /// + /// An empty `header` writes no header line and leaves the row's + /// field count unchecked — see [`CsvFile::new`]. + pub fn create(path: impl AsRef, header: &[&str]) -> Result { + let path = path.as_ref(); + + // The file is created before the header is written so that a failure to write the header doesn't leave a partially written file. + let file = Self::new(create_file(path)?, path.display().to_string(), header)?; + debug!(path = %path.display(), fields = header.len(), "csv file created"); + Ok(file) + } +} + +impl CsvFile { + /// Wraps an already-open destination, writing `header` as its first + /// line. + /// + /// `label` is what this file is called in any [`Error`] it produces; + /// [`CsvFile::create`] uses the path for it. + /// + /// An empty `header` writes no header line, and leaves every row's + /// field count unchecked — for a file whose columns aren't known up + /// front. With a header, a row with a different number of fields is + /// an [`Error::FieldCount`]. + pub fn new(inner: W, label: impl Into, header: &[&str]) -> Result { + let mut file = Self { + target: Target::new(inner, label.into()), + fields: None, + buf: Vec::new(), + }; + + if !header.is_empty() { + // Written through `Row` like any other line, so a header + // with a comma or a quote in it is quoted the same way a + // field would be. The field count is still `None` here, so + // the header itself is what sets the count rather than being + // checked against it. + let mut row = file.row(); + for field in header { + row = row.text(field); + } + row.end()?; + file.fields = Some(header.len()); + } + + Ok(file) + } + + /// Starts a row. Add its fields, then call [`Row::end`]. + /// + /// Nothing is written to the file until `end`, and a row dropped + /// without it writes nothing at all. + pub fn row(&mut self) -> Row<'_, W> { + self.buf.clear(); + Row { + file: self, + count: 0, + error: None, + } + } + + /// Flushes everything written so far to the destination. + pub fn flush(&mut self) -> Result<(), Error> { + self.target.flush() + } + + /// Flushes and closes the file, reporting a failure instead of + /// swallowing it like [`Drop`] has to. + pub fn close(mut self) -> Result<(), Error> { + self.target.close() + } + + /// Borrows the destination, e.g. to read back what was written to an + /// in-memory buffer. + pub fn get_ref(&self) -> &W { + self.target.get_ref() + } + + /// Whether an earlier write or flush failed, leaving this file + /// closed to further writes. + pub fn is_poisoned(&self) -> bool { + self.target.is_poisoned() + } + + /// What this file is called in its errors: the path it was created + /// with, or the label it was given. + /// + /// Worth having beyond [`Error`]'s own text: a caller that notices a + /// file went [`CsvFile::is_poisoned`] has no error in hand any more, + /// and still needs to say which file stopped. + pub fn label(&self) -> &str { + self.target.label() + } + + /// Every byte handed to the destination so far, header included — + /// the file's size on disk, once flushed. + pub fn bytes_written(&self) -> u64 { + self.target.bytes_written() + } + + /// The bytes written since the last successful flush. + /// + /// This is what a flush policy is built on: "flush every so many + /// kilobytes, or every so often" is the caller's decision (see this + /// module's docs), and this saves it from keeping its own tally for + /// each of the hundreds of files it may have open. + pub fn bytes_since_flush(&self) -> u64 { + self.target.bytes_since_flush() + } + + /// Writes the row held in `buf`, terminator included, as one call. + fn write_row(&mut self) -> Result<(), Error> { + self.buf.push(b'\n'); + self.target.write_all(&self.buf) + } +} + +/// A single row being built, field by field. +/// +/// Every field method appends to the file's row buffer and keeps the +/// first error it hits, so a row reads as one expression without a `?` +/// per field; [`Row::end`] is where that error — and the field count — +/// is reported. +#[derive(Debug)] +pub struct Row<'a, W: Write> { + file: &'a mut CsvFile, + count: usize, + error: Option, +} + +impl Row<'_, W> { + /// Appends an integer field. + pub fn int(self, value: i64) -> Self { + self.number(format_args!("{value}")) + } + + /// Appends a floating point field. + /// + /// Written with its [`fmt::Display`], i.e. the shortest form that + /// round-trips back to the same `f64`: a value with no fractional + /// part has no decimal point (`1.0` is written `1`), and `NaN` and + /// the infinities are written as `NaN`, `inf` and `-inf` rather than + /// replaced by an empty field — if a board sent one, the log should + /// say so. + pub fn num(self, value: f64) -> Self { + self.number(format_args!("{value}")) + } + + /// Appends a boolean field, as `true` or `false`. + pub fn bool(self, value: bool) -> Self { + self.number(format_args!("{value}")) + } + + /// Appends a text field, quoted if it needs to be. + /// + /// A field containing a comma, a double quote, a carriage return or + /// a line feed is wrapped in double quotes, with every inner quote + /// doubled (RFC 4180). This is the only method that can need + /// quoting — a number or a boolean never contains any of those — and + /// the one that matters: a board's free-text message or the path it + /// came from can contain all four. + pub fn text(mut self, value: &str) -> Self { + if self.error.is_some() { + return self; + } + + let separated = self.count > 0; + match append_text(&mut self.file.buf, value, separated) { + Ok(()) => { + self.count += 1; + self + } + Err(source) => { + self.error = Some(Error::Write { + label: self.file.target.label().to_string(), + source, + }); + self + } + } + } + + /// Validates the row against the file's header and writes it. + /// + /// Errors with [`Error::FieldCount`] — writing nothing — if the row + /// doesn't have as many fields as the header declares. + pub fn end(mut self) -> Result<(), Error> { + if let Some(error) = self.error.take() { + return Err(error); + } + + if self.file.target.is_poisoned() { + return Err(self.file.target.poisoned_error()); + } + + if let Some(expected) = self.file.fields + && self.count != expected + { + return Err(Error::FieldCount { + label: self.file.target.label().to_string(), + expected, + got: self.count, + }); + } + + self.file.write_row() + } + + /// Appends a field that can't need quoting: every numeric and + /// boolean field goes through here, which is also what makes them + /// the cheap ones. + fn number(mut self, value: fmt::Arguments<'_>) -> Self { + if self.error.is_some() { + return self; + } + + let separator = if self.count > 0 { "," } else { "" }; + // Appending to a `Vec` can only fail by running out of + // memory, but `write!` is fallible all the same: keep the error + // rather than discard it, and let `end` be the one to report it. + match write!(self.file.buf, "{separator}{value}") { + Ok(()) => { + self.count += 1; + self + } + Err(source) => { + self.error = Some(Error::Write { + label: self.file.target.label().to_string(), + source, + }); + self + } + } + } +} + +/// Appends `value` to `buf`, preceded by a separator if `separated`, and +/// quoted per RFC 4180 if it contains anything that needs it. +fn append_text(buf: &mut Vec, value: &str, separated: bool) -> std::io::Result<()> { + if separated { + buf.write_all(b",")?; + } + + if !value.contains([',', '"', '\n', '\r']) { + return buf.write_all(value.as_bytes()); + } + + buf.write_all(b"\"")?; + let mut rest = value; + while let Some(quote) = rest.find('"') { + buf.write_all(&rest.as_bytes()[..quote])?; + buf.write_all(b"\"\"")?; + rest = &rest[quote + 1..]; + } + buf.write_all(rest.as_bytes())?; + buf.write_all(b"\"") +} + +#[cfg(test)] +mod tests { + use super::*; + use std::fs; + + type TestResult = Result>; + + fn in_memory(header: &[&str]) -> TestResult>> { + Ok(CsvFile::new(Vec::new(), "in memory", header)?) + } + + fn written(csv: &CsvFile>) -> String { + String::from_utf8_lossy(csv.get_ref()).into_owned() + } + + /// A destination that takes `ok_writes` writes and fails every one + /// after that — what a full disk looks like from in here. + #[derive(Debug)] + struct FailsAfter { + ok_writes: usize, + taken: Vec, + } + + impl Write for FailsAfter { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + if self.ok_writes == 0 { + return Err(std::io::Error::other("disk full")); + } + self.ok_writes -= 1; + self.taken.extend_from_slice(buf); + Ok(buf.len()) + } + + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } + } + + #[test] + fn the_header_is_the_files_first_line() -> TestResult { + let csv = in_memory(&["t", "value"])?; + assert_eq!(written(&csv), "t,value\n"); + Ok(()) + } + + #[test] + fn an_empty_header_writes_nothing_and_leaves_the_field_count_unchecked() -> TestResult { + let mut csv = in_memory(&[])?; + assert_eq!(written(&csv), ""); + + csv.row().int(1).end()?; + csv.row().int(1).int(2).int(3).end()?; + + assert_eq!(written(&csv), "1\n1,2,3\n"); + Ok(()) + } + + #[test] + fn a_text_field_is_quoted_only_when_it_has_to_be() -> TestResult { + let mut csv = in_memory(&[])?; + + csv.row().text("LCU").end()?; + csv.row().text("LCU, bay 2").end()?; + csv.row().text("say \"hi\"").end()?; + csv.row().text("two\nlines").end()?; + csv.row().text("carriage\rreturn").end()?; + + assert_eq!( + written(&csv), + "LCU\n\"LCU, bay 2\"\n\"say \"\"hi\"\"\"\n\"two\nlines\"\n\"carriage\rreturn\"\n" + ); + Ok(()) + } + + #[test] + fn a_header_field_is_quoted_like_any_other_text() -> TestResult { + let csv = in_memory(&["t", "value, raw"])?; + assert_eq!(written(&csv), "t,\"value, raw\"\n"); + Ok(()) + } + + #[test] + fn numbers_and_booleans_are_never_quoted() -> TestResult { + let mut csv = in_memory(&[])?; + csv.row() + .int(-1_250) + .num(53.2) + .bool(true) + .bool(false) + .end()?; + assert_eq!(written(&csv), "-1250,53.2,true,false\n"); + Ok(()) + } + + #[test] + fn a_float_is_written_as_the_shortest_form_that_round_trips() -> TestResult { + let mut csv = in_memory(&[])?; + csv.row() + .num(1.0) + .num(53.2) + .num(-0.5) + .num(f64::NAN) + .num(f64::INFINITY) + .end()?; + assert_eq!(written(&csv), "1,53.2,-0.5,NaN,inf\n"); + Ok(()) + } + + #[test] + fn a_row_with_the_wrong_number_of_fields_is_rejected_whole() -> TestResult { + let mut csv = in_memory(&["t", "value"])?; + + let too_few = csv.row().int(1).end(); + assert!(matches!( + too_few, + Err(Error::FieldCount { + expected: 2, + got: 1, + .. + }) + )); + + let too_many = csv.row().int(1).int(2).int(3).end(); + assert!(matches!( + too_many, + Err(Error::FieldCount { + expected: 2, + got: 3, + .. + }) + )); + + // Neither rejected row reached the file, and the file still + // takes a correct row afterwards. + assert_eq!(written(&csv), "t,value\n"); + csv.row().int(1).num(2.5).end()?; + assert_eq!(written(&csv), "t,value\n1,2.5\n"); + Ok(()) + } + + #[test] + fn a_row_dropped_without_end_writes_nothing() -> TestResult { + let mut csv = in_memory(&["t"])?; + + let _ = csv.row().int(7); + assert_eq!(written(&csv), "t\n"); + + csv.row().int(8).end()?; + assert_eq!(written(&csv), "t\n8\n"); + Ok(()) + } + + #[test] + fn a_failed_write_poisons_the_file_instead_of_reporting_once_per_row() -> TestResult { + // One write for the header, so the first row is what fails. + let destination = FailsAfter { + ok_writes: 1, + taken: Vec::new(), + }; + let mut csv = CsvFile::new(destination, "failing", &["t"])?; + + assert!(matches!(csv.row().int(1).end(), Err(Error::Write { .. }))); + assert!(csv.is_poisoned()); + + assert!(matches!( + csv.row().int(2).end(), + Err(Error::Poisoned { .. }) + )); + assert!(matches!(csv.flush(), Err(Error::Poisoned { .. }))); + + // Nothing past the header ever reached the destination. + assert_eq!(String::from_utf8_lossy(&csv.get_ref().taken), "t\n"); + Ok(()) + } + + #[test] + fn writing_rows_reuses_one_buffer_instead_of_allocating_per_row() -> TestResult { + let mut csv = in_memory(&["t", "origin", "value"])?; + + // Two identical passes: the first lets the row buffer grow to + // whatever the widest of these rows needs, the second must not + // make it grow at all. Comparing passes rather than asserting + // some size keeps this about reuse and not about how wide a + // formatted `f64` happens to be. + let mut after_first_pass = None; + for _pass in 0..2 { + for i in 0..10_000usize { + let origin = &"src/boards/lcu/main.cpp"[..(i % 23) + 1]; + csv.row().int(i as i64).text(origin).num(i as f64).end()?; + } + + match after_first_pass { + None => after_first_pass = Some(csv.buf.capacity()), + Some(grown) => assert_eq!( + csv.buf.capacity(), + grown, + "the row buffer grew again on the second pass" + ), + } + } + // And it is one row's worth, not every row appended: if `row()` + // ever stopped clearing it, this would be in the megabytes. + assert!( + csv.buf.capacity() < 256, + "row buffer grew to {} bytes", + csv.buf.capacity() + ); + Ok(()) + } + + #[test] + fn a_file_reports_the_name_it_answers_to_in_its_errors() -> TestResult { + let temp = tempfile::tempdir()?; + let path = temp.path().join("current.csv"); + + let on_disk = CsvFile::create(&path, &["t"])?; + assert_eq!(on_disk.label(), path.display().to_string()); + + let in_memory = in_memory(&["t"])?; + assert_eq!(in_memory.label(), "in memory"); + Ok(()) + } + + #[test] + fn bytes_written_counts_the_header_and_every_row() -> TestResult { + let mut csv = in_memory(&["t", "value"])?; + assert_eq!(csv.bytes_written(), "t,value\n".len() as u64); + + csv.row().int(1).num(2.5).end()?; + assert_eq!(csv.bytes_written(), "t,value\n1,2.5\n".len() as u64); + Ok(()) + } + + #[test] + fn bytes_since_flush_is_what_a_flush_policy_reads_and_resets() -> TestResult { + let mut csv = in_memory(&["t"])?; + csv.row().int(1).end()?; + assert_eq!(csv.bytes_since_flush(), "t\n1\n".len() as u64); + + csv.flush()?; + assert_eq!(csv.bytes_since_flush(), 0); + // Flushing doesn't reset the total, only what is pending. + assert_eq!(csv.bytes_written(), "t\n1\n".len() as u64); + + csv.row().int(2).end()?; + assert_eq!(csv.bytes_since_flush(), "2\n".len() as u64); + Ok(()) + } + + #[test] + fn a_rejected_row_counts_no_bytes() -> TestResult { + let mut csv = in_memory(&["t", "value"])?; + let header = csv.bytes_written(); + + assert!(csv.row().int(1).end().is_err()); + assert_eq!(csv.bytes_written(), header); + Ok(()) + } + + #[test] + fn create_makes_the_parent_directories_and_close_persists_every_row() -> TestResult { + let temp = tempfile::tempdir()?; + let path = temp.path().join("session/data/LCU/current.csv"); + + let mut csv = CsvFile::create(&path, &["t", "value"])?; + csv.row().int(0).num(1.5).end()?; + csv.row().int(1_000).num(2.5).end()?; + csv.close()?; + + assert_eq!(fs::read_to_string(&path)?, "t,value\n0,1.5\n1000,2.5\n"); + Ok(()) + } +} From 773854037375b9200f9b1f28ddce79b9e754d3b9 Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Tue, 10 Nov 2026 19:28:32 +0100 Subject: [PATCH 104/225] feat(backend,logger: json --- backend/crates/core/src/logger.rs | 89 ++++ backend/crates/core/src/logger/error.rs | 30 ++ backend/crates/core/src/logger/json.rs | 619 ++++++++++++++++++++++++ 3 files changed, 738 insertions(+) create mode 100644 backend/crates/core/src/logger.rs create mode 100644 backend/crates/core/src/logger/json.rs diff --git a/backend/crates/core/src/logger.rs b/backend/crates/core/src/logger.rs new file mode 100644 index 000000000..24ec6452f --- /dev/null +++ b/backend/crates/core/src/logger.rs @@ -0,0 +1,89 @@ +//! Plain, synchronous file writing: the one place that knows how to put +//! a CSV row, a line of text or a JSON document on disk without +//! corrupting it. +//! +//! Deliberately boring, and deliberately small. It knows nothing about +//! the vehicle — no [`crate::model`] types, no ADJ, no boards, no +//! recording session, no notion of a timestamp or of a log level. +//! Deciding *what* to write, *when*, and under which name is the job of +//! the backend's own `station::logging`, which will own the four +//! subloggers (data, protections, messages and orders), the session +//! directory and the hot enable/disable. This module only answers "how +//! do I write this file". +//! +//! What it buys over calling [`std::fs`] from each of those subloggers: +//! +//! - **Flushing is explicit.** [`crate::logger::CsvFile::close`] and [`crate::logger::CsvFile::flush`] +//! return a `Result`. A fatal error in the backend ends in +//! `std::process::exit`, which runs no destructor, so a file that only +//! flushes when it is dropped loses its tail exactly in the case the +//! log was there to explain. [`Drop`] is kept as a courtesy flush that +//! traces its own failure, never as the plan. *When* to flush stays +//! the caller's decision, but it doesn't have to keep its own tally to +//! make it: every file reports its `bytes_since_flush`, so "flush +//! every so many kilobytes, or every so often" is a couple of lines +//! over a map of open files. +//! - **Errors name the file.** A bare [`std::io::Error`] says what went +//! wrong but not where; every [`crate::logger::Error`] here carries the path or the +//! label of the file it happened on. +//! - **A row can't silently go out of step.** A [`crate::logger::CsvFile`] knows its +//! header, so a row with one field too few is an error, not a file +//! whose columns are shifted from that line on. +//! - **Quoting is done once, here.** A board's free-text message and the +//! path it came from can both contain commas, quotes and newlines. +//! [`crate::logger::Row::text`] quotes per RFC 4180; four subloggers formatting their +//! own lines would each get a chance to get that wrong. +//! - **A row allocates nothing.** Fields are formatted into a buffer the +//! file reuses, not into a `Vec` built and thrown away per +//! row — at telemetry rates that is tens of thousands of rows a +//! second. +//! +//! The three formats are *not* one abstraction, and that is deliberate. +//! What they share is how a file is **held** — the label it answers to +//! in its errors, the poisoning after a failed write, the explicit +//! flush, the courtesy flush on drop — and that lives in one private +//! place (`target`), so it is one behaviour instead of three copies of +//! it that drift apart. What they don't share is how a file is +//! **written**, because it genuinely isn't the same operation: a CSV row +//! is typed fields validated against a header, a text line is a string +//! taken verbatim, and a JSON document is a whole value serialized in +//! one go with no handle to keep. [`crate::logger::CsvFile`] and +//! [`crate::logger::TextFile`] therefore expose the same vocabulary — +//! `create`, `new`, `flush`, `close`, `get_ref`, `is_poisoned` — while +//! [`crate::logger::write_json`] stays a free function, since a file +//! written once and closed has no handle to give back. +//! +//! There is no public trait over the three. A trait would only pay for +//! itself once some caller needs to be generic over the format — the +//! same code path writing either CSV or JSON lines, say — and no caller +//! does today; reaching for one now would mean either flattening the +//! API down to "write these bytes", which throws away the field +//! validation and the quoting that are the point, or inventing an +//! open/write/close lifecycle for JSON that it doesn't have. Adding the +//! trait later is backwards compatible, so it can wait for the second +//! caller. +//! +//! Reading is in for JSON only ([`crate::logger::read_json`], +//! [`crate::logger::JsonDocument`]), and for one reason: a document that +//! gains properties over time can't be added to without being read +//! first. A CSV or a text log is appended to and never revisited, and +//! nothing here will read one back. +//! +//! Not here, on purpose: reading a CSV or a text log back, sessions, timestamps, file +//! rotation, copying files around, keeping a registry of many open files +//! (a `HashMap` with `entry().or_insert_with(...)` in the +//! caller is shorter and clearer than anything this module could wrap it +//! in), and anything asynchronous. These functions block; a caller +//! inside a `tokio` task is the one that decides whether to run them on +//! a thread of their own. + +mod csv; +mod error; +mod json; +mod target; +mod text; + +pub use csv::{CsvFile, Row}; +pub use error::Error; +pub use json::{JsonDocument, read_json, write_json}; +pub use text::TextFile; diff --git a/backend/crates/core/src/logger/error.rs b/backend/crates/core/src/logger/error.rs index 9a68b2b11..691f43e08 100644 --- a/backend/crates/core/src/logger/error.rs +++ b/backend/crates/core/src/logger/error.rs @@ -74,6 +74,36 @@ pub enum Error { label: String, }, + /// Couldn't read the file. + #[error("couldn't read {path:?}")] + Read { + /// The file that couldn't be read. + path: PathBuf, + /// The underlying I/O error. + #[source] + source: std::io::Error, + }, + + /// Couldn't parse the file as JSON, or couldn't read one of its + /// properties as the type it was asked for. + #[error("couldn't parse {path:?} as JSON")] + Parse { + /// The file that failed to parse. + path: PathBuf, + /// The underlying `serde_json` error, which says where in the + /// document the problem is. + #[source] + source: serde_json::Error, + }, + + /// The file is valid JSON, but its root isn't an object, so it has + /// no properties to read or add to. + #[error("{path:?} is valid JSON but its root is not an object")] + NotAnObject { + /// The file whose root isn't an object. + path: PathBuf, + }, + /// Couldn't put the finished file in place of the old one. /// /// A JSON document is built in a temporary file next to its diff --git a/backend/crates/core/src/logger/json.rs b/backend/crates/core/src/logger/json.rs new file mode 100644 index 000000000..b2b78510a --- /dev/null +++ b/backend/crates/core/src/logger/json.rs @@ -0,0 +1,619 @@ +//! JSON documents: written whole, read back whole, and updated by +//! being replaced. +//! +//! Two ways in, for two different jobs. [`write_json`] and [`read_json`] +//! are one-shot and typed: the caller has a type for the whole document +//! and hands it over, or gets it back. [`JsonDocument`] is for the file +//! that gains properties over time — a recording's metadata, written +//! when it starts and added to when it stops — which has to be read +//! before it can be added to, and whose properties this crate knows +//! nothing about have to survive the round trip all the same. +//! +//! Reading is deliberate here and nowhere else in the module: a JSON +//! document is small, whole and structured, so reading it back to change +//! it is the only way to change it. A CSV or a text log is appended to, +//! never revisited, and nothing here will read one back. +//! +//! None of this keeps a file open between calls, which is why nothing +//! here uses the `Target` that `csv` and `text` are built on: a document +//! lives in memory, and getting it onto the disk is one atomic +//! replacement, the same one [`write_json`] performs. + +use super::Error; +use super::target::create_file; +use serde::Serialize; +use serde::de::DeserializeOwned; +use serde_json::{Map, Value}; +use std::ffi::OsString; +use std::fs; +use std::io::Write; +use std::path::{Path, PathBuf}; +use tracing::debug; + +/// Writes `value` to `path` as pretty-printed JSON, creating its parent +/// directories and replacing whatever was there. +/// +/// Pretty-printed, with a trailing newline, because these are the files +/// a person opens to find out what a recording was: a session's +/// metadata, the ADJ commit it ran against, a dump of the configuration +/// in use. Anything appended to over time wants a CSV +/// ([`super::CsvFile`]) instead — this function writes the file once and +/// closes it. +/// +/// Written through a temporary file next to the destination, flushed to +/// the disk and then renamed over it, so `path` is never seen +/// half-written: either the old contents or the new ones, nothing in +/// between. That matters more here than anywhere else in this module — +/// a fatal error in the backend ends in `std::process::exit`, and a +/// session's metadata truncated at that moment is what makes every CSV +/// next to it unreadable. The rename needs both files on the same +/// filesystem, which they are by construction, being siblings. What +/// isn't covered: the directory entry itself isn't synced, so a power +/// cut in the instant after the rename can still lose it — surviving +/// that would mean syncing the directory too, which isn't worth it for +/// what this writes. +/// +/// # Example +/// +/// ``` +/// use software_core::logger::write_json; +/// use std::collections::BTreeMap; +/// +/// let path = std::env::temp_dir().join("software-core-logger-doc/write.json"); +/// let settings = BTreeMap::from([("adj_commit", "4f1c3b0"), ("time_unit", "us")]); +/// +/// write_json(&path, &settings)?; +/// +/// assert_eq!( +/// std::fs::read_to_string(&path)?, +/// "{\n \"adj_commit\": \"4f1c3b0\",\n \"time_unit\": \"us\"\n}\n", +/// ); +/// # std::fs::remove_file(&path)?; +/// # Ok::<(), Box>(()) +/// ``` +pub fn write_json(path: impl AsRef, value: &T) -> Result<(), Error> +where + T: Serialize + ?Sized, +{ + let path = path.as_ref(); + let temporary = temporary_path(path); + + // Anything that fails from here on leaves the destination untouched, + // so the temporary file is cleaned up and the error is about `path`, + // which is the file the caller asked for and the only one it knows. + match build(&temporary, path, value) { + Ok(()) => {} + Err(error) => { + // Best effort: the write already failed, and failing to + // remove the leftover is not what the caller needs to hear. + let _ = fs::remove_file(&temporary); + return Err(error); + } + } + + fs::rename(&temporary, path).map_err(|source| Error::Replace { + path: path.to_path_buf(), + source, + })?; + + debug!(path = %path.display(), "json file written"); + Ok(()) +} + +/// Serializes `value` into `temporary` and gets it onto the disk, with +/// every error reported against `path`, the destination it is about to +/// be renamed to. +fn build(temporary: &Path, path: &Path, value: &T) -> Result<(), Error> +where + T: Serialize + ?Sized, +{ + // `create_file` reports the file it actually tried to make: the + // temporary one, which the caller never named. Every error out of + // here is about the destination, so put its path back. + let mut writer = create_file(temporary).map_err(|error| match error { + Error::Create { source, .. } => Error::Create { + path: path.to_path_buf(), + source, + }, + other => other, + })?; + + serde_json::to_writer_pretty(&mut writer, value).map_err(|source| Error::Serialize { + path: path.to_path_buf(), + source, + })?; + + // `to_writer_pretty` leaves no terminator: add one so the file reads + // well with `cat` and behaves for anything line-oriented. + writer.write_all(b"\n").map_err(|source| Error::Write { + label: path.display().to_string(), + source, + })?; + + // The buffer is dropped with this function, and a drop swallows the + // flush error — so flush here, where it can still be reported. + writer.flush().map_err(|source| Error::Flush { + label: path.display().to_string(), + source, + })?; + + // Flushing only hands the bytes to the operating system. Syncing + // before the rename is what makes the swap meaningful: otherwise the + // rename can be on the disk while the contents it points at are + // still only in the page cache. Affordable here, where it happens + // once per file, in a way it wouldn't be per CSV row. + writer.get_ref().sync_all().map_err(|source| Error::Flush { + label: path.display().to_string(), + source, + }) +} + +/// The temporary name a document is built under: the destination's own +/// name plus `.tmp`, so it lands in the same directory — and therefore +/// the same filesystem, which [`fs::rename`] needs to be atomic. +fn temporary_path(path: &Path) -> PathBuf { + let mut name = OsString::from(path); + name.push(".tmp"); + PathBuf::from(name) +} + +/// Reads `path` and parses the whole document as `T`. +/// +/// The counterpart of [`write_json`], for a document whose shape the +/// caller has a type for. To read one property out of a document, or to +/// add properties to it, use [`JsonDocument`] instead. +/// +/// # Example +/// +/// ``` +/// use software_core::logger::{read_json, write_json}; +/// use std::collections::BTreeMap; +/// +/// let path = std::env::temp_dir().join("software-core-logger-doc/read.json"); +/// let written = BTreeMap::from([("time_unit".to_string(), "us".to_string())]); +/// write_json(&path, &written)?; +/// +/// let read: BTreeMap = read_json(&path)?; +/// assert_eq!(read, written); +/// # std::fs::remove_file(&path)?; +/// # Ok::<(), Box>(()) +/// ``` +pub fn read_json(path: impl AsRef) -> Result +where + T: DeserializeOwned, +{ + let path = path.as_ref(); + let text = read_text(path)?; + + serde_json::from_str(&text).map_err(|source| Error::Parse { + path: path.to_path_buf(), + source, + }) +} + +/// A JSON object held in memory, together with the file it came from. +/// +/// For the document that is added to over time instead of written once: +/// open it, set the properties that are known now, save, and later open +/// it again and set the ones that weren't. Properties nobody here knows +/// about are kept as they were — the document is edited, not rebuilt +/// from a struct that would have dropped them. +/// +/// Changes stay in memory until [`JsonDocument::save`], which replaces +/// the file atomically. Nothing is held open in between, so a document +/// can be opened, saved and forgotten without any flushing discipline. +/// +/// Properties come out in alphabetical order, which is `serde_json`'s +/// own ordering for an object and not something this type imposes: the +/// same document always serializes the same way, which is what makes it +/// readable in a diff. +/// +/// # Example +/// +/// ``` +/// use software_core::logger::JsonDocument; +/// +/// let path = std::env::temp_dir().join("software-core-logger-doc/document.json"); +/// +/// let mut session = JsonDocument::new(&path); +/// session +/// .set("adj_commit", "4f1c3b0")? +/// .set("time_unit", "us")?; +/// session.save()?; +/// +/// // Later, when the recording stops, by whoever has the path. +/// let mut session = JsonDocument::open(&path)?; +/// session.set("rows", 128_000u64)?.set("stopped", true)?; +/// session.save()?; +/// +/// let session = JsonDocument::open(&path)?; +/// assert_eq!(session.get::("adj_commit")?.as_deref(), Some("4f1c3b0")); +/// assert_eq!(session.get::("rows")?, Some(128_000)); +/// # std::fs::remove_file(&path)?; +/// # Ok::<(), Box>(()) +/// ``` +#[derive(Debug, Clone)] +pub struct JsonDocument { + path: PathBuf, + properties: Map, +} + +impl JsonDocument { + /// An empty document for `path`, which isn't touched until + /// [`JsonDocument::save`]. + pub fn new(path: impl Into) -> Self { + Self { + path: path.into(), + properties: Map::new(), + } + } + + /// Reads the document at `path`. + /// + /// Errors if the file isn't there ([`Error::Read`]), isn't valid + /// JSON ([`Error::Parse`]), or is valid JSON whose root isn't an + /// object and therefore has no properties + /// ([`Error::NotAnObject`]). Use [`JsonDocument::open_or_new`] when + /// a missing file just means there is nothing in it yet. + pub fn open(path: impl Into) -> Result { + let path = path.into(); + let text = read_text(&path)?; + + let value: Value = serde_json::from_str(&text).map_err(|source| Error::Parse { + path: path.clone(), + source, + })?; + + match value { + Value::Object(properties) => Ok(Self { path, properties }), + _ => Err(Error::NotAnObject { path }), + } + } + + /// Like [`JsonDocument::open`], but a file that isn't there yet + /// gives an empty document instead of an error. + /// + /// Only a missing file is forgiven: one that exists and is broken + /// still errors, rather than quietly starting over and overwriting + /// it on the next save. + pub fn open_or_new(path: impl Into) -> Result { + let path = path.into(); + + match Self::open(&path) { + Err(Error::Read { source, .. }) if source.kind() == std::io::ErrorKind::NotFound => { + Ok(Self::new(path)) + } + other => other, + } + } + + /// Sets `key`, replacing whatever was there. + /// + /// Takes anything serializable, so a property can be a number, a + /// string, a list or a whole struct. Returns `&mut Self` so several + /// can be chained: `doc.set("a", 1)?.set("b", 2)?;`. + pub fn set( + &mut self, + key: impl Into, + value: impl Serialize, + ) -> Result<&mut Self, Error> { + let value = serde_json::to_value(value).map_err(|source| Error::Serialize { + path: self.path.clone(), + source, + })?; + + self.properties.insert(key.into(), value); + Ok(self) + } + + /// Reads `key` as `T`, or `None` if the document has no such + /// property. + /// + /// Errors with [`Error::Parse`] if the property is there but isn't a + /// `T`. + pub fn get(&self, key: &str) -> Result, Error> + where + T: DeserializeOwned, + { + let Some(value) = self.properties.get(key) else { + return Ok(None); + }; + + serde_json::from_value(value.clone()) + .map(Some) + .map_err(|source| Error::Parse { + path: self.path.clone(), + source, + }) + } + + /// Whether the document has a `key` property. + pub fn contains(&self, key: &str) -> bool { + self.properties.contains_key(key) + } + + /// Removes `key`, reporting whether it was there. + pub fn remove(&mut self, key: &str) -> bool { + self.properties.remove(key).is_some() + } + + /// Every property, as they will be written. + pub fn properties(&self) -> &Map { + &self.properties + } + + /// The file this document is read from and saved to. + pub fn path(&self) -> &Path { + &self.path + } + + /// Writes the document back, replacing the file atomically. + pub fn save(&self) -> Result<(), Error> { + write_json(&self.path, &self.properties) + } +} + +/// Reads a whole file as text, naming it in the error. +fn read_text(path: &Path) -> Result { + fs::read_to_string(path).map_err(|source| Error::Read { + path: path.to_path_buf(), + source, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use serde::Serializer; + use std::collections::BTreeMap; + use std::fs; + + type TestResult = Result>; + + fn settings() -> BTreeMap { + BTreeMap::from([ + ("adj_commit".to_string(), "4f1c3b0".to_string()), + ("time_unit".to_string(), "us".to_string()), + ]) + } + + #[test] + fn writes_pretty_json_with_a_trailing_newline_creating_the_parents() -> TestResult { + let temp = tempfile::tempdir()?; + let path = temp.path().join("session/others/settings.json"); + + write_json(&path, &settings())?; + + assert_eq!( + fs::read_to_string(&path)?, + "{\n \"adj_commit\": \"4f1c3b0\",\n \"time_unit\": \"us\"\n}\n" + ); + Ok(()) + } + + #[test] + fn what_was_written_parses_back_to_the_same_value() -> TestResult { + let temp = tempfile::tempdir()?; + let path = temp.path().join("settings.json"); + + write_json(&path, &settings())?; + + let read: BTreeMap = serde_json::from_str(&fs::read_to_string(&path)?)?; + assert_eq!(read, settings()); + Ok(()) + } + + #[test] + fn writing_replaces_an_existing_file_rather_than_appending() -> TestResult { + let temp = tempfile::tempdir()?; + let path = temp.path().join("settings.json"); + + write_json(&path, &settings())?; + write_json(&path, &BTreeMap::from([("time_unit", "ms")]))?; + + assert_eq!( + fs::read_to_string(&path)?, + "{\n \"time_unit\": \"ms\"\n}\n" + ); + Ok(()) + } + + /// A value that fails halfway through being serialized, to check + /// what the destination looks like when that happens. + #[derive(Debug)] + struct Unserializable; + + impl Serialize for Unserializable { + fn serialize(&self, _serializer: S) -> Result { + Err(serde::ser::Error::custom("not today")) + } + } + + #[test] + fn a_successful_write_leaves_no_temporary_file_behind() -> TestResult { + let temp = tempfile::tempdir()?; + let path = temp.path().join("settings.json"); + + write_json(&path, &settings())?; + + assert!(path.exists()); + assert!(!temporary_path(&path).exists()); + Ok(()) + } + + #[test] + fn a_failed_write_leaves_the_previous_contents_untouched() -> TestResult { + let temp = tempfile::tempdir()?; + let path = temp.path().join("settings.json"); + write_json(&path, &settings())?; + let before = fs::read_to_string(&path)?; + + let Err(error) = write_json(&path, &Unserializable) else { + unreachable!("this value can't be serialized"); + }; + assert!(matches!(error, Error::Serialize { .. })); + + // The destination still holds the old document, whole, and the + // half-written one is gone rather than left next to it. + assert_eq!(fs::read_to_string(&path)?, before); + assert!(!temporary_path(&path).exists()); + Ok(()) + } + + #[test] + fn the_temporary_file_is_a_sibling_so_the_rename_stays_atomic() { + let path = Path::new("/var/log/session/settings.json"); + let temporary = temporary_path(path); + + assert_eq!(temporary.parent(), path.parent()); + assert_eq!(temporary.file_name(), Some("settings.json.tmp".as_ref())); + } + + #[test] + fn read_json_gets_back_what_write_json_put_there() -> TestResult { + let temp = tempfile::tempdir()?; + let path = temp.path().join("settings.json"); + write_json(&path, &settings())?; + + let read: BTreeMap = read_json(&path)?; + + assert_eq!(read, settings()); + Ok(()) + } + + #[test] + fn reading_names_the_file_when_it_is_missing_or_broken() -> TestResult { + let temp = tempfile::tempdir()?; + let missing = temp.path().join("not-there.json"); + let broken = temp.path().join("broken.json"); + fs::write(&broken, "{ not json")?; + + let Err(absent) = read_json::>(&missing) else { + unreachable!("that file was never written"); + }; + assert!(matches!(&absent, Error::Read { path, .. } if path == &missing)); + + let Err(malformed) = read_json::>(&broken) else { + unreachable!("that file is not valid JSON"); + }; + assert!(matches!(&malformed, Error::Parse { path, .. } if path == &broken)); + Ok(()) + } + + #[test] + fn a_document_takes_several_properties_and_reads_them_back() -> TestResult { + let temp = tempfile::tempdir()?; + let path = temp.path().join("session.json"); + + let mut session = JsonDocument::new(&path); + session + .set("adj_commit", "4f1c3b0")? + .set("time_unit", "us")? + .set("rows", 128_000u64)?; + session.save()?; + + let session = JsonDocument::open(&path)?; + assert_eq!( + session.get::("adj_commit")?.as_deref(), + Some("4f1c3b0") + ); + assert_eq!(session.get::("rows")?, Some(128_000)); + assert_eq!(session.get::("never_set")?, None); + assert!(session.contains("time_unit")); + Ok(()) + } + + #[test] + fn adding_properties_keeps_the_ones_already_in_the_file() -> TestResult { + let temp = tempfile::tempdir()?; + let path = temp.path().join("session.json"); + // A document with a property no type in this crate mentions. + fs::write(&path, "{\n \"written_by_someone_else\": [1, 2, 3]\n}\n")?; + + let mut session = JsonDocument::open(&path)?; + session.set("stopped", true)?; + session.save()?; + + let session = JsonDocument::open(&path)?; + assert_eq!( + session.get::>("written_by_someone_else")?, + Some(vec![1, 2, 3]) + ); + assert_eq!(session.get::("stopped")?, Some(true)); + Ok(()) + } + + #[test] + fn a_property_read_as_the_wrong_type_is_an_error_not_a_none() -> TestResult { + let path = Path::new("in-memory.json"); + let mut session = JsonDocument::new(path); + session.set("rows", "not a number")?; + + let Err(error) = session.get::("rows") else { + unreachable!("a string is not a u64"); + }; + + assert!(matches!(&error, Error::Parse { path: named, .. } if named == path)); + Ok(()) + } + + #[test] + fn removing_a_property_reports_whether_it_was_there() -> TestResult { + let mut session = JsonDocument::new("in-memory.json"); + session.set("time_unit", "us")?; + + assert!(session.remove("time_unit")); + assert!(!session.remove("time_unit")); + assert!(session.properties().is_empty()); + Ok(()) + } + + #[test] + fn open_or_new_forgives_a_missing_file_but_not_a_broken_one() -> TestResult { + let temp = tempfile::tempdir()?; + let missing = temp.path().join("session.json"); + let broken = temp.path().join("broken.json"); + fs::write(&broken, "{ not json")?; + + let mut session = JsonDocument::open_or_new(&missing)?; + assert!(session.properties().is_empty()); + session.set("time_unit", "us")?; + session.save()?; + assert!(missing.exists()); + + assert!(matches!( + JsonDocument::open_or_new(&broken), + Err(Error::Parse { .. }) + )); + Ok(()) + } + + #[test] + fn a_document_whose_root_is_not_an_object_has_no_properties_to_add_to() -> TestResult { + let temp = tempfile::tempdir()?; + let path = temp.path().join("list.json"); + fs::write(&path, "[1, 2, 3]\n")?; + + let Err(error) = JsonDocument::open(&path) else { + unreachable!("the root of that document is an array"); + }; + + assert!(matches!(&error, Error::NotAnObject { path: named } if named == &path)); + Ok(()) + } + + #[test] + fn a_path_whose_parent_is_a_file_reports_which_file_it_was() -> TestResult { + let temp = tempfile::tempdir()?; + let blocking = temp.path().join("settings.json"); + write_json(&blocking, &settings())?; + + let path = blocking.join("nested.json"); + let Err(error) = write_json(&path, &settings()) else { + unreachable!("a file can't be used as a directory"); + }; + + assert!(matches!(&error, Error::Create { path: failed, .. } if failed == &path)); + Ok(()) + } +} From b980a3b117d0c1d9950103028112c2223326a8dc Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Tue, 10 Nov 2026 20:54:56 +0100 Subject: [PATCH 105/225] feat(backend, logger): more info --- backend/Cargo.lock | 79 ++- backend/crates/core/Cargo.toml | 23 + backend/crates/core/src/lib.rs | 11 +- backend/crates/core/src/logger.rs | 24 +- backend/crates/core/src/logger/csv.rs | 110 +++- backend/crates/core/src/logger/files.rs | 366 +++++++++++++ backend/crates/core/src/logger/files/error.rs | 66 +++ backend/crates/core/src/logger/host.rs | 480 ++++++++++++++++++ backend/crates/core/src/logger/target.rs | 78 ++- backend/crates/core/src/logger/text.rs | 54 +- 10 files changed, 1283 insertions(+), 8 deletions(-) create mode 100644 backend/crates/core/src/logger/files.rs create mode 100644 backend/crates/core/src/logger/files/error.rs create mode 100644 backend/crates/core/src/logger/host.rs diff --git a/backend/Cargo.lock b/backend/Cargo.lock index 3d6daa45d..3a3943da1 100644 --- a/backend/Cargo.lock +++ b/backend/Cargo.lock @@ -558,7 +558,7 @@ dependencies = [ "cfg-if", "js-sys", "libc", - "wasi", + "wasi 0.11.1+wasi-snapshot-preview1", "wasm-bindgen", ] @@ -2074,7 +2074,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee" dependencies = [ "libc", - "wasi", + "wasi 0.11.1+wasi-snapshot-preview1", "windows-sys 0.61.2", ] @@ -2126,6 +2126,24 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" +[[package]] +name = "objc2-core-foundation" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536" +dependencies = [ + "bitflags 2.13.2", +] + +[[package]] +name = "objc2-system-configuration" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7216bd11cbda54ccabcab84d523dc93b858ec75ecfb3a7d89513fa22464da396" +dependencies = [ + "objc2-core-foundation", +] + [[package]] name = "once_cell" version = "1.21.4" @@ -2435,6 +2453,15 @@ dependencies = [ "windows-sys 0.52.0", ] +[[package]] +name = "rlimit" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f35ee2729c56bb610f6dba436bf78135f728b7373bdffae2ec815b2d3eb98cc3" +dependencies = [ + "libc", +] + [[package]] name = "rustc-hash" version = "2.1.3" @@ -2751,6 +2778,7 @@ dependencies = [ "dirs", "gix", "ntp_usg-server", + "rlimit", "serde", "serde_json", "tempfile", @@ -2759,6 +2787,7 @@ dependencies = [ "tracing", "tracing-appender", "tracing-subscriber", + "whoami", ] [[package]] @@ -3248,6 +3277,33 @@ version = "0.11.1+wasi-snapshot-preview1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" +[[package]] +name = "wasi" +version = "0.14.7+wasi-0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "883478de20367e224c0090af9cf5f9fa85bed63a95c1abf3afc5c083ebc06e8c" +dependencies = [ + "wasip2", +] + +[[package]] +name = "wasip2" +version = "1.0.4+wasi-0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "wasite" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "66fe902b4a6b8028a753d5424909b764ccf79b7a209eac9bf97e59cda9f71a42" +dependencies = [ + "wasi 0.14.7+wasi-0.2.4", +] + [[package]] name = "wasm-bindgen" version = "0.2.129" @@ -3333,6 +3389,19 @@ dependencies = [ "rustls-pki-types", ] +[[package]] +name = "whoami" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "626c4bac6755d76ffc12cb01b2eac751db1996b9e0041de9aa02c8c211ddc82c" +dependencies = [ + "libc", + "libredox", + "objc2-system-configuration", + "wasite", + "web-sys", +] + [[package]] name = "winapi" version = "0.3.9" @@ -3464,6 +3533,12 @@ version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81" +[[package]] +name = "wit-bindgen" +version = "0.57.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" + [[package]] name = "writeable" version = "0.6.4" diff --git a/backend/crates/core/Cargo.toml b/backend/crates/core/Cargo.toml index 83985c825..4d78f7050 100644 --- a/backend/crates/core/Cargo.toml +++ b/backend/crates/core/Cargo.toml @@ -20,6 +20,15 @@ git = ["dep:tempfile", "dep:dirs", "dep:gix"] pcap = ["net"] # CSV data logger (records, sessions, subloggers) logger = [] +# `logger::files`: copying, moving and removing files. No dependencies +# of its own: a tool that only wants to copy a file shouldn't have to +# take anything else with it, beyond the `logger` module it lives in. +files = ["logger"] +# `logger::host`: a snapshot of the machine, the user and the build, for +# the metadata of a recording. `rlimit` is only a dependency on unix, so +# on Windows this enables `whoami` alone and `logger::host::open_file_limit` +# reports nothing. +host = ["logger", "dep:whoami", "dep:rlimit"] # Reusable tracing/diagnostics setup (console + non-blocking file + stderr layers) trace = ["dep:tracing-subscriber", "dep:tracing-appender"] @@ -36,6 +45,20 @@ gix = { version = "0.87.1", optional = true, features = ["blocking-http-transpor dirs = { version = "7.0.0", optional = true } tempfile = { version = "3.27", optional = true } ntp_usg-server = { version = "5.0.0", optional = true, features = ["ipv4", "tokio"] } +# User, machine and OS metadata. Every call returns a `Result`, which is +# what makes a best-effort snapshot cheap to build. +whoami = { version = "2.1.3", optional = true } + +# `getrlimit` has no meaning on Windows, so the dependency isn't there +# either; `logger::host::open_file_limit` is `None` on that target. +[target.'cfg(unix)'.dependencies] +rlimit = { version = "0.11.0", optional = true } + +# The `logger` and `files` tests need a real directory to write into; +# `tempfile` is also an optional dependency of the `git` feature, which is +# why it shows up twice. +[dev-dependencies] +tempfile = "3.27" # `workspace = true` can't be combined with extra lints in the same table, # so the workspace list is repeated here with `missing_docs` added: this is diff --git a/backend/crates/core/src/lib.rs b/backend/crates/core/src/lib.rs index fdf802844..697257960 100644 --- a/backend/crates/core/src/lib.rs +++ b/backend/crates/core/src/lib.rs @@ -4,7 +4,7 @@ pub mod hello_world; /// # Git module /// Handles updates and changes within the ADJ. -/// Checks the ADJ Github repository and +/// Checks the ADJ Github repository and #[cfg(feature = "git")] pub mod git; @@ -25,3 +25,12 @@ pub mod adj; /// [`adj`] declares as the schema. See [`protocol::wire`], /// [`protocol::tcp`], [`protocol::udp`]. pub mod protocol; + +/// Everything a recording needs on disk: writing CSV, text and JSON +/// files without knowing what is in them ([`logger::CsvFile`]), moving +/// those files around ([`logger::files`], feature `files`) and the +/// snapshot of the machine that produced them ([`logger::host`], +/// feature `host`). The policy — which files a recording has, what goes +/// in each row — belongs to whoever calls this. +#[cfg(feature = "logger")] +pub mod logger; diff --git a/backend/crates/core/src/logger.rs b/backend/crates/core/src/logger.rs index 24ec6452f..6d2146c27 100644 --- a/backend/crates/core/src/logger.rs +++ b/backend/crates/core/src/logger.rs @@ -69,8 +69,18 @@ //! first. A CSV or a text log is appended to and never revisited, and //! nothing here will read one back. //! +//! Two neighbours live alongside the three formats, each behind its own +//! feature because neither is needed to write a file: +//! [`crate::logger::files`] (feature `files`) copies, moves and removes +//! them, which is what makes these types usable on a file that already +//! exists, and [`crate::logger::host`] (feature `host`) is the snapshot +//! of the machine that goes into a recording's metadata. Both are about +//! a recording's files rather than about a vehicle, which is why they +//! are here and not modules of their own; neither is used by `csv`, +//! `text` or `json`, which still know nothing about what they write. +//! //! Not here, on purpose: reading a CSV or a text log back, sessions, timestamps, file -//! rotation, copying files around, keeping a registry of many open files +//! rotation, keeping a registry of many open files //! (a `HashMap` with `entry().or_insert_with(...)` in the //! caller is shorter and clearer than anything this module could wrap it //! in), and anything asynchronous. These functions block; a caller @@ -83,6 +93,18 @@ mod json; mod target; mod text; +/// Copies, moves and removes files, creating the directories a +/// destination needs and naming the file in every error. See +/// [`files::copy_file`]. +#[cfg(feature = "files")] +pub mod files; + +/// A best-effort snapshot of the machine, the user and the build, for +/// the metadata of a recording. Nothing in it fails: what the system +/// won't say is left empty. See [`host::HostInfo`]. +#[cfg(feature = "host")] +pub mod host; + pub use csv::{CsvFile, Row}; pub use error::Error; pub use json::{JsonDocument, read_json, write_json}; diff --git a/backend/crates/core/src/logger/csv.rs b/backend/crates/core/src/logger/csv.rs index 243f55456..8c2fbd723 100644 --- a/backend/crates/core/src/logger/csv.rs +++ b/backend/crates/core/src/logger/csv.rs @@ -1,7 +1,7 @@ //! A CSV file that knows its own header. use super::Error; -use super::target::{Target, create_file}; +use super::target::{Target, append_file, create_file}; use std::fmt; use std::fs::File; use std::io::{BufWriter, Write}; @@ -77,6 +77,47 @@ impl CsvFile> { debug!(path = %path.display(), fields = header.len(), "csv file created"); Ok(file) } + + /// Opens the file at `path` to add rows to the end of it, creating it + /// and its parent directories if they aren't there. + /// + /// `header` is written only when the file is empty or brand new. + /// Otherwise it is taken as a statement of how many fields a row has — + /// what [`Error::FieldCount`] is checked against — and **what the file + /// already contains is not looked at**: if its columns are not these + /// ones, both shapes end up in the same file and nothing says so. The + /// caller is the one who knows that the file it opens is the file it + /// thinks it is; copying one with [`CsvFile::create`]'s own header is + /// the way to be sure. + /// + /// The one thing that *is* checked is the line boundary: if the + /// existing content doesn't end in a newline, one is written first, so + /// the first new row can't be glued onto a half-finished line. + pub fn append(path: impl AsRef, header: &[&str]) -> Result { + let path = path.as_ref(); + let (writer, existing) = append_file(path)?; + + let file = if existing == 0 { + Self::new(writer, path.display().to_string(), header)? + } else { + Self { + target: Target::new(writer, path.display().to_string()), + // No header line to write, so the count is taken from the + // argument instead of from what was just written. An empty + // header leaves rows unchecked, as in `new`. + fields: (!header.is_empty()).then_some(header.len()), + buf: Vec::new(), + } + }; + + debug!( + path = %path.display(), + existing_bytes = existing, + fields = header.len(), + "csv file opened to append" + ); + Ok(file) + } } impl CsvFile { @@ -362,6 +403,73 @@ mod tests { } } + #[test] + fn appending_continues_a_file_without_writing_the_header_again() -> TestResult { + let temp = tempfile::tempdir()?; + let path = temp.path().join("data/lcu.csv"); + + let mut csv = CsvFile::create(&path, &["t", "value"])?; + csv.row().int(1).num(1.5).end()?; + csv.close()?; + + let mut csv = CsvFile::append(&path, &["t", "value"])?; + csv.row().int(2).num(2.5).end()?; + csv.close()?; + + assert_eq!(fs::read_to_string(&path)?, "t,value\n1,1.5\n2,2.5\n"); + Ok(()) + } + + #[test] + fn appending_to_a_file_that_is_not_there_yet_writes_the_header() -> TestResult { + let temp = tempfile::tempdir()?; + let path = temp.path().join("data/lcu.csv"); + + let mut csv = CsvFile::append(&path, &["t", "value"])?; + csv.row().int(1).num(1.5).end()?; + csv.close()?; + + assert_eq!(fs::read_to_string(&path)?, "t,value\n1,1.5\n"); + Ok(()) + } + + #[test] + fn appending_to_content_that_lacks_its_last_newline_starts_a_fresh_line() -> TestResult { + let temp = tempfile::tempdir()?; + let path = temp.path().join("copied.csv"); + // What a file copied from elsewhere can easily look like. + fs::write(&path, "t,value\n1,1.5")?; + + let mut csv = CsvFile::append(&path, &["t", "value"])?; + csv.row().int(2).num(2.5).end()?; + csv.close()?; + + assert_eq!(fs::read_to_string(&path)?, "t,value\n1,1.5\n2,2.5\n"); + Ok(()) + } + + #[test] + fn an_appended_row_is_still_checked_against_the_header_it_was_given() -> TestResult { + let temp = tempfile::tempdir()?; + let path = temp.path().join("data.csv"); + fs::write(&path, "t,value\n")?; + + let mut csv = CsvFile::append(&path, &["t", "value"])?; + let Err(error) = csv.row().int(1).num(1.5).text("extra").end() else { + unreachable!("three fields where the header says two"); + }; + + assert!(matches!( + error, + Error::FieldCount { + expected: 2, + got: 3, + .. + } + )); + Ok(()) + } + #[test] fn the_header_is_the_files_first_line() -> TestResult { let csv = in_memory(&["t", "value"])?; diff --git a/backend/crates/core/src/logger/files.rs b/backend/crates/core/src/logger/files.rs new file mode 100644 index 000000000..af15e325e --- /dev/null +++ b/backend/crates/core/src/logger/files.rs @@ -0,0 +1,366 @@ +//! Copying, moving and removing files. +//! +//! Plain [`std::fs`] with two things added, which is all this is for: +//! the destination's parent directories get created instead of the +//! operation failing, and every error names the file — both files, for +//! the operations that have two — which is what makes it actionable by +//! the time it has travelled up to whoever decides what to do about it. +//! +//! No dependencies, on purpose: a tool that wants to copy a file +//! shouldn't have to take anything else with it. +//! +//! Copying is also what makes the types in [`crate::logger`] usable on a +//! file that already exists: copy it, then open the copy and carry on +//! writing to it. +//! +//! ```no_run +//! use software_core::logger::files; +//! use software_core::logger::{CsvFile, JsonDocument}; +//! +//! // A recording that starts from the previous session's layout. +//! files::copy_file("sessions/12/session.json", "sessions/13/session.json")?; +//! +//! let mut session = JsonDocument::open("sessions/13/session.json")?; +//! session.set("started", true)?; +//! session.save()?; +//! +//! // And a CSV that is continued rather than started over. +//! files::copy_file("sessions/12/data/speed.csv", "sessions/13/data/speed.csv")?; +//! let mut speed = CsvFile::append("sessions/13/data/speed.csv", &["t_us", "value"])?; +//! speed.row().int(1_024).num(37.5).end()?; +//! speed.close()?; +//! # Ok::<(), Box>(()) +//! ``` +//! +//! Not wrapped: asking whether a file is there. That is +//! [`std::path::Path::exists`], and a wrapper around it would only add a +//! name to learn. +//! +//! Not here at all: anything that walks a tree looking for something, +//! rotation, quotas, watching for changes, and anything asynchronous. A +//! recording copies a handful of files at the start and at the end; when +//! that stops being true, whatever needs more can say so then. + +mod error; + +pub use error::Error; + +use std::fs; +use std::path::Path; +use tracing::debug; + +/// Copies `from` over `to`, creating `to`'s parent directories, and +/// returns how many bytes were copied. +/// +/// An existing `to` is replaced. The copy is not atomic: an interrupted +/// copy leaves a partial file behind, so a reader that could see the +/// destination mid-copy should be given a finished file under a +/// different name and then [`move_file`]d into place. +/// +/// # Example +/// +/// ```no_run +/// use software_core::logger::files; +/// +/// let bytes = files::copy_file("settings.json", "backup/settings.json")?; +/// # Ok::<(), software_core::logger::files::Error>(()) +/// ``` +pub fn copy_file(from: impl AsRef, to: impl AsRef) -> Result { + let (from, to) = (from.as_ref(), to.as_ref()); + create_parents(to)?; + + let bytes = fs::copy(from, to).map_err(|source| Error::Copy { + from: from.to_path_buf(), + to: to.to_path_buf(), + source, + })?; + + debug!(from = %from.display(), to = %to.display(), bytes, "file copied"); + Ok(bytes) +} + +/// Copies everything under `from` into `to`, recursively, and returns +/// how many files were copied. +/// +/// Directories are recreated as needed; existing files in `to` are +/// replaced. A symbolic link is followed and its target copied as a +/// plain file, so the result is a directory of real files rather than a +/// tree of links pointing back at the original. +pub fn copy_dir(from: impl AsRef, to: impl AsRef) -> Result { + let (from, to) = (from.as_ref(), to.as_ref()); + let copied = copy_dir_inner(from, to)?; + + debug!(from = %from.display(), to = %to.display(), files = copied, "directory copied"); + Ok(copied) +} + +/// The recursive half of [`copy_dir`], without the event per level. +fn copy_dir_inner(from: &Path, to: &Path) -> Result { + fs::create_dir_all(to).map_err(|source| Error::CreateDir { + path: to.to_path_buf(), + source, + })?; + + let entries = fs::read_dir(from).map_err(|source| Error::Read { + path: from.to_path_buf(), + source, + })?; + + let mut copied = 0; + for entry in entries { + let entry = entry.map_err(|source| Error::Read { + path: from.to_path_buf(), + source, + })?; + + let source_path = entry.path(); + let destination = to.join(entry.file_name()); + + // `file_type` is the entry's own kind, so a link to a directory + // is not a directory here; `metadata` below follows it. + let kind = entry.file_type().map_err(|source| Error::Read { + path: source_path.clone(), + source, + })?; + + let is_dir = if kind.is_symlink() { + fs::metadata(&source_path) + .map_err(|source| Error::Read { + path: source_path.clone(), + source, + })? + .is_dir() + } else { + kind.is_dir() + }; + + if is_dir { + copied += copy_dir_inner(&source_path, &destination)?; + } else { + fs::copy(&source_path, &destination).map_err(|source| Error::Copy { + from: source_path.clone(), + to: destination.clone(), + source, + })?; + copied += 1; + } + } + + Ok(copied) +} + +/// Moves `from` to `to`, creating `to`'s parent directories. +/// +/// A rename when both paths are on the same filesystem, which is atomic +/// and costs nothing whatever the file's size. When they are not — a log +/// directory on a USB stick, say — a rename can't be done at all, so the +/// file is copied and the original removed, which is neither atomic nor +/// free. +pub fn move_file(from: impl AsRef, to: impl AsRef) -> Result<(), Error> { + let (from, to) = (from.as_ref(), to.as_ref()); + create_parents(to)?; + + match fs::rename(from, to) { + Ok(()) => { + debug!(from = %from.display(), to = %to.display(), "file moved"); + Ok(()) + } + Err(source) if source.kind() == std::io::ErrorKind::CrossesDevices => { + copy_file(from, to)?; + remove_file(from)?; + debug!( + from = %from.display(), + to = %to.display(), + "file moved across filesystems by copying" + ); + Ok(()) + } + Err(source) => Err(Error::Move { + from: from.to_path_buf(), + to: to.to_path_buf(), + source, + }), + } +} + +/// Removes the file at `path`. +/// +/// A file that isn't there is an error, like it is in [`std::fs`]: the +/// caller is the one who knows whether that was expected. +pub fn remove_file(path: impl AsRef) -> Result<(), Error> { + let path = path.as_ref(); + + fs::remove_file(path).map_err(|source| Error::Remove { + path: path.to_path_buf(), + source, + })?; + + debug!(path = %path.display(), "file removed"); + Ok(()) +} + +/// How many bytes the file at `path` holds. +pub fn size(path: impl AsRef) -> Result { + let path = path.as_ref(); + + let metadata = fs::metadata(path).map_err(|source| Error::Read { + path: path.to_path_buf(), + source, + })?; + + Ok(metadata.len()) +} + +/// Creates the directories a file is going to live in. +fn create_parents(path: &Path) -> Result<(), Error> { + let Some(parent) = path.parent() else { + return Ok(()); + }; + + // An empty parent is what `Path::parent` gives for a bare file name: + // the current directory, which already exists. + if parent.as_os_str().is_empty() { + return Ok(()); + } + + fs::create_dir_all(parent).map_err(|source| Error::CreateDir { + path: parent.to_path_buf(), + source, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + type TestResult = Result>; + + #[test] + fn copying_creates_the_directories_the_destination_needs() -> TestResult { + let temp = tempfile::tempdir()?; + let from = temp.path().join("settings.json"); + let to = temp.path().join("backup/2026/settings.json"); + fs::write(&from, "{}\n")?; + + let bytes = copy_file(&from, &to)?; + + assert_eq!(bytes, 3); + assert_eq!(fs::read_to_string(&to)?, "{}\n"); + Ok(()) + } + + #[test] + fn copying_over_an_existing_file_replaces_it() -> TestResult { + let temp = tempfile::tempdir()?; + let from = temp.path().join("new.csv"); + let to = temp.path().join("old.csv"); + fs::write(&from, "new\n")?; + fs::write(&to, "a much longer old file\n")?; + + copy_file(&from, &to)?; + + assert_eq!(fs::read_to_string(&to)?, "new\n"); + Ok(()) + } + + #[test] + fn a_failed_copy_names_both_paths() -> TestResult { + let temp = tempfile::tempdir()?; + let from = temp.path().join("missing.csv"); + let to = temp.path().join("copy.csv"); + + let Err(error) = copy_file(&from, &to) else { + unreachable!("the source was never written"); + }; + + let Error::Copy { + from: named_from, + to: named_to, + .. + } = &error + else { + unreachable!("a failed copy is an Error::Copy, got {error:?}"); + }; + assert_eq!(named_from, &from); + assert_eq!(named_to, &to); + Ok(()) + } + + #[test] + fn copying_a_directory_walks_into_its_subdirectories() -> TestResult { + let temp = tempfile::tempdir()?; + let from = temp.path().join("session"); + let to = temp.path().join("copy"); + fs::create_dir_all(from.join("data/lcu"))?; + fs::write(from.join("session.json"), "{}\n")?; + fs::write(from.join("data/lcu/speed.csv"), "t,value\n")?; + fs::write(from.join("data/lcu/current.csv"), "t,value\n")?; + + let copied = copy_dir(&from, &to)?; + + assert_eq!(copied, 3); + assert_eq!(fs::read_to_string(to.join("session.json"))?, "{}\n"); + assert_eq!( + fs::read_to_string(to.join("data/lcu/speed.csv"))?, + "t,value\n" + ); + Ok(()) + } + + #[test] + fn copying_a_directory_that_is_not_there_names_it() -> TestResult { + let temp = tempfile::tempdir()?; + let from = temp.path().join("not-a-session"); + + let Err(error) = copy_dir(&from, temp.path().join("copy")) else { + unreachable!("that directory was never created"); + }; + + assert!(matches!(&error, Error::Read { path, .. } if path == &from)); + Ok(()) + } + + #[test] + fn moving_leaves_nothing_behind() -> TestResult { + let temp = tempfile::tempdir()?; + let from = temp.path().join("session.json"); + let to = temp.path().join("done/session.json"); + fs::write(&from, "{}\n")?; + + move_file(&from, &to)?; + + assert!(!from.exists()); + assert_eq!(fs::read_to_string(&to)?, "{}\n"); + Ok(()) + } + + #[test] + fn size_and_remove_report_which_file_was_missing() -> TestResult { + let temp = tempfile::tempdir()?; + let path = temp.path().join("data.csv"); + fs::write(&path, "t,value\n")?; + + assert_eq!(size(&path)?, 8); + remove_file(&path)?; + + let Err(error) = size(&path) else { + unreachable!("the file was just removed"); + }; + assert!(matches!(&error, Error::Read { path: named, .. } if named == &path)); + + let Err(error) = remove_file(&path) else { + unreachable!("the file was just removed"); + }; + assert!(matches!(&error, Error::Remove { path: named, .. } if named == &path)); + Ok(()) + } + + #[test] + fn a_bare_file_name_has_no_directory_to_create() -> TestResult { + // `Path::parent` of a bare name is an empty path, which must not + // reach `create_dir_all` — it would fail, and the directory the + // file is going into (the current one) is already there. + create_parents(Path::new("bare.txt"))?; + Ok(()) + } +} diff --git a/backend/crates/core/src/logger/files/error.rs b/backend/crates/core/src/logger/files/error.rs new file mode 100644 index 000000000..bf3bfeb41 --- /dev/null +++ b/backend/crates/core/src/logger/files/error.rs @@ -0,0 +1,66 @@ +//! Errors produced by the operations in [`crate::logger::files`]. +//! +//! Every variant names the file it happened on, and the two that work on +//! a pair of paths name **both**: "couldn't copy" without saying where to +//! leaves the caller with nothing to act on, and the destination is the +//! half that is usually wrong. + +use std::path::PathBuf; + +/// An error working with a file. +#[derive(Debug, thiserror::Error)] +pub enum Error { + /// Couldn't copy the file. + #[error("couldn't copy {from:?} to {to:?}")] + Copy { + /// The file being copied. + from: PathBuf, + /// Where it was being copied to. + to: PathBuf, + /// The underlying I/O error. + #[source] + source: std::io::Error, + }, + + /// Couldn't move the file. + #[error("couldn't move {from:?} to {to:?}")] + Move { + /// The file being moved. + from: PathBuf, + /// Where it was being moved to. + to: PathBuf, + /// The underlying I/O error. + #[source] + source: std::io::Error, + }, + + /// Couldn't create a directory. + #[error("couldn't create the directory {path:?}")] + CreateDir { + /// The directory that couldn't be created. + path: PathBuf, + /// The underlying I/O error. + #[source] + source: std::io::Error, + }, + + /// Couldn't read the file, the directory, or their metadata. + #[error("couldn't read {path:?}")] + Read { + /// The file or directory that couldn't be read. + path: PathBuf, + /// The underlying I/O error. + #[source] + source: std::io::Error, + }, + + /// Couldn't remove the file. + #[error("couldn't remove {path:?}")] + Remove { + /// The file that couldn't be removed. + path: PathBuf, + /// The underlying I/O error. + #[source] + source: std::io::Error, + }, +} diff --git a/backend/crates/core/src/logger/host.rs b/backend/crates/core/src/logger/host.rs new file mode 100644 index 000000000..68ffac93e --- /dev/null +++ b/backend/crates/core/src/logger/host.rs @@ -0,0 +1,480 @@ +//! What the operating system will say about who is running this and +//! where. +//! +//! Part of [`crate::logger`] because it is part of a recording, but +//! not of how one is written: this is the *content* of a recording's +//! metadata, not a way of putting bytes on a disk. Nothing in +//! `logger`'s three formats — nor in [`crate::logger::files`] — uses +//! this module; they still write files without knowing what is in them, +//! and that is worth keeping. +//! +//! One snapshot, [`crate::logger::host::HostInfo::collect`], meant to be written into a +//! recording's metadata so that months later it is still possible to +//! answer *which machine produced this, running which build, and with +//! whose clock and locale*. Every field is optional and nothing here +//! returns a [`Result`]: what the system won't say is simply absent, +//! because a recording must never fail to start over a missing user +//! name. +//! +//! What is deliberately not here: free disk space and memory (another +//! dependency, and the disk is better checked by whoever is about to +//! fill it), the battery, and the network interfaces the backend bound +//! to — that last one belongs to whatever opened the sockets, which is +//! the only thing that actually knows. + +use serde::Serialize; +use std::env; +use std::path::PathBuf; +use std::time::{SystemTime, UNIX_EPOCH}; +use tracing::debug; + +/// Who and what produced a recording. +/// +/// Built with [`HostInfo::collect`] and serialized straight into a +/// metadata file. It is a *snapshot*: the values are read once, when it +/// is built, and never refreshed. +/// +/// Serialize-only on purpose. Reading one back is reading JSON, not +/// rebuilding this struct, and a field like [`HostInfo::os`] is a +/// compile-time constant of the build that wrote it rather than +/// something to parse. +#[derive(Debug, Clone, Serialize)] +pub struct HostInfo { + /// The login name (`javier`), from the operating system. + #[serde(skip_serializing_if = "Option::is_none")] + pub user: Option, + + /// The user's full name as the operating system knows it + /// (`Javier Ribal del Río`), which is not the login name. + #[serde(skip_serializing_if = "Option::is_none")] + pub real_name: Option, + + /// `user.name` from the global git configuration. + #[serde(skip_serializing_if = "Option::is_none")] + pub git_name: Option, + + /// An email address for whoever is running this. See + /// [`HostInfo::collect`] for where it is looked for, and why no + /// operating system is one of the places. + #[serde(skip_serializing_if = "Option::is_none")] + pub email: Option, + + /// The machine's name: the one a person would recognize if the + /// system has one, and its network hostname otherwise. + #[serde(skip_serializing_if = "Option::is_none")] + pub host: Option, + + /// The operating system this was built for: `linux`, `macos`, + /// `windows`. + pub os: &'static str, + + /// The processor architecture this was built for: `x86_64`, + /// `aarch64`. + pub arch: &'static str, + + /// The operating system's own name for itself, with its version: + /// `Fedora Linux 44`, `macOS 15.1`, `Windows 11`. + #[serde(skip_serializing_if = "Option::is_none")] + pub distro: Option, + + /// How many threads the machine can actually run at once. + #[serde(skip_serializing_if = "Option::is_none")] + pub cpus: Option, + + /// The version of `software-core` that wrote this. The version of + /// the *binary* is the binary's own to add: this crate can only see + /// its own. + pub core_version: &'static str, + + /// Whether this was built without optimizations and with debug + /// assertions on, which is worth knowing before reading anything + /// into the timings of a recording. + pub debug_build: bool, + + /// The process id, for pairing a recording with whatever else was + /// logging at the time. + pub pid: u32, + + /// The binary that is running, which says which build this was far + /// more precisely than a version number does. + #[serde(skip_serializing_if = "Option::is_none")] + pub exe: Option, + + /// The arguments it was started with, without the program name + /// (which is [`HostInfo::exe`]). Usually this is where the + /// configuration file is named. + pub args: Vec, + + /// The directory it was started from, which is what any relative + /// path in those arguments was resolved against. + #[serde(skip_serializing_if = "Option::is_none")] + pub working_dir: Option, + + /// The time zone the machine is in, as a name like `Europe/Madrid`. + /// + /// Worth more here than it looks: protections and messages carry a + /// time of day and no date or zone, so without knowing the zone of + /// the machine that recorded them they can't be placed on a real + /// timeline, or lined up against video or another machine's log. + #[serde(skip_serializing_if = "Option::is_none")] + pub timezone: Option, + + /// The locale, which decides how dates and numbers get formatted by + /// anything that reads this with the system's settings. + #[serde(skip_serializing_if = "Option::is_none")] + pub locale: Option, + + /// When the snapshot was taken, in seconds since the Unix epoch. + #[serde(skip_serializing_if = "Option::is_none")] + pub started_at_unix: Option, + + /// How many files this process is allowed to have open at once. See + /// [`open_file_limit`], which is the reason this field exists. + #[serde(skip_serializing_if = "Option::is_none")] + pub open_file_limit: Option, +} + +impl HostInfo { + /// Reads everything the system will say, right now. + /// + /// Never fails and never panics: each field is attempted on its own + /// and left empty if it can't be read. + /// + /// The email is looked for in four places, in this order: `user.email` + /// in the global git configuration, then `$GIT_AUTHOR_EMAIL`, then + /// `$EMAIL`, then the account name if it happens to look like an + /// address. **No operating system exposes an email address + /// portably** — macOS keeps one in Contacts and Windows only knows + /// one on a domain-joined machine — so git's own identity is used + /// instead, which is both reliable on a developer's machine and the + /// identity the person is already known by. The git configuration is + /// only read with the `git` feature on; without it, the environment + /// variables are all that is left. + /// + /// # Example + /// + /// ``` + /// use software_core::logger::host::HostInfo; + /// + /// let host = HostInfo::collect(); + /// println!("{}", serde_json::to_string_pretty(&host)?); + /// # Ok::<(), serde_json::Error>(()) + /// ``` + pub fn collect() -> Self { + let git = git_identity(); + + let info = Self { + user: whoami::username().ok(), + real_name: whoami::realname().ok(), + git_name: git.name, + email: git + .email + .or_else(|| var("GIT_AUTHOR_EMAIL")) + .or_else(|| var("EMAIL")) + .or_else(account_email), + host: device_name(), + os: env::consts::OS, + arch: env::consts::ARCH, + distro: whoami::distro().ok(), + cpus: std::thread::available_parallelism().ok().map(Into::into), + core_version: env!("CARGO_PKG_VERSION"), + debug_build: cfg!(debug_assertions), + pid: std::process::id(), + exe: env::current_exe().ok(), + // `args_os`, not `args`: the latter panics on an argument + // that isn't valid Unicode, and nothing in here is allowed + // to bring the process down. + args: env::args_os() + .skip(1) + .map(|arg| arg.to_string_lossy().into_owned()) + .collect(), + working_dir: env::current_dir().ok(), + timezone: timezone(), + locale: locale(), + started_at_unix: unix_seconds(), + open_file_limit: open_file_limit(), + }; + + debug!( + user = ?info.user, + host = ?info.host, + os = info.os, + open_file_limit = ?info.open_file_limit, + "host snapshot taken" + ); + info + } + + /// The same snapshot with everything that identifies a person + /// removed: the user name, the real name, the git name, the email + /// and the machine's name. + /// + /// For when a recording is going to be shared outside the team and + /// only the machine and the build matter. + pub fn without_identity(mut self) -> Self { + self.user = None; + self.real_name = None; + self.git_name = None; + self.email = None; + self.host = None; + self + } +} + +/// The soft limit on how many files this process may have open at once. +/// +/// Worth checking before opening a file per measurement: the default on +/// macOS is **256**, and on Linux usually 1024. Past it, opening a file +/// starts failing in the middle of a recording, which looks like a disk +/// problem and isn't one. +/// +/// `None` on Windows, honestly rather than as a failure: it has no +/// equivalent limit for the handles Rust's [`std::fs::File`] uses. +#[cfg(unix)] +pub fn open_file_limit() -> Option { + rlimit::getrlimit(rlimit::Resource::NOFILE) + .ok() + .map(|(soft, _hard)| soft) +} + +/// The soft limit on how many files this process may have open at once, +/// which Windows does not define for the handles [`std::fs::File`] uses. +#[cfg(not(unix))] +pub fn open_file_limit() -> Option { + None +} + +/// The machine's name. +/// +/// The pretty name first — what a desktop shows, from +/// `/etc/machine-info` on Linux and the sharing name on macOS and +/// Windows — and the network hostname when there isn't one, which on a +/// plain Linux install is the usual case. +fn device_name() -> Option { + whoami::devicename().or_else(|_| whoami::hostname()).ok() +} + +/// The time zone the machine is in, as a zone name. +/// +/// `$TZ` when it is set, which on Linux it usually isn't: the system zone +/// lives in `/etc/localtime`, a link into the zone database whose target +/// ends in the name (`/usr/share/zoneinfo/Europe/Madrid`). Reading the +/// link is how every other tool finds it. Windows keeps its zones under +/// different names entirely and isn't read here, so there it comes down +/// to `$TZ`. +/// +/// A *name* and not an offset on purpose: the offset depends on the date, +/// and the recording this ends up next to may well straddle the day +/// summer time changes. +fn timezone() -> Option { + if let Some(from_environment) = var("TZ") { + return Some(from_environment); + } + + let target = std::fs::read_link("/etc/localtime").ok()?; + + zone_from_link(&target.to_string_lossy()) +} + +/// The zone name at the end of a link into the zone database, or `None` +/// if the target doesn't look like one. +fn zone_from_link(target: &str) -> Option { + let (_, zone) = target.rsplit_once("zoneinfo/")?; + + (!zone.is_empty()).then(|| zone.to_string()) +} + +/// An environment variable, if it is set to something that isn't empty. +fn var(name: &str) -> Option { + let value = env::var_os(name)?; + let value = value.to_string_lossy().trim().to_string(); + + (!value.is_empty()).then_some(value) +} + +/// Seconds since the Unix epoch, or `None` if the clock is set before +/// 1970. +fn unix_seconds() -> Option { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .ok() + .map(|since| since.as_secs()) +} + +/// The locale, from the environment first and from the operating +/// system's own language preferences otherwise — which is what a machine +/// with no `LANG` set, meaning most Windows and macOS desktops, needs. +fn locale() -> Option { + if let Some(from_environment) = var("LC_ALL").or_else(|| var("LANG")) { + return Some(from_environment); + } + + let preferences = whoami::lang_prefs().ok()?; + preferences.time_langs().next().map(|lang| lang.to_string()) +} + +/// Some accounts are named after an email address — a domain-joined +/// Windows account, a managed macOS one — and that is the one place an +/// operating system does hand one over. When the account name looks like +/// an address, take it as one. +fn account_email() -> Option { + whoami::account() + .ok() + .filter(|account| account.contains('@')) +} + +/// The name and email git would sign a commit with on this machine. +#[derive(Debug, Default)] +struct GitIdentity { + /// `user.name`, if it is set. + name: Option, + /// `user.email`, if it is set. + email: Option, +} + +/// Reads `user.name` and `user.email` from the git configuration. +/// +/// Global and system files only. No repository is opened: the identity +/// wanted here is the person's, and it must not depend on which +/// directory the backend happens to have been started from. A global +/// `includeIf` makes this fail, since resolving one needs a repository — +/// hence an empty identity rather than an error. +#[cfg(feature = "git")] +fn git_identity() -> GitIdentity { + let Ok(config) = gix::config::File::from_globals() else { + return GitIdentity::default(); + }; + + let value = |key| { + let raw = config.string(key)?; + let text = String::from_utf8_lossy(&raw).trim().to_string(); + (!text.is_empty()).then_some(text) + }; + + GitIdentity { + name: value("user.name"), + email: value("user.email"), + } +} + +/// Without the `git` feature there is no git configuration to read, so +/// the identity is left to the environment variables. +#[cfg(not(feature = "git"))] +fn git_identity() -> GitIdentity { + GitIdentity::default() +} + +#[cfg(test)] +mod tests { + use super::*; + + type TestResult = Result>; + + #[test] + fn a_snapshot_fills_in_what_the_build_already_knows() -> TestResult { + let host = HostInfo::collect(); + + // The fields that can't be missing, because they are decided at + // compile time or by the process itself. Everything else depends + // on the machine the tests run on and is not asserted here. + assert!(!host.os.is_empty()); + assert!(!host.arch.is_empty()); + assert!(!host.core_version.is_empty()); + assert!(host.pid > 0); + assert_eq!(host.debug_build, cfg!(debug_assertions)); + Ok(()) + } + + #[test] + fn a_snapshot_serializes_without_the_fields_it_could_not_read() -> TestResult { + let host = HostInfo { + user: None, + real_name: None, + git_name: None, + email: None, + host: None, + distro: None, + cpus: None, + exe: None, + working_dir: None, + timezone: None, + locale: None, + started_at_unix: None, + open_file_limit: None, + ..HostInfo::collect() + }; + + let json = serde_json::to_string(&host)?; + + assert!(!json.contains("null"), "{json}"); + assert!(json.contains("\"os\""), "{json}"); + Ok(()) + } + + #[test] + fn without_identity_leaves_the_machine_and_takes_the_person() -> TestResult { + let host = HostInfo { + user: Some("javier".into()), + real_name: Some("Javier".into()), + git_name: Some("Javier".into()), + email: Some("someone@example.test".into()), + host: Some("a-laptop".into()), + ..HostInfo::collect() + } + .without_identity(); + + assert_eq!(host.user, None); + assert_eq!(host.real_name, None); + assert_eq!(host.git_name, None); + assert_eq!(host.email, None); + assert_eq!(host.host, None); + + // The machine and the build survive, which is the point. + assert!(!host.os.is_empty()); + assert!(!host.core_version.is_empty()); + Ok(()) + } + + #[test] + fn unix_reports_a_file_limit_and_windows_says_nothing() -> TestResult { + let limit = open_file_limit(); + + if cfg!(unix) { + let Some(limit) = limit else { + unreachable!("every unix defines RLIMIT_NOFILE"); + }; + assert!(limit > 0); + } else { + assert_eq!(limit, None); + } + Ok(()) + } + + #[test] + fn a_zone_name_is_whatever_follows_the_zone_database() -> TestResult { + assert_eq!( + zone_from_link("/usr/share/zoneinfo/Europe/Madrid").as_deref(), + Some("Europe/Madrid") + ); + // Relative links are just as common as absolute ones. + assert_eq!( + zone_from_link("../usr/share/zoneinfo/UTC").as_deref(), + Some("UTC") + ); + + // Nothing that isn't a zone database link. + assert_eq!(zone_from_link("/etc/localtime"), None); + assert_eq!(zone_from_link("/usr/share/zoneinfo/"), None); + Ok(()) + } + + #[test] + fn a_variable_that_is_not_set_reads_as_none() -> TestResult { + // The other half of `var` — that a variable set to an empty or + // blank string also reads as `None` — can't be tested here: + // setting an environment variable is `unsafe` in this edition, + // and this crate forbids `unsafe`. + assert_eq!(var("SOFTWARE_CORE_UTILS_HOST_UNSET"), None); + Ok(()) + } +} diff --git a/backend/crates/core/src/logger/target.rs b/backend/crates/core/src/logger/target.rs index b0deb783c..f6bb33325 100644 --- a/backend/crates/core/src/logger/target.rs +++ b/backend/crates/core/src/logger/target.rs @@ -9,8 +9,8 @@ //! behaviour rather than two copies of it that can drift. use super::Error; -use std::fs::{self, File}; -use std::io::{BufWriter, Write}; +use std::fs::{self, File, OpenOptions}; +use std::io::{BufWriter, Read, Seek, SeekFrom, Write}; use std::path::Path; use tracing::error; @@ -166,3 +166,77 @@ pub(super) fn create_file(path: &Path) -> Result, Error> { Ok(BufWriter::new(file)) } + +/// Opens `path` to add to the end of it, creating the file and its parent +/// directories if they aren't there. +/// +/// Returns the destination together with how many bytes the file already +/// held, which is what tells a brand new (or empty) file from one that +/// has content in it. +/// +/// If that content doesn't end in a newline, one is written before +/// anything else, so what gets appended starts on its own line instead of +/// being glued onto the last one. That is the only thing looked at: what +/// the existing content *says* is never read or checked. +pub(super) fn append_file(path: &Path) -> Result<(BufWriter, u64), Error> { + if let Some(parent) = path.parent() { + fs::create_dir_all(parent).map_err(|source| Error::Create { + path: path.to_path_buf(), + source, + })?; + } + + let mut file = OpenOptions::new() + // Readable as well as appendable: the last byte has to be looked + // at to know whether a newline is owed. Appending still lands at + // the end of the file however the read leaves the cursor. + .read(true) + .append(true) + .create(true) + .open(path) + .map_err(|source| Error::Create { + path: path.to_path_buf(), + source, + })?; + + let existing = file + .metadata() + .map_err(|source| Error::Read { + path: path.to_path_buf(), + source, + })? + .len(); + + if !ends_with_newline(&mut file, existing, path)? { + // Opened in append mode, so this lands at the end of the file + // wherever the read above left the cursor. + file.write_all(b"\n").map_err(|source| Error::Write { + label: path.display().to_string(), + source, + })?; + } + + Ok((BufWriter::new(file), existing)) +} + +/// Whether the last byte of `file` is a newline. An empty file counts as +/// ending in one: there is no half-written line to finish. +fn ends_with_newline(file: &mut File, len: u64, path: &Path) -> Result { + let Some(last_byte) = len.checked_sub(1) else { + return Ok(true); + }; + + file.seek(SeekFrom::Start(last_byte)) + .map_err(|source| Error::Read { + path: path.to_path_buf(), + source, + })?; + + let mut last = [0u8; 1]; + file.read_exact(&mut last).map_err(|source| Error::Read { + path: path.to_path_buf(), + source, + })?; + + Ok(last[0] == b'\n') +} diff --git a/backend/crates/core/src/logger/text.rs b/backend/crates/core/src/logger/text.rs index b60b663ea..e27d4a8b2 100644 --- a/backend/crates/core/src/logger/text.rs +++ b/backend/crates/core/src/logger/text.rs @@ -1,7 +1,7 @@ //! A plain text file, written a line at a time. use super::Error; -use super::target::{Target, create_file}; +use super::target::{Target, append_file, create_file}; use std::fs::File; use std::io::{BufWriter, Write}; use std::path::Path; @@ -51,6 +51,24 @@ impl TextFile> { debug!(path = %path.display(), "text file created"); Ok(file) } + + /// Opens the file at `path` to add lines to the end of it, creating it + /// and its parent directories if they aren't there. + /// + /// Nothing about what the file already contains is read, with one + /// exception: if it doesn't end in a newline, one is written first, so + /// the first new line can't continue a half-finished one. + pub fn append(path: impl AsRef) -> Result { + let path = path.as_ref(); + let (writer, existing) = append_file(path)?; + let file = Self::new(writer, path.display().to_string()); + debug!( + path = %path.display(), + existing_bytes = existing, + "text file opened to append" + ); + Ok(file) + } } impl TextFile { @@ -162,6 +180,40 @@ mod tests { } } + #[test] + fn appending_keeps_the_lines_that_were_already_there() -> TestResult { + let temp = tempfile::tempdir()?; + let path = temp.path().join("output/build.txt"); + + let mut log = TextFile::create(&path)?; + log.write_line("compiling")?; + log.close()?; + + let mut log = TextFile::append(&path)?; + log.write_line("done")?; + log.close()?; + + assert_eq!(fs::read_to_string(&path)?, "compiling\ndone\n"); + Ok(()) + } + + #[test] + fn appending_to_content_that_lacks_its_last_newline_starts_a_fresh_line() -> TestResult { + let temp = tempfile::tempdir()?; + let path = temp.path().join("script.log"); + fs::write(&path, "the script stopped here")?; + + let mut log = TextFile::append(&path)?; + log.write_line("and this is ours")?; + log.close()?; + + assert_eq!( + fs::read_to_string(&path)?, + "the script stopped here\nand this is ours\n" + ); + Ok(()) + } + #[test] fn every_line_is_written_with_its_terminator() -> TestResult { let mut text = TextFile::new(Vec::new(), "in memory"); From c95f2106ce73d14e8e420ce3092c34af20abac07 Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Tue, 10 Nov 2026 21:19:18 +0100 Subject: [PATCH 106/225] feat(backend,logger): docs --- backend/crates/core/src/logger/README.md | 408 +++++++++++++++++++++++ 1 file changed, 408 insertions(+) create mode 100644 backend/crates/core/src/logger/README.md diff --git a/backend/crates/core/src/logger/README.md b/backend/crates/core/src/logger/README.md new file mode 100644 index 000000000..c386b60a3 --- /dev/null +++ b/backend/crates/core/src/logger/README.md @@ -0,0 +1,408 @@ +# Logger Module (`logger`) + +Everything a recording needs on disk: writing CSV, text and JSON files +without knowing what is in them, moving those files around, and the +snapshot of the machine that produced them. + +Deliberately boring, and deliberately small. It knows nothing about the +vehicle — no `model` types, no ADJ, no boards, no session, no notion of a +timestamp or of a log level. Deciding **what** to write, **when**, and +under which name is the job of the backend's own `station::logging`, +which owns the subloggers (data, protections, messages and orders), the +session directory and the hot enable/disable. This module only answers +*"how do I write this file"*. + +Everything here blocks. A caller inside a `tokio` task is the one that +decides whether to run it on a thread of its own. + +--- + +## Directory Structure + +``` +logger/ +├── error.rs # `Error`: one variant per failure, every one naming its file +├── target.rs # private: the handle discipline the three formats share +├── csv.rs # `CsvFile`, `Row` — a CSV file that knows its header +├── text.rs # `TextFile` — one line at a time, verbatim +├── json.rs # `write_json`, `read_json`, `JsonDocument` +├── files.rs # `files` (feature `files`): copy, move, remove, size +│ └── error.rs # its own `Error`, naming both paths when there are two +└── host.rs # `host` (feature `host`): `HostInfo`, `open_file_limit` +``` + +Public API, re-exported at the module root: `CsvFile`, `Row`, `TextFile`, +`JsonDocument`, `read_json`, `write_json`, `Error`. The two submodules +stay namespaced (`logger::files`, `logger::host`) because they are used +far less often than the formats and read better qualified. + +--- + +## What It Buys Over Calling `std::fs` + +- **Flushing is explicit.** `close` and `flush` return a `Result`. A + fatal error in the backend ends in `std::process::exit`, which runs no + destructor, so a file that only flushes when it is dropped loses its + tail exactly in the case the log was there to explain. `Drop` is kept + as a courtesy flush that traces its own failure, never as the plan. + *When* to flush stays the caller's decision, but it doesn't have to + keep its own tally to make it: every file reports its + `bytes_since_flush`, so "flush every so many kilobytes, or every so + often" is a couple of lines over a map of open files. +- **Errors name the file.** A bare `std::io::Error` says what went wrong + but not where; every `Error` here carries the path or the label of the + file it happened on. +- **A row can't silently go out of step.** A `CsvFile` knows its header, + so a row with one field too few is an error, not a file whose columns + are shifted from that line on. +- **Quoting is done once, here.** A board's free-text message and the + path it came from can both contain commas, quotes and newlines; + `Row::text` quotes per RFC 4180. Four subloggers formatting their own + lines would each get a chance to get that wrong. +- **A row allocates nothing.** Fields are formatted into a buffer the + file reuses, not into a `Vec` built and thrown away per row — + at telemetry rates that is tens of thousands of rows a second. + +Nothing is traced per row, on purpose: that would be tens of thousands +of events per second. Only opening a file (`debug`), a copy or a move +(`debug`), and a failed flush on drop (`error`) are traced. + +--- + +## `target.rs` — The Shared Handle Discipline + +Private, and **not a trait**. `CsvFile` and `TextFile` differ in what +they put *in* a file (columns and quoting versus lines), not in how they +hold one, so the holding lives here once: + +| Behaviour | What it means | +| --- | --- | +| `label` | The name the file answers to in every `Error` — its path, or whatever a caller of `new` passed for an in-memory destination. | +| Poisoning | The first failed write or flush poisons the file: every later call returns `Error::Poisoned` instead of appending to something already inconsistent, or repeating the same I/O error once per row. | +| Explicit flush | `flush`/`close` report failure; `bytes_written` and `bytes_since_flush` are the counters a flush policy is built on. | +| Courtesy flush on drop | A file dropped without `close` is flushed best-effort, and a failure is traced (it cannot be returned, and the workspace lints rule out panicking). | + +It also owns the two ways a file is opened: + +- `create_file` — creates or truncates, creating parent directories, + behind a `BufWriter` of the default capacity (a bigger buffer is less + I/O but more lost if the process dies before the next flush, and that + trade is the caller's). +- `append_file` — opens for appending, creating the file and its parents + if needed, and reports how many bytes it already held. If that content + doesn't end in a newline, one is written first, so what gets appended + starts on its own line. That is the **only** thing looked at: what the + existing content *says* is never read or checked. + +--- + +## `csv.rs` — `CsvFile` and `Row` + +A CSV file written one row at a time, generic over its destination +(`CsvFile`, defaulting to `BufWriter`) so the format can +be exercised against an in-memory buffer. + +```rust +use software_core::logger::CsvFile; + +let mut csv = CsvFile::create("sessions/13/data/speed.csv", &["t_us", "origin", "value"])?; +csv.row().int(1_250).text("LCU, bay 2").num(53.2).end()?; +csv.flush()?; +csv.close()?; +``` + +**Constructors:** `create` (truncates, writes the header), `append` +(adds to the end; the header is written only if the file is new or +empty), `new` (wraps an already-open `W` with a label of its own). + +**A row:** `row()` starts one, then `int`, `num`, `bool` and `text` +append fields and `end()` validates and writes it. Every field method +keeps the first error it hits and returns `Self`, so a row reads as one +expression without a `?` per field; `end` is where that error — and the +field count — is reported. Nothing reaches the file until `end`, and a +row dropped without it writes nothing, so a row lands whole or not at +all, as a single `write_all`. + +**The header is the contract.** With a non-empty header, a row with a +different number of fields is an `Error::FieldCount` and is rejected +whole. An empty header writes no header line and leaves rows unchecked, +for a file whose columns aren't known up front. On `append`, the header +is *not* compared against what the file already holds — it is only taken +as a statement of how many fields a row has. The caller is the one who +knows that the file it opens is the file it thinks it is. + +**Formatting:** numbers and booleans are written with their `Display`, +i.e. the shortest form that round-trips (`1.0` is written `1`, and `NaN`, +`inf` and `-inf` are written as such rather than blanked — if a board +sent one, the log should say so). Only `text` can need quoting, and it is +the only one that does any: a field containing `,`, `"`, `\r` or `\n` is +wrapped in double quotes with inner quotes doubled, per RFC 4180. The +header goes through `Row` too, so a column name with a comma in it is +quoted the same way. + +**Also on the handle:** `flush`, `close`, `get_ref`, `is_poisoned`, +`label`, `bytes_written`, `bytes_since_flush` (see `target.rs` above). + +--- + +## `text.rs` — `TextFile` + +The same vocabulary as `CsvFile` — `create`, `append`, `new`, `flush`, +`close`, `get_ref`, `is_poisoned`, `label`, the byte counters, the same +`Error`, the same poisoning and the same courtesy flush — so there is +nothing to relearn moving between the two. `new` is the one that +differs: it can't fail, because there is no header to write. + +`write_line(line)` writes the line and its `\n` as a single write, so a +line lands whole or not at all. What `TextFile` does *not* have is +everything that only means something for columns: no header, no field +count, no quoting. A line is written exactly as given, and a line with a +comma or a quote in it is not special in any way — which also means a +text file can't tell you a line came out malformed. If the content has +fields in it, it wants `CsvFile` instead. + +--- + +## `json.rs` — Documents Written Whole + +Two ways in, for two different jobs: + +- **One-shot and typed.** `write_json(path, &value)` writes any + `Serialize` as pretty-printed JSON with a trailing newline, and + `read_json(path)` parses a whole document back as a `T`. Pretty, + because these are the files a person opens to find out what a + recording was. +- **A document that grows.** `JsonDocument` is for the file written when + a recording starts and added to when it stops: `new`/`open`/ + `open_or_new`, then `set`, `get`, `contains`, `remove`, `properties`, + `path` and `save`. It is held in memory as a `serde_json::Map`, so + properties this crate knows nothing about survive the round trip — the + document is edited, not rebuilt from a struct that would have dropped + them. `set` returns `&mut Self`, so several can be chained. + `open_or_new` forgives only a *missing* file; one that exists and is + broken still errors rather than quietly starting over and overwriting + it on the next save. + +```rust +use software_core::logger::JsonDocument; + +let mut session = JsonDocument::new("sessions/13/session.json"); +session.set("adj_commit", "4f1c3b0")?.set("time_unit", "us")?; +session.save()?; + +// Later, when the recording stops. +let mut session = JsonDocument::open("sessions/13/session.json")?; +session.set("rows", 128_000u64)?.set("stopped", true)?; +session.save()?; +``` + +**Every save is atomic.** The document is serialized into a `.tmp` +sibling, flushed, `sync_all`ed and then renamed over the destination, so +the file is never seen half-written: either the old contents or the new +ones. That matters more here than anywhere else in the module — a fatal +error in the backend ends in `std::process::exit`, and a session's +metadata truncated at that moment is what makes every CSV next to it +unreadable. The rename needs both files on one filesystem, which they +are by construction, being siblings. Not covered: the directory entry +isn't synced, so a power cut in the instant after the rename can still +lose it. + +**Properties come out in alphabetical order**, which is `serde_json`'s +own ordering for an object rather than something imposed here: the same +document always serializes the same way, which is what makes it readable +in a diff. + +Nothing is kept open between calls, which is why this file doesn't use +`Target` at all. Reading is in for JSON **only**, and for one reason: a +document that gains properties over time can't be added to without being +read first. A CSV or a text log is appended to and never revisited, and +nothing here will read one back. + +--- + +## `error.rs` — `logger::Error` + +One enum for the three formats. `Create`, `Read`, `Parse`, +`NotAnObject`, `Replace` and `Serialize` carry a `PathBuf`, since they +can only happen to a real file on disk; `Write`, `Flush`, `FieldCount` +and `Poisoned` carry a plain `label`, because a `CsvFile` can wrap any +`std::io::Write` and an in-memory buffer has no path. + +| Variant | When | +| --- | --- | +| `Create` | The file, or one of its parent directories, couldn't be created. | +| `Write` | A write to the file failed. The file is now poisoned. | +| `Flush` | The buffer couldn't be flushed, so what was written since the last flush may not have reached the disk. | +| `FieldCount` | A row didn't have as many fields as the header declares. Nothing was written. | +| `Poisoned` | An earlier write failed, so the file is no longer written to at all. | +| `Read` | The file couldn't be read (`read_json`, `JsonDocument::open`). | +| `Parse` | Not valid JSON, or a property isn't the type it was asked for. | +| `NotAnObject` | Valid JSON whose root isn't an object, so it has no properties. | +| `Replace` | The finished temporary file couldn't be renamed over its destination. | +| `Serialize` | A value couldn't be serialized as JSON, or its bytes couldn't be written. | + +`logger::files` has an `Error` of its own, listed below: a copy that +fails is not a failure of a file this module holds open, and its +variants name two paths rather than one. + +--- + +## `files.rs` — Moving Files Around *(feature `files`)* + +Plain `std::fs` with two things added, which is all it is for: the +destination's parent directories get created instead of the operation +failing, and every error names the file — both files, for the operations +that have two. + +| Function | Notes | +| --- | --- | +| `copy_file(from, to)` → `u64` | Replaces an existing `to` and returns the bytes copied. **Not atomic**: an interrupted copy leaves a partial file, so a reader that could see the destination mid-copy should be given a finished file under another name and then `move_file`d into place. | +| `copy_dir(from, to)` → `usize` | Recursive, returning how many files were copied. Directories are recreated as needed; a symbolic link is followed and its target copied as a plain file, so the result is real files rather than links pointing back at the original. | +| `move_file(from, to)` | A rename, atomic and free whatever the file's size. Across filesystems — a log directory on a USB stick — a rename is impossible, so it falls back to copy-then-remove, which is neither. | +| `remove_file(path)` | A file that isn't there is an error, as in `std::fs`: the caller is the one who knows whether that was expected. | +| `size(path)` → `u64` | How many bytes the file holds. | + +Its `Error` has `Copy`, `Move`, `CreateDir`, `Read` and `Remove`; +`Copy` and `Move` name both paths, since "couldn't copy" without saying +where to leaves the caller with nothing to act on. + +This is also what makes `CsvFile` and `JsonDocument` usable on a file +that already exists: copy it, then open the copy and carry on writing. + +```rust +use software_core::logger::{CsvFile, files}; + +files::copy_file("sessions/12/data/speed.csv", "sessions/13/data/speed.csv")?; +let mut speed = CsvFile::append("sessions/13/data/speed.csv", &["t_us", "value"])?; +speed.row().int(1_024).num(37.5).end()?; +speed.close()?; +``` + +Not wrapped: asking whether a file is there — that is `Path::exists`, +and a wrapper would only add a name to learn. Not here at all: anything +that walks a tree looking for something, rotation, quotas, watching for +changes, and anything asynchronous. + +--- + +## `host.rs` — Who Produced This *(feature `host`)* + +`HostInfo::collect()` takes one snapshot of the machine, the user and +the build, meant to be serialized straight into a recording's metadata +so that months later it is still possible to answer *which machine +produced this, running which build, and with whose clock and locale*. + +It is part of `logger` because it is part of a recording, but not of how +one is written: this is the **content** of a metadata file, not a way of +putting bytes on a disk. Nothing in `csv`, `text`, `json` or `files` +uses it; they still write files without knowing what is in them. + +**Nothing in it fails.** Every field is attempted on its own and left +empty if the system won't say, `collect` returns no `Result` and nothing +panics — a recording must never fail to start over a missing user name. +`Option` fields are skipped when serializing, so an unknown value is +absent from the JSON rather than `null`. + +What it reads: `user`, `real_name`, `git_name`, `email`, `host`, `os`, +`arch`, `distro`, `cpus`, `core_version`, `debug_build`, `pid`, `exe`, +`args`, `working_dir`, `timezone`, `locale`, `started_at_unix`, +`open_file_limit`. + +Three of those are worth their own note: + +- **`email`** is looked for in four places, in order: `user.email` in + the global git configuration, `$GIT_AUTHOR_EMAIL`, `$EMAIL`, then the + account name if it happens to look like an address. No operating + system exposes an email address portably, so git's own identity is + used instead — reliable on a developer's machine, and the identity the + person is already known by. The git configuration is only read with + the `git` feature on (global and system files only, never a + repository, so the result can't depend on which directory the backend + was started from); without it, the environment variables are all that + is left. +- **`timezone`** is a zone *name* (`Europe/Madrid`), not an offset, + because the offset depends on the date and a recording may straddle + the day summer time changes. It comes from `$TZ`, or from the target + of the `/etc/localtime` link. It is worth more than it looks: + protections and messages carry a time of day with no date or zone, so + without the recording machine's zone they can't be placed on a real + timeline or lined up against video. +- **`open_file_limit`** is also a free function, + `host::open_file_limit()`, worth calling before opening a file per + measurement: the soft limit is **256** by default on macOS and usually + 1024 on Linux, and past it opening a file starts failing in the middle + of a recording, which looks like a disk problem and isn't one. `None` + on Windows, honestly rather than as a failure — it has no equivalent + limit for the handles `std::fs::File` uses. + +`HostInfo::without_identity()` returns the same snapshot with the user +name, real name, git name, email and machine name removed, for a +recording that is going to be shared outside the team. + +`HostInfo` is `Serialize` only, on purpose: reading one back is reading +JSON, not rebuilding this struct, and a field like `os` is a +compile-time constant of the build that wrote it rather than something +to parse. Deliberately absent: free disk space and memory (another +dependency, and the disk is better checked by whoever is about to fill +it), the battery, and the network interfaces the backend bound to — +that last one belongs to whatever opened the sockets, the only thing +that actually knows. + +--- + +## Features + +| Feature | Enables | Dependencies | +| --- | --- | --- | +| `logger` | `CsvFile`, `TextFile`, the JSON API, `Error` | none beyond the crate's own `serde`/`serde_json`/`tracing` | +| `files` | `logger::files` (implies `logger`) | none of its own | +| `host` | `logger::host` (implies `logger`) | `whoami`, plus `rlimit` on unix | + +`files` and `host` are separate features because neither is needed to +write a file: a tool that only wants to put CSV rows on a disk shouldn't +have to take `whoami` with it. With the `git` feature also on, +`HostInfo` fills in the git identity as described above. + +--- + +## Why There Is No Trait Over The Three Formats + +What the formats share is how a file is **held**, and that is +`target.rs`. What they don't share is how a file is **written**, because +it genuinely isn't the same operation: a CSV row is typed fields +validated against a header, a text line is a string taken verbatim, and +a JSON document is a whole value serialized in one go with no handle to +keep. That is why `CsvFile` and `TextFile` expose the same vocabulary +while `write_json` stays a free function. + +A trait would only pay for itself once some caller needs to be generic +over the format — the same code path writing either CSV or JSON lines, +say — and no caller does today. Reaching for one now would mean either +flattening the API down to "write these bytes", which throws away the +field validation and the quoting that are the point, or inventing an +open/write/close lifecycle for JSON that it doesn't have. Adding the +trait later is backwards compatible, so it can wait for the second +caller. + +--- + +## Not Here, On Purpose + +Reading a CSV or a text log back, sessions, timestamps, file rotation, +quotas, keeping a registry of many open files (a `HashMap` +with `entry().or_insert_with(...)` in the caller is shorter and clearer +than anything this module could wrap it in), and anything asynchronous. + +--- + +## Verification + +```bash +cargo test -p software-core -F logger,files,host +cargo clippy -p software-core --features logger,files,host --all-targets -- -D warnings +cargo doc --open -p software-core -F logger,files,host --no-deps +``` + +The tests write into temporary directories (`tempfile`, a dev +dependency) and against in-memory buffers; none of them needs a network +or a real session directory. From a3432037310a1fcaab53533850384a175dea48af Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Tue, 10 Nov 2026 21:52:33 +0100 Subject: [PATCH 107/225] chore: format --- backend/crates/core/src/git/update.rs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/backend/crates/core/src/git/update.rs b/backend/crates/core/src/git/update.rs index 65fe5655c..603788b47 100644 --- a/backend/crates/core/src/git/update.rs +++ b/backend/crates/core/src/git/update.rs @@ -45,11 +45,9 @@ pub fn update_adj(path: Option, branch: &str) -> Result Result<(), Box> { + fn detects_missing_and_invalid_repositories() + -> Result<(), Box> { let temp = tempfile::tempdir()?; let path = temp.path().join("adj"); assert!(adj_exists_repo(Some(path.clone()))?.0.is_none()); From 4a36bb2d67ad0c4a1c8abbeafd019d28713a64da Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Fri, 13 Nov 2026 12:54:06 +0100 Subject: [PATCH 108/225] build(backend, http): add axum, and cargo update --- backend/Cargo.lock | 507 ++++++++++++++++++++++++--------- backend/crates/core/Cargo.toml | 4 + 2 files changed, 373 insertions(+), 138 deletions(-) diff --git a/backend/Cargo.lock b/backend/Cargo.lock index 3d6daa45d..6c129a49e 100644 --- a/backend/Cargo.lock +++ b/backend/Cargo.lock @@ -19,9 +19,9 @@ checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" [[package]] name = "arc-swap" -version = "1.9.2" +version = "1.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c049c0be4daef0b145cb3555416b3b8ef5b7888a38aea1a3a155801fe7b0810b" +checksum = "84a22b5d51209f6de83d37a0b33d320acb8da88823e42a94c075140708f032a5" dependencies = [ "rustversion", ] @@ -46,9 +46,9 @@ checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" [[package]] name = "aws-lc-rs" -version = "1.18.2" +version = "1.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "faac5829c2b74c28f830747e7818ccfb684261b5f48a1118b1e2a13d36dfab13" +checksum = "048006790404103c488e6c5616b3e7e702a71292aadda08e8f7698a9e0d2eb53" dependencies = [ "aws-lc-sys", "zeroize", @@ -56,9 +56,9 @@ dependencies = [ [[package]] name = "aws-lc-sys" -version = "0.46.0" +version = "0.47.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f1622d8446a2d4b2ce0c7eefc73dd43a99779028d5ee5c2dd8073a658ba8a2bc" +checksum = "8bfbe32ac36b3c428696ce315464181bc4029d689fd58e3f2a4e58c252242f52" dependencies = [ "cc", "cmake", @@ -67,6 +67,61 @@ dependencies = [ "pkg-config", ] +[[package]] +name = "axum" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90" +dependencies = [ + "axum-core", + "base64 0.22.1", + "bytes", + "form_urlencoded", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-util", + "itoa", + "matchit", + "memchr", + "mime", + "percent-encoding", + "pin-project-lite", + "serde_core", + "serde_json", + "serde_path_to_error", + "serde_urlencoded", + "sha1", + "sync_wrapper", + "tokio", + "tokio-tungstenite", + "tower", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "axum-core" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "http-body-util", + "mime", + "pin-project-lite", + "sync_wrapper", + "tower-layer", + "tower-service", + "tracing", +] + [[package]] name = "base64" version = "0.22.1" @@ -137,9 +192,9 @@ checksum = "7354288c522e7e980fafd2075d63d1285794c3a6a16cdd492f189ea406e5f18b" [[package]] name = "cc" -version = "1.8.0" +version = "1.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6651c9ed80effdc7db0ff72512157f901af5e3549e341e24b1dd4887d836d838" +checksum = "4ff2a8126fff0f8c839080d619675a585e61720bb12d2baceae45769fd66f155" dependencies = [ "find-msvc-tools", "jobserver", @@ -167,7 +222,7 @@ checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" dependencies = [ "cfg-if", "cpufeatures 0.3.1", - "rand_core", + "rand_core 0.10.1", ] [[package]] @@ -190,9 +245,9 @@ dependencies = [ [[package]] name = "combine" -version = "4.6.8" +version = "4.6.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cfc320937d09e6de266b31b9afb480f197d7a861be86be7cb2ea7e5d1bfffc5e" +checksum = "4356eba6976435498d05a311ee9fc486da3bc81c200d3f0d7dd9703b41913f92" dependencies = [ "bytes", "memchr", @@ -240,9 +295,9 @@ dependencies = [ [[package]] name = "crc32fast" -version = "1.5.2" +version = "1.5.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "01a7799fd6b852db0e61728dde9a204c423b44d689dbd432522543614b490e78" +checksum = "2b929dd2a135771f40afabd1073f85eed59c800b7c61901e5c254270497dad64" dependencies = [ "cfg-if", ] @@ -305,20 +360,26 @@ dependencies = [ "parking_lot_core", ] +[[package]] +name = "data-encoding" +version = "2.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06" + [[package]] name = "defmt" -version = "0.3.100" +version = "0.3.101" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f0963443817029b2024136fc4dd07a5107eb8f977eaf18fcd1fdeb11306b64ad" +checksum = "4deef977660e373c458df605a913d4ab121db0ccd18d1ad6976dff7d37cddb53" dependencies = [ - "defmt 1.1.1", + "defmt 1.2.0", ] [[package]] name = "defmt" -version = "1.1.1" +version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e2953bfe4f93bbd20cc71198842756f77d161884c99ebbabc41d80231ded88d1" +checksum = "e4a0795ac740cb54d7b3775c9c17345f6aaecf884c01733b39d6017738e0e3e1" dependencies = [ "bitflags 1.3.2", "defmt-macros", @@ -326,30 +387,30 @@ dependencies = [ [[package]] name = "defmt-macros" -version = "1.1.1" +version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bad9c72e7ca2137e0dc3813245a0d282fd6daad32fd800af018306a9169b5fe8" +checksum = "840bb056bd99c495c9188198a258ab787c79f306d864db3e6e8451442d6d8366" dependencies = [ "defmt-parser", "proc-macro2", "quote", - "syn 2.0.119", + "syn 3.0.10", ] [[package]] name = "defmt-parser" -version = "1.0.0" +version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "10d60334b3b2e7c9d91ef8150abfb6fa4c1c39ebbcf4a81c2e346aad939fee3e" +checksum = "71958f69fb2de856c5dd51ac9377e986ca1aa5919f931bf5395a807277f889a0" dependencies = [ "thiserror", ] [[package]] name = "deranged" -version = "0.5.8" +version = "0.5.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c" +checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" [[package]] name = "digest" @@ -390,7 +451,7 @@ checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", ] [[package]] @@ -401,9 +462,9 @@ checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" [[package]] name = "encoding_rs" -version = "0.8.42" +version = "0.8.44" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e985e0451871ad22fb8d2b6b076e2028a502a0d3950998c2c5c0a4f9b5d9679" +checksum = "89253175e704ab869b04f9db224d38630e0211a53841a79181deae0889e169f5" dependencies = [ "cfg-if", "core_detect", @@ -415,15 +476,15 @@ dependencies = [ [[package]] name = "equivalent" -version = "1.0.2" +version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" [[package]] name = "errno" -version = "0.3.14" +version = "0.3.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776" dependencies = [ "libc", "windows-sys 0.61.2", @@ -436,7 +497,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "04839bdf9d8c10f66806fad16b852fc72aab80873aebc3cb69d85b4fa41543ed" dependencies = [ "autocfg", - "defmt 0.3.100", + "defmt 0.3.101", "heapless", "serde", ] @@ -459,9 +520,9 @@ dependencies = [ [[package]] name = "find-msvc-tools" -version = "0.1.14" +version = "0.1.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aedcfb3409746eddb02b9e19ebda1c3394f759a152e48ee875a0844d1b955484" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" [[package]] name = "fnv" @@ -562,6 +623,18 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "libc", + "r-efi 5.3.0", + "wasip2", +] + [[package]] name = "getrandom" version = "0.4.3" @@ -571,8 +644,8 @@ dependencies = [ "cfg-if", "js-sys", "libc", - "r-efi", - "rand_core", + "r-efi 6.0.0", + "rand_core 0.10.1", "wasm-bindgen", ] @@ -1657,6 +1730,12 @@ version = "1.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" +[[package]] +name = "httpdate" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" + [[package]] name = "human_format" version = "1.2.1" @@ -1677,6 +1756,7 @@ dependencies = [ "http", "http-body", "httparse", + "httpdate", "itoa", "pin-project-lite", "smallvec", @@ -1725,9 +1805,9 @@ dependencies = [ [[package]] name = "icu_collections" -version = "2.3.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fa68d21081c4a05d5a901a1c62add574c77048b6a1c67be3b50ce0b60d4ca513" +checksum = "fe090a42a0d3140fed8c63263ed1fecc02422cb2f4bfe55cd8de2de1b8e105dd" dependencies = [ "displaydoc", "potential_utf", @@ -1739,9 +1819,9 @@ dependencies = [ [[package]] name = "icu_locale_core" -version = "2.3.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d56e28588da92eee5c3201a6eff33fabdd49b62269c8938d4ff050ce4d900deb" +checksum = "25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0" dependencies = [ "displaydoc", "litemap", @@ -1752,9 +1832,9 @@ dependencies = [ [[package]] name = "icu_normalizer" -version = "2.3.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "12f9cf5f235641ed274641dd81c3f28d870e276763d0797aeeab72317b1c646f" +checksum = "404a3b8c486f205c87fe7f23ab6894d84a4ad76d6e4671ae1981ba7def87c599" dependencies = [ "icu_collections", "icu_normalizer_data", @@ -1766,15 +1846,15 @@ dependencies = [ [[package]] name = "icu_normalizer_data" -version = "2.3.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1563da1ed3e0b3bf3d74c9b85917ac9c56464d2f57242270c09c9e752f8021a0" +checksum = "20f0088bfb7441f7a37fa0c9e20cb1e9cba1cac6b9ce8cd2a6dc44294f8e8cbc" [[package]] name = "icu_properties" -version = "2.3.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7e7ca276ad3145661a65914e6daf131ca5120cd3dcee8f8f3214b8875184a148" +checksum = "2ea83d991c56158f7cf898bf86436c1dfe7c07ee82fe88951f2695c9f37a379f" dependencies = [ "displaydoc", "icu_collections", @@ -1787,15 +1867,15 @@ dependencies = [ [[package]] name = "icu_properties_data" -version = "2.3.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e590f038c1464a96894fd6d10127e90a8be4509f56ff7ecef851b15cee0b7caa" +checksum = "b98f29af82d02b163fe50161388350e743bb3107cc8e8c2f7314cb505faddfcf" [[package]] name = "icu_provider" -version = "2.3.1" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d27bbb9d3abbefac45d55f647c9de1d44aafcd1186eb91879afef17c396c3e73" +checksum = "413099315636c588ee8f011190b329b971a09a8fae9d157e01dcae8379468514" dependencies = [ "displaydoc", "icu_locale_core", @@ -1855,17 +1935,16 @@ checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" [[package]] name = "itoa" -version = "1.0.18" +version = "1.0.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" [[package]] name = "jiff" -version = "0.2.38" +version = "0.2.43" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b2b005715dcbeb0089a3c0dab99f2ff1cc3b2525323552703d648585d342a383" +checksum = "26699905cc795a23e3949585cc7ba3ee8ade090872a27e4316304a777297894a" dependencies = [ - "defmt 1.1.1", "jiff-core", "jiff-static", "jiff-tzdb-platform", @@ -1878,19 +1957,18 @@ dependencies = [ [[package]] name = "jiff-core" -version = "0.1.1" +version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5e52fe76043ccecc9005d2305ebaadf7d7fc0cc89ca6baa10a94d6bc68c7128c" +checksum = "ffe6854081f5ac0a3046a9b223729ccd7a20b1e0e8277e44dc0660eedf67dfe2" dependencies = [ - "defmt 1.1.1", "log", ] [[package]] name = "jiff-static" -version = "0.2.38" +version = "0.2.43" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2cc9817253cf7c7ee4684451bd327e88d6f3658014e54a29198625590650695c" +checksum = "4b4ff49b2887190c760b86207b55cdcaabbdecaf7a0660d68aa2ed6f652abf0a" dependencies = [ "jiff-core", "proc-macro2", @@ -1974,9 +2052,9 @@ dependencies = [ [[package]] name = "js-sys" -version = "0.3.106" +version = "0.3.107" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7883d941dae510fb2d978fc3fe018c71c9e2892fd38854de3e8b92c2e5ad9cc5" +checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a" dependencies = [ "cfg-if", "futures-util", @@ -1991,9 +2069,9 @@ checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" [[package]] name = "libc" -version = "0.2.190" +version = "0.2.191" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce5d3ddc6d3fa000eb1536d85e147bfe31aacaba692ed6a876f95cb7c855be78" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" [[package]] name = "libredox" @@ -2027,9 +2105,9 @@ dependencies = [ [[package]] name = "log" -version = "0.4.34" +version = "0.4.35" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" [[package]] name = "lru-slab" @@ -2046,6 +2124,12 @@ dependencies = [ "regex-automata", ] +[[package]] +name = "matchit" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3" + [[package]] name = "memchr" version = "2.8.3" @@ -2054,18 +2138,18 @@ checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" [[package]] name = "memmap2" -version = "0.9.11" +version = "0.9.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d1219ed1b7f229ee7104d281dd01d6802fe28bb6e95d292942c4daacdeb798c0" +checksum = "6b0ca1155a9ecc25aa12e8313a119f32edf0255fea2f44839c4ac0a12b2ac157" dependencies = [ "libc", ] [[package]] name = "mime" -version = "0.3.17" +version = "0.3.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" +checksum = "d5848f5a9e8117cf94f2f90faac24a87ff81600ff8628c1e3deaab572e76bfa1" [[package]] name = "mio" @@ -2134,9 +2218,9 @@ checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" [[package]] name = "openssl-probe" -version = "0.2.1" +version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe" +checksum = "7e036b411754132fd6b74e94b74e9a13c5cf606fa93d1885c35860d3060820b1" [[package]] name = "option-ext" @@ -2215,6 +2299,15 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958" +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + [[package]] name = "proc-macro2" version = "1.0.107" @@ -2265,7 +2358,7 @@ dependencies = [ "bytes", "getrandom 0.4.3", "lru-slab", - "rand", + "rand 0.10.3", "rand_pcg", "ring", "rustc-hash", @@ -2301,12 +2394,28 @@ dependencies = [ "proc-macro2", ] +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + [[package]] name = "r-efi" version = "6.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" +[[package]] +name = "rand" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41" +dependencies = [ + "rand_chacha", + "rand_core 0.9.5", +] + [[package]] name = "rand" version = "0.10.3" @@ -2315,7 +2424,26 @@ checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af" dependencies = [ "chacha20", "getrandom 0.4.3", - "rand_core", + "rand_core 0.10.1", +] + +[[package]] +name = "rand_chacha" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" +dependencies = [ + "ppv-lite86", + "rand_core 0.9.5", +] + +[[package]] +name = "rand_core" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" +dependencies = [ + "getrandom 0.3.4", ] [[package]] @@ -2330,7 +2458,7 @@ version = "0.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "caa0f4137e1c0a72f4c651489402276c8e8e1cf081f3b0ba156d2cbeef09e86a" dependencies = [ - "rand_core", + "rand_core 0.10.1", ] [[package]] @@ -2452,9 +2580,9 @@ dependencies = [ [[package]] name = "rustix" -version = "1.1.5" +version = "1.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" dependencies = [ "bitflags 2.13.2", "errno", @@ -2465,9 +2593,9 @@ dependencies = [ [[package]] name = "rustls" -version = "0.23.45" +version = "0.23.46" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d41d731c7d2f962d1ccc364cec258de3c0e93b38c2fb3ba97ac74513048d634" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" dependencies = [ "aws-lc-rs", "once_cell", @@ -2479,9 +2607,9 @@ dependencies = [ [[package]] name = "rustls-native-certs" -version = "0.8.4" +version = "0.8.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dab5152771c58876a2146916e53e35057e1a4dfa2b9df0f0305b07f611fdea4d" +checksum = "4a073f5dc7469f984c52ad2752b63b0807745133b6de880b7b64c1ac4c48aec4" dependencies = [ "openssl-probe", "rustls-pki-types", @@ -2491,9 +2619,9 @@ dependencies = [ [[package]] name = "rustls-pki-types" -version = "1.15.1" +version = "1.16.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" +checksum = "102f35f7de7b06d8c61f1cff6592f5253e0dea431c74867aad5dfd70f44663fb" dependencies = [ "web-time", "zeroize", @@ -2528,9 +2656,9 @@ checksum = "eec689c0bc40ff2458a5977b6619cb718087084a18e02a131c599b62d05e1a5f" [[package]] name = "rustls-webpki" -version = "0.103.15" +version = "0.103.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2" +checksum = "e3a0760a887c14823fca5a1c970b01d47c328c696c0c64829d1df50e8f853fd5" dependencies = [ "aws-lc-rs", "ring", @@ -2544,6 +2672,12 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + [[package]] name = "same-file" version = "1.0.6" @@ -2555,9 +2689,9 @@ dependencies = [ [[package]] name = "schannel" -version = "0.1.29" +version = "0.1.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "91c1b7e4904c873ef0710c1f407dde2e6287de2bebc1bbbf7d430bb7cbffd939" +checksum = "9cb23c424d8ee841bb4d813677ca237e2a610067d594fec130f87d6093495ab5" dependencies = [ "windows-sys 0.61.2", ] @@ -2624,7 +2758,7 @@ checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", ] [[package]] @@ -2640,15 +2774,38 @@ dependencies = [ "zmij", ] +[[package]] +name = "serde_path_to_error" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457" +dependencies = [ + "itoa", + "serde", + "serde_core", +] + [[package]] name = "serde_spanned" -version = "1.1.2" +version = "1.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4e7523beb55eece201a2356bee0bbca0d1ab466c14c07703b2e0ee6d42cb0c2c" +checksum = "9c187e0a369471c550af028cba56d4f4fa2a489ad28151ae95a4d340a2a8b782" dependencies = [ "serde_core", ] +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + [[package]] name = "sha1" version = "0.10.7" @@ -2687,9 +2844,9 @@ checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" [[package]] name = "signal-hook" -version = "0.4.5" +version = "0.4.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b29ffa27d3d59a049bb328258de100f8012848d1b08d444e08bbc02ac468435e" +checksum = "49f7447afd772ca79ad17ae0a3972a6b0df0cb4b80990fd82707593e9e012a74" dependencies = [ "libc", "signal-hook-registry", @@ -2729,9 +2886,9 @@ checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" [[package]] name = "smallvec" -version = "1.16.3" +version = "1.16.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b3dc8af474f516a851ff4bd12db780f948b9250ad37211e4eec0bccea54e01b" +checksum = "149309498a5f7334b12ddae0cad8aba81ce785fe91755068867e017cf98fee46" [[package]] name = "socket2" @@ -2747,6 +2904,7 @@ dependencies = [ name = "software-core" version = "0.1.0" dependencies = [ + "axum", "bytes", "dirs", "gix", @@ -2756,6 +2914,7 @@ dependencies = [ "tempfile", "thiserror", "tokio", + "tower", "tracing", "tracing-appender", "tracing-subscriber", @@ -2805,9 +2964,9 @@ dependencies = [ [[package]] name = "syn" -version = "3.0.9" +version = "3.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" dependencies = [ "proc-macro2", "quote", @@ -2831,7 +2990,7 @@ checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", ] [[package]] @@ -2864,7 +3023,7 @@ checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", ] [[package]] @@ -2908,9 +3067,9 @@ dependencies = [ [[package]] name = "tinystr" -version = "0.8.4" +version = "0.8.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b1e27c91459209c2986af3dcf603a5a74a4368754ce37414f59acc971167f643" +checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a" dependencies = [ "displaydoc", "zerovec", @@ -2924,9 +3083,9 @@ checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" [[package]] name = "tokio" -version = "1.53.2" +version = "1.54.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e95f91fcc7a621e8b030f6aa23c71fe9838ae2fb4d8118b75602a328f5144044" +checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" dependencies = [ "bytes", "libc", @@ -2946,7 +3105,7 @@ checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", ] [[package]] @@ -2959,6 +3118,18 @@ dependencies = [ "tokio", ] +[[package]] +name = "tokio-tungstenite" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f72a05e828585856dacd553fba484c242c46e391fb0e58917c942ee9202915c" +dependencies = [ + "futures-util", + "log", + "tokio", + "tungstenite", +] + [[package]] name = "tokio-util" version = "0.7.20" @@ -3003,14 +3174,14 @@ version = "1.1.5+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c" dependencies = [ - "winnow 1.0.4", + "winnow 1.0.5", ] [[package]] name = "toml_writer" -version = "1.1.3+spec-1.1.0" +version = "1.2.0+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "06bdbd8cfc056b8d2e2e85f29b56a3bdbecb527cef81eb39e3e7b98af4652770" +checksum = "009dbb7700f11c55ef83aebbe4c0e9cf1f1ac0844bd8d6f00dc38f302026e13a" [[package]] name = "tower" @@ -3025,6 +3196,7 @@ dependencies = [ "tokio", "tower-layer", "tower-service", + "tracing", ] [[package]] @@ -3151,6 +3323,22 @@ version = "0.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" +[[package]] +name = "tungstenite" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c01152af293afb9c7c2a57e4b559c5620b421f6d133261c60dd2d0cdb38e6b8" +dependencies = [ + "bytes", + "data-encoding", + "http", + "httparse", + "log", + "rand 0.9.5", + "sha1", + "thiserror", +] + [[package]] name = "typenum" version = "1.20.1" @@ -3180,9 +3368,9 @@ checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" [[package]] name = "unicode-normalization" -version = "0.1.25" +version = "0.1.26" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5fd4f6878c9cb28d874b009da9e8d183b5abc80117c40bbd187a1fde336be6e8" +checksum = "75cd3fb03d5288b3ba9a1ee103ac7e9cbb59f0b03d64f8ddfcc04dd42758a85d" dependencies = [ "tinyvec", ] @@ -3207,9 +3395,18 @@ dependencies = [ [[package]] name = "utf8_iter" -version = "1.0.4" +version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" +checksum = "af3bd9d3e571c26fcce9d033b87ea5ab061b8d2ffe9b7a5675d810d68f03edf0" +dependencies = [ + "utf_types", +] + +[[package]] +name = "utf_types" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6" [[package]] name = "valuable" @@ -3248,14 +3445,22 @@ version = "0.11.1+wasi-snapshot-preview1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" +[[package]] +name = "wasip2" +version = "1.0.4+wasi-0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487" +dependencies = [ + "wit-bindgen", +] + [[package]] name = "wasm-bindgen" -version = "0.2.129" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9bb54f33acc68fd454578d9820b0bde1a1a3d17aa17bb7b6595806d02886d409" +checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c" dependencies = [ "cfg-if", - "once_cell", "rustversion", "wasm-bindgen-macro", "wasm-bindgen-shared", @@ -3263,9 +3468,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-futures" -version = "0.4.79" +version = "0.4.80" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3cbab34de2d982e9b48e18d216d04c4a6f641066ff19ffb699980f591ee3610e" +checksum = "5e14e0327cb5368ad60ccb22d04a9827a693c95a926d8d125e9fa39e0baec501" dependencies = [ "js-sys", "tokio", @@ -3274,9 +3479,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro" -version = "0.2.129" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2e29d0c35b16e224a7eeb5cd2d25e3e1968fbd65604117b44d3b789d00ee8535" +checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9" dependencies = [ "quote", "wasm-bindgen-macro-support", @@ -3284,31 +3489,31 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro-support" -version = "0.2.129" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6f501a8bc3719dba86ef8ae4728879c08001bea749eb1333ac5b91e040e2a6b7" +checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a" dependencies = [ "bumpalo", "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-shared" -version = "0.2.129" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "23f0c9c52aa7cd7d77769a4cfe2a9adb1b331f489a41d912ce14513d5ab995c6" +checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e" dependencies = [ "unicode-ident", ] [[package]] name = "web-sys" -version = "0.3.106" +version = "0.3.107" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "88261b9deccee56594c11a3460c462c41f58d148598fe70ad77070126a68aba4" +checksum = "d7d179596ff5ec0f6de4db64d54011bde6289cc49603d3a6e4ce3f329207ab88" dependencies = [ "js-sys", "wasm-bindgen", @@ -3326,9 +3531,9 @@ dependencies = [ [[package]] name = "webpki-root-certs" -version = "1.0.9" +version = "1.0.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b96554aa2acc8ccdb7e1c9a58a7a68dd5d13bccc69cd124cb09406db612a1c9b" +checksum = "293198dcebfb821155b5092ab94b5a82ff180eddd7241df3bd6e66a4ffd1a585" dependencies = [ "rustls-pki-types", ] @@ -3460,9 +3665,15 @@ checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945" [[package]] name = "winnow" -version = "1.0.4" +version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81" +checksum = "8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef" + +[[package]] +name = "wit-bindgen" +version = "0.57.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" [[package]] name = "writeable" @@ -3472,9 +3683,9 @@ checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" [[package]] name = "yoke" -version = "0.8.3" +version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5" +checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3" dependencies = [ "stable_deref_trait", "yoke-derive", @@ -3489,10 +3700,30 @@ checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", "synstructure", ] +[[package]] +name = "zerocopy" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "zerofrom" version = "0.1.8" @@ -3510,7 +3741,7 @@ checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", "synstructure", ] @@ -3533,9 +3764,9 @@ dependencies = [ [[package]] name = "zerovec" -version = "0.11.8" +version = "0.11.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb0464e17806c1d976d5cba29399c7f08e516e279e2ba493f63123b5fca67dd8" +checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40" dependencies = [ "yoke", "zerofrom", @@ -3544,13 +3775,13 @@ dependencies = [ [[package]] name = "zerovec-derive" -version = "0.11.6" +version = "0.11.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "34df6fc39dbd26ddc9c10e6a2984476e13acce22e64e4487636ef494369225da" +checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", ] [[package]] diff --git a/backend/crates/core/Cargo.toml b/backend/crates/core/Cargo.toml index 83985c825..50bcde557 100644 --- a/backend/crates/core/Cargo.toml +++ b/backend/crates/core/Cargo.toml @@ -22,6 +22,8 @@ pcap = ["net"] logger = [] # Reusable tracing/diagnostics setup (console + non-blocking file + stderr layers) trace = ["dep:tracing-subscriber", "dep:tracing-appender"] +# HTTP +http = ["dep:tokio"] [dependencies] bytes.workspace = true @@ -36,6 +38,8 @@ gix = { version = "0.87.1", optional = true, features = ["blocking-http-transpor dirs = { version = "7.0.0", optional = true } tempfile = { version = "3.27", optional = true } ntp_usg-server = { version = "5.0.0", optional = true, features = ["ipv4", "tokio"] } +axum = { version = "0.8.9", features = ["ws", "http2", "http1"] } +tower = { version = "0.5.3", features = ["util"] } # `workspace = true` can't be combined with extra lints in the same table, # so the workspace list is repeated here with `missing_docs` added: this is From 56d4aeff6b3e82faafad16abb021b02cd234459a Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Fri, 13 Nov 2026 12:54:46 +0100 Subject: [PATCH 109/225] feat(backend, http): add datapacket structure response --- backend/crates/core/src/http.rs | 10 ++ backend/crates/core/src/http/response.rs | 3 + backend/crates/core/src/http/response/data.rs | 112 ++++++++++++++++++ backend/crates/core/src/lib.rs | 3 + 4 files changed, 128 insertions(+) create mode 100644 backend/crates/core/src/http.rs create mode 100644 backend/crates/core/src/http/response.rs create mode 100644 backend/crates/core/src/http/response/data.rs diff --git a/backend/crates/core/src/http.rs b/backend/crates/core/src/http.rs new file mode 100644 index 000000000..ca413fc77 --- /dev/null +++ b/backend/crates/core/src/http.rs @@ -0,0 +1,10 @@ +//! HTTP server built on Axum. +//! +//! Currently exposes only `GET /health`, returning `{"status":"ok"}`. +//! This reports that HTTP is responding, not that the vehicle is ready. + +mod handlers; +pub mod response; +mod server; + +pub use server::serve; diff --git a/backend/crates/core/src/http/response.rs b/backend/crates/core/src/http/response.rs new file mode 100644 index 000000000..30fd88c3a --- /dev/null +++ b/backend/crates/core/src/http/response.rs @@ -0,0 +1,3 @@ +//! Models for HTTP response bodies. + +pub mod data; diff --git a/backend/crates/core/src/http/response/data.rs b/backend/crates/core/src/http/response/data.rs new file mode 100644 index 000000000..6bdc1cd99 --- /dev/null +++ b/backend/crates/core/src/http/response/data.rs @@ -0,0 +1,112 @@ +//! ADJ v3 data packet catalog returned by `/backend/adj/DataPackets`. + +use serde::{Serialize, Serializer}; + +use crate::model::{AdjId, BoardId, NumericKind}; + +/// Data packet definitions grouped by board. +/// +/// Serialized as a JSON object containing a `boards` array. +/// See `example/data.json` for the response shape. +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct DataResponse { + /// Boards and their data packet definitions. + pub boards: Vec, +} + +/// A board and the data packets it declares. +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct DataBoardResponse { + /// Numeric board id from the ADJ. + #[serde(serialize_with = "serialize_board_id")] + pub id: BoardId, + /// Human-readable board name. + pub name: String, + /// Data packet definitions, each carrying its own numeric id. + pub packets: Vec, +} + +/// A data packet's ADJ metadata, not its current telemetry values. +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct DataPacketResponse { + /// Numeric packet id from the ADJ. + #[serde(serialize_with = "serialize_adj_id")] + pub id: AdjId, + /// Human-readable packet name. + pub name: String, + /// ADJ packet type: `data` for this endpoint. + #[serde(rename = "type")] + pub packet_type: String, + /// Declared transmission period, expressed in `period_type` units. + pub period: f64, + /// ADJ period unit, e.g. `ms`. + pub period_type: String, + /// Name of the socket declared by the ADJ. + pub socket: String, + /// Measurement definitions in wire order, without protections. + pub measurements: Vec, +} + +/// A measurement's definition with protection metadata deliberately omitted. +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct DataMeasurementResponse { + /// Numeric measurement id, distinct from its textual alias. + #[serde(serialize_with = "serialize_adj_id")] + pub id: AdjId, + /// Textual identifier declared in the ADJ. + pub alias: String, + /// Human-readable measurement name. + pub name: String, + /// Unit label displayed to the user. + pub display_units: String, + /// Numeric, boolean or enum metadata. + pub kind: DataMeasurementKind, +} + +/// Measurement metadata tagged with an explicit `type` field in JSON. +#[derive(Debug, Clone, PartialEq, Serialize)] +#[serde(tag = "type", rename_all = "snake_case")] +pub enum DataMeasurementKind { + /// Numeric measurement, including its binary representation. + Numeric { + /// Wire type, serialized with its ADJ name, e.g. `float32`. + #[serde(serialize_with = "serialize_numeric_kind")] + wire_type: NumericKind, + }, + /// Boolean measurement, serialized as `{"type":"boolean"}`. + Boolean, + /// Enumeration with variants in ADJ order. + Enum { + /// Allowed variant names. + options: Vec, + }, +} + +// Serialize domain types locally without changing the internal model. +fn serialize_board_id(id: &BoardId, serializer: S) -> Result { + serializer.serialize_u16(id.0) +} + +fn serialize_adj_id(id: &AdjId, serializer: S) -> Result { + serializer.serialize_u16(id.0) +} + +// Serialize numeric kind to match ADJv3 types +fn serialize_numeric_kind( + kind: &NumericKind, + serializer: S, +) -> Result { + let name = match kind { + NumericKind::U8 => "uint8", + NumericKind::U16 => "uint16", + NumericKind::U32 => "uint32", + NumericKind::U64 => "uint64", + NumericKind::I8 => "int8", + NumericKind::I16 => "int16", + NumericKind::I32 => "int32", + NumericKind::I64 => "int64", + NumericKind::F32 => "float32", + NumericKind::F64 => "float64", + }; + serializer.serialize_str(name) +} diff --git a/backend/crates/core/src/lib.rs b/backend/crates/core/src/lib.rs index fdf802844..23d062bf2 100644 --- a/backend/crates/core/src/lib.rs +++ b/backend/crates/core/src/lib.rs @@ -25,3 +25,6 @@ pub mod adj; /// [`adj`] declares as the schema. See [`protocol::wire`], /// [`protocol::tcp`], [`protocol::udp`]. pub mod protocol; + +#[cfg(feature = "http")] +pub mod http; \ No newline at end of file From dfbc4a6521ec42db1db99e54ccc7c21311756fd2 Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Fri, 13 Nov 2026 13:12:56 +0100 Subject: [PATCH 110/225] feat(backend, http): add orderpacket structure response and separate utils file for serialize specific kinds of data --- backend/crates/core/src/http/response.rs | 2 + backend/crates/core/src/http/response/data.rs | 35 +------- .../crates/core/src/http/response/order.rs | 80 +++++++++++++++++++ .../crates/core/src/http/response/utils.rs | 65 +++++++++++++++ 4 files changed, 151 insertions(+), 31 deletions(-) create mode 100644 backend/crates/core/src/http/response/order.rs create mode 100644 backend/crates/core/src/http/response/utils.rs diff --git a/backend/crates/core/src/http/response.rs b/backend/crates/core/src/http/response.rs index 30fd88c3a..0c9be06ea 100644 --- a/backend/crates/core/src/http/response.rs +++ b/backend/crates/core/src/http/response.rs @@ -1,3 +1,5 @@ //! Models for HTTP response bodies. pub mod data; +pub mod order; +mod utils; diff --git a/backend/crates/core/src/http/response/data.rs b/backend/crates/core/src/http/response/data.rs index 6bdc1cd99..922608835 100644 --- a/backend/crates/core/src/http/response/data.rs +++ b/backend/crates/core/src/http/response/data.rs @@ -1,9 +1,11 @@ //! ADJ v3 data packet catalog returned by `/backend/adj/DataPackets`. -use serde::{Serialize, Serializer}; +use serde::Serialize; use crate::model::{AdjId, BoardId, NumericKind}; +use super::utils::{serialize_adj_id, serialize_board_id, serialize_numeric_kind}; + /// Data packet definitions grouped by board. /// /// Serialized as a JSON object containing a `boards` array. @@ -80,33 +82,4 @@ pub enum DataMeasurementKind { /// Allowed variant names. options: Vec, }, -} - -// Serialize domain types locally without changing the internal model. -fn serialize_board_id(id: &BoardId, serializer: S) -> Result { - serializer.serialize_u16(id.0) -} - -fn serialize_adj_id(id: &AdjId, serializer: S) -> Result { - serializer.serialize_u16(id.0) -} - -// Serialize numeric kind to match ADJv3 types -fn serialize_numeric_kind( - kind: &NumericKind, - serializer: S, -) -> Result { - let name = match kind { - NumericKind::U8 => "uint8", - NumericKind::U16 => "uint16", - NumericKind::U32 => "uint32", - NumericKind::U64 => "uint64", - NumericKind::I8 => "int8", - NumericKind::I16 => "int16", - NumericKind::I32 => "int32", - NumericKind::I64 => "int64", - NumericKind::F32 => "float32", - NumericKind::F64 => "float64", - }; - serializer.serialize_str(name) -} +} \ No newline at end of file diff --git a/backend/crates/core/src/http/response/order.rs b/backend/crates/core/src/http/response/order.rs new file mode 100644 index 000000000..1845f0d94 --- /dev/null +++ b/backend/crates/core/src/http/response/order.rs @@ -0,0 +1,80 @@ +//! ADJ v3 order catalog returned by `/backend/adj/OrderPackets`. + +use std::time::Duration; + +use serde::Serialize; + +use crate::model::{AdjId, BoardId, ProtectionKind, Severity}; + +use super::{ + data::DataMeasurementKind, + utils::{serialize_adj_id, serialize_board_id, serialize_protection_kind, serialize_severity}, +}; + +/// Order definitions grouped by board, matching `example/order.json`. +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct OrderResponse { + /// Boards and their order definitions. + pub boards: Vec, +} + +/// A board and the orders it declares. +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct OrderBoardResponse { + /// Numeric board id from the ADJ. + #[serde(serialize_with = "serialize_board_id")] + pub id: BoardId, + /// Human-readable board name. + pub name: String, + /// Order definitions, each carrying its own numeric id. + pub orders: Vec, +} + +/// An order definition, not a request to execute that order. +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct OrderPacketResponse { + /// Numeric order id from the ADJ. + #[serde(serialize_with = "serialize_adj_id")] + pub id: AdjId, + /// Human-readable order name. + pub name: String, + /// ADJ packet type: `order` for this endpoint. + #[serde(rename = "type")] + pub packet_type: String, + /// Parameters in wire order; empty for parameterless orders. + pub measurements: Vec, +} + +/// An order parameter's ADJ definition, including its protections. +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct OrderMeasurementResponse { + /// Numeric measurement id, distinct from its textual alias. + #[serde(serialize_with = "serialize_adj_id")] + pub id: AdjId, + /// Textual identifier declared in the ADJ. + pub alias: String, + /// Human-readable parameter name. + pub name: String, + /// Unit label displayed to the user. + pub display_units: String, + /// Same numeric, boolean or enum metadata used by data measurements. + pub kind: DataMeasurementKind, + /// Protection definitions in ADJ order; empty when none are declared. + pub protections: Vec, +} + +/// A parameter protection's definition, not a triggered protection event. +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct OrderProtectionResponse { + /// One-based protection position within its measurement, not a packet id. + #[serde(serialize_with = "serialize_adj_id")] + pub id: AdjId, + /// Trigger condition, serialized with its type and named bounds. + #[serde(serialize_with = "serialize_protection_kind")] + pub kind: ProtectionKind, + /// Severity serialized as `fault` or `warning`. + #[serde(serialize_with = "serialize_severity")] + pub severity: Severity, + /// Required duration, serialized as `{"secs": ..., "nanos": ...}`. + pub time: Duration, +} diff --git a/backend/crates/core/src/http/response/utils.rs b/backend/crates/core/src/http/response/utils.rs new file mode 100644 index 000000000..cd145feed --- /dev/null +++ b/backend/crates/core/src/http/response/utils.rs @@ -0,0 +1,65 @@ +use crate::model::{AdjId, BoardId, NumericKind, ProtectionKind, Severity}; +use serde::{Serialize, Serializer}; + +// Serialize domain types locally without changing the internal model. +pub(crate) fn serialize_board_id( + id: &BoardId, + serializer: S, +) -> Result { + serializer.serialize_u16(id.0) +} + +pub(crate) fn serialize_adj_id( + id: &AdjId, + serializer: S, +) -> Result { + serializer.serialize_u16(id.0) +} + +// Serialize numeric kind to match ADJv3 types. +pub(crate) fn serialize_numeric_kind( + kind: &NumericKind, + serializer: S, +) -> Result { + let name = match kind { + NumericKind::U8 => "uint8", + NumericKind::U16 => "uint16", + NumericKind::U32 => "uint32", + NumericKind::U64 => "uint64", + NumericKind::I8 => "int8", + NumericKind::I16 => "int16", + NumericKind::I32 => "int32", + NumericKind::I64 => "int64", + NumericKind::F32 => "float32", + NumericKind::F64 => "float64", + }; + serializer.serialize_str(name) +} + +// A remote derive keeps the JSON representation here, without changing model. +#[derive(Serialize)] +#[serde(remote = "ProtectionKind", tag = "type", rename_all = "snake_case")] +enum ProtectionKindDef { + Above { limit: f64 }, + Below { limit: f64 }, + Equal { target: f64 }, + NotEqual { target: f64 }, + Range { min: f64, max: f64 }, +} + +pub(crate) fn serialize_protection_kind( + kind: &ProtectionKind, + serializer: S, +) -> Result { + ProtectionKindDef::serialize(kind, serializer) +} + +pub(crate) fn serialize_severity( + severity: &Severity, + serializer: S, +) -> Result { + serializer.serialize_str(match severity { + Severity::Fault => "fault", + Severity::Warning => "warning", + }) +} From 77dd8113116aac9659926228b49411fb93544f66 Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Fri, 13 Nov 2026 13:41:13 +0100 Subject: [PATCH 111/225] feat(backend, http): add protectionpacket response structure and some more utils to serialize --- backend/crates/core/src/http/response.rs | 1 + .../core/src/http/response/protection.rs | 59 +++++++++++++++++++ .../crates/core/src/http/response/utils.rs | 19 ++++++ 3 files changed, 79 insertions(+) create mode 100644 backend/crates/core/src/http/response/protection.rs diff --git a/backend/crates/core/src/http/response.rs b/backend/crates/core/src/http/response.rs index 0c9be06ea..c6a8a1325 100644 --- a/backend/crates/core/src/http/response.rs +++ b/backend/crates/core/src/http/response.rs @@ -2,4 +2,5 @@ pub mod data; pub mod order; +pub mod protection; mod utils; diff --git a/backend/crates/core/src/http/response/protection.rs b/backend/crates/core/src/http/response/protection.rs new file mode 100644 index 000000000..ada304151 --- /dev/null +++ b/backend/crates/core/src/http/response/protection.rs @@ -0,0 +1,59 @@ +//! Flat ADJ v3 protection catalog returned by `/backend/adj/ProtectionPackets`. + +use std::{collections::HashMap, time::Duration}; + +use serde::Serialize; + +use crate::model::{AdjId, BoardId, ProtectionKind, Severity}; + +use super::utils::{ + serialize_adj_id, serialize_adj_protection_kind, serialize_board_id, serialize_severity, +}; + +/// Protection definitions and their display metadata, matching `example/protection.json`. +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct ProtectionResponse { + /// Flat list of protections, not grouped by board or measurement. + pub protections: Vec, + /// Contents of the ADJ's `protectionTypes`, keyed by names such as `Range`. + pub info: HashMap, +} + +/// A single protection definition referencing its board and measurement by id. +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct ProtectionInfoResponse { + /// Compound packet id already assigned by the ADJ loader. + /// Its low 13 bits identify the measurement and its high 3 bits the + /// one-based protection position. This is not the position alone. + #[serde(serialize_with = "serialize_adj_id")] + pub id: AdjId, + /// Name assigned to the synthesized protection packet by the loader. + pub name: String, + /// Id of the board declaring this protection. + #[serde(serialize_with = "serialize_board_id")] + pub board_id: BoardId, + /// Id of the watched measurement, also encoded in the compound packet id. + #[serde(serialize_with = "serialize_adj_id")] + pub measurement_id: AdjId, + /// Trigger condition; `type` preserves the ADJ name to index `info` directly. + #[serde(serialize_with = "serialize_adj_protection_kind")] + pub kind: ProtectionKind, + /// Severity serialized as `fault` or `warning`. + #[serde(serialize_with = "serialize_severity")] + pub severity: Severity, + /// Required duration, serialized as `{"secs": ..., "nanos": ...}`. + pub time: Duration, +} + +/// Display metadata for one entry of `general_info.json`'s `protectionTypes`. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct ProtectionTypeResponse { + /// Whether the protection takes an interval instead of a single bound. + #[serde(rename = "range")] + pub is_range: bool, + /// Display template; `{}` marks bounds and `%` the measured value. + pub text: String, + /// Optional time-related display template, omitted if absent from the ADJ. + #[serde(rename = "textTime", skip_serializing_if = "Option::is_none")] + pub text_time: Option, +} diff --git a/backend/crates/core/src/http/response/utils.rs b/backend/crates/core/src/http/response/utils.rs index cd145feed..99e880cfe 100644 --- a/backend/crates/core/src/http/response/utils.rs +++ b/backend/crates/core/src/http/response/utils.rs @@ -54,6 +54,25 @@ pub(crate) fn serialize_protection_kind( ProtectionKindDef::serialize(kind, serializer) } +// This endpoint indexes general_info.json's protectionTypes by the original +// ADJ names. Keep the order response's existing snake_case format unchanged. +#[derive(Serialize)] +#[serde(remote = "ProtectionKind", tag = "type")] +enum AdjProtectionKindDef { + Above { limit: f64 }, + Below { limit: f64 }, + Equal { target: f64 }, + NotEqual { target: f64 }, + Range { min: f64, max: f64 }, +} + +pub(crate) fn serialize_adj_protection_kind( + kind: &ProtectionKind, + serializer: S, +) -> Result { + AdjProtectionKindDef::serialize(kind, serializer) +} + pub(crate) fn serialize_severity( severity: &Severity, serializer: S, From 56e4d7332952d02865b84ecb907b60b36cd651d4 Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Fri, 13 Nov 2026 13:42:43 +0100 Subject: [PATCH 112/225] schema(backend, http): some simple example responses to understand the structure --- .../core/src/http/response/example/data.json | 95 +++++++++++++++++++ .../core/src/http/response/example/order.json | 78 +++++++++++++++ .../src/http/response/example/protection.json | 65 +++++++++++++ 3 files changed, 238 insertions(+) create mode 100644 backend/crates/core/src/http/response/example/data.json create mode 100644 backend/crates/core/src/http/response/example/order.json create mode 100644 backend/crates/core/src/http/response/example/protection.json diff --git a/backend/crates/core/src/http/response/example/data.json b/backend/crates/core/src/http/response/example/data.json new file mode 100644 index 000000000..06482e265 --- /dev/null +++ b/backend/crates/core/src/http/response/example/data.json @@ -0,0 +1,95 @@ +{ + "boards": [ + { + "id": 1, + "name": "LCU", + "packets": [ + { + "id": 936, + "name": "Temperatures", + "type": "data", + "period": 10.0, + "period_type": "ms", + "socket": "control_station_udp", + "measurements": [ + { + "id": 3000, + "alias": "temperature_1", + "name": "Motor temperature", + "display_units": "ºC", + "kind": { + "type": "numeric", + "wire_type": "float32" + } + } + ] + }, + { + "id": 967, + "name": "Levitation distance", + "type": "data", + "period": 10.0, + "period_type": "ms", + "socket": "control_station_udp", + "measurements": [ + { + "id": 3001, + "alias": "levitation_distance", + "name": "Levitation distance", + "display_units": "mm", + "kind": { + "type": "numeric", + "wire_type": "float32" + } + } + ] + } + ] + }, + { + "id": 2, + "name": "HVBMS", + "packets": [ + { + "id": 1200, + "name": "Battery voltage", + "type": "data", + "period": 20.0, + "period_type": "ms", + "socket": "control_station_udp", + "measurements": [ + { + "id": 3100, + "alias": "pack_voltage", + "name": "Pack voltage", + "display_units": "V", + "kind": { + "type": "numeric", + "wire_type": "float32" + } + } + ] + }, + { + "id": 1201, + "name": "Contactors status", + "type": "data", + "period": 100.0, + "period_type": "ms", + "socket": "control_station_udp", + "measurements": [ + { + "id": 3101, + "alias": "contactor_closed", + "name": "Contactor closed", + "display_units": "", + "kind": { + "type": "boolean" + } + } + ] + } + ] + } + ] +} diff --git a/backend/crates/core/src/http/response/example/order.json b/backend/crates/core/src/http/response/example/order.json new file mode 100644 index 000000000..f4951532b --- /dev/null +++ b/backend/crates/core/src/http/response/example/order.json @@ -0,0 +1,78 @@ +{ + "boards": [ + { + "id": 1, + "name": "LCU", + "orders": [ + { + "id": 1001, + "name": "Set target speed", + "type": "order", + "measurements": [ + { + "id": 3001, + "alias": "target_speed", + "name": "Target speed", + "display_units": "m/s", + "kind": { + "type": "numeric", + "wire_type": "float32" + }, + "protections": [ + { + "id": 1, + "kind": { + "type": "range", + "min": 0.0, + "max": 50.0 + }, + "severity": "fault", + "time": { + "secs": 0, + "nanos": 0 + } + }, + { + "id": 2, + "kind": { + "type": "above", + "limit": 40.0 + }, + "severity": "warning", + "time": { + "secs": 0, + "nanos": 500000000 + } + } + ] + } + ] + }, + { + "id": 1002, + "name": "Stop", + "type": "order", + "measurements": [] + } + ] + }, + { + "id": 2, + "name": "HVBMS", + "orders": [ + { + "id": 2001, + "name": "Open Contactors", + "type": "order", + "measurements": [] + }, + { + "id": 2003, + "name": "Start Precharge", + "type": "order", + "measurements": [] + } + ] + } + ] +} diff --git a/backend/crates/core/src/http/response/example/protection.json b/backend/crates/core/src/http/response/example/protection.json new file mode 100644 index 000000000..3c4cf66d7 --- /dev/null +++ b/backend/crates/core/src/http/response/example/protection.json @@ -0,0 +1,65 @@ +{ + "protections": [ + { + "id": 11192, + "name": "LCU_temperature_1_protection_1", + "board_id": 1, + "measurement_id": 3000, + "kind": { + "type": "Range", + "min": 0.0, + "max": 100.0 + }, + "severity": "fault", + "time": { + "secs": 0, + "nanos": 500000000 + } + }, + { + "id": 19384, + "name": "LCU_temperature_1_protection_2", + "board_id": 1, + "measurement_id": 3000, + "kind": { + "type": "Below", + "limit": 10.0 + }, + "severity": "warning", + "time": { + "secs": 1, + "nanos": 0 + } + }, + { + "id": 11292, + "name": "HVBMS_pack_voltage_protection_1", + "board_id": 2, + "measurement_id": 3100, + "kind": { + "type": "Range", + "min": 300.0, + "max": 500.0 + }, + "severity": "fault", + "time": { + "secs": 0, + "nanos": 0 + } + } + ], + "info": { + "Equal": { + "range": false, + "text": "Value is equal to {} (measured: %)" + }, + "Range": { + "range": true, + "text": "Value out of range {} (measured: %)" + }, + "Below": { + "range": false, + "text": "Value below {} (measured: %)" + } + } +} From 86726e5da92fd85f13357ee3251e50b1716621c9 Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Fri, 13 Nov 2026 14:00:11 +0100 Subject: [PATCH 113/225] fix(backend, http): delete unimportant fields in datapackets --- backend/crates/core/src/http/response/data.rs | 8 +------- .../crates/core/src/http/response/example/data.json | 12 ------------ 2 files changed, 1 insertion(+), 19 deletions(-) diff --git a/backend/crates/core/src/http/response/data.rs b/backend/crates/core/src/http/response/data.rs index 922608835..c16c1867f 100644 --- a/backend/crates/core/src/http/response/data.rs +++ b/backend/crates/core/src/http/response/data.rs @@ -39,12 +39,6 @@ pub struct DataPacketResponse { /// ADJ packet type: `data` for this endpoint. #[serde(rename = "type")] pub packet_type: String, - /// Declared transmission period, expressed in `period_type` units. - pub period: f64, - /// ADJ period unit, e.g. `ms`. - pub period_type: String, - /// Name of the socket declared by the ADJ. - pub socket: String, /// Measurement definitions in wire order, without protections. pub measurements: Vec, } @@ -82,4 +76,4 @@ pub enum DataMeasurementKind { /// Allowed variant names. options: Vec, }, -} \ No newline at end of file +} diff --git a/backend/crates/core/src/http/response/example/data.json b/backend/crates/core/src/http/response/example/data.json index 06482e265..e383f07eb 100644 --- a/backend/crates/core/src/http/response/example/data.json +++ b/backend/crates/core/src/http/response/example/data.json @@ -8,9 +8,6 @@ "id": 936, "name": "Temperatures", "type": "data", - "period": 10.0, - "period_type": "ms", - "socket": "control_station_udp", "measurements": [ { "id": 3000, @@ -28,9 +25,6 @@ "id": 967, "name": "Levitation distance", "type": "data", - "period": 10.0, - "period_type": "ms", - "socket": "control_station_udp", "measurements": [ { "id": 3001, @@ -54,9 +48,6 @@ "id": 1200, "name": "Battery voltage", "type": "data", - "period": 20.0, - "period_type": "ms", - "socket": "control_station_udp", "measurements": [ { "id": 3100, @@ -74,9 +65,6 @@ "id": 1201, "name": "Contactors status", "type": "data", - "period": 100.0, - "period_type": "ms", - "socket": "control_station_udp", "measurements": [ { "id": 3101, From c5c35626d1e65964e5e2c534eb690a366b345f3e Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Fri, 13 Nov 2026 14:18:36 +0100 Subject: [PATCH 114/225] feat(backend, http): setup functions for responses --- backend/crates/core/src/http/response.rs | 12 +- .../crates/core/src/http/response/setup.rs | 202 ++++++++++++++++++ 2 files changed, 211 insertions(+), 3 deletions(-) create mode 100644 backend/crates/core/src/http/response/setup.rs diff --git a/backend/crates/core/src/http/response.rs b/backend/crates/core/src/http/response.rs index c6a8a1325..c85f3ea0b 100644 --- a/backend/crates/core/src/http/response.rs +++ b/backend/crates/core/src/http/response.rs @@ -1,6 +1,12 @@ //! Models for HTTP response bodies. -pub mod data; -pub mod order; -pub mod protection; +mod data; +mod order; +mod protection; +mod setup; mod utils; + +pub use data::DataResponse; +pub use order::OrderResponse; +pub use protection::ProtectionResponse; +pub use setup::{data_response, order_response, protection_response}; diff --git a/backend/crates/core/src/http/response/setup.rs b/backend/crates/core/src/http/response/setup.rs new file mode 100644 index 000000000..d8c006e66 --- /dev/null +++ b/backend/crates/core/src/http/response/setup.rs @@ -0,0 +1,202 @@ +//! Builds HTTP response models from a loaded ADJ. + +use crate::{ + adj::Adj, + model::{MeasurementKind, PacketType}, +}; + +use super::data::{ + DataBoardResponse, DataMeasurementKind, DataMeasurementResponse, DataPacketResponse, + DataResponse, +}; +use super::order::{ + OrderBoardResponse, OrderMeasurementResponse, OrderPacketResponse, OrderProtectionResponse, + OrderResponse, +}; +use super::protection::{ProtectionInfoResponse, ProtectionResponse, ProtectionTypeResponse}; + +/// Builds the data catalog without modifying or consuming the ADJ. +/// +/// Boards and data packets are sorted by id. Boards without data packets are +/// retained with an empty list. Measurements keep their wire order and omit +/// protection metadata. +pub fn data_response(adj: &Adj) -> DataResponse { + let mut boards: Vec = adj + .pod_data + .boards + .values() + .map(|board| { + let mut packets: Vec = board + .packets + .values() + .filter_map(|packet| { + let PacketType::Data(measurements) = &packet.packet_type else { + return None; + }; + + Some(DataPacketResponse { + id: packet.id, + name: packet.name.clone(), + packet_type: "data".to_string(), + measurements: measurements + .iter() + .map(|measurement| DataMeasurementResponse { + id: measurement.id, + alias: measurement.alias.clone(), + name: measurement.name.clone(), + display_units: measurement.display_units.clone(), + kind: match &measurement.kind { + MeasurementKind::Numeric { wire_type } => { + DataMeasurementKind::Numeric { + wire_type: *wire_type, + } + } + MeasurementKind::Boolean => DataMeasurementKind::Boolean, + MeasurementKind::Enum { options } => { + DataMeasurementKind::Enum { + options: options.clone(), + } + } + }, + }) + .collect(), + }) + }) + .collect(); + packets.sort_unstable_by_key(|packet| packet.id.0); + + DataBoardResponse { + id: board.id, + name: board.name.clone(), + packets, + } + }) + .collect(); + boards.sort_unstable_by_key(|board| board.id.0); + + DataResponse { boards } +} + +/// Builds the order catalog without modifying or consuming the ADJ. +/// +/// Boards and orders are sorted by id. Boards without orders are retained with +/// an empty list. Parameters and their protections keep their ADJ order; +/// protection ids remain their one-based positions within each measurement. +pub fn order_response(adj: &Adj) -> OrderResponse { + let mut boards: Vec = adj + .pod_data + .boards + .values() + .map(|board| { + let mut orders: Vec = board + .packets + .values() + .filter_map(|packet| { + let PacketType::Order(measurements) = &packet.packet_type else { + return None; + }; + + Some(OrderPacketResponse { + id: packet.id, + name: packet.name.clone(), + packet_type: "order".to_string(), + measurements: measurements + .iter() + .map(|measurement| OrderMeasurementResponse { + id: measurement.id, + alias: measurement.alias.clone(), + name: measurement.name.clone(), + display_units: measurement.display_units.clone(), + kind: match &measurement.kind { + MeasurementKind::Numeric { wire_type } => { + DataMeasurementKind::Numeric { + wire_type: *wire_type, + } + } + MeasurementKind::Boolean => DataMeasurementKind::Boolean, + MeasurementKind::Enum { options } => { + DataMeasurementKind::Enum { + options: options.clone(), + } + } + }, + protections: measurement + .protections + .iter() + .map(|protection| OrderProtectionResponse { + id: protection.id, + kind: protection.kind, + severity: protection.severity, + time: protection.time, + }) + .collect(), + }) + .collect(), + }) + }) + .collect(); + orders.sort_unstable_by_key(|order| order.id.0); + + OrderBoardResponse { + id: board.id, + name: board.name.clone(), + orders, + } + }) + .collect(); + boards.sort_unstable_by_key(|board| board.id.0); + + OrderResponse { boards } +} + +/// Builds the flat protection catalog without modifying or consuming the ADJ. +/// +/// Protection packet ids and names are reused from the loader. The position in +/// each compound id selects its definition within the watched measurement. +/// Packets with no definition at that position are omitted. The resulting list +/// is sorted by packet id, then board id to break ties. +pub fn protection_response(adj: &Adj) -> ProtectionResponse { + let mut protections: Vec = adj + .pod_data + .boards + .values() + .flat_map(|board| board.packets.values()) + .filter_map(|packet| { + let PacketType::Protection(measurement) = &packet.packet_type else { + return None; + }; + + let index = usize::from(packet.id.protection_position()).checked_sub(1)?; + let protection = measurement.protections.get(index)?; + + Some(ProtectionInfoResponse { + id: packet.id, + name: packet.name.clone(), + board_id: packet.board, + measurement_id: measurement.id, + kind: protection.kind, + severity: protection.severity, + time: protection.time, + }) + }) + .collect(); + protections.sort_unstable_by_key(|protection| (protection.id.0, protection.board_id.0)); + + let info = adj + .info + .protection_types + .iter() + .map(|(name, metadata)| { + ( + name.clone(), + ProtectionTypeResponse { + is_range: metadata.is_range, + text: metadata.text.clone(), + text_time: metadata.text_time.clone(), + }, + ) + }) + .collect(); + + ProtectionResponse { protections, info } +} From 7bfb4332e99d83f386b40531caf8e6ca8a7e91b5 Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Fri, 13 Nov 2026 15:02:24 +0100 Subject: [PATCH 115/225] chore(backend, http): move response to new submodule http of module adj --- backend/crates/core/src/adj.rs | 3 +++ backend/crates/core/src/{http/response.rs => adj/http.rs} | 0 backend/crates/core/src/{http/response => adj/http}/data.rs | 0 .../core/src/{http/response => adj/http}/example/data.json | 0 .../core/src/{http/response => adj/http}/example/order.json | 0 .../src/{http/response => adj/http}/example/protection.json | 0 backend/crates/core/src/{http/response => adj/http}/order.rs | 0 .../crates/core/src/{http/response => adj/http}/protection.rs | 0 backend/crates/core/src/{http/response => adj/http}/setup.rs | 0 backend/crates/core/src/{http/response => adj/http}/utils.rs | 0 backend/crates/core/src/http.rs | 1 - 11 files changed, 3 insertions(+), 1 deletion(-) rename backend/crates/core/src/{http/response.rs => adj/http.rs} (100%) rename backend/crates/core/src/{http/response => adj/http}/data.rs (100%) rename backend/crates/core/src/{http/response => adj/http}/example/data.json (100%) rename backend/crates/core/src/{http/response => adj/http}/example/order.json (100%) rename backend/crates/core/src/{http/response => adj/http}/example/protection.json (100%) rename backend/crates/core/src/{http/response => adj/http}/order.rs (100%) rename backend/crates/core/src/{http/response => adj/http}/protection.rs (100%) rename backend/crates/core/src/{http/response => adj/http}/setup.rs (100%) rename backend/crates/core/src/{http/response => adj/http}/utils.rs (100%) diff --git a/backend/crates/core/src/adj.rs b/backend/crates/core/src/adj.rs index ccd420add..7633fd818 100644 --- a/backend/crates/core/src/adj.rs +++ b/backend/crates/core/src/adj.rs @@ -20,6 +20,9 @@ mod error; mod info; mod raw; +#[cfg(feature = "http")] +pub mod http; + #[cfg(feature = "git")] use std::path::PathBuf; #[cfg(feature = "git")] diff --git a/backend/crates/core/src/http/response.rs b/backend/crates/core/src/adj/http.rs similarity index 100% rename from backend/crates/core/src/http/response.rs rename to backend/crates/core/src/adj/http.rs diff --git a/backend/crates/core/src/http/response/data.rs b/backend/crates/core/src/adj/http/data.rs similarity index 100% rename from backend/crates/core/src/http/response/data.rs rename to backend/crates/core/src/adj/http/data.rs diff --git a/backend/crates/core/src/http/response/example/data.json b/backend/crates/core/src/adj/http/example/data.json similarity index 100% rename from backend/crates/core/src/http/response/example/data.json rename to backend/crates/core/src/adj/http/example/data.json diff --git a/backend/crates/core/src/http/response/example/order.json b/backend/crates/core/src/adj/http/example/order.json similarity index 100% rename from backend/crates/core/src/http/response/example/order.json rename to backend/crates/core/src/adj/http/example/order.json diff --git a/backend/crates/core/src/http/response/example/protection.json b/backend/crates/core/src/adj/http/example/protection.json similarity index 100% rename from backend/crates/core/src/http/response/example/protection.json rename to backend/crates/core/src/adj/http/example/protection.json diff --git a/backend/crates/core/src/http/response/order.rs b/backend/crates/core/src/adj/http/order.rs similarity index 100% rename from backend/crates/core/src/http/response/order.rs rename to backend/crates/core/src/adj/http/order.rs diff --git a/backend/crates/core/src/http/response/protection.rs b/backend/crates/core/src/adj/http/protection.rs similarity index 100% rename from backend/crates/core/src/http/response/protection.rs rename to backend/crates/core/src/adj/http/protection.rs diff --git a/backend/crates/core/src/http/response/setup.rs b/backend/crates/core/src/adj/http/setup.rs similarity index 100% rename from backend/crates/core/src/http/response/setup.rs rename to backend/crates/core/src/adj/http/setup.rs diff --git a/backend/crates/core/src/http/response/utils.rs b/backend/crates/core/src/adj/http/utils.rs similarity index 100% rename from backend/crates/core/src/http/response/utils.rs rename to backend/crates/core/src/adj/http/utils.rs diff --git a/backend/crates/core/src/http.rs b/backend/crates/core/src/http.rs index ca413fc77..5086b05ab 100644 --- a/backend/crates/core/src/http.rs +++ b/backend/crates/core/src/http.rs @@ -4,7 +4,6 @@ //! This reports that HTTP is responding, not that the vehicle is ready. mod handlers; -pub mod response; mod server; pub use server::serve; From 48f4abd70d078ea3fcd8d12ca603b503d08a3e5d Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Fri, 13 Nov 2026 15:14:07 +0100 Subject: [PATCH 116/225] chore(backend, http): move http to station, change http dependencies --- backend/Cargo.lock | 9 +++++---- backend/crates/core/Cargo.toml | 6 ++---- backend/crates/core/src/http.rs | 9 --------- backend/crates/core/src/lib.rs | 5 +---- backend/crates/station/Cargo.toml | 6 ++++-- backend/crates/station/src/http.rs | 0 backend/crates/station/src/lib.rs | 1 + 7 files changed, 13 insertions(+), 23 deletions(-) delete mode 100644 backend/crates/core/src/http.rs create mode 100644 backend/crates/station/src/http.rs create mode 100644 backend/crates/station/src/lib.rs diff --git a/backend/Cargo.lock b/backend/Cargo.lock index 6c129a49e..ee029ddc0 100644 --- a/backend/Cargo.lock +++ b/backend/Cargo.lock @@ -192,9 +192,9 @@ checksum = "7354288c522e7e980fafd2075d63d1285794c3a6a16cdd492f189ea406e5f18b" [[package]] name = "cc" -version = "1.11.1" +version = "1.11.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ff2a8126fff0f8c839080d619675a585e61720bb12d2baceae45769fd66f155" +checksum = "33ef9e3e8154a45c7a95cff4c1299702106ad94062d7bb85fdc5d3a5afd91d45" dependencies = [ "find-msvc-tools", "jobserver", @@ -2904,7 +2904,6 @@ dependencies = [ name = "software-core" version = "0.1.0" dependencies = [ - "axum", "bytes", "dirs", "gix", @@ -2914,7 +2913,6 @@ dependencies = [ "tempfile", "thiserror", "tokio", - "tower", "tracing", "tracing-appender", "tracing-subscriber", @@ -2930,11 +2928,14 @@ checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" name = "station" version = "0.1.0" dependencies = [ + "axum", "serde", + "serde_json", "software-core", "thiserror", "tokio", "toml", + "tower", "tracing", "tracing-subscriber", ] diff --git a/backend/crates/core/Cargo.toml b/backend/crates/core/Cargo.toml index 50bcde557..e9476294c 100644 --- a/backend/crates/core/Cargo.toml +++ b/backend/crates/core/Cargo.toml @@ -22,8 +22,8 @@ pcap = ["net"] logger = [] # Reusable tracing/diagnostics setup (console + non-blocking file + stderr layers) trace = ["dep:tracing-subscriber", "dep:tracing-appender"] -# HTTP -http = ["dep:tokio"] +# Structure responses for HTTP petitions +http = [] [dependencies] bytes.workspace = true @@ -38,8 +38,6 @@ gix = { version = "0.87.1", optional = true, features = ["blocking-http-transpor dirs = { version = "7.0.0", optional = true } tempfile = { version = "3.27", optional = true } ntp_usg-server = { version = "5.0.0", optional = true, features = ["ipv4", "tokio"] } -axum = { version = "0.8.9", features = ["ws", "http2", "http1"] } -tower = { version = "0.5.3", features = ["util"] } # `workspace = true` can't be combined with extra lints in the same table, # so the workspace list is repeated here with `missing_docs` added: this is diff --git a/backend/crates/core/src/http.rs b/backend/crates/core/src/http.rs deleted file mode 100644 index 5086b05ab..000000000 --- a/backend/crates/core/src/http.rs +++ /dev/null @@ -1,9 +0,0 @@ -//! HTTP server built on Axum. -//! -//! Currently exposes only `GET /health`, returning `{"status":"ok"}`. -//! This reports that HTTP is responding, not that the vehicle is ready. - -mod handlers; -mod server; - -pub use server::serve; diff --git a/backend/crates/core/src/lib.rs b/backend/crates/core/src/lib.rs index 23d062bf2..40cf80793 100644 --- a/backend/crates/core/src/lib.rs +++ b/backend/crates/core/src/lib.rs @@ -24,7 +24,4 @@ pub mod adj; /// Translates bytes into typed packets and back, using the shapes /// [`adj`] declares as the schema. See [`protocol::wire`], /// [`protocol::tcp`], [`protocol::udp`]. -pub mod protocol; - -#[cfg(feature = "http")] -pub mod http; \ No newline at end of file +pub mod protocol; \ No newline at end of file diff --git a/backend/crates/station/Cargo.toml b/backend/crates/station/Cargo.toml index 20c403657..7855005ac 100644 --- a/backend/crates/station/Cargo.toml +++ b/backend/crates/station/Cargo.toml @@ -9,14 +9,16 @@ authors.workspace = true repository.workspace = true [dependencies] -software-core = { workspace = true, features = ["net", "git"] } - +software-core = { workspace = true, features = ["net", "git", "http"] } serde.workspace = true thiserror.workspace = true tokio.workspace = true toml.workspace = true tracing.workspace = true tracing-subscriber.workspace = true +serde_json.workspace = true +tower = "0.5.3" +axum = { version = "0.8.9", features = ["ws", "http1", "http2"] } [lints] workspace = true diff --git a/backend/crates/station/src/http.rs b/backend/crates/station/src/http.rs new file mode 100644 index 000000000..e69de29bb diff --git a/backend/crates/station/src/lib.rs b/backend/crates/station/src/lib.rs new file mode 100644 index 000000000..e05256f75 --- /dev/null +++ b/backend/crates/station/src/lib.rs @@ -0,0 +1 @@ +pub mod http; \ No newline at end of file From 8f3c53da6655823354462527c0fe6f77fdd217e4 Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Fri, 13 Nov 2026 16:07:55 +0100 Subject: [PATCH 117/225] feat(backend, http): handlers for each endpoint --- backend/crates/station/src/http/handlers.rs | 33 +++++++++++++++++++++ backend/crates/station/src/lib.rs | 1 - 2 files changed, 33 insertions(+), 1 deletion(-) create mode 100644 backend/crates/station/src/http/handlers.rs delete mode 100644 backend/crates/station/src/lib.rs diff --git a/backend/crates/station/src/http/handlers.rs b/backend/crates/station/src/http/handlers.rs new file mode 100644 index 000000000..41b48ce6b --- /dev/null +++ b/backend/crates/station/src/http/handlers.rs @@ -0,0 +1,33 @@ +use std::sync::Arc; + +use axum::{Json, extract::State}; +use software_core::{adj::{Adj, http::{DataResponse, OrderResponse, ProtectionResponse, data_response, order_response, protection_response}}}; + +pub(super) struct Responses { + pub(super) data_response: DataResponse, + pub(super) order_response: OrderResponse, + pub(super) protection_response: ProtectionResponse +} + +impl Responses { + pub fn new(adj: &Adj) -> Self { + Self { + data_response: data_response(adj), + order_response: order_response(adj), + protection_response: protection_response(adj) + } + } +} + +pub(super) async fn data_packet(State(responses): State>) -> Json { + Json(responses.data_response.clone()) +} + +pub(super) async fn order_packet(State(responses): State>) -> Json { + Json(responses.order_response.clone()) +} + +pub(super) async fn protection_packet(State(responses): State>) -> Json { + Json(responses.protection_response.clone()) +} + diff --git a/backend/crates/station/src/lib.rs b/backend/crates/station/src/lib.rs deleted file mode 100644 index e05256f75..000000000 --- a/backend/crates/station/src/lib.rs +++ /dev/null @@ -1 +0,0 @@ -pub mod http; \ No newline at end of file From d5174f63706c80db2cb7abb3d51457e3c09a1a59 Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Fri, 13 Nov 2026 16:09:22 +0100 Subject: [PATCH 118/225] feat(backend, http): basic server with 3 enpoints --- backend/crates/station/src/http.rs | 4 +++ backend/crates/station/src/http/server.rs | 39 +++++++++++++++++++++++ backend/crates/station/src/main.rs | 13 +++++++- 3 files changed, 55 insertions(+), 1 deletion(-) create mode 100644 backend/crates/station/src/http/server.rs diff --git a/backend/crates/station/src/http.rs b/backend/crates/station/src/http.rs index e69de29bb..0549b6199 100644 --- a/backend/crates/station/src/http.rs +++ b/backend/crates/station/src/http.rs @@ -0,0 +1,4 @@ +mod handlers; +mod server; + +pub use server::serve; \ No newline at end of file diff --git a/backend/crates/station/src/http/server.rs b/backend/crates/station/src/http/server.rs new file mode 100644 index 000000000..35704e3ce --- /dev/null +++ b/backend/crates/station/src/http/server.rs @@ -0,0 +1,39 @@ +use std::io; + +use axum::{Router, routing::get}; +use software_core::adj::Adj; +use tokio::{net::TcpListener}; +use std::sync::Arc; + +use crate::http::handlers::{Responses, data_packet, order_packet, protection_packet}; + +/// Serves HTTP requests on an already-bound listener. +/// +/// The caller chooses the interface and port when binding the listener. +/// This future runs until the server stops; await it or spawn it on Tokio. +/// +/// # Errors +/// +/// Returns errors reported by Axum's server. +pub async fn serve(listener: TcpListener, adj: &Adj) -> io::Result<()> { + axum::serve(listener, router(adj)).await +} + +fn router(adj: &Adj) -> Router { + let responses = Arc::new(Responses::new(adj)); + + Router::new() + .route( + "/backend/adj/DataPackets", + get(data_packet) + ) + .route( + "/backend/adj/OrderPackets", + get(order_packet) + ) + .route( + "/backend/adj/ProtectionPackets", + get(protection_packet) + ) + .with_state(responses) +} \ No newline at end of file diff --git a/backend/crates/station/src/main.rs b/backend/crates/station/src/main.rs index 27767e13f..b4fb5790e 100644 --- a/backend/crates/station/src/main.rs +++ b/backend/crates/station/src/main.rs @@ -1,8 +1,10 @@ //! Ejecutable mínimo para demostrar la integración con `software-core`. use tracing_subscriber::EnvFilter; +use tokio::net::TcpListener; -fn main() { +#[tokio::main] +async fn main() -> Result<(), std::io::Error>{ let filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info")); tracing_subscriber::fmt().with_env_filter(filter).init(); @@ -21,5 +23,14 @@ fn main() { }; tracing::info!(boards = adj.pod_data.boards.len(), "adj de prueba cargado"); + // Just testing, not the actual address + let listener = TcpListener::bind("127.0.0.1:8080").await?; + + http::serve(listener, &adj).await?; + tracing::info!("demo finalizada"); + + Ok(()) } + +mod http; \ No newline at end of file From 8c666f7a4cf814c76ebb1747f459a1fadb1a8bd6 Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Fri, 13 Nov 2026 16:19:38 +0100 Subject: [PATCH 119/225] fix(backend, http): efficient responses for endpoint (no clone) --- backend/crates/station/src/http/handlers.rs | 46 +++++++++++++-------- 1 file changed, 29 insertions(+), 17 deletions(-) diff --git a/backend/crates/station/src/http/handlers.rs b/backend/crates/station/src/http/handlers.rs index 41b48ce6b..d40829702 100644 --- a/backend/crates/station/src/http/handlers.rs +++ b/backend/crates/station/src/http/handlers.rs @@ -1,33 +1,45 @@ use std::sync::Arc; -use axum::{Json, extract::State}; -use software_core::{adj::{Adj, http::{DataResponse, OrderResponse, ProtectionResponse, data_response, order_response, protection_response}}}; +use axum::{ + body::Bytes, + extract::State, + http::header, + response::{IntoResponse, Response}, +}; +use software_core::adj::{ + Adj, + http::{data_response, order_response, protection_response}, +}; pub(super) struct Responses { - pub(super) data_response: DataResponse, - pub(super) order_response: OrderResponse, - pub(super) protection_response: ProtectionResponse + data_response: Bytes, + order_response: Bytes, + protection_response: Bytes, } impl Responses { - pub fn new(adj: &Adj) -> Self { - Self { - data_response: data_response(adj), - order_response: order_response(adj), - protection_response: protection_response(adj) - } + // Serialize once at startup; Bytes clones share the existing JSON buffer. + pub(super) fn new(adj: &Adj) -> Result { + Ok(Self { + data_response: serde_json::to_vec(&data_response(adj))?.into(), + order_response: serde_json::to_vec(&order_response(adj))?.into(), + protection_response: serde_json::to_vec(&protection_response(adj))?.into(), + }) } } -pub(super) async fn data_packet(State(responses): State>) -> Json { - Json(responses.data_response.clone()) +pub(super) async fn data_packet(State(responses): State>) -> Response { + json_response(responses.data_response.clone()) } -pub(super) async fn order_packet(State(responses): State>) -> Json { - Json(responses.order_response.clone()) +pub(super) async fn order_packet(State(responses): State>) -> Response { + json_response(responses.order_response.clone()) } -pub(super) async fn protection_packet(State(responses): State>) -> Json { - Json(responses.protection_response.clone()) +pub(super) async fn protection_packet(State(responses): State>) -> Response { + json_response(responses.protection_response.clone()) } +fn json_response(body: Bytes) -> Response { + ([(header::CONTENT_TYPE, "application/json")], body).into_response() +} From caee95da0a9575b8d68b55e950fa98c8151c26cb Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Fri, 13 Nov 2026 16:22:24 +0100 Subject: [PATCH 120/225] test(backend, http): add tests to server --- backend/crates/station/src/http/server.rs | 116 +++++++++++++++++----- backend/crates/station/src/main.rs | 6 +- 2 files changed, 96 insertions(+), 26 deletions(-) diff --git a/backend/crates/station/src/http/server.rs b/backend/crates/station/src/http/server.rs index 35704e3ce..43780a113 100644 --- a/backend/crates/station/src/http/server.rs +++ b/backend/crates/station/src/http/server.rs @@ -1,9 +1,8 @@ -use std::io; +use std::{io, sync::Arc}; use axum::{Router, routing::get}; use software_core::adj::Adj; -use tokio::{net::TcpListener}; -use std::sync::Arc; +use tokio::net::TcpListener; use crate::http::handlers::{Responses, data_packet, order_packet, protection_packet}; @@ -14,26 +13,97 @@ use crate::http::handlers::{Responses, data_packet, order_packet, protection_pac /// /// # Errors /// -/// Returns errors reported by Axum's server. +/// Returns errors serializing the catalogs at startup or reported by Axum's server. pub async fn serve(listener: TcpListener, adj: &Adj) -> io::Result<()> { - axum::serve(listener, router(adj)).await + axum::serve(listener, router(adj)?).await } -fn router(adj: &Adj) -> Router { - let responses = Arc::new(Responses::new(adj)); - - Router::new() - .route( - "/backend/adj/DataPackets", - get(data_packet) - ) - .route( - "/backend/adj/OrderPackets", - get(order_packet) - ) - .route( - "/backend/adj/ProtectionPackets", - get(protection_packet) - ) - .with_state(responses) -} \ No newline at end of file +fn router(adj: &Adj) -> io::Result { + let responses = Arc::new(Responses::new(adj).map_err(io::Error::other)?); + + Ok(Router::new() + .route("/backend/adj/DataPackets", get(data_packet)) + .route("/backend/adj/OrderPackets", get(order_packet)) + .route("/backend/adj/ProtectionPackets", get(protection_packet)) + .with_state(responses)) +} + +#[cfg(test)] +mod tests { + use std::path::Path; + + use axum::{ + body::{Body, to_bytes}, + http::{Request, StatusCode, header}, + }; + use software_core::adj::{ + Adj, + http::{data_response, order_response, protection_response}, + load_from_dir, + }; + use tower::ServiceExt; + + use super::router; + + const PATHS: [&str; 3] = [ + "/backend/adj/DataPackets", + "/backend/adj/OrderPackets", + "/backend/adj/ProtectionPackets", + ]; + + #[tokio::test] + async fn catalogs_return_cached_json() -> Result<(), Box> { + let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("../core/src/adj/test/adj"); + let adj = load_from_dir(&path)?; + let expected = [ + serde_json::to_value(data_response(&adj))?, + serde_json::to_value(order_response(&adj))?, + serde_json::to_value(protection_response(&adj))?, + ]; + let app = router(&adj)?; + drop(adj); + + for (path, expected) in PATHS.into_iter().zip(expected) { + let mut previous_body = None; + for _ in 0..2 { + let response = app + .clone() + .oneshot(Request::builder().uri(path).body(Body::empty())?) + .await?; + + assert_eq!(response.status(), StatusCode::OK); + assert_eq!(response.headers()[header::CONTENT_TYPE], "application/json"); + let body = to_bytes(response.into_body(), usize::MAX).await?; + let actual: serde_json::Value = serde_json::from_slice(&body)?; + assert_eq!(actual, expected); + if let Some(previous) = previous_body { + assert_eq!(body, previous); + } + previous_body = Some(body); + } + } + Ok(()) + } + + #[tokio::test] + async fn empty_catalogs_return_json_objects() -> Result<(), Box> { + let app = router(&Adj::default())?; + let expected = [ + serde_json::json!({"boards": []}), + serde_json::json!({"boards": []}), + serde_json::json!({"protections": [], "info": {}}), + ]; + + for (path, expected) in PATHS.into_iter().zip(expected) { + let response = app + .clone() + .oneshot(Request::builder().uri(path).body(Body::empty())?) + .await?; + assert_eq!(response.status(), StatusCode::OK); + let body = to_bytes(response.into_body(), 1024).await?; + let actual: serde_json::Value = serde_json::from_slice(&body)?; + assert_eq!(actual, expected); + } + Ok(()) + } +} diff --git a/backend/crates/station/src/main.rs b/backend/crates/station/src/main.rs index b4fb5790e..06ce2789e 100644 --- a/backend/crates/station/src/main.rs +++ b/backend/crates/station/src/main.rs @@ -1,10 +1,10 @@ //! Ejecutable mínimo para demostrar la integración con `software-core`. -use tracing_subscriber::EnvFilter; use tokio::net::TcpListener; +use tracing_subscriber::EnvFilter; #[tokio::main] -async fn main() -> Result<(), std::io::Error>{ +async fn main() -> std::io::Result<()> { let filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info")); tracing_subscriber::fmt().with_env_filter(filter).init(); @@ -33,4 +33,4 @@ async fn main() -> Result<(), std::io::Error>{ Ok(()) } -mod http; \ No newline at end of file +mod http; From e484ad3e5b1485ce46a5ac82699d5f9b4be86750 Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Fri, 13 Nov 2026 16:45:53 +0100 Subject: [PATCH 121/225] docs(backend, http): docs in adj module --- backend/crates/core/src/adj/README.md | 4 ++- backend/crates/core/src/adj/http/README.md | 39 ++++++++++++++++++++++ 2 files changed, 42 insertions(+), 1 deletion(-) create mode 100644 backend/crates/core/src/adj/http/README.md diff --git a/backend/crates/core/src/adj/README.md b/backend/crates/core/src/adj/README.md index c167bdfbc..a468ad4de 100644 --- a/backend/crates/core/src/adj/README.md +++ b/backend/crates/core/src/adj/README.md @@ -2,6 +2,8 @@ This module deserializes, validates, and loads ADJ JSON fixtures into the backend domain model. +The `http` submodule converts a loaded `Adj` into serializable data, order, and protection catalogs for HTTP responses. It defines response bodies, not routes or a server. See the [HTTP submodule README](http/README.md) for usage and JSON examples. + For schema specifications, packet/measurement ID conventions, and network requirements, refer directly to the official documentation in the **ADJ repository**. --- @@ -89,4 +91,4 @@ The `Adj` object enforces a clear architectural boundary between **vehicle topol The raw deserialization types and the loader logic live isolated inside `raw`[cite: 2]. This enables non-station tools (such as bus sniffers, test runners, or simulators) to parse and ingest ADJ directories without dragging along application-level UI or station state logic. ### 3. Unified Packet Map (`packets`) -Protections defined under measurements are materialized during loading as first-class `PacketType::Protection(Measurement)` packets alongside the explicit data, order and message packets declared in `packets.json`. Downstream networking layers can route and handle every wire event uniformly via `Board::packets` without needing specialized traversal logic for nested measurement alarms. `packets.json` itself never declares a `"type": "protection"` entry directly — that shape only exists synthesized, one per protection a measurement declares, never as a free-standing declaration with its own arbitrary variable list. \ No newline at end of file +Protections defined under measurements are materialized during loading as first-class `PacketType::Protection(Measurement)` packets alongside the explicit data, order and message packets declared in `packets.json`. Downstream networking layers can route and handle every wire event uniformly via `Board::packets` without needing specialized traversal logic for nested measurement alarms. `packets.json` itself never declares a `"type": "protection"` entry directly — that shape only exists synthesized, one per protection a measurement declares, never as a free-standing declaration with its own arbitrary variable list. diff --git a/backend/crates/core/src/adj/http/README.md b/backend/crates/core/src/adj/http/README.md new file mode 100644 index 000000000..ce881f870 --- /dev/null +++ b/backend/crates/core/src/adj/http/README.md @@ -0,0 +1,39 @@ +# ADJ HTTP (`adj::http`) + +Builds serializable HTTP response bodies from a loaded `Adj`, without modifying +or consuming it. This submodule contains catalog models and builders only; +HTTP routes and server setup belong to the application. + +## Catalogs + +| Builder | Response | Contents | JSON example | +| --- | --- | --- | --- | +| `data_response(&adj)` | `DataResponse` | Data packets grouped by board, with measurement definitions but no protections. | [data.json](example/data.json) | +| `order_response(&adj)` | `OrderResponse` | Orders grouped by board, including parameters and their protections. | [order.json](example/order.json) | +| `protection_response(&adj)` | `ProtectionResponse` | Flat protection list and display metadata from the ADJ's `protectionTypes`. | [protection.json](example/protection.json) | + +These are definitions, not live telemetry, order execution requests, or triggered +protection events. Boards and their packets/orders are sorted by ID; measurement +order is preserved. The flat protection list is sorted by packet ID, then board ID. + +## Usage + +Enable the `http` feature in the application's dependency: + +```bash +cargo add software-core -F http +``` + +With an already loaded `adj`: + +```rust +use software_core::adj::http::{data_response, order_response, protection_response}; + +let data = data_response(&adj); +let orders = order_response(&adj); +let protections = protection_response(&adj); +``` + +All three responses implement `serde::Serialize`, so the application can return +them as JSON using its HTTP framework. Serialization details are kept here, +without changing the internal domain model. From 05d2783dad854ac07b0becda980ad0eb58c6acb8 Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Fri, 13 Nov 2026 17:21:24 +0100 Subject: [PATCH 122/225] refactor(backend, http): implementation in struct Adj of setups --- backend/crates/core/src/adj.rs | 205 ++++++++++++++++++ backend/crates/core/src/adj/http.rs | 9 +- backend/crates/core/src/adj/http/data.rs | 7 +- backend/crates/core/src/adj/http/order.rs | 12 +- .../crates/core/src/adj/http/protection.rs | 9 +- backend/crates/core/src/adj/http/setup.rs | 202 ----------------- backend/crates/core/src/lib.rs | 5 +- backend/crates/core/src/utils.rs | 2 + .../{adj/http/utils.rs => utils/serialize.rs} | 0 9 files changed, 230 insertions(+), 221 deletions(-) delete mode 100644 backend/crates/core/src/adj/http/setup.rs create mode 100644 backend/crates/core/src/utils.rs rename backend/crates/core/src/{adj/http/utils.rs => utils/serialize.rs} (100%) diff --git a/backend/crates/core/src/adj.rs b/backend/crates/core/src/adj.rs index 7633fd818..854800f4f 100644 --- a/backend/crates/core/src/adj.rs +++ b/backend/crates/core/src/adj.rs @@ -47,6 +47,211 @@ pub struct Adj { pub info: AdjInfo, } +#[cfg(feature = "http")] +use self::http::{ + data::{ + DataBoardResponse, DataMeasurementKind, DataMeasurementResponse, DataPacketResponse, + DataResponse, + }, + order::{ + OrderBoardResponse, OrderMeasurementResponse, OrderPacketResponse, OrderProtectionResponse, + OrderResponse, + }, + protection::{ProtectionInfoResponse, ProtectionResponse, ProtectionTypeResponse}, +}; + +#[cfg(feature = "http")] +use crate::model::{MeasurementKind, PacketType}; + +#[cfg(feature = "http")] +impl Adj { + /// Builds the data catalog without modifying or consuming the ADJ. + /// + /// Boards and data packets are sorted by id. Boards without data packets are + /// retained with an empty list. Measurements keep their wire order and omit + /// protection metadata. + pub fn data_response(&self) -> DataResponse { + let mut boards: Vec = self + .pod_data + .boards + .values() + .map(|board| { + let mut packets: Vec = board + .packets + .values() + .filter_map(|packet| { + let PacketType::Data(measurements) = &packet.packet_type else { + return None; + }; + + Some(DataPacketResponse { + id: packet.id, + name: packet.name.clone(), + packet_type: "data".to_string(), + measurements: measurements + .iter() + .map(|measurement| DataMeasurementResponse { + id: measurement.id, + alias: measurement.alias.clone(), + name: measurement.name.clone(), + display_units: measurement.display_units.clone(), + kind: match &measurement.kind { + MeasurementKind::Numeric { wire_type } => { + DataMeasurementKind::Numeric { + wire_type: *wire_type, + } + } + MeasurementKind::Boolean => DataMeasurementKind::Boolean, + MeasurementKind::Enum { options } => { + DataMeasurementKind::Enum { + options: options.clone(), + } + } + }, + }) + .collect(), + }) + }) + .collect(); + packets.sort_unstable_by_key(|packet| packet.id.0); + + DataBoardResponse { + id: board.id, + name: board.name.clone(), + packets, + } + }) + .collect(); + boards.sort_unstable_by_key(|board| board.id.0); + + DataResponse { boards } + } + + /// Builds the order catalog without modifying or consuming the ADJ. + /// + /// Boards and orders are sorted by id. Boards without orders are retained with + /// an empty list. Parameters and their protections keep their ADJ order; + /// protection ids remain their one-based positions within each measurement. + pub fn order_response(&self) -> OrderResponse { + let mut boards: Vec = self + .pod_data + .boards + .values() + .map(|board| { + let mut orders: Vec = board + .packets + .values() + .filter_map(|packet| { + let PacketType::Order(measurements) = &packet.packet_type else { + return None; + }; + + Some(OrderPacketResponse { + id: packet.id, + name: packet.name.clone(), + packet_type: "order".to_string(), + measurements: measurements + .iter() + .map(|measurement| OrderMeasurementResponse { + id: measurement.id, + alias: measurement.alias.clone(), + name: measurement.name.clone(), + display_units: measurement.display_units.clone(), + kind: match &measurement.kind { + MeasurementKind::Numeric { wire_type } => { + DataMeasurementKind::Numeric { + wire_type: *wire_type, + } + } + MeasurementKind::Boolean => DataMeasurementKind::Boolean, + MeasurementKind::Enum { options } => { + DataMeasurementKind::Enum { + options: options.clone(), + } + } + }, + protections: measurement + .protections + .iter() + .map(|protection| OrderProtectionResponse { + id: protection.id, + kind: protection.kind, + severity: protection.severity, + time: protection.time, + }) + .collect(), + }) + .collect(), + }) + }) + .collect(); + orders.sort_unstable_by_key(|order| order.id.0); + + OrderBoardResponse { + id: board.id, + name: board.name.clone(), + orders, + } + }) + .collect(); + boards.sort_unstable_by_key(|board| board.id.0); + + OrderResponse { boards } + } + + /// Builds the flat protection catalog without modifying or consuming the ADJ. + /// + /// Protection packet ids and names are reused from the loader. The position in + /// each compound id selects its definition within the watched measurement. + /// Packets with no definition at that position are omitted. The resulting list + /// is sorted by packet id, then board id to break ties. + pub fn protection_response(&self) -> ProtectionResponse { + let mut protections: Vec = self + .pod_data + .boards + .values() + .flat_map(|board| board.packets.values()) + .filter_map(|packet| { + let PacketType::Protection(measurement) = &packet.packet_type else { + return None; + }; + + let index = usize::from(packet.id.protection_position()).checked_sub(1)?; + let protection = measurement.protections.get(index)?; + + Some(ProtectionInfoResponse { + id: packet.id, + name: packet.name.clone(), + board_id: packet.board, + measurement_id: measurement.id, + kind: protection.kind, + severity: protection.severity, + time: protection.time, + }) + }) + .collect(); + protections.sort_unstable_by_key(|protection| (protection.id.0, protection.board_id.0)); + + let info = self + .info + .protection_types + .iter() + .map(|(name, metadata)| { + ( + name.clone(), + ProtectionTypeResponse { + is_range: metadata.is_range, + text: metadata.text.clone(), + text_time: metadata.text_time.clone(), + }, + ) + }) + .collect(); + + ProtectionResponse { protections, info } + } +} + /// The result of [`auto_adj`]: the loaded ADJ data and the checked-out commit hash. #[cfg(feature = "git")] #[derive(Debug, Clone)] diff --git a/backend/crates/core/src/adj/http.rs b/backend/crates/core/src/adj/http.rs index c85f3ea0b..d577f026c 100644 --- a/backend/crates/core/src/adj/http.rs +++ b/backend/crates/core/src/adj/http.rs @@ -1,12 +1,9 @@ //! Models for HTTP response bodies. -mod data; -mod order; -mod protection; -mod setup; -mod utils; +pub(super) mod data; +pub(super) mod order; +pub(super) mod protection; pub use data::DataResponse; pub use order::OrderResponse; pub use protection::ProtectionResponse; -pub use setup::{data_response, order_response, protection_response}; diff --git a/backend/crates/core/src/adj/http/data.rs b/backend/crates/core/src/adj/http/data.rs index c16c1867f..dbb1778dc 100644 --- a/backend/crates/core/src/adj/http/data.rs +++ b/backend/crates/core/src/adj/http/data.rs @@ -2,9 +2,10 @@ use serde::Serialize; -use crate::model::{AdjId, BoardId, NumericKind}; - -use super::utils::{serialize_adj_id, serialize_board_id, serialize_numeric_kind}; +use crate::{ + model::{AdjId, BoardId, NumericKind}, + utils::serialize::{serialize_adj_id, serialize_board_id, serialize_numeric_kind}, +}; /// Data packet definitions grouped by board. /// diff --git a/backend/crates/core/src/adj/http/order.rs b/backend/crates/core/src/adj/http/order.rs index 1845f0d94..330615022 100644 --- a/backend/crates/core/src/adj/http/order.rs +++ b/backend/crates/core/src/adj/http/order.rs @@ -4,13 +4,15 @@ use std::time::Duration; use serde::Serialize; -use crate::model::{AdjId, BoardId, ProtectionKind, Severity}; - -use super::{ - data::DataMeasurementKind, - utils::{serialize_adj_id, serialize_board_id, serialize_protection_kind, serialize_severity}, +use crate::{ + model::{AdjId, BoardId, ProtectionKind, Severity}, + utils::serialize::{ + serialize_adj_id, serialize_board_id, serialize_protection_kind, serialize_severity, + }, }; +use super::data::DataMeasurementKind; + /// Order definitions grouped by board, matching `example/order.json`. #[derive(Debug, Clone, PartialEq, Serialize)] pub struct OrderResponse { diff --git a/backend/crates/core/src/adj/http/protection.rs b/backend/crates/core/src/adj/http/protection.rs index ada304151..a19cabde6 100644 --- a/backend/crates/core/src/adj/http/protection.rs +++ b/backend/crates/core/src/adj/http/protection.rs @@ -4,10 +4,11 @@ use std::{collections::HashMap, time::Duration}; use serde::Serialize; -use crate::model::{AdjId, BoardId, ProtectionKind, Severity}; - -use super::utils::{ - serialize_adj_id, serialize_adj_protection_kind, serialize_board_id, serialize_severity, +use crate::{ + model::{AdjId, BoardId, ProtectionKind, Severity}, + utils::serialize::{ + serialize_adj_id, serialize_adj_protection_kind, serialize_board_id, serialize_severity, + }, }; /// Protection definitions and their display metadata, matching `example/protection.json`. diff --git a/backend/crates/core/src/adj/http/setup.rs b/backend/crates/core/src/adj/http/setup.rs deleted file mode 100644 index d8c006e66..000000000 --- a/backend/crates/core/src/adj/http/setup.rs +++ /dev/null @@ -1,202 +0,0 @@ -//! Builds HTTP response models from a loaded ADJ. - -use crate::{ - adj::Adj, - model::{MeasurementKind, PacketType}, -}; - -use super::data::{ - DataBoardResponse, DataMeasurementKind, DataMeasurementResponse, DataPacketResponse, - DataResponse, -}; -use super::order::{ - OrderBoardResponse, OrderMeasurementResponse, OrderPacketResponse, OrderProtectionResponse, - OrderResponse, -}; -use super::protection::{ProtectionInfoResponse, ProtectionResponse, ProtectionTypeResponse}; - -/// Builds the data catalog without modifying or consuming the ADJ. -/// -/// Boards and data packets are sorted by id. Boards without data packets are -/// retained with an empty list. Measurements keep their wire order and omit -/// protection metadata. -pub fn data_response(adj: &Adj) -> DataResponse { - let mut boards: Vec = adj - .pod_data - .boards - .values() - .map(|board| { - let mut packets: Vec = board - .packets - .values() - .filter_map(|packet| { - let PacketType::Data(measurements) = &packet.packet_type else { - return None; - }; - - Some(DataPacketResponse { - id: packet.id, - name: packet.name.clone(), - packet_type: "data".to_string(), - measurements: measurements - .iter() - .map(|measurement| DataMeasurementResponse { - id: measurement.id, - alias: measurement.alias.clone(), - name: measurement.name.clone(), - display_units: measurement.display_units.clone(), - kind: match &measurement.kind { - MeasurementKind::Numeric { wire_type } => { - DataMeasurementKind::Numeric { - wire_type: *wire_type, - } - } - MeasurementKind::Boolean => DataMeasurementKind::Boolean, - MeasurementKind::Enum { options } => { - DataMeasurementKind::Enum { - options: options.clone(), - } - } - }, - }) - .collect(), - }) - }) - .collect(); - packets.sort_unstable_by_key(|packet| packet.id.0); - - DataBoardResponse { - id: board.id, - name: board.name.clone(), - packets, - } - }) - .collect(); - boards.sort_unstable_by_key(|board| board.id.0); - - DataResponse { boards } -} - -/// Builds the order catalog without modifying or consuming the ADJ. -/// -/// Boards and orders are sorted by id. Boards without orders are retained with -/// an empty list. Parameters and their protections keep their ADJ order; -/// protection ids remain their one-based positions within each measurement. -pub fn order_response(adj: &Adj) -> OrderResponse { - let mut boards: Vec = adj - .pod_data - .boards - .values() - .map(|board| { - let mut orders: Vec = board - .packets - .values() - .filter_map(|packet| { - let PacketType::Order(measurements) = &packet.packet_type else { - return None; - }; - - Some(OrderPacketResponse { - id: packet.id, - name: packet.name.clone(), - packet_type: "order".to_string(), - measurements: measurements - .iter() - .map(|measurement| OrderMeasurementResponse { - id: measurement.id, - alias: measurement.alias.clone(), - name: measurement.name.clone(), - display_units: measurement.display_units.clone(), - kind: match &measurement.kind { - MeasurementKind::Numeric { wire_type } => { - DataMeasurementKind::Numeric { - wire_type: *wire_type, - } - } - MeasurementKind::Boolean => DataMeasurementKind::Boolean, - MeasurementKind::Enum { options } => { - DataMeasurementKind::Enum { - options: options.clone(), - } - } - }, - protections: measurement - .protections - .iter() - .map(|protection| OrderProtectionResponse { - id: protection.id, - kind: protection.kind, - severity: protection.severity, - time: protection.time, - }) - .collect(), - }) - .collect(), - }) - }) - .collect(); - orders.sort_unstable_by_key(|order| order.id.0); - - OrderBoardResponse { - id: board.id, - name: board.name.clone(), - orders, - } - }) - .collect(); - boards.sort_unstable_by_key(|board| board.id.0); - - OrderResponse { boards } -} - -/// Builds the flat protection catalog without modifying or consuming the ADJ. -/// -/// Protection packet ids and names are reused from the loader. The position in -/// each compound id selects its definition within the watched measurement. -/// Packets with no definition at that position are omitted. The resulting list -/// is sorted by packet id, then board id to break ties. -pub fn protection_response(adj: &Adj) -> ProtectionResponse { - let mut protections: Vec = adj - .pod_data - .boards - .values() - .flat_map(|board| board.packets.values()) - .filter_map(|packet| { - let PacketType::Protection(measurement) = &packet.packet_type else { - return None; - }; - - let index = usize::from(packet.id.protection_position()).checked_sub(1)?; - let protection = measurement.protections.get(index)?; - - Some(ProtectionInfoResponse { - id: packet.id, - name: packet.name.clone(), - board_id: packet.board, - measurement_id: measurement.id, - kind: protection.kind, - severity: protection.severity, - time: protection.time, - }) - }) - .collect(); - protections.sort_unstable_by_key(|protection| (protection.id.0, protection.board_id.0)); - - let info = adj - .info - .protection_types - .iter() - .map(|(name, metadata)| { - ( - name.clone(), - ProtectionTypeResponse { - is_range: metadata.is_range, - text: metadata.text.clone(), - text_time: metadata.text_time.clone(), - }, - ) - }) - .collect(); - - ProtectionResponse { protections, info } -} diff --git a/backend/crates/core/src/lib.rs b/backend/crates/core/src/lib.rs index 40cf80793..32595115f 100644 --- a/backend/crates/core/src/lib.rs +++ b/backend/crates/core/src/lib.rs @@ -24,4 +24,7 @@ pub mod adj; /// Translates bytes into typed packets and back, using the shapes /// [`adj`] declares as the schema. See [`protocol::wire`], /// [`protocol::tcp`], [`protocol::udp`]. -pub mod protocol; \ No newline at end of file +pub mod protocol; + +// Utils module +pub(crate) mod utils; \ No newline at end of file diff --git a/backend/crates/core/src/utils.rs b/backend/crates/core/src/utils.rs new file mode 100644 index 000000000..8e32a77ad --- /dev/null +++ b/backend/crates/core/src/utils.rs @@ -0,0 +1,2 @@ +#[cfg(feature = "http")] +pub(crate) mod serialize; \ No newline at end of file diff --git a/backend/crates/core/src/adj/http/utils.rs b/backend/crates/core/src/utils/serialize.rs similarity index 100% rename from backend/crates/core/src/adj/http/utils.rs rename to backend/crates/core/src/utils/serialize.rs From 441ddf13a7ff08f74c19e5a9bb1c307d2ef7f4f5 Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Fri, 13 Nov 2026 17:25:49 +0100 Subject: [PATCH 123/225] feat(backend, http): websocket support --- backend/crates/station/src/http.rs | 22 ++- backend/crates/station/src/http/handlers.rs | 83 ++++++++-- backend/crates/station/src/http/server.rs | 172 +++++++++++++++++--- 3 files changed, 237 insertions(+), 40 deletions(-) diff --git a/backend/crates/station/src/http.rs b/backend/crates/station/src/http.rs index 0549b6199..a7f23e6f2 100644 --- a/backend/crates/station/src/http.rs +++ b/backend/crates/station/src/http.rs @@ -1,4 +1,24 @@ +//! Station HTTP API: ADJ catalogs and incoming WebSocket connections. +//! +//! This module only negotiates WebSocket upgrades and hands sockets to a +//! channel. Message handling and client management belong to the future +//! WebSocket module, which will own the channel's receiver. + +use std::io; + +use software_core::adj::Adj; +use tokio::net::TcpListener; + mod handlers; mod server; -pub use server::serve; \ No newline at end of file +pub use server::serve_with_websocket; + +/// Serves the catalogs without connecting a WebSocket consumer yet. +/// +/// Preserves the entry point used by the test startup code. Upgrade requests +/// to `/backend` receive `503` until [`serve_with_websocket`] is used with a +/// channel connected to the future WebSocket module. +pub async fn serve(listener: TcpListener, adj: &Adj) -> io::Result<()> { + serve_with_websocket(listener, adj, None).await +} diff --git a/backend/crates/station/src/http/handlers.rs b/backend/crates/station/src/http/handlers.rs index d40829702..815e33385 100644 --- a/backend/crates/station/src/http/handlers.rs +++ b/backend/crates/station/src/http/handlers.rs @@ -1,45 +1,92 @@ +//! Handlers for precomputed catalogs and WebSocket upgrades. + use std::sync::Arc; use axum::{ body::Bytes, - extract::State, - http::header, + extract::{State, WebSocketUpgrade, ws::WebSocket}, + http::{StatusCode, header}, response::{IntoResponse, Response}, }; -use software_core::adj::{ - Adj, - http::{data_response, order_response, protection_response}, -}; +use software_core::adj::Adj; +use tokio::sync::mpsc; + +/// Immutable state shared by all requests without a mutex. +pub(super) struct HttpState { + responses: Responses, + websocket_connections: Option>, +} -pub(super) struct Responses { +impl HttpState { + pub(super) fn new( + adj: &Adj, + websocket_connections: Option>, + ) -> Result { + Ok(Self { + responses: Responses::new(adj)?, + websocket_connections, + }) + } +} + +/// Pre-serialized JSON. Each Bytes clone shares the same underlying content. +struct Responses { data_response: Bytes, order_response: Bytes, protection_response: Bytes, } impl Responses { - // Serialize once at startup; Bytes clones share the existing JSON buffer. - pub(super) fn new(adj: &Adj) -> Result { + // ADJ transformation and serialization happen only at startup. + fn new(adj: &Adj) -> Result { Ok(Self { - data_response: serde_json::to_vec(&data_response(adj))?.into(), - order_response: serde_json::to_vec(&order_response(adj))?.into(), - protection_response: serde_json::to_vec(&protection_response(adj))?.into(), + data_response: serde_json::to_vec(&adj.data_response())?.into(), + order_response: serde_json::to_vec(&adj.order_response())?.into(), + protection_response: serde_json::to_vec(&adj.protection_response())?.into(), }) } } -pub(super) async fn data_packet(State(responses): State>) -> Response { - json_response(responses.data_response.clone()) +pub(super) async fn data_packet(State(state): State>) -> Response { + json_response(state.responses.data_response.clone()) +} + +pub(super) async fn order_packet(State(state): State>) -> Response { + json_response(state.responses.order_response.clone()) } -pub(super) async fn order_packet(State(responses): State>) -> Response { - json_response(responses.order_response.clone()) +pub(super) async fn protection_packet(State(state): State>) -> Response { + json_response(state.responses.protection_response.clone()) } -pub(super) async fn protection_packet(State(responses): State>) -> Response { - json_response(responses.protection_response.clone()) +/// Negotiates the connection without reading messages or implementing the frontend protocol. +pub(super) async fn websocket( + State(state): State>, + upgrade: WebSocketUpgrade, +) -> Response { + let Some(connections) = &state.websocket_connections else { + return StatusCode::SERVICE_UNAVAILABLE.into_response(); + }; + + // Reserve a slot before returning 101: a closed or full channel must reject + // the request rather than accept a socket that cannot be handed off. + let permit = match connections.clone().try_reserve_owned() { + Ok(permit) => permit, + Err(_) => return StatusCode::SERVICE_UNAVAILABLE.into_response(), + }; + + upgrade + .on_failed_upgrade(|error| { + tracing::warn!(%error, "falló el upgrade WebSocket"); + }) + .on_upgrade(move |socket| async move { + // The receiver now owns the socket and manages its lifetime and + // closure. If the receiver disappears, the socket is dropped. + permit.send(socket); + }) } fn json_response(body: Bytes) -> Response { + // Do not wrap these bytes in Json: that would serialize the content again. ([(header::CONTENT_TYPE, "application/json")], body).into_response() } diff --git a/backend/crates/station/src/http/server.rs b/backend/crates/station/src/http/server.rs index 43780a113..d8226cb29 100644 --- a/backend/crates/station/src/http/server.rs +++ b/backend/crates/station/src/http/server.rs @@ -1,45 +1,60 @@ +//! Router construction and server execution using an existing listener. + use std::{io, sync::Arc}; -use axum::{Router, routing::get}; +use axum::{Router, extract::ws::WebSocket, routing::get}; use software_core::adj::Adj; -use tokio::net::TcpListener; +use tokio::{net::TcpListener, sync::mpsc}; -use crate::http::handlers::{Responses, data_packet, order_packet, protection_packet}; +use super::handlers::{HttpState, data_packet, order_packet, protection_packet, websocket}; -/// Serves HTTP requests on an already-bound listener. +/// Serves the catalogs and hands connections to the future WebSocket module. +/// +/// The caller chooses the address and port when binding the listener. To enable +/// WebSocket, pass `Some(sender)` from a bounded channel and keep its receiver +/// in the module that will manage the sockets. With `None`, a closed receiver, +/// or a full channel, upgrade requests receive `503`. /// -/// The caller chooses the interface and port when binding the listener. /// This future runs until the server stops; await it or spawn it on Tokio. /// /// # Errors /// -/// Returns errors serializing the catalogs at startup or reported by Axum's server. -pub async fn serve(listener: TcpListener, adj: &Adj) -> io::Result<()> { - axum::serve(listener, router(adj)?).await +/// Propagates errors serializing the catalogs or running the Axum server. +pub async fn serve_with_websocket( + listener: TcpListener, + adj: &Adj, + websocket_connections: Option>, +) -> io::Result<()> { + axum::serve(listener, router(adj, websocket_connections)?).await } -fn router(adj: &Adj) -> io::Result { - let responses = Arc::new(Responses::new(adj).map_err(io::Error::other)?); +fn router(adj: &Adj, websocket_connections: Option>) -> io::Result { + // Build and serialize the catalogs once, before accepting requests. The + // state retains the bytes even after the Adj is dropped. + let state = Arc::new(HttpState::new(adj, websocket_connections).map_err(io::Error::other)?); Ok(Router::new() .route("/backend/adj/DataPackets", get(data_packet)) .route("/backend/adj/OrderPackets", get(order_packet)) .route("/backend/adj/ProtectionPackets", get(protection_packet)) - .with_state(responses)) + .route("/backend", get(websocket)) + .with_state(state)) } #[cfg(test)] mod tests { - use std::path::Path; + use std::{io, path::Path, time::Duration}; use axum::{ body::{Body, to_bytes}, http::{Request, StatusCode, header}, }; - use software_core::adj::{ - Adj, - http::{data_response, order_response, protection_response}, - load_from_dir, + use software_core::adj::{Adj, load_from_dir}; + use tokio::{ + io::{AsyncBufReadExt, AsyncWriteExt, BufReader}, + net::{TcpListener, TcpStream}, + sync::{mpsc, oneshot}, + time::timeout, }; use tower::ServiceExt; @@ -56,11 +71,11 @@ mod tests { let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("../core/src/adj/test/adj"); let adj = load_from_dir(&path)?; let expected = [ - serde_json::to_value(data_response(&adj))?, - serde_json::to_value(order_response(&adj))?, - serde_json::to_value(protection_response(&adj))?, + serde_json::to_value(&adj.data_response())?, + serde_json::to_value(&adj.order_response())?, + serde_json::to_value(&adj.protection_response())?, ]; - let app = router(&adj)?; + let app = router(&adj, None)?; drop(adj); for (path, expected) in PATHS.into_iter().zip(expected) { @@ -87,7 +102,7 @@ mod tests { #[tokio::test] async fn empty_catalogs_return_json_objects() -> Result<(), Box> { - let app = router(&Adj::default())?; + let app = router(&Adj::default(), None)?; let expected = [ serde_json::json!({"boards": []}), serde_json::json!({"boards": []}), @@ -106,4 +121,119 @@ mod tests { } Ok(()) } + + // Upgrades require a real HTTP connection: oneshot does not provide Hyper's + // OnUpgrade extension. The server only runs for the duration of the test. + async fn handshake( + app: axum::Router, + ) -> Result<(String, TcpStream), Box> { + let listener = TcpListener::bind("127.0.0.1:0").await?; + let address = listener.local_addr()?; + let (shutdown, stopped) = oneshot::channel(); + let server = tokio::spawn(async move { + axum::serve(listener, app) + .with_graceful_shutdown(async move { + let _ = stopped.await; + }) + .await + }); + + let response = timeout(Duration::from_secs(5), async { + let mut stream = TcpStream::connect(address).await?; + let request = format!( + "GET /backend HTTP/1.1\r\n\ + Host: {address}\r\n\ + Connection: Upgrade\r\n\ + Upgrade: websocket\r\n\ + Sec-WebSocket-Version: 13\r\n\ + Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n\r\n" + ); + stream.write_all(request.as_bytes()).await?; + + let mut reader = BufReader::new(stream); + let mut headers = String::new(); + while !headers.ends_with("\r\n\r\n") { + if reader.read_line(&mut headers).await? == 0 { + return Err(io::Error::from(io::ErrorKind::UnexpectedEof)); + } + } + Ok((headers, reader.into_inner())) + }) + .await; + + let _ = shutdown.send(()); + timeout(Duration::from_secs(5), server).await???; + Ok(response??) + } + + #[tokio::test] + async fn websocket_upgrade_delivers_the_socket() -> Result<(), Box> { + let (connections, mut receiver) = mpsc::channel(1); + let app = router(&Adj::default(), Some(connections.clone()))?; + let (headers, _client) = handshake(app).await?; + + assert!(headers.starts_with("HTTP/1.1 101 Switching Protocols\r\n")); + assert!( + headers + .to_ascii_lowercase() + .contains("sec-websocket-accept: s3pplmbitxaq9kygzzhzrbk+xoo=\r\n") + ); + let socket = timeout(Duration::from_secs(5), receiver.recv()) + .await? + .ok_or_else(|| io::Error::other("no se entregó el socket"))?; + assert_eq!(connections.capacity(), 1); + drop(socket); + Ok(()) + } + + #[tokio::test] + async fn websocket_without_a_consumer_returns_unavailable() + -> Result<(), Box> { + let app = router(&Adj::default(), None)?; + let (headers, _client) = handshake(app).await?; + assert!(headers.starts_with("HTTP/1.1 503 Service Unavailable\r\n")); + Ok(()) + } + + #[tokio::test] + async fn websocket_with_a_closed_channel_returns_unavailable() + -> Result<(), Box> { + let (connections, receiver) = mpsc::channel(1); + drop(receiver); + let app = router(&Adj::default(), Some(connections))?; + let (headers, _client) = handshake(app).await?; + assert!(headers.starts_with("HTTP/1.1 503 Service Unavailable\r\n")); + Ok(()) + } + + #[tokio::test] + async fn websocket_with_a_full_channel_returns_unavailable() + -> Result<(), Box> { + let (connections, _receiver) = mpsc::channel(1); + // Simulate an occupied slot without requiring another test socket. + let reservation = connections.clone().try_reserve_owned()?; + let app = router(&Adj::default(), Some(connections))?; + let (headers, _client) = handshake(app).await?; + assert!(headers.starts_with("HTTP/1.1 503 Service Unavailable\r\n")); + drop(reservation); + Ok(()) + } + + #[tokio::test] + async fn websocket_rejects_requests_without_upgrade_headers() + -> Result<(), Box> { + let (connections, mut receiver) = mpsc::channel(1); + let app = router(&Adj::default(), Some(connections.clone()))?; + let response = app + .oneshot(Request::builder().uri("/backend").body(Body::empty())?) + .await?; + + assert_eq!(response.status(), StatusCode::BAD_REQUEST); + assert_eq!(connections.capacity(), 1); + assert!(matches!( + receiver.try_recv(), + Err(mpsc::error::TryRecvError::Empty) + )); + Ok(()) + } } From 6a3d2a85b5e0f78cc2cb6a0c57a5b3071a48e25d Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Fri, 13 Nov 2026 17:42:46 +0100 Subject: [PATCH 124/225] todo(backend, http): everything related with configuration (future module config) --- backend/crates/station/src/http/server.rs | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/backend/crates/station/src/http/server.rs b/backend/crates/station/src/http/server.rs index d8226cb29..6a8718051 100644 --- a/backend/crates/station/src/http/server.rs +++ b/backend/crates/station/src/http/server.rs @@ -8,6 +8,25 @@ use tokio::{net::TcpListener, sync::mpsc}; use super::handlers::{HttpState, data_packet, order_packet, protection_packet, websocket}; +/// Configures the HTTP server using the future application configuration. +/// +/// Once `HttpConfig` is defined, this function should translate its settings +/// into the server setup: select the listening address and port, apply the +/// allowed CORS origins, and configure cache headers for the ADJ catalogs. +/// Invalid settings should be reported before the server starts accepting +/// requests, rather than silently falling back to other values. +/// +/// It should consume configuration already loaded by the application, not read +/// configuration files or environment variables itself. ADJ loading and +/// WebSocket message handling remain outside its responsibilities. +/// +/// The parameter and return type will be finalized when the configuration +/// module is available. This placeholder is not called by the current startup. +#[expect(dead_code, reason = "Waiting for the application configuration module")] +fn configure_server(/* config: &HttpConfig */) { + todo!("Configure the HTTP server once HttpConfig is available"); +} + /// Serves the catalogs and hands connections to the future WebSocket module. /// /// The caller chooses the address and port when binding the listener. To enable From b074dd4a22c07cf6d555cb4d7fd10e9986667463 Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Fri, 13 Nov 2026 17:43:16 +0100 Subject: [PATCH 125/225] feat(backend, http): small test of the endpoints in main --- backend/crates/station/src/main.rs | 1 + backend/crates/station/src/vehicle.rs | 0 2 files changed, 1 insertion(+) create mode 100644 backend/crates/station/src/vehicle.rs diff --git a/backend/crates/station/src/main.rs b/backend/crates/station/src/main.rs index 06ce2789e..c3288c29d 100644 --- a/backend/crates/station/src/main.rs +++ b/backend/crates/station/src/main.rs @@ -34,3 +34,4 @@ async fn main() -> std::io::Result<()> { } mod http; +mod vehicle; \ No newline at end of file diff --git a/backend/crates/station/src/vehicle.rs b/backend/crates/station/src/vehicle.rs new file mode 100644 index 000000000..e69de29bb From 69af8ebe5c219a09667719fe851484b1adb71475 Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Fri, 13 Nov 2026 23:06:25 +0100 Subject: [PATCH 126/225] feat(backend, http): add HTTP server configuration with CORS and cache policies --- backend/Cargo.lock | 1 + backend/crates/station/Cargo.toml | 1 + backend/crates/station/src/http.rs | 8 + backend/crates/station/src/http/configure.rs | 381 +++++++++++++++++++ backend/crates/station/src/http/server.rs | 59 +-- 5 files changed, 424 insertions(+), 26 deletions(-) create mode 100644 backend/crates/station/src/http/configure.rs diff --git a/backend/Cargo.lock b/backend/Cargo.lock index ee029ddc0..2f7055784 100644 --- a/backend/Cargo.lock +++ b/backend/Cargo.lock @@ -2936,6 +2936,7 @@ dependencies = [ "tokio", "toml", "tower", + "tower-http", "tracing", "tracing-subscriber", ] diff --git a/backend/crates/station/Cargo.toml b/backend/crates/station/Cargo.toml index 7855005ac..9eed62cbe 100644 --- a/backend/crates/station/Cargo.toml +++ b/backend/crates/station/Cargo.toml @@ -19,6 +19,7 @@ tracing-subscriber.workspace = true serde_json.workspace = true tower = "0.5.3" axum = { version = "0.8.9", features = ["ws", "http1", "http2"] } +tower-http = { version = "0.6.11", features = ["cors", "set-header"] } [lints] workspace = true diff --git a/backend/crates/station/src/http.rs b/backend/crates/station/src/http.rs index a7f23e6f2..f0d2d6484 100644 --- a/backend/crates/station/src/http.rs +++ b/backend/crates/station/src/http.rs @@ -9,10 +9,18 @@ use std::io; use software_core::adj::Adj; use tokio::net::TcpListener; +mod configure; mod handlers; mod server; pub use server::serve_with_websocket; +// The test main still uses the listener-based entry point. Configuration will +// be connected by the application startup when its config module is available. +#[allow( + unused_imports, + reason = "The test startup does not use configuration yet" +)] +pub use configure::{CachePolicy, HttpConfig, configure_server}; /// Serves the catalogs without connecting a WebSocket consumer yet. /// diff --git a/backend/crates/station/src/http/configure.rs b/backend/crates/station/src/http/configure.rs new file mode 100644 index 000000000..bf6a4a38f --- /dev/null +++ b/backend/crates/station/src/http/configure.rs @@ -0,0 +1,381 @@ +//! Provisional HTTP settings, validation, and server preparation. + +use std::{io, net::SocketAddr}; + +use axum::{ + Router, + extract::ws::WebSocket, + http::{HeaderValue, Method, Uri, header}, +}; +use software_core::adj::Adj; +use tokio::{net::TcpListener, sync::mpsc}; +use tower_http::cors::{AllowOrigin, CorsLayer}; + +use super::server::router_with_cache; + +/// Provisional HTTP settings, independent of configuration files and ADJ data. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct HttpConfig { + /// Address and port to bind. Port zero requests an available port from the OS. + pub bind_addr: SocketAddr, + /// Exact HTTP(S) origins permitted by CORS; an empty list grants none. + /// + /// Wildcards, credentials, paths, queries, and fragments are not accepted. + /// The opaque origin `null` can be explicitly allowed for local-file clients, + /// but it is shared by other opaque origins too, not exclusive to Electron. + /// This list does not perform WebSocket Origin validation. + pub allowed_origins: Vec, + /// Cache-Control policy for the three catalog routes, not WebSocket upgrades. + pub cache_policy: CachePolicy, +} + +impl HttpConfig { + /// Uses an explicit bind address, no allowed CORS origins, and `no-store`. + pub fn new(bind_addr: SocketAddr) -> Self { + Self { + bind_addr, + allowed_origins: Vec::new(), + cache_policy: CachePolicy::default(), + } + } +} + +/// HTTP caching is independent of the pre-serialized buffers held by the server. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum CachePolicy { + /// Do not emit an explicit Cache-Control header. + Unspecified, + /// Allow storage, but require revalidation before reuse (`no-cache`). + NoCache, + /// Prevent clients and intermediaries from storing responses (`no-store`). + #[default] + NoStore, +} + +impl CachePolicy { + pub(super) fn header_value(self) -> Option { + match self { + Self::Unspecified => None, + Self::NoCache => Some(HeaderValue::from_static("no-cache")), + Self::NoStore => Some(HeaderValue::from_static("no-store")), + } + } +} + +/// Validates settings and prepares a bound listener and router without serving. +/// +/// The returned router owns the precomputed catalogs, CORS middleware, optional +/// WebSocket sender, and catalog cache policy. The caller can then run +/// `axum::serve(listener, router)`. Configuration is validated and responses are +/// serialized before binding, so invalid input does not leave a bound listener. +/// +/// This function consumes already-loaded settings and ADJ data. It does not +/// read configuration files or implement WebSocket Origin checks or messages. +/// +/// # Errors +/// +/// Returns `InvalidInput` for invalid CORS origins, serialization errors wrapped +/// in `io::Error`, or the error from binding the configured address. +pub async fn configure_server( + config: &HttpConfig, + adj: &Adj, + websocket_connections: Option>, +) -> io::Result<(TcpListener, Router)> { + let cors = cors_layer(&config.allowed_origins)?; + let app = router_with_cache(adj, websocket_connections, config.cache_policy)?.layer(cors); + let listener = TcpListener::bind(config.bind_addr).await?; + Ok((listener, app)) +} + +/// Validates the explicit origin list and builds CORS rules for GET and HEAD. +/// Rejects malformed origins with `InvalidInput`; an empty list permits none. +/// Handles preflight requests without enabling credentials or wildcard origins. +fn cors_layer(allowed_origins: &[String]) -> io::Result { + let origins = allowed_origins + .iter() + .map(|origin| { + let invalid = || { + io::Error::new( + io::ErrorKind::InvalidInput, + format!("invalid CORS origin {origin:?}: expected an HTTP(S) origin or null"), + ) + }; + let value = origin.parse::().map_err(|_| invalid())?; + if origin == "null" { + return Ok(value); + } + + let uri = origin.parse::().map_err(|_| invalid())?; + let (Some(scheme), Some(authority)) = (uri.scheme_str(), uri.authority()) else { + return Err(invalid()); + }; + if !matches!(scheme, "http" | "https") + || origin != &format!("{scheme}://{authority}") + || authority.host().is_empty() + || authority.as_str().contains(['@', '*']) + || (authority.as_str() != authority.host() && authority.port_u16().is_none()) + { + return Err(invalid()); + } + Ok(value) + }) + .collect::>>()?; + + // CORS controls browser access, not authentication or WebSocket origins. + Ok(CorsLayer::new() + .allow_origin(AllowOrigin::list(origins)) + .allow_methods([Method::GET, Method::HEAD]) + .allow_headers([header::ACCEPT, header::CONTENT_TYPE])) +} + +#[cfg(test)] +mod tests { + use std::{io, time::Duration}; + + use axum::{ + body::Body, + http::{Request, StatusCode, header}, + }; + use software_core::adj::Adj; + use tokio::{net::TcpListener, sync::mpsc, time::timeout}; + use tower::ServiceExt; + + use super::{CachePolicy, HttpConfig, configure_server, cors_layer}; + use crate::http::server::tests::{PATHS, handshake_on}; + + #[tokio::test] + async fn configuration_binds_the_requested_address_and_defaults_to_no_store() + -> Result<(), Box> { + let config = HttpConfig::new("127.0.0.1:0".parse()?); + assert!(config.allowed_origins.is_empty()); + assert_eq!(config.cache_policy, CachePolicy::NoStore); + let (listener, app) = configure_server(&config, &Adj::default(), None).await?; + assert_eq!(listener.local_addr()?.ip(), config.bind_addr.ip()); + assert_ne!(listener.local_addr()?.port(), 0); + + for path in PATHS { + let response = app + .clone() + .oneshot(Request::builder().uri(path).body(Body::empty())?) + .await?; + assert_eq!(response.status(), StatusCode::OK); + assert_eq!(response.headers()[header::CACHE_CONTROL], "no-store"); + assert_eq!(response.headers()[header::CONTENT_TYPE], "application/json"); + assert!( + !response + .headers() + .contains_key(header::ACCESS_CONTROL_ALLOW_ORIGIN) + ); + } + Ok(()) + } + + #[tokio::test] + async fn configured_cors_allows_only_explicit_origins() -> Result<(), Box> + { + let mut config = HttpConfig::new("127.0.0.1:0".parse()?); + config.allowed_origins = vec![ + "http://localhost:9000".into(), + "https://station.example".into(), + ]; + let (_listener, app) = configure_server(&config, &Adj::default(), None).await?; + + for origin in [ + "http://localhost:9000", + "https://station.example", + "http://untrusted.example", + ] { + let response = app + .clone() + .oneshot( + Request::builder() + .uri(PATHS[0]) + .header(header::ORIGIN, origin) + .body(Body::empty())?, + ) + .await?; + // CORS restricts browser access; it is not authorization for HTTP clients. + assert_eq!(response.status(), StatusCode::OK); + if config + .allowed_origins + .iter() + .any(|allowed| allowed == origin) + { + assert_eq!( + response.headers()[header::ACCESS_CONTROL_ALLOW_ORIGIN], + origin + ); + } else { + assert!( + !response + .headers() + .contains_key(header::ACCESS_CONTROL_ALLOW_ORIGIN) + ); + } + assert!( + !response + .headers() + .contains_key(header::ACCESS_CONTROL_ALLOW_CREDENTIALS) + ); + } + Ok(()) + } + + #[tokio::test] + async fn configured_cors_handles_preflight() -> Result<(), Box> { + let mut config = HttpConfig::new("127.0.0.1:0".parse()?); + config.allowed_origins.push("http://localhost:9000".into()); + let (_listener, app) = configure_server(&config, &Adj::default(), None).await?; + + for (origin, method, expected_origin) in [ + ( + "http://localhost:9000", + "GET", + Some("http://localhost:9000"), + ), + ("http://untrusted.example", "GET", None), + ( + "http://localhost:9000", + "POST", + Some("http://localhost:9000"), + ), + ] { + let response = app + .clone() + .oneshot( + Request::builder() + .method("OPTIONS") + .uri(PATHS[0]) + .header(header::ORIGIN, origin) + .header(header::ACCESS_CONTROL_REQUEST_METHOD, method) + .header(header::ACCESS_CONTROL_REQUEST_HEADERS, "content-type") + .body(Body::empty())?, + ) + .await?; + assert!(response.status().is_success()); + assert_eq!( + response + .headers() + .get(header::ACCESS_CONTROL_ALLOW_ORIGIN) + .map(|value| value.to_str()) + .transpose()?, + expected_origin + ); + let methods = response.headers()[header::ACCESS_CONTROL_ALLOW_METHODS].to_str()?; + assert!(methods.split(',').any(|value| value.trim() == "GET")); + assert!(!methods.split(',').any(|value| value.trim() == "POST")); + assert!( + response.headers()[header::ACCESS_CONTROL_ALLOW_HEADERS] + .to_str()? + .contains("content-type") + ); + } + Ok(()) + } + + #[tokio::test] + async fn invalid_origins_are_rejected_before_binding() -> Result<(), Box> + { + let occupied = TcpListener::bind("127.0.0.1:0").await?; + for origin in [ + "*", + "", + "localhost:9000", + "ws://localhost:9000", + "http://*.example.com", + "http://localhost:9000/", + "http://localhost:9000/path", + "http://localhost?query=1", + "http://localhost#fragment", + "http://user:password@localhost", + "http://localhost:", + "http://localhost:abc", + "http://localhost:99999", + "http://localhost\r\nInjected: value", + ] { + let mut config = HttpConfig::new(occupied.local_addr()?); + config.allowed_origins = vec![origin.into()]; + let error = configure_server(&config, &Adj::default(), None) + .await + .err() + .ok_or_else(|| io::Error::other("invalid origin was accepted"))?; + assert_eq!(error.kind(), io::ErrorKind::InvalidInput, "{origin:?}"); + } + Ok(()) + } + + #[test] + fn explicit_opaque_and_ipv6_origins_are_valid() -> Result<(), Box> { + for origin in [ + "null", + "http://[::1]:9000", + "https://example.com", + "http://127.0.0.1:9000", + ] { + let _ = cors_layer(&[origin.into()])?; + } + Ok(()) + } + + #[tokio::test] + async fn binding_errors_are_propagated_without_fallback() + -> Result<(), Box> { + let occupied = TcpListener::bind("127.0.0.1:0").await?; + let config = HttpConfig::new(occupied.local_addr()?); + let error = configure_server(&config, &Adj::default(), None) + .await + .err() + .ok_or_else(|| io::Error::other("occupied address did not fail"))?; + assert_eq!(error.kind(), io::ErrorKind::AddrInUse); + Ok(()) + } + + #[tokio::test] + async fn cache_policy_is_applied_only_to_catalogs() -> Result<(), Box> { + for (policy, expected) in [ + (CachePolicy::NoStore, Some("no-store")), + (CachePolicy::NoCache, Some("no-cache")), + (CachePolicy::Unspecified, None), + ] { + let mut config = HttpConfig::new("127.0.0.1:0".parse()?); + config.cache_policy = policy; + let (_listener, app) = configure_server(&config, &Adj::default(), None).await?; + for path in PATHS { + let response = app + .clone() + .oneshot(Request::builder().uri(path).body(Body::empty())?) + .await?; + assert_eq!( + response + .headers() + .get(header::CACHE_CONTROL) + .map(|value| value.to_str()) + .transpose()?, + expected + ); + } + let response = app + .oneshot(Request::builder().uri("/backend").body(Body::empty())?) + .await?; + assert_eq!(response.status(), StatusCode::BAD_REQUEST); + assert!(!response.headers().contains_key(header::CACHE_CONTROL)); + } + Ok(()) + } + + #[tokio::test] + async fn configured_server_preserves_websocket_handoff() + -> Result<(), Box> { + let config = HttpConfig::new("127.0.0.1:0".parse()?); + let (connections, mut receiver) = mpsc::channel(1); + let (listener, app) = configure_server(&config, &Adj::default(), Some(connections)).await?; + let (headers, _client) = handshake_on(listener, app).await?; + assert!(headers.starts_with("HTTP/1.1 101 Switching Protocols\r\n")); + assert!(!headers.to_ascii_lowercase().contains("cache-control:")); + let socket = timeout(Duration::from_secs(5), receiver.recv()) + .await? + .ok_or_else(|| io::Error::other("socket was not handed off"))?; + drop(socket); + Ok(()) + } +} diff --git a/backend/crates/station/src/http/server.rs b/backend/crates/station/src/http/server.rs index 6a8718051..073d8c86c 100644 --- a/backend/crates/station/src/http/server.rs +++ b/backend/crates/station/src/http/server.rs @@ -2,31 +2,14 @@ use std::{io, sync::Arc}; -use axum::{Router, extract::ws::WebSocket, routing::get}; +use axum::{Router, extract::ws::WebSocket, http::header, routing::get}; use software_core::adj::Adj; use tokio::{net::TcpListener, sync::mpsc}; +use tower_http::set_header::SetResponseHeaderLayer; +use super::configure::CachePolicy; use super::handlers::{HttpState, data_packet, order_packet, protection_packet, websocket}; -/// Configures the HTTP server using the future application configuration. -/// -/// Once `HttpConfig` is defined, this function should translate its settings -/// into the server setup: select the listening address and port, apply the -/// allowed CORS origins, and configure cache headers for the ADJ catalogs. -/// Invalid settings should be reported before the server starts accepting -/// requests, rather than silently falling back to other values. -/// -/// It should consume configuration already loaded by the application, not read -/// configuration files or environment variables itself. ADJ loading and -/// WebSocket message handling remain outside its responsibilities. -/// -/// The parameter and return type will be finalized when the configuration -/// module is available. This placeholder is not called by the current startup. -#[expect(dead_code, reason = "Waiting for the application configuration module")] -fn configure_server(/* config: &HttpConfig */) { - todo!("Configure the HTTP server once HttpConfig is available"); -} - /// Serves the catalogs and hands connections to the future WebSocket module. /// /// The caller chooses the address and port when binding the listener. To enable @@ -48,20 +31,37 @@ pub async fn serve_with_websocket( } fn router(adj: &Adj, websocket_connections: Option>) -> io::Result { + // Keep the existing listener-based entry points unchanged for test startup. + router_with_cache(adj, websocket_connections, CachePolicy::Unspecified) +} + +pub(super) fn router_with_cache( + adj: &Adj, + websocket_connections: Option>, + cache_policy: CachePolicy, +) -> io::Result { // Build and serialize the catalogs once, before accepting requests. The // state retains the bytes even after the Adj is dropped. let state = Arc::new(HttpState::new(adj, websocket_connections).map_err(io::Error::other)?); - Ok(Router::new() + let mut catalogs = Router::new() .route("/backend/adj/DataPackets", get(data_packet)) .route("/backend/adj/OrderPackets", get(order_packet)) - .route("/backend/adj/ProtectionPackets", get(protection_packet)) - .route("/backend", get(websocket)) - .with_state(state)) + .route("/backend/adj/ProtectionPackets", get(protection_packet)); + + if let Some(value) = cache_policy.header_value() { + catalogs = catalogs.layer(SetResponseHeaderLayer::overriding( + header::CACHE_CONTROL, + value, + )); + } + + // Register WebSocket after the catalog layer so upgrades are not cached. + Ok(catalogs.route("/backend", get(websocket)).with_state(state)) } #[cfg(test)] -mod tests { +pub(super) mod tests { use std::{io, path::Path, time::Duration}; use axum::{ @@ -79,7 +79,7 @@ mod tests { use super::router; - const PATHS: [&str; 3] = [ + pub(in crate::http) const PATHS: [&str; 3] = [ "/backend/adj/DataPackets", "/backend/adj/OrderPackets", "/backend/adj/ProtectionPackets", @@ -147,6 +147,13 @@ mod tests { app: axum::Router, ) -> Result<(String, TcpStream), Box> { let listener = TcpListener::bind("127.0.0.1:0").await?; + handshake_on(listener, app).await + } + + pub(in crate::http) async fn handshake_on( + listener: TcpListener, + app: axum::Router, + ) -> Result<(String, TcpStream), Box> { let address = listener.local_addr()?; let (shutdown, stopped) = oneshot::channel(); let server = tokio::spawn(async move { From 7f8a3805b9ee6f3785d609d2d6345d5119df84a8 Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Fri, 13 Nov 2026 23:07:41 +0100 Subject: [PATCH 127/225] docs(backend, http): docs HTTP endpoints, configuration and ws handoff --- backend/crates/station/src/http/README.md | 166 ++++++++++++++++++++++ 1 file changed, 166 insertions(+) create mode 100644 backend/crates/station/src/http/README.md diff --git a/backend/crates/station/src/http/README.md b/backend/crates/station/src/http/README.md new file mode 100644 index 000000000..9c905dbd2 --- /dev/null +++ b/backend/crates/station/src/http/README.md @@ -0,0 +1,166 @@ +# HTTP + +Station's Axum server exposes the ADJ catalogs and accepts WebSocket upgrades +from the frontend. It does not load the ADJ or handle WebSocket messages. + +## Files + +| File | Responsibility | +| --- | --- | +| [`../http.rs`](../http.rs) | Module entry points, with or without a WebSocket consumer. | +| [`configure.rs`](configure.rs) | Provisional HTTP configuration, validation, server preparation, and configuration tests. | +| [`server.rs`](server.rs) | Router construction, server execution, and route/WebSocket tests. | +| [`handlers.rs`](handlers.rs) | Shared state, pre-serialized catalog responses, and WebSocket handoff. | + +The response models and transformations from `Adj` belong to +[`software_core::adj`](../../../core/src/adj.rs). Their JSON examples are in +[`core/src/adj/http/example`](../../../core/src/adj/http/example). + +## Routes + +| Method | Path | Response | +| --- | --- | --- | +| GET | `/backend/adj/DataPackets` | Boards and data packet definitions, without measurement protections. | +| GET | `/backend/adj/OrderPackets` | Boards and order definitions, including parameter protections. | +| GET | `/backend/adj/ProtectionPackets` | Flat protection catalog and protection-type display metadata. | +| GET with WebSocket upgrade headers | `/backend` | Upgrades the connection and hands the socket to the configured channel. | + +Catalog responses return `200 OK` with `Content-Type: application/json`. + +## Catalog lifecycle + +When the router is built, the server: + +1. Builds the three response structures from the already-loaded `Adj`. +2. Serializes each response once into `Bytes`. +3. Stores the bytes in shared `Arc` state. + +Each request clones the relevant `Bytes` handle and sends the existing JSON +buffer. It does not rebuild the catalog, copy the whole buffer, or serialize +the response again. No application-level mutex is needed for these reads. + +The catalogs are a snapshot of the ADJ at startup; they are not refreshed +automatically. Serialization errors are propagated before requests are served. +This in-memory reuse is separate from browser caching. `configure_server` +applies the configured `Cache-Control` policy to the catalog routes. The older +listener-based entry points do not set an explicit cache policy. + +## Starting the server + +The caller supplies a bound `tokio::net::TcpListener` and an already-loaded +`&Adj`. The listener determines the address and port. Both entry points are +async and run until the server stops. + +Without a WebSocket consumer: + +```rust +http::serve(listener, &adj).await?; +``` + +With a bounded `tokio::sync::mpsc::Sender` whose +receiver belongs to the future WebSocket module: + +```rust +http::serve_with_websocket(listener, &adj, Some(sender)).await?; +``` + +Passing `None` to `serve_with_websocket` has the same behavior as `serve`. + +## WebSocket handoff + +The HTTP handler only performs the handshake and transfers ownership of the +socket. It does not read messages, manage clients, implement subscriptions, +broadcast telemetry, or execute orders. + +Before approving an upgrade, it reserves a slot in the bounded channel: + +- With an available slot, it completes the handshake (`101 Switching Protocols` + for HTTP/1.1) and places the socket in the channel. +- Without a configured channel, with a closed receiver, or with no available + capacity, it returns `503 Service Unavailable` instead of upgrading. +- Invalid upgrade requests are rejected by Axum's `WebSocketUpgrade` extractor. + +The future WebSocket module must consume the receiver and manage each socket's +lifetime, messages, and closure. Keeping a receiver alive without reading it +does not provide a functioning WebSocket service; the queue will eventually +fill. If the receiver disappears during the handoff, the socket is dropped. + +## Configuration + +`HttpConfig` is defined provisionally in `configure.rs` and reexported by `http`. +It does not depend on the future application configuration module or read files +and environment variables. + +| Field | Purpose | +| --- | --- | +| `bind_addr` | Explicit IP address and port to bind; port zero requests an available port. | +| `allowed_origins` | Exact HTTP(S) origins allowed by CORS; an empty list allows none. | +| `cache_policy` | Catalog policy: `NoStore`, `NoCache`, or `Unspecified`. | + +`HttpConfig::new(bind_addr)` uses no allowed CORS origins and defaults to +`CachePolicy::NoStore` (`Cache-Control: no-store`). `NoCache` allows storage +but requires revalidation before reuse; `Unspecified` sets no Cache-Control +header. These policies do not affect the server's reusable JSON buffers and +are not applied to WebSocket upgrades. + +The configuration path prepares the server without starting it: + +```rust +let mut config = http::HttpConfig::new("127.0.0.1:8080".parse()?); +config.allowed_origins = vec!["http://localhost:9000".into()]; + +let (listener, router) = http::configure_server(&config, &adj, None).await?; +axum::serve(listener, router).await?; +``` + +`configure_server` validates origins and serializes the catalogs before binding +the listener. Invalid settings and binding errors are returned to the caller; +there is no fallback to another address or port. To enable socket handoff, +replace `None` with `Some(sender)` as described above. + +CORS permits GET and HEAD from explicitly listed origins, handles preflight +requests, and does not enable credentials. Wildcards and origin URLs with +embedded credentials, paths (including a trailing slash), queries, fragments, +or invalid ports are rejected. The opaque origin `null` can be explicitly +listed for local-file clients, but it is not exclusive to Electron: other +opaque origins share it too. + +CORS controls browser access to responses; it is not HTTP authentication. +WebSocket Origin validation is still not implemented and is independent of +CORS. The existing `serve` and `serve_with_websocket` entry points remain +available for the current test startup and do not apply `HttpConfig` policies. + +## Manual checks + +From the backend workspace root, the current `main.rs` test startup can be run +with: + +```sh +cargo run -p station --locked +``` + +It currently loads the ADJ fixture and listens on `127.0.0.1:8080`. These are +temporary test settings, not configuration defaults. It uses `http::serve`, so +valid WebSocket upgrade requests receive `503` until a consumer is integrated. + +In another terminal: + +```sh +curl -i http://127.0.0.1:8080/backend/adj/DataPackets +curl -i http://127.0.0.1:8080/backend/adj/OrderPackets +curl -i http://127.0.0.1:8080/backend/adj/ProtectionPackets +``` + +## Tests + +From the backend workspace root: + +```sh +cargo test -p station http:: --locked +``` + +The tests cover catalog contents and repeated responses, empty catalogs, +configuration validation, binding errors, cache headers, CORS and preflight +handling, WebSocket upgrade and socket delivery over a real TCP connection, +unavailable channels (missing, closed, or full), and requests without upgrade +headers. From 8896a8e9e08b7e875318ec3e56cca76a13d6aba3 Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Mon, 16 Nov 2026 18:19:53 +0100 Subject: [PATCH 128/225] refactor(backend, http): move http to model and simplify adj.rs moving the implementation of Adj to http.rs --- backend/crates/core/src/adj.rs | 206 +---------------- backend/crates/core/src/adj/http.rs | 210 +++++++++++++++++- backend/crates/core/src/model.rs | 3 + backend/crates/core/src/model/http.rs | 9 + .../core/src/{adj => model}/http/README.md | 0 .../core/src/{adj => model}/http/data.rs | 0 .../src/{adj => model}/http/example/data.json | 0 .../{adj => model}/http/example/order.json | 0 .../http/example/protection.json | 0 .../core/src/{adj => model}/http/order.rs | 0 .../src/{adj => model}/http/protection.rs | 0 11 files changed, 216 insertions(+), 212 deletions(-) create mode 100644 backend/crates/core/src/model/http.rs rename backend/crates/core/src/{adj => model}/http/README.md (100%) rename backend/crates/core/src/{adj => model}/http/data.rs (100%) rename backend/crates/core/src/{adj => model}/http/example/data.json (100%) rename backend/crates/core/src/{adj => model}/http/example/order.json (100%) rename backend/crates/core/src/{adj => model}/http/example/protection.json (100%) rename backend/crates/core/src/{adj => model}/http/order.rs (100%) rename backend/crates/core/src/{adj => model}/http/protection.rs (100%) diff --git a/backend/crates/core/src/adj.rs b/backend/crates/core/src/adj.rs index 854800f4f..0110db68d 100644 --- a/backend/crates/core/src/adj.rs +++ b/backend/crates/core/src/adj.rs @@ -21,6 +21,7 @@ mod info; mod raw; #[cfg(feature = "http")] +/// asdfasd pub mod http; #[cfg(feature = "git")] @@ -47,211 +48,6 @@ pub struct Adj { pub info: AdjInfo, } -#[cfg(feature = "http")] -use self::http::{ - data::{ - DataBoardResponse, DataMeasurementKind, DataMeasurementResponse, DataPacketResponse, - DataResponse, - }, - order::{ - OrderBoardResponse, OrderMeasurementResponse, OrderPacketResponse, OrderProtectionResponse, - OrderResponse, - }, - protection::{ProtectionInfoResponse, ProtectionResponse, ProtectionTypeResponse}, -}; - -#[cfg(feature = "http")] -use crate::model::{MeasurementKind, PacketType}; - -#[cfg(feature = "http")] -impl Adj { - /// Builds the data catalog without modifying or consuming the ADJ. - /// - /// Boards and data packets are sorted by id. Boards without data packets are - /// retained with an empty list. Measurements keep their wire order and omit - /// protection metadata. - pub fn data_response(&self) -> DataResponse { - let mut boards: Vec = self - .pod_data - .boards - .values() - .map(|board| { - let mut packets: Vec = board - .packets - .values() - .filter_map(|packet| { - let PacketType::Data(measurements) = &packet.packet_type else { - return None; - }; - - Some(DataPacketResponse { - id: packet.id, - name: packet.name.clone(), - packet_type: "data".to_string(), - measurements: measurements - .iter() - .map(|measurement| DataMeasurementResponse { - id: measurement.id, - alias: measurement.alias.clone(), - name: measurement.name.clone(), - display_units: measurement.display_units.clone(), - kind: match &measurement.kind { - MeasurementKind::Numeric { wire_type } => { - DataMeasurementKind::Numeric { - wire_type: *wire_type, - } - } - MeasurementKind::Boolean => DataMeasurementKind::Boolean, - MeasurementKind::Enum { options } => { - DataMeasurementKind::Enum { - options: options.clone(), - } - } - }, - }) - .collect(), - }) - }) - .collect(); - packets.sort_unstable_by_key(|packet| packet.id.0); - - DataBoardResponse { - id: board.id, - name: board.name.clone(), - packets, - } - }) - .collect(); - boards.sort_unstable_by_key(|board| board.id.0); - - DataResponse { boards } - } - - /// Builds the order catalog without modifying or consuming the ADJ. - /// - /// Boards and orders are sorted by id. Boards without orders are retained with - /// an empty list. Parameters and their protections keep their ADJ order; - /// protection ids remain their one-based positions within each measurement. - pub fn order_response(&self) -> OrderResponse { - let mut boards: Vec = self - .pod_data - .boards - .values() - .map(|board| { - let mut orders: Vec = board - .packets - .values() - .filter_map(|packet| { - let PacketType::Order(measurements) = &packet.packet_type else { - return None; - }; - - Some(OrderPacketResponse { - id: packet.id, - name: packet.name.clone(), - packet_type: "order".to_string(), - measurements: measurements - .iter() - .map(|measurement| OrderMeasurementResponse { - id: measurement.id, - alias: measurement.alias.clone(), - name: measurement.name.clone(), - display_units: measurement.display_units.clone(), - kind: match &measurement.kind { - MeasurementKind::Numeric { wire_type } => { - DataMeasurementKind::Numeric { - wire_type: *wire_type, - } - } - MeasurementKind::Boolean => DataMeasurementKind::Boolean, - MeasurementKind::Enum { options } => { - DataMeasurementKind::Enum { - options: options.clone(), - } - } - }, - protections: measurement - .protections - .iter() - .map(|protection| OrderProtectionResponse { - id: protection.id, - kind: protection.kind, - severity: protection.severity, - time: protection.time, - }) - .collect(), - }) - .collect(), - }) - }) - .collect(); - orders.sort_unstable_by_key(|order| order.id.0); - - OrderBoardResponse { - id: board.id, - name: board.name.clone(), - orders, - } - }) - .collect(); - boards.sort_unstable_by_key(|board| board.id.0); - - OrderResponse { boards } - } - - /// Builds the flat protection catalog without modifying or consuming the ADJ. - /// - /// Protection packet ids and names are reused from the loader. The position in - /// each compound id selects its definition within the watched measurement. - /// Packets with no definition at that position are omitted. The resulting list - /// is sorted by packet id, then board id to break ties. - pub fn protection_response(&self) -> ProtectionResponse { - let mut protections: Vec = self - .pod_data - .boards - .values() - .flat_map(|board| board.packets.values()) - .filter_map(|packet| { - let PacketType::Protection(measurement) = &packet.packet_type else { - return None; - }; - - let index = usize::from(packet.id.protection_position()).checked_sub(1)?; - let protection = measurement.protections.get(index)?; - - Some(ProtectionInfoResponse { - id: packet.id, - name: packet.name.clone(), - board_id: packet.board, - measurement_id: measurement.id, - kind: protection.kind, - severity: protection.severity, - time: protection.time, - }) - }) - .collect(); - protections.sort_unstable_by_key(|protection| (protection.id.0, protection.board_id.0)); - - let info = self - .info - .protection_types - .iter() - .map(|(name, metadata)| { - ( - name.clone(), - ProtectionTypeResponse { - is_range: metadata.is_range, - text: metadata.text.clone(), - text_time: metadata.text_time.clone(), - }, - ) - }) - .collect(); - - ProtectionResponse { protections, info } - } -} - /// The result of [`auto_adj`]: the loaded ADJ data and the checked-out commit hash. #[cfg(feature = "git")] #[derive(Debug, Clone)] diff --git a/backend/crates/core/src/adj/http.rs b/backend/crates/core/src/adj/http.rs index d577f026c..f96c7ef1a 100644 --- a/backend/crates/core/src/adj/http.rs +++ b/backend/crates/core/src/adj/http.rs @@ -1,9 +1,205 @@ -//! Models for HTTP response bodies. +use crate::{ + adj::Adj, + model::{ + MeasurementKind, PacketType, + http::{ + data::{ + DataBoardResponse, DataMeasurementKind, DataMeasurementResponse, + DataPacketResponse, DataResponse, + }, + order::{ + OrderBoardResponse, OrderMeasurementResponse, OrderPacketResponse, + OrderProtectionResponse, OrderResponse, + }, + protection::{ProtectionInfoResponse, ProtectionResponse, ProtectionTypeResponse}, + }, + }, +}; -pub(super) mod data; -pub(super) mod order; -pub(super) mod protection; +impl Adj { + /// Builds the data catalog without modifying or consuming the ADJ. + /// + /// Boards and data packets are sorted by id. Boards without data packets are + /// retained with an empty list. Measurements keep their wire order and omit + /// protection metadata. + pub fn data_response(&self) -> DataResponse { + let mut boards: Vec = self + .pod_data + .boards + .values() + .map(|board| { + let mut packets: Vec = board + .packets + .values() + .filter_map(|packet| { + let PacketType::Data(measurements) = &packet.packet_type else { + return None; + }; -pub use data::DataResponse; -pub use order::OrderResponse; -pub use protection::ProtectionResponse; + Some(DataPacketResponse { + id: packet.id, + name: packet.name.clone(), + packet_type: "data".to_string(), + measurements: measurements + .iter() + .map(|measurement| DataMeasurementResponse { + id: measurement.id, + alias: measurement.alias.clone(), + name: measurement.name.clone(), + display_units: measurement.display_units.clone(), + kind: match &measurement.kind { + MeasurementKind::Numeric { wire_type } => { + DataMeasurementKind::Numeric { + wire_type: *wire_type, + } + } + MeasurementKind::Boolean => DataMeasurementKind::Boolean, + MeasurementKind::Enum { options } => { + DataMeasurementKind::Enum { + options: options.clone(), + } + } + }, + }) + .collect(), + }) + }) + .collect(); + packets.sort_unstable_by_key(|packet| packet.id.0); + + DataBoardResponse { + id: board.id, + name: board.name.clone(), + packets, + } + }) + .collect(); + boards.sort_unstable_by_key(|board| board.id.0); + + DataResponse { boards } + } + + /// Builds the order catalog without modifying or consuming the ADJ. + /// + /// Boards and orders are sorted by id. Boards without orders are retained with + /// an empty list. Parameters and their protections keep their ADJ order; + /// protection ids remain their one-based positions within each measurement. + pub fn order_response(&self) -> OrderResponse { + let mut boards: Vec = self + .pod_data + .boards + .values() + .map(|board| { + let mut orders: Vec = board + .packets + .values() + .filter_map(|packet| { + let PacketType::Order(measurements) = &packet.packet_type else { + return None; + }; + + Some(OrderPacketResponse { + id: packet.id, + name: packet.name.clone(), + packet_type: "order".to_string(), + measurements: measurements + .iter() + .map(|measurement| OrderMeasurementResponse { + id: measurement.id, + alias: measurement.alias.clone(), + name: measurement.name.clone(), + display_units: measurement.display_units.clone(), + kind: match &measurement.kind { + MeasurementKind::Numeric { wire_type } => { + DataMeasurementKind::Numeric { + wire_type: *wire_type, + } + } + MeasurementKind::Boolean => DataMeasurementKind::Boolean, + MeasurementKind::Enum { options } => { + DataMeasurementKind::Enum { + options: options.clone(), + } + } + }, + protections: measurement + .protections + .iter() + .map(|protection| OrderProtectionResponse { + id: protection.id, + kind: protection.kind, + severity: protection.severity, + time: protection.time, + }) + .collect(), + }) + .collect(), + }) + }) + .collect(); + orders.sort_unstable_by_key(|order| order.id.0); + + OrderBoardResponse { + id: board.id, + name: board.name.clone(), + orders, + } + }) + .collect(); + boards.sort_unstable_by_key(|board| board.id.0); + + OrderResponse { boards } + } + + /// Builds the flat protection catalog without modifying or consuming the ADJ. + /// + /// Protection packet ids and names are reused from the loader. The position in + /// each compound id selects its definition within the watched measurement. + /// Packets with no definition at that position are omitted. The resulting list + /// is sorted by packet id, then board id to break ties. + pub fn protection_response(&self) -> ProtectionResponse { + let mut protections: Vec = self + .pod_data + .boards + .values() + .flat_map(|board| board.packets.values()) + .filter_map(|packet| { + let PacketType::Protection(measurement) = &packet.packet_type else { + return None; + }; + + let index = usize::from(packet.id.protection_position()).checked_sub(1)?; + let protection = measurement.protections.get(index)?; + + Some(ProtectionInfoResponse { + id: packet.id, + name: packet.name.clone(), + board_id: packet.board, + measurement_id: measurement.id, + kind: protection.kind, + severity: protection.severity, + time: protection.time, + }) + }) + .collect(); + protections.sort_unstable_by_key(|protection| (protection.id.0, protection.board_id.0)); + + let info = self + .info + .protection_types + .iter() + .map(|(name, metadata)| { + ( + name.clone(), + ProtectionTypeResponse { + is_range: metadata.is_range, + text: metadata.text.clone(), + text_time: metadata.text_time.clone(), + }, + ) + }) + .collect(); + + ProtectionResponse { protections, info } + } +} diff --git a/backend/crates/core/src/model.rs b/backend/crates/core/src/model.rs index 75cdb319e..74b79b99a 100644 --- a/backend/crates/core/src/model.rs +++ b/backend/crates/core/src/model.rs @@ -17,6 +17,9 @@ mod packet; mod protections; mod value; +#[cfg(feature = "http")] +pub mod http; + pub use board::{Board, PacketDef, PacketType, PodData}; pub use id::{AdjId, BoardId, MacAddress, Port}; pub use measurement::{Measurement, MeasurementKind, NumericKind, Range}; diff --git a/backend/crates/core/src/model/http.rs b/backend/crates/core/src/model/http.rs new file mode 100644 index 000000000..837d95618 --- /dev/null +++ b/backend/crates/core/src/model/http.rs @@ -0,0 +1,9 @@ +//! Models for HTTP response bodies. + +pub(crate) mod data; +pub(crate) mod order; +pub(crate) mod protection; + +pub use data::DataResponse; +pub use order::OrderResponse; +pub use protection::ProtectionResponse; diff --git a/backend/crates/core/src/adj/http/README.md b/backend/crates/core/src/model/http/README.md similarity index 100% rename from backend/crates/core/src/adj/http/README.md rename to backend/crates/core/src/model/http/README.md diff --git a/backend/crates/core/src/adj/http/data.rs b/backend/crates/core/src/model/http/data.rs similarity index 100% rename from backend/crates/core/src/adj/http/data.rs rename to backend/crates/core/src/model/http/data.rs diff --git a/backend/crates/core/src/adj/http/example/data.json b/backend/crates/core/src/model/http/example/data.json similarity index 100% rename from backend/crates/core/src/adj/http/example/data.json rename to backend/crates/core/src/model/http/example/data.json diff --git a/backend/crates/core/src/adj/http/example/order.json b/backend/crates/core/src/model/http/example/order.json similarity index 100% rename from backend/crates/core/src/adj/http/example/order.json rename to backend/crates/core/src/model/http/example/order.json diff --git a/backend/crates/core/src/adj/http/example/protection.json b/backend/crates/core/src/model/http/example/protection.json similarity index 100% rename from backend/crates/core/src/adj/http/example/protection.json rename to backend/crates/core/src/model/http/example/protection.json diff --git a/backend/crates/core/src/adj/http/order.rs b/backend/crates/core/src/model/http/order.rs similarity index 100% rename from backend/crates/core/src/adj/http/order.rs rename to backend/crates/core/src/model/http/order.rs diff --git a/backend/crates/core/src/adj/http/protection.rs b/backend/crates/core/src/model/http/protection.rs similarity index 100% rename from backend/crates/core/src/adj/http/protection.rs rename to backend/crates/core/src/model/http/protection.rs From e30d059448a4ef783602b54647e47a4052a06397 Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Tue, 17 Nov 2026 00:22:39 +0100 Subject: [PATCH 129/225] fix(backend, http): problems with time and other minor fixes --- backend/crates/core/src/adj.rs | 5 +- backend/crates/core/src/adj/http.rs | 69 +++++++++++-------- .../core/src/model/http/example/order.json | 11 +-- .../src/model/http/example/protection.json | 16 +---- backend/crates/core/src/model/http/order.rs | 9 ++- .../crates/core/src/model/http/protection.rs | 9 +-- 6 files changed, 57 insertions(+), 62 deletions(-) diff --git a/backend/crates/core/src/adj.rs b/backend/crates/core/src/adj.rs index 0110db68d..d47286223 100644 --- a/backend/crates/core/src/adj.rs +++ b/backend/crates/core/src/adj.rs @@ -20,10 +20,13 @@ mod error; mod info; mod raw; +// To activate this module the feature "http" is required +// The structures used in this module aren't used for any other reason #[cfg(feature = "http")] -/// asdfasd +/// Strctures for the responses of the HTTP requests pub mod http; +// Imports for the "git" feature #[cfg(feature = "git")] use std::path::PathBuf; #[cfg(feature = "git")] diff --git a/backend/crates/core/src/adj/http.rs b/backend/crates/core/src/adj/http.rs index f96c7ef1a..1d57463f2 100644 --- a/backend/crates/core/src/adj/http.rs +++ b/backend/crates/core/src/adj/http.rs @@ -1,7 +1,7 @@ use crate::{ adj::Adj, model::{ - MeasurementKind, PacketType, + AdjId, MeasurementKind, PacketType, http::{ data::{ DataBoardResponse, DataMeasurementKind, DataMeasurementResponse, @@ -16,6 +16,8 @@ use crate::{ }, }; +use std::time::Duration; + impl Adj { /// Builds the data catalog without modifying or consuming the ADJ. /// @@ -47,19 +49,7 @@ impl Adj { alias: measurement.alias.clone(), name: measurement.name.clone(), display_units: measurement.display_units.clone(), - kind: match &measurement.kind { - MeasurementKind::Numeric { wire_type } => { - DataMeasurementKind::Numeric { - wire_type: *wire_type, - } - } - MeasurementKind::Boolean => DataMeasurementKind::Boolean, - MeasurementKind::Enum { options } => { - DataMeasurementKind::Enum { - options: options.clone(), - } - } - }, + kind: match_measurement_kind(&measurement.kind), }) .collect(), }) @@ -109,27 +99,15 @@ impl Adj { alias: measurement.alias.clone(), name: measurement.name.clone(), display_units: measurement.display_units.clone(), - kind: match &measurement.kind { - MeasurementKind::Numeric { wire_type } => { - DataMeasurementKind::Numeric { - wire_type: *wire_type, - } - } - MeasurementKind::Boolean => DataMeasurementKind::Boolean, - MeasurementKind::Enum { options } => { - DataMeasurementKind::Enum { - options: options.clone(), - } - } - }, + kind: match_measurement_kind(&measurement.kind), protections: measurement .protections .iter() .map(|protection| OrderProtectionResponse { - id: protection.id, + id: AdjId((protection.id.0 << 13) | measurement.id.0), kind: protection.kind, severity: protection.severity, - time: protection.time, + time: protection_time_to_nanos(protection.time), }) .collect(), }) @@ -178,7 +156,7 @@ impl Adj { measurement_id: measurement.id, kind: protection.kind, severity: protection.severity, - time: protection.time, + time: protection_time_to_nanos(protection.time), }) }) .collect(); @@ -203,3 +181,34 @@ impl Adj { ProtectionResponse { protections, info } } } + +// Returns Some("(time)xs") if the time is not 0 +fn protection_time_to_nanos(time: Duration) -> Option { + if time == Duration::new(0, 0) { + None + } else { + // If the duration is in nanoseconds (default) + let mut res = format!("{}ns", time.as_nanos().to_string()); + + if time.as_millis() > 0 { + res = format!("{}ms", time.as_millis().to_string()); + } else if time.as_micros() > 0 { + res = format!("{}us", time.as_micros().to_string()); + } + + Some(res) + } +} + +// Matches the kind of measurement and returns the specific type/structure +fn match_measurement_kind(measurement: &MeasurementKind) -> DataMeasurementKind { + match measurement { + MeasurementKind::Numeric { wire_type } => DataMeasurementKind::Numeric { + wire_type: *wire_type, + }, + MeasurementKind::Boolean => DataMeasurementKind::Boolean, + MeasurementKind::Enum { options } => DataMeasurementKind::Enum { + options: options.clone(), + }, + } +} diff --git a/backend/crates/core/src/model/http/example/order.json b/backend/crates/core/src/model/http/example/order.json index f4951532b..06d460bbe 100644 --- a/backend/crates/core/src/model/http/example/order.json +++ b/backend/crates/core/src/model/http/example/order.json @@ -26,11 +26,7 @@ "min": 0.0, "max": 50.0 }, - "severity": "fault", - "time": { - "secs": 0, - "nanos": 0 - } + "severity": "fault" }, { "id": 2, @@ -39,10 +35,7 @@ "limit": 40.0 }, "severity": "warning", - "time": { - "secs": 0, - "nanos": 500000000 - } + "time": "200ms" } ] } diff --git a/backend/crates/core/src/model/http/example/protection.json b/backend/crates/core/src/model/http/example/protection.json index 3c4cf66d7..4cb3cd0ba 100644 --- a/backend/crates/core/src/model/http/example/protection.json +++ b/backend/crates/core/src/model/http/example/protection.json @@ -11,10 +11,7 @@ "max": 100.0 }, "severity": "fault", - "time": { - "secs": 0, - "nanos": 500000000 - } + "time": "500ms" }, { "id": 19384, @@ -26,10 +23,7 @@ "limit": 10.0 }, "severity": "warning", - "time": { - "secs": 1, - "nanos": 0 - } + "time": "1s" }, { "id": 11292, @@ -41,11 +35,7 @@ "min": 300.0, "max": 500.0 }, - "severity": "fault", - "time": { - "secs": 0, - "nanos": 0 - } + "severity": "fault" } ], "info": { diff --git a/backend/crates/core/src/model/http/order.rs b/backend/crates/core/src/model/http/order.rs index 330615022..feb7d8614 100644 --- a/backend/crates/core/src/model/http/order.rs +++ b/backend/crates/core/src/model/http/order.rs @@ -1,7 +1,5 @@ //! ADJ v3 order catalog returned by `/backend/adj/OrderPackets`. -use std::time::Duration; - use serde::Serialize; use crate::{ @@ -68,7 +66,7 @@ pub struct OrderMeasurementResponse { /// A parameter protection's definition, not a triggered protection event. #[derive(Debug, Clone, PartialEq, Serialize)] pub struct OrderProtectionResponse { - /// One-based protection position within its measurement, not a packet id. + /// id of the protection, composed as specified #[serde(serialize_with = "serialize_adj_id")] pub id: AdjId, /// Trigger condition, serialized with its type and named bounds. @@ -77,6 +75,7 @@ pub struct OrderProtectionResponse { /// Severity serialized as `fault` or `warning`. #[serde(serialize_with = "serialize_severity")] pub severity: Severity, - /// Required duration, serialized as `{"secs": ..., "nanos": ...}`. - pub time: Duration, + /// Optional duration. + #[serde(skip_serializing_if = "Option::is_none")] + pub time: Option, } diff --git a/backend/crates/core/src/model/http/protection.rs b/backend/crates/core/src/model/http/protection.rs index a19cabde6..f5965e0fd 100644 --- a/backend/crates/core/src/model/http/protection.rs +++ b/backend/crates/core/src/model/http/protection.rs @@ -1,6 +1,6 @@ //! Flat ADJ v3 protection catalog returned by `/backend/adj/ProtectionPackets`. -use std::{collections::HashMap, time::Duration}; +use std::collections::HashMap; use serde::Serialize; @@ -42,8 +42,9 @@ pub struct ProtectionInfoResponse { /// Severity serialized as `fault` or `warning`. #[serde(serialize_with = "serialize_severity")] pub severity: Severity, - /// Required duration, serialized as `{"secs": ..., "nanos": ...}`. - pub time: Duration, + /// Optional duration. + #[serde(skip_serializing_if = "Option::is_none")] + pub time: Option, } /// Display metadata for one entry of `general_info.json`'s `protectionTypes`. @@ -55,6 +56,6 @@ pub struct ProtectionTypeResponse { /// Display template; `{}` marks bounds and `%` the measured value. pub text: String, /// Optional time-related display template, omitted if absent from the ADJ. - #[serde(rename = "textTime", skip_serializing_if = "Option::is_none")] + #[serde(skip_serializing_if = "Option::is_none")] pub text_time: Option, } From 9b5045e5640c9e766c65d913efa1d6fe32aca0ec Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Tue, 17 Nov 2026 00:55:29 +0100 Subject: [PATCH 130/225] fix(backend, http): add comments --- backend/crates/core/src/adj/http.rs | 14 ++++++++ .../crates/core/src/model/http/protection.rs | 4 +-- backend/crates/core/src/utils/serialize.rs | 32 ++++++++----------- 3 files changed, 29 insertions(+), 21 deletions(-) diff --git a/backend/crates/core/src/adj/http.rs b/backend/crates/core/src/adj/http.rs index 1d57463f2..5feeca4a5 100644 --- a/backend/crates/core/src/adj/http.rs +++ b/backend/crates/core/src/adj/http.rs @@ -29,11 +29,14 @@ impl Adj { .pod_data .boards .values() + // For each board .map(|board| { let mut packets: Vec = board .packets .values() + // For each packet of this board .filter_map(|packet| { + // If the PacketType is Data, return Some(DataPacketResponse) -> Will be a Vec let PacketType::Data(measurements) = &packet.packet_type else { return None; }; @@ -57,13 +60,17 @@ impl Adj { .collect(); packets.sort_unstable_by_key(|packet| packet.id.0); + // Set up each packet DataBoardResponse { id: board.id, name: board.name.clone(), packets, } }) + // Obtain a Vec<> of all the packets .collect(); + + // Sort the responses by board.id boards.sort_unstable_by_key(|board| board.id.0); DataResponse { boards } @@ -79,15 +86,19 @@ impl Adj { .pod_data .boards .values() + // For each board .map(|board| { let mut orders: Vec = board .packets .values() + // For each order of this board .filter_map(|packet| { + // If the packet is an Order... let PacketType::Order(measurements) = &packet.packet_type else { return None; }; + // Setup of the response Some(OrderPacketResponse { id: packet.id, name: packet.name.clone(), @@ -114,6 +125,7 @@ impl Adj { .collect(), }) }) + // Collect all the OrderPacketResponses .collect(); orders.sort_unstable_by_key(|order| order.id.0); @@ -140,8 +152,10 @@ impl Adj { .pod_data .boards .values() + // For each board .flat_map(|board| board.packets.values()) .filter_map(|packet| { + // If the packet is of type Protection... let PacketType::Protection(measurement) = &packet.packet_type else { return None; }; diff --git a/backend/crates/core/src/model/http/protection.rs b/backend/crates/core/src/model/http/protection.rs index f5965e0fd..132f4e66d 100644 --- a/backend/crates/core/src/model/http/protection.rs +++ b/backend/crates/core/src/model/http/protection.rs @@ -7,7 +7,7 @@ use serde::Serialize; use crate::{ model::{AdjId, BoardId, ProtectionKind, Severity}, utils::serialize::{ - serialize_adj_id, serialize_adj_protection_kind, serialize_board_id, serialize_severity, + serialize_adj_id, serialize_protection_kind, serialize_board_id, serialize_severity, }, }; @@ -37,7 +37,7 @@ pub struct ProtectionInfoResponse { #[serde(serialize_with = "serialize_adj_id")] pub measurement_id: AdjId, /// Trigger condition; `type` preserves the ADJ name to index `info` directly. - #[serde(serialize_with = "serialize_adj_protection_kind")] + #[serde(serialize_with = "serialize_protection_kind")] pub kind: ProtectionKind, /// Severity serialized as `fault` or `warning`. #[serde(serialize_with = "serialize_severity")] diff --git a/backend/crates/core/src/utils/serialize.rs b/backend/crates/core/src/utils/serialize.rs index 99e880cfe..1a8e3354d 100644 --- a/backend/crates/core/src/utils/serialize.rs +++ b/backend/crates/core/src/utils/serialize.rs @@ -1,6 +1,17 @@ use crate::model::{AdjId, BoardId, NumericKind, ProtectionKind, Severity}; use serde::{Serialize, Serializer}; +// EXPLANATION OF THE OBJECT SERIALIZER +// When using the macro #[serde(serialize_with = "")] you specify a function +// which takes to arguments: +// - 1st with the type of the atribute you apply the object +// - 2nd with the type `Serializer` +// The second one is just for setting the specified value obtained in the function +// when the serialization occurs. Very simple. +// +// If you want to serialize a structure you have to implement the trait Serialize, +// which + // Serialize domain types locally without changing the internal model. pub(crate) fn serialize_board_id( id: &BoardId, @@ -38,6 +49,7 @@ pub(crate) fn serialize_numeric_kind( // A remote derive keeps the JSON representation here, without changing model. #[derive(Serialize)] +// Mirroring the struct `ProtectionKind`, we our rules for serialization. #[serde(remote = "ProtectionKind", tag = "type", rename_all = "snake_case")] enum ProtectionKindDef { Above { limit: f64 }, @@ -51,28 +63,10 @@ pub(crate) fn serialize_protection_kind( kind: &ProtectionKind, serializer: S, ) -> Result { + // We apply the serialization to this specific enum, with rules setted in the definition ProtectionKindDef::serialize(kind, serializer) } -// This endpoint indexes general_info.json's protectionTypes by the original -// ADJ names. Keep the order response's existing snake_case format unchanged. -#[derive(Serialize)] -#[serde(remote = "ProtectionKind", tag = "type")] -enum AdjProtectionKindDef { - Above { limit: f64 }, - Below { limit: f64 }, - Equal { target: f64 }, - NotEqual { target: f64 }, - Range { min: f64, max: f64 }, -} - -pub(crate) fn serialize_adj_protection_kind( - kind: &ProtectionKind, - serializer: S, -) -> Result { - AdjProtectionKindDef::serialize(kind, serializer) -} - pub(crate) fn serialize_severity( severity: &Severity, serializer: S, From 2817ae7829536b6964f6c88455220ff3ad561983 Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Tue, 17 Nov 2026 01:20:22 +0100 Subject: [PATCH 131/225] fix(backend, http): simplification of server configuration --- backend/crates/station/src/http.rs | 23 +- backend/crates/station/src/http/configure.rs | 381 ------------------- backend/crates/station/src/http/handlers.rs | 2 +- backend/crates/station/src/http/server.rs | 151 ++++++-- 4 files changed, 120 insertions(+), 437 deletions(-) delete mode 100644 backend/crates/station/src/http/configure.rs diff --git a/backend/crates/station/src/http.rs b/backend/crates/station/src/http.rs index f0d2d6484..50183c88e 100644 --- a/backend/crates/station/src/http.rs +++ b/backend/crates/station/src/http.rs @@ -6,27 +6,24 @@ use std::io; +use axum::extract::ws::WebSocket; use software_core::adj::Adj; -use tokio::net::TcpListener; +use tokio::{net::TcpListener, sync::mpsc}; + +use crate::http::server::setup_router; -mod configure; mod handlers; mod server; -pub use server::serve_with_websocket; -// The test main still uses the listener-based entry point. Configuration will -// be connected by the application startup when its config module is available. -#[allow( - unused_imports, - reason = "The test startup does not use configuration yet" -)] -pub use configure::{CachePolicy, HttpConfig, configure_server}; - /// Serves the catalogs without connecting a WebSocket consumer yet. /// /// Preserves the entry point used by the test startup code. Upgrade requests /// to `/backend` receive `503` until [`serve_with_websocket`] is used with a /// channel connected to the future WebSocket module. -pub async fn serve(listener: TcpListener, adj: &Adj) -> io::Result<()> { - serve_with_websocket(listener, adj, None).await +pub async fn serve( + listener: TcpListener, + adj: &Adj, + ws: Option>, +) -> io::Result<()> { + axum::serve(listener, setup_router(adj, ws)?).await } diff --git a/backend/crates/station/src/http/configure.rs b/backend/crates/station/src/http/configure.rs deleted file mode 100644 index bf6a4a38f..000000000 --- a/backend/crates/station/src/http/configure.rs +++ /dev/null @@ -1,381 +0,0 @@ -//! Provisional HTTP settings, validation, and server preparation. - -use std::{io, net::SocketAddr}; - -use axum::{ - Router, - extract::ws::WebSocket, - http::{HeaderValue, Method, Uri, header}, -}; -use software_core::adj::Adj; -use tokio::{net::TcpListener, sync::mpsc}; -use tower_http::cors::{AllowOrigin, CorsLayer}; - -use super::server::router_with_cache; - -/// Provisional HTTP settings, independent of configuration files and ADJ data. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct HttpConfig { - /// Address and port to bind. Port zero requests an available port from the OS. - pub bind_addr: SocketAddr, - /// Exact HTTP(S) origins permitted by CORS; an empty list grants none. - /// - /// Wildcards, credentials, paths, queries, and fragments are not accepted. - /// The opaque origin `null` can be explicitly allowed for local-file clients, - /// but it is shared by other opaque origins too, not exclusive to Electron. - /// This list does not perform WebSocket Origin validation. - pub allowed_origins: Vec, - /// Cache-Control policy for the three catalog routes, not WebSocket upgrades. - pub cache_policy: CachePolicy, -} - -impl HttpConfig { - /// Uses an explicit bind address, no allowed CORS origins, and `no-store`. - pub fn new(bind_addr: SocketAddr) -> Self { - Self { - bind_addr, - allowed_origins: Vec::new(), - cache_policy: CachePolicy::default(), - } - } -} - -/// HTTP caching is independent of the pre-serialized buffers held by the server. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] -pub enum CachePolicy { - /// Do not emit an explicit Cache-Control header. - Unspecified, - /// Allow storage, but require revalidation before reuse (`no-cache`). - NoCache, - /// Prevent clients and intermediaries from storing responses (`no-store`). - #[default] - NoStore, -} - -impl CachePolicy { - pub(super) fn header_value(self) -> Option { - match self { - Self::Unspecified => None, - Self::NoCache => Some(HeaderValue::from_static("no-cache")), - Self::NoStore => Some(HeaderValue::from_static("no-store")), - } - } -} - -/// Validates settings and prepares a bound listener and router without serving. -/// -/// The returned router owns the precomputed catalogs, CORS middleware, optional -/// WebSocket sender, and catalog cache policy. The caller can then run -/// `axum::serve(listener, router)`. Configuration is validated and responses are -/// serialized before binding, so invalid input does not leave a bound listener. -/// -/// This function consumes already-loaded settings and ADJ data. It does not -/// read configuration files or implement WebSocket Origin checks or messages. -/// -/// # Errors -/// -/// Returns `InvalidInput` for invalid CORS origins, serialization errors wrapped -/// in `io::Error`, or the error from binding the configured address. -pub async fn configure_server( - config: &HttpConfig, - adj: &Adj, - websocket_connections: Option>, -) -> io::Result<(TcpListener, Router)> { - let cors = cors_layer(&config.allowed_origins)?; - let app = router_with_cache(adj, websocket_connections, config.cache_policy)?.layer(cors); - let listener = TcpListener::bind(config.bind_addr).await?; - Ok((listener, app)) -} - -/// Validates the explicit origin list and builds CORS rules for GET and HEAD. -/// Rejects malformed origins with `InvalidInput`; an empty list permits none. -/// Handles preflight requests without enabling credentials or wildcard origins. -fn cors_layer(allowed_origins: &[String]) -> io::Result { - let origins = allowed_origins - .iter() - .map(|origin| { - let invalid = || { - io::Error::new( - io::ErrorKind::InvalidInput, - format!("invalid CORS origin {origin:?}: expected an HTTP(S) origin or null"), - ) - }; - let value = origin.parse::().map_err(|_| invalid())?; - if origin == "null" { - return Ok(value); - } - - let uri = origin.parse::().map_err(|_| invalid())?; - let (Some(scheme), Some(authority)) = (uri.scheme_str(), uri.authority()) else { - return Err(invalid()); - }; - if !matches!(scheme, "http" | "https") - || origin != &format!("{scheme}://{authority}") - || authority.host().is_empty() - || authority.as_str().contains(['@', '*']) - || (authority.as_str() != authority.host() && authority.port_u16().is_none()) - { - return Err(invalid()); - } - Ok(value) - }) - .collect::>>()?; - - // CORS controls browser access, not authentication or WebSocket origins. - Ok(CorsLayer::new() - .allow_origin(AllowOrigin::list(origins)) - .allow_methods([Method::GET, Method::HEAD]) - .allow_headers([header::ACCEPT, header::CONTENT_TYPE])) -} - -#[cfg(test)] -mod tests { - use std::{io, time::Duration}; - - use axum::{ - body::Body, - http::{Request, StatusCode, header}, - }; - use software_core::adj::Adj; - use tokio::{net::TcpListener, sync::mpsc, time::timeout}; - use tower::ServiceExt; - - use super::{CachePolicy, HttpConfig, configure_server, cors_layer}; - use crate::http::server::tests::{PATHS, handshake_on}; - - #[tokio::test] - async fn configuration_binds_the_requested_address_and_defaults_to_no_store() - -> Result<(), Box> { - let config = HttpConfig::new("127.0.0.1:0".parse()?); - assert!(config.allowed_origins.is_empty()); - assert_eq!(config.cache_policy, CachePolicy::NoStore); - let (listener, app) = configure_server(&config, &Adj::default(), None).await?; - assert_eq!(listener.local_addr()?.ip(), config.bind_addr.ip()); - assert_ne!(listener.local_addr()?.port(), 0); - - for path in PATHS { - let response = app - .clone() - .oneshot(Request::builder().uri(path).body(Body::empty())?) - .await?; - assert_eq!(response.status(), StatusCode::OK); - assert_eq!(response.headers()[header::CACHE_CONTROL], "no-store"); - assert_eq!(response.headers()[header::CONTENT_TYPE], "application/json"); - assert!( - !response - .headers() - .contains_key(header::ACCESS_CONTROL_ALLOW_ORIGIN) - ); - } - Ok(()) - } - - #[tokio::test] - async fn configured_cors_allows_only_explicit_origins() -> Result<(), Box> - { - let mut config = HttpConfig::new("127.0.0.1:0".parse()?); - config.allowed_origins = vec![ - "http://localhost:9000".into(), - "https://station.example".into(), - ]; - let (_listener, app) = configure_server(&config, &Adj::default(), None).await?; - - for origin in [ - "http://localhost:9000", - "https://station.example", - "http://untrusted.example", - ] { - let response = app - .clone() - .oneshot( - Request::builder() - .uri(PATHS[0]) - .header(header::ORIGIN, origin) - .body(Body::empty())?, - ) - .await?; - // CORS restricts browser access; it is not authorization for HTTP clients. - assert_eq!(response.status(), StatusCode::OK); - if config - .allowed_origins - .iter() - .any(|allowed| allowed == origin) - { - assert_eq!( - response.headers()[header::ACCESS_CONTROL_ALLOW_ORIGIN], - origin - ); - } else { - assert!( - !response - .headers() - .contains_key(header::ACCESS_CONTROL_ALLOW_ORIGIN) - ); - } - assert!( - !response - .headers() - .contains_key(header::ACCESS_CONTROL_ALLOW_CREDENTIALS) - ); - } - Ok(()) - } - - #[tokio::test] - async fn configured_cors_handles_preflight() -> Result<(), Box> { - let mut config = HttpConfig::new("127.0.0.1:0".parse()?); - config.allowed_origins.push("http://localhost:9000".into()); - let (_listener, app) = configure_server(&config, &Adj::default(), None).await?; - - for (origin, method, expected_origin) in [ - ( - "http://localhost:9000", - "GET", - Some("http://localhost:9000"), - ), - ("http://untrusted.example", "GET", None), - ( - "http://localhost:9000", - "POST", - Some("http://localhost:9000"), - ), - ] { - let response = app - .clone() - .oneshot( - Request::builder() - .method("OPTIONS") - .uri(PATHS[0]) - .header(header::ORIGIN, origin) - .header(header::ACCESS_CONTROL_REQUEST_METHOD, method) - .header(header::ACCESS_CONTROL_REQUEST_HEADERS, "content-type") - .body(Body::empty())?, - ) - .await?; - assert!(response.status().is_success()); - assert_eq!( - response - .headers() - .get(header::ACCESS_CONTROL_ALLOW_ORIGIN) - .map(|value| value.to_str()) - .transpose()?, - expected_origin - ); - let methods = response.headers()[header::ACCESS_CONTROL_ALLOW_METHODS].to_str()?; - assert!(methods.split(',').any(|value| value.trim() == "GET")); - assert!(!methods.split(',').any(|value| value.trim() == "POST")); - assert!( - response.headers()[header::ACCESS_CONTROL_ALLOW_HEADERS] - .to_str()? - .contains("content-type") - ); - } - Ok(()) - } - - #[tokio::test] - async fn invalid_origins_are_rejected_before_binding() -> Result<(), Box> - { - let occupied = TcpListener::bind("127.0.0.1:0").await?; - for origin in [ - "*", - "", - "localhost:9000", - "ws://localhost:9000", - "http://*.example.com", - "http://localhost:9000/", - "http://localhost:9000/path", - "http://localhost?query=1", - "http://localhost#fragment", - "http://user:password@localhost", - "http://localhost:", - "http://localhost:abc", - "http://localhost:99999", - "http://localhost\r\nInjected: value", - ] { - let mut config = HttpConfig::new(occupied.local_addr()?); - config.allowed_origins = vec![origin.into()]; - let error = configure_server(&config, &Adj::default(), None) - .await - .err() - .ok_or_else(|| io::Error::other("invalid origin was accepted"))?; - assert_eq!(error.kind(), io::ErrorKind::InvalidInput, "{origin:?}"); - } - Ok(()) - } - - #[test] - fn explicit_opaque_and_ipv6_origins_are_valid() -> Result<(), Box> { - for origin in [ - "null", - "http://[::1]:9000", - "https://example.com", - "http://127.0.0.1:9000", - ] { - let _ = cors_layer(&[origin.into()])?; - } - Ok(()) - } - - #[tokio::test] - async fn binding_errors_are_propagated_without_fallback() - -> Result<(), Box> { - let occupied = TcpListener::bind("127.0.0.1:0").await?; - let config = HttpConfig::new(occupied.local_addr()?); - let error = configure_server(&config, &Adj::default(), None) - .await - .err() - .ok_or_else(|| io::Error::other("occupied address did not fail"))?; - assert_eq!(error.kind(), io::ErrorKind::AddrInUse); - Ok(()) - } - - #[tokio::test] - async fn cache_policy_is_applied_only_to_catalogs() -> Result<(), Box> { - for (policy, expected) in [ - (CachePolicy::NoStore, Some("no-store")), - (CachePolicy::NoCache, Some("no-cache")), - (CachePolicy::Unspecified, None), - ] { - let mut config = HttpConfig::new("127.0.0.1:0".parse()?); - config.cache_policy = policy; - let (_listener, app) = configure_server(&config, &Adj::default(), None).await?; - for path in PATHS { - let response = app - .clone() - .oneshot(Request::builder().uri(path).body(Body::empty())?) - .await?; - assert_eq!( - response - .headers() - .get(header::CACHE_CONTROL) - .map(|value| value.to_str()) - .transpose()?, - expected - ); - } - let response = app - .oneshot(Request::builder().uri("/backend").body(Body::empty())?) - .await?; - assert_eq!(response.status(), StatusCode::BAD_REQUEST); - assert!(!response.headers().contains_key(header::CACHE_CONTROL)); - } - Ok(()) - } - - #[tokio::test] - async fn configured_server_preserves_websocket_handoff() - -> Result<(), Box> { - let config = HttpConfig::new("127.0.0.1:0".parse()?); - let (connections, mut receiver) = mpsc::channel(1); - let (listener, app) = configure_server(&config, &Adj::default(), Some(connections)).await?; - let (headers, _client) = handshake_on(listener, app).await?; - assert!(headers.starts_with("HTTP/1.1 101 Switching Protocols\r\n")); - assert!(!headers.to_ascii_lowercase().contains("cache-control:")); - let socket = timeout(Duration::from_secs(5), receiver.recv()) - .await? - .ok_or_else(|| io::Error::other("socket was not handed off"))?; - drop(socket); - Ok(()) - } -} diff --git a/backend/crates/station/src/http/handlers.rs b/backend/crates/station/src/http/handlers.rs index 815e33385..52ca92c01 100644 --- a/backend/crates/station/src/http/handlers.rs +++ b/backend/crates/station/src/http/handlers.rs @@ -77,7 +77,7 @@ pub(super) async fn websocket( upgrade .on_failed_upgrade(|error| { - tracing::warn!(%error, "falló el upgrade WebSocket"); + tracing::warn!(%error, "WebSocket upgrade failed"); }) .on_upgrade(move |socket| async move { // The receiver now owns the socket and manages its lifetime and diff --git a/backend/crates/station/src/http/server.rs b/backend/crates/station/src/http/server.rs index 073d8c86c..0bb27dedf 100644 --- a/backend/crates/station/src/http/server.rs +++ b/backend/crates/station/src/http/server.rs @@ -2,12 +2,16 @@ use std::{io, sync::Arc}; -use axum::{Router, extract::ws::WebSocket, http::header, routing::get}; +use axum::{ + Router, + extract::ws::WebSocket, + http::{HeaderValue, header}, + routing::get, +}; use software_core::adj::Adj; -use tokio::{net::TcpListener, sync::mpsc}; -use tower_http::set_header::SetResponseHeaderLayer; +use tokio::sync::mpsc; +use tower_http::{cors::CorsLayer, set_header::SetResponseHeaderLayer}; -use super::configure::CachePolicy; use super::handlers::{HttpState, data_packet, order_packet, protection_packet, websocket}; /// Serves the catalogs and hands connections to the future WebSocket module. @@ -22,42 +26,25 @@ use super::handlers::{HttpState, data_packet, order_packet, protection_packet, w /// # Errors /// /// Propagates errors serializing the catalogs or running the Axum server. -pub async fn serve_with_websocket( - listener: TcpListener, +pub(super) fn setup_router( adj: &Adj, websocket_connections: Option>, -) -> io::Result<()> { - axum::serve(listener, router(adj, websocket_connections)?).await -} - -fn router(adj: &Adj, websocket_connections: Option>) -> io::Result { - // Keep the existing listener-based entry points unchanged for test startup. - router_with_cache(adj, websocket_connections, CachePolicy::Unspecified) -} - -pub(super) fn router_with_cache( - adj: &Adj, - websocket_connections: Option>, - cache_policy: CachePolicy, ) -> io::Result { // Build and serialize the catalogs once, before accepting requests. The // state retains the bytes even after the Adj is dropped. let state = Arc::new(HttpState::new(adj, websocket_connections).map_err(io::Error::other)?); - let mut catalogs = Router::new() + Ok(Router::new() .route("/backend/adj/DataPackets", get(data_packet)) .route("/backend/adj/OrderPackets", get(order_packet)) - .route("/backend/adj/ProtectionPackets", get(protection_packet)); - - if let Some(value) = cache_policy.header_value() { - catalogs = catalogs.layer(SetResponseHeaderLayer::overriding( + .route("/backend/adj/ProtectionPackets", get(protection_packet)) + .route("/backend/ws", get(websocket)) + .layer(CorsLayer::permissive()) + .layer(SetResponseHeaderLayer::overriding( header::CACHE_CONTROL, - value, - )); - } - - // Register WebSocket after the catalog layer so upgrades are not cached. - Ok(catalogs.route("/backend", get(websocket)).with_state(state)) + HeaderValue::from_static("no-cache"), + )) + .with_state(state)) } #[cfg(test)] @@ -66,7 +53,7 @@ pub(super) mod tests { use axum::{ body::{Body, to_bytes}, - http::{Request, StatusCode, header}, + http::{Method, Request, StatusCode, header}, }; use software_core::adj::{Adj, load_from_dir}; use tokio::{ @@ -77,7 +64,7 @@ pub(super) mod tests { }; use tower::ServiceExt; - use super::router; + use super::setup_router; pub(in crate::http) const PATHS: [&str; 3] = [ "/backend/adj/DataPackets", @@ -86,7 +73,7 @@ pub(super) mod tests { ]; #[tokio::test] - async fn catalogs_return_cached_json() -> Result<(), Box> { + async fn catalogs_return_precomputed_json() -> Result<(), Box> { let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("../core/src/adj/test/adj"); let adj = load_from_dir(&path)?; let expected = [ @@ -94,7 +81,7 @@ pub(super) mod tests { serde_json::to_value(&adj.order_response())?, serde_json::to_value(&adj.protection_response())?, ]; - let app = router(&adj, None)?; + let app = setup_router(&adj, None)?; drop(adj); for (path, expected) in PATHS.into_iter().zip(expected) { @@ -121,7 +108,7 @@ pub(super) mod tests { #[tokio::test] async fn empty_catalogs_return_json_objects() -> Result<(), Box> { - let app = router(&Adj::default(), None)?; + let app = setup_router(&Adj::default(), None)?; let expected = [ serde_json::json!({"boards": []}), serde_json::json!({"boards": []}), @@ -141,6 +128,75 @@ pub(super) mod tests { Ok(()) } + #[tokio::test] + async fn all_routes_return_no_cache_and_allow_any_origin() + -> Result<(), Box> { + let app = setup_router(&Adj::default(), None)?; + + for path in PATHS.into_iter().chain(["/backend/ws"]) { + for origin in ["http://localhost:3000", "https://example.com"] { + let response = app + .clone() + .oneshot( + Request::builder() + .uri(path) + .header(header::ORIGIN, origin) + .body(Body::empty())?, + ) + .await?; + + let expected_status = if path == "/backend/ws" { + StatusCode::BAD_REQUEST + } else { + StatusCode::OK + }; + assert_eq!(response.status(), expected_status); + assert_eq!(response.headers()[header::CACHE_CONTROL], "no-cache"); + assert_eq!(response.headers()[header::ACCESS_CONTROL_ALLOW_ORIGIN], "*"); + assert!( + !response + .headers() + .contains_key(header::ACCESS_CONTROL_ALLOW_CREDENTIALS) + ); + } + } + Ok(()) + } + + #[tokio::test] + async fn all_routes_allow_cors_preflight_with_no_cache() + -> Result<(), Box> { + let app = setup_router(&Adj::default(), None)?; + + for path in PATHS.into_iter().chain(["/backend/ws"]) { + let response = app + .clone() + .oneshot( + Request::builder() + .method(Method::OPTIONS) + .uri(path) + .header(header::ORIGIN, "http://localhost:3000") + .header(header::ACCESS_CONTROL_REQUEST_METHOD, "GET") + .header(header::ACCESS_CONTROL_REQUEST_HEADERS, "x-client-id") + .body(Body::empty())?, + ) + .await?; + + assert_eq!(response.status(), StatusCode::OK); + assert_eq!(response.headers()[header::CACHE_CONTROL], "no-cache"); + assert_eq!(response.headers()[header::ACCESS_CONTROL_ALLOW_ORIGIN], "*"); + assert_eq!( + response.headers()[header::ACCESS_CONTROL_ALLOW_METHODS], + "*" + ); + assert_eq!( + response.headers()[header::ACCESS_CONTROL_ALLOW_HEADERS], + "*" + ); + } + Ok(()) + } + // Upgrades require a real HTTP connection: oneshot does not provide Hyper's // OnUpgrade extension. The server only runs for the duration of the test. async fn handshake( @@ -167,8 +223,9 @@ pub(super) mod tests { let response = timeout(Duration::from_secs(5), async { let mut stream = TcpStream::connect(address).await?; let request = format!( - "GET /backend HTTP/1.1\r\n\ + "GET /backend/ws HTTP/1.1\r\n\ Host: {address}\r\n\ + Origin: http://localhost:3000\r\n\ Connection: Upgrade\r\n\ Upgrade: websocket\r\n\ Sec-WebSocket-Version: 13\r\n\ @@ -195,7 +252,7 @@ pub(super) mod tests { #[tokio::test] async fn websocket_upgrade_delivers_the_socket() -> Result<(), Box> { let (connections, mut receiver) = mpsc::channel(1); - let app = router(&Adj::default(), Some(connections.clone()))?; + let app = setup_router(&Adj::default(), Some(connections.clone()))?; let (headers, _client) = handshake(app).await?; assert!(headers.starts_with("HTTP/1.1 101 Switching Protocols\r\n")); @@ -204,6 +261,16 @@ pub(super) mod tests { .to_ascii_lowercase() .contains("sec-websocket-accept: s3pplmbitxaq9kygzzhzrbk+xoo=\r\n") ); + assert!( + headers + .to_ascii_lowercase() + .contains("cache-control: no-cache\r\n") + ); + assert!( + headers + .to_ascii_lowercase() + .contains("access-control-allow-origin: *\r\n") + ); let socket = timeout(Duration::from_secs(5), receiver.recv()) .await? .ok_or_else(|| io::Error::other("no se entregó el socket"))?; @@ -215,7 +282,7 @@ pub(super) mod tests { #[tokio::test] async fn websocket_without_a_consumer_returns_unavailable() -> Result<(), Box> { - let app = router(&Adj::default(), None)?; + let app = setup_router(&Adj::default(), None)?; let (headers, _client) = handshake(app).await?; assert!(headers.starts_with("HTTP/1.1 503 Service Unavailable\r\n")); Ok(()) @@ -226,7 +293,7 @@ pub(super) mod tests { -> Result<(), Box> { let (connections, receiver) = mpsc::channel(1); drop(receiver); - let app = router(&Adj::default(), Some(connections))?; + let app = setup_router(&Adj::default(), Some(connections))?; let (headers, _client) = handshake(app).await?; assert!(headers.starts_with("HTTP/1.1 503 Service Unavailable\r\n")); Ok(()) @@ -238,7 +305,7 @@ pub(super) mod tests { let (connections, _receiver) = mpsc::channel(1); // Simulate an occupied slot without requiring another test socket. let reservation = connections.clone().try_reserve_owned()?; - let app = router(&Adj::default(), Some(connections))?; + let app = setup_router(&Adj::default(), Some(connections))?; let (headers, _client) = handshake(app).await?; assert!(headers.starts_with("HTTP/1.1 503 Service Unavailable\r\n")); drop(reservation); @@ -249,9 +316,9 @@ pub(super) mod tests { async fn websocket_rejects_requests_without_upgrade_headers() -> Result<(), Box> { let (connections, mut receiver) = mpsc::channel(1); - let app = router(&Adj::default(), Some(connections.clone()))?; + let app = setup_router(&Adj::default(), Some(connections.clone()))?; let response = app - .oneshot(Request::builder().uri("/backend").body(Body::empty())?) + .oneshot(Request::builder().uri("/backend/ws").body(Body::empty())?) .await?; assert_eq!(response.status(), StatusCode::BAD_REQUEST); From 69eaf1b88a85e018367ec29e95a4c77b9dcee134 Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Tue, 17 Nov 2026 01:36:48 +0100 Subject: [PATCH 132/225] docs(backend, http): update readme and correct errors --- backend/crates/core/src/adj/README.md | 35 ++- backend/crates/core/src/model/README.md | 39 ++- backend/crates/core/src/model/http/README.md | 239 ++++++++++++++++-- .../core/src/model/http/example/order.json | 4 +- .../src/model/http/example/protection.json | 34 +-- 5 files changed, 306 insertions(+), 45 deletions(-) diff --git a/backend/crates/core/src/adj/README.md b/backend/crates/core/src/adj/README.md index a468ad4de..b60b6668a 100644 --- a/backend/crates/core/src/adj/README.md +++ b/backend/crates/core/src/adj/README.md @@ -2,7 +2,7 @@ This module deserializes, validates, and loads ADJ JSON fixtures into the backend domain model. -The `http` submodule converts a loaded `Adj` into serializable data, order, and protection catalogs for HTTP responses. It defines response bodies, not routes or a server. See the [HTTP submodule README](http/README.md) for usage and JSON examples. +With the `http` feature enabled, `adj/http.rs` adds catalog-building methods to `Adj`. The serializable response types live separately in `model::http`; routes, middleware, and server setup belong to the application (`station`). See the [HTTP response models README](../model/http/README.md) for usage, JSON types, and examples. For schema specifications, packet/measurement ID conventions, and network requirements, refer directly to the official documentation in the **ADJ repository**. @@ -23,7 +23,6 @@ pub struct Adj { Adj ├── pod_data (PodData) │ └── boards: HashMap -│ ├── measurements: HashMap │ └── packets: HashMap │ ├── explicit (Data, Order, Message — declared in packets.json; │ │ a "message"-type packet's own `name` must be one of @@ -40,6 +39,11 @@ Adj └── protection_types: HashMap ``` +`Board` also carries its `id`, `name`, `ip`, and `mac`. There is no persistent +`Board::measurements` map: the loader uses a temporary alias-to-measurement map +to resolve packet variables, then stores the resolved measurements inside +`PacketType::Data`, `PacketType::Order`, and `PacketType::Protection`. + `message_ids` is the ADJ's own direction: a name (e.g. `"fault"`) to its id. Not every entry is one of `model::MessageLevel`'s four severities — other reserved names (e.g. `add_state_order`) share this same map. @@ -49,7 +53,7 @@ other reserved names (e.g. `add_state_order`) share this same map. between. It's the reverse of `message_ids`, restricted to whichever of `MessageLevel::ALL`'s four names `message_ids` declares — built once in `adj::raw::types`'s `TryFrom for AdjInfo`, right after -`message_ids` itself, so it can never drift out of sync with it: +`message_ids` itself, so the two maps agree when loaded: ```rust let message_levels: HashMap = MessageLevel::ALL @@ -59,7 +63,7 @@ let message_levels: HashMap = MessageLevel::ALL ``` Which ADJ name corresponds to which `MessageLevel` is **not** decided -here — `level.name()`/`MessageLevel::from_name` (see `model/README.md` +here — `level.name()`/`MessageLevel::from_name` (see [model](../model/README.md) §4.4) is the one place that association is spelled out, so `adj` doesn't hardcode `"fault"`/`"warning"`/`"info"`/`"panic"` itself. @@ -78,6 +82,27 @@ free-text log frame can reuse the same `"fault"` id. See --- +## HTTP Catalog Builders (`http` feature) + +The methods implemented in `adj/http.rs` borrow `&self`; they do not consume or +modify the loaded ADJ: + +| Method | Return type (in `model::http`) | Contents | +| --- | --- | --- | +| `adj.data_response()` | `DataResponse` | Data definitions grouped by board, without protection metadata. | +| `adj.order_response()` | `OrderResponse` | Order definitions grouped by board, including parameters and their protections. | +| `adj.protection_response()` | `ProtectionResponse` | Flat catalog of synthetic protection packets, plus display metadata. | + +These methods return owned response models, not JSON bytes or HTTP responses. +The application chooses when to call them and serialize the results. They do +not configure routes, CORS, or caching. + +In the order and protection catalogs, protection IDs are compound IDs: +`(position << 13) | measurement_id`. The internal `Protection::id` remains the +one-based position (`1–7`) within its measurement. Empty lists are retained; +zero protection durations are omitted from JSON. See the +[HTTP contract](../model/http/README.md) for the complete serialized shapes. + ## Why It Is Structured This Way The `Adj` object enforces a clear architectural boundary between **vehicle topology** and **session configuration**: @@ -88,7 +113,7 @@ The `Adj` object enforces a clear architectural boundary between **vehicle topol * **Design rationale**: The vehicle itself does not know or care about backend socket configurations or display strings. Separating them prevents UI and orchestration details from polluting the core telemetry model. ### 2. Standalone Loader Submodule (`raw`) -The raw deserialization types and the loader logic live isolated inside `raw`[cite: 2]. This enables non-station tools (such as bus sniffers, test runners, or simulators) to parse and ingest ADJ directories without dragging along application-level UI or station state logic. +The raw deserialization types and the loader logic live isolated inside `raw`. This enables non-station tools (such as bus sniffers, test runners, or simulators) to parse and ingest ADJ directories without dragging along application-level UI or station state logic. ### 3. Unified Packet Map (`packets`) Protections defined under measurements are materialized during loading as first-class `PacketType::Protection(Measurement)` packets alongside the explicit data, order and message packets declared in `packets.json`. Downstream networking layers can route and handle every wire event uniformly via `Board::packets` without needing specialized traversal logic for nested measurement alarms. `packets.json` itself never declares a `"type": "protection"` entry directly — that shape only exists synthesized, one per protection a measurement declares, never as a free-standing declaration with its own arbitrary variable list. diff --git a/backend/crates/core/src/model/README.md b/backend/crates/core/src/model/README.md index 20db8642d..40001c283 100644 --- a/backend/crates/core/src/model/README.md +++ b/backend/crates/core/src/model/README.md @@ -4,6 +4,10 @@ This module is meant to store and organize all the different structs, enums and other data structures necessary for the backend project. +The domain types describe vehicle definitions and decoded packets. With the +`http` feature enabled, `model::http` also exposes separate, serializable catalog +response models; see [section 7](#7-http-http-feature). + ## 1. `board.rs` All structs and enums needed for the Pod can be found defined in this file. ### 1.1 `PacketType` @@ -83,9 +87,13 @@ Enum used to classify every numerical value type a measurement can use. - 64-bit floating point number (`F64`) ### 3.2 `Range` -Struct used to define a maximum and minimum value of any measurement. +An inclusive range with independently optional lower and upper bounds. This +helper is not a field of the current `MeasurementKind::Numeric` variant; +protection bounds are represented by `ProtectionKind` instead. #### `min` +Optional lower bound (`Option`); `None` means no lower limit. #### `max` +Optional upper bound (`Option`); `None` means no upper limit. ### 3.3 `MeasurementKind` Enum used to classify the kind of measurement. @@ -219,7 +227,7 @@ Wraps a `ProtectionPacket` (triggered protection event). #### `Message` Wraps a `MessagePacket` (free-text log/diagnostic message). -## 5. `protection.rs` +## 5. `protections.rs` A `Protection` is a bound checked against a measurement's decoded value, as declared in the ADJ (`_measurements.json`). This defines the *declaration* (what to watch for, thresholds, and severity) rather than the runtime wire packet emitted when triggered (`ProtectionPacket` in `packet.rs`). In ADJv3, protections and messages are distinct formats with separate lifecycles. ### 5.1 `ProtectionKind` @@ -249,6 +257,10 @@ Struct defining a single protection rule attached to a measurement. #### `id` The protection's relative slot index within its parent measurement's protection list, stored as an `AdjId` in the `1–7` range. This is a local index rather than a global ID; it forms the upper 3 bits of the compound wire identifier alongside the 13-bit measurement ID. + +Do not confuse this internal position with an HTTP protection ID: both +`OrderResponse` and `ProtectionResponse` expose the compound ID +`(position << 13) | measurement_id`, as does `ProtectionPacket` on the wire. #### `kind` The evaluation rule and threshold bounds (`ProtectionKind`). #### `severity` @@ -267,4 +279,25 @@ A numeric measurement, regardless of its original wire type (`u8`, `i32`, `f32`, #### `Bool(bool)` A boolean measurement (`true` or `false`). #### `Enum(String)` -The selected variant name of an enumerated measurement (e.g. `"Operational"`). \ No newline at end of file +The selected variant name of an enumerated measurement (e.g. `"Operational"`). + +## 7. `http` (`http` feature) + +`model/http.rs` publicly re-exports three response types: + +- `DataResponse`: data packet definitions grouped by board, without protections. +- `OrderResponse`: order definitions grouped by board, including parameter protections. +- `ProtectionResponse`: flat protection definitions and display metadata. + +Their nested response structs live in `model/http/data.rs`, `order.rs`, and +`protection.rs`. Those submodules are crate-visible, not public import paths. +The response models derive `serde::Serialize`; the domain types do not need to +adopt the HTTP representation. Shared custom serializers live in +`utils/serialize.rs`. + +The builders are methods of `Adj`, implemented in `adj/http.rs`: +`adj.data_response()`, `adj.order_response()`, and `adj.protection_response()`. +This module defines no HTTP server, routes, CORS, or cache policy. + +See the [HTTP response models README](http/README.md) for usage, JSON type +notation, field omission rules, and concrete examples. diff --git a/backend/crates/core/src/model/http/README.md b/backend/crates/core/src/model/http/README.md index ce881f870..c099a5893 100644 --- a/backend/crates/core/src/model/http/README.md +++ b/backend/crates/core/src/model/http/README.md @@ -1,20 +1,29 @@ -# ADJ HTTP (`adj::http`) +# HTTP Response Models (`model::http`) -Builds serializable HTTP response bodies from a loaded `Adj`, without modifying -or consuming it. This submodule contains catalog models and builders only; -HTTP routes and server setup belong to the application. +Serializable models for the data, order, and protection catalogs of a loaded +ADJ. These are definitions, not live telemetry, order execution requests, or +triggered protection events. + +The `http` feature enables both sides of the conversion: + +- `model/http.rs` and `model/http/`: response types and their JSON representation. +- `adj/http.rs`: methods on `Adj` that build those response types without + consuming or modifying the ADJ. + +Routes, middleware, and server execution belong to the application (`station`), +not to either of these core modules. Shared custom serializers are implemented +in `utils/serialize.rs`, leaving the internal domain representation unchanged. ## Catalogs -| Builder | Response | Contents | JSON example | +| `Adj` method | Public response type | Station GET route | JSON example | | --- | --- | --- | --- | -| `data_response(&adj)` | `DataResponse` | Data packets grouped by board, with measurement definitions but no protections. | [data.json](example/data.json) | -| `order_response(&adj)` | `OrderResponse` | Orders grouped by board, including parameters and their protections. | [order.json](example/order.json) | -| `protection_response(&adj)` | `ProtectionResponse` | Flat protection list and display metadata from the ADJ's `protectionTypes`. | [protection.json](example/protection.json) | +| `adj.data_response()` | `model::http::DataResponse` | `/backend/adj/DataPackets` | [data.json](example/data.json) | +| `adj.order_response()` | `model::http::OrderResponse` | `/backend/adj/OrderPackets` | [order.json](example/order.json) | +| `adj.protection_response()` | `model::http::ProtectionResponse` | `/backend/adj/ProtectionPackets` | [protection.json](example/protection.json) | -These are definitions, not live telemetry, order execution requests, or triggered -protection events. Boards and their packets/orders are sorted by ID; measurement -order is preserved. The flat protection list is sorted by packet ID, then board ID. +Each example is a standalone illustrative catalog, not a snapshot of the +bundled test ADJ or part of a shared vehicle fixture. ## Usage @@ -24,16 +33,210 @@ Enable the `http` feature in the application's dependency: cargo add software-core -F http ``` -With an already loaded `adj`: +With an already loaded `adj: Adj`: ```rust -use software_core::adj::http::{data_response, order_response, protection_response}; +use software_core::model::http::{DataResponse, OrderResponse, ProtectionResponse}; -let data = data_response(&adj); -let orders = order_response(&adj); -let protections = protection_response(&adj); +let data: DataResponse = adj.data_response(); +let orders: OrderResponse = adj.order_response(); +let protections: ProtectionResponse = adj.protection_response(); ``` All three responses implement `serde::Serialize`, so the application can return -them as JSON using its HTTP framework. Serialization details are kept here, -without changing the internal domain model. +them as JSON using its HTTP framework. Only these three root types are publicly +re-exported; the nested Rust response types are in crate-visible submodules. + +## JSON Structure Templates + +These templates keep the JSON object and array structure, replacing values +with their types: `number`, `string`, or `boolean`. Quoted values such as +`"data"` are literals. Comments explain constraints and optional properties. +These are documentation templates, not valid JSON payloads; see the linked +`.json` files for concrete values. + +Each array shows one representative item but can contain zero or more items. +IDs are unsigned 16-bit integers, not strings or wrapper objects. +The catalog templates show numeric measurements and range protections; +the other possible `kind` shapes are listed below. + +### Data Catalog (`DataResponse`) + +```jsonc +{ + "boards": [ + { + "id": number, + "name": string, + "packets": [ + { + "id": number, + "name": string, + "type": "data", + "measurements": [ + { + "id": number, + "alias": string, + "name": string, + "display_units": string, + "kind": { + "type": "numeric", + "wire_type": string + } + } + ] + } + ] + } + ] +} +``` + +Data measurements deliberately have no `protections` property, even if their +internal ADJ definitions declare protections. + +### Order Catalog (`OrderResponse`) + +```jsonc +{ + "boards": [ + { + "id": number, + "name": string, + "orders": [ + { + "id": number, + "name": string, + "type": "order", + "measurements": [ + { + "id": number, + "alias": string, + "name": string, + "display_units": string, + "kind": { + "type": "numeric", + "wire_type": string + }, + "protections": [ + { + "id": number, // Compound ID, not the local position (1–7). + "kind": { + "type": "range", + "min": number, + "max": number + }, + "severity": string, // "fault" or "warning". + "time": string // Optional: omitted for a zero duration. + } + ] + } + ] + } + ] + } + ] +} +``` + +Only protections attached to an order's parameter measurements are included, +not every protection on its board. A parameterless order has `measurements: []`; +a parameter with no declared protections has `protections: []`. + +### Protection Catalog (`ProtectionResponse`) + +```jsonc +{ + "protections": [ + { + "id": number, // Compound ID. + "name": string, + "board_id": number, + "measurement_id": number, + "kind": { + "type": "range", + "min": number, + "max": number + }, + "severity": string, // "fault" or "warning". + "time": string // Optional: omitted for a zero duration. + } + ], + "info": { + "": { + "range": boolean, + "text": string, + "text_time": string // Optional: only included when declared in the ADJ. + } + } +} +``` + +`info` comes from `general_info.json`'s `protectionTypes`. Its keys preserve the +ADJ names, such as `"Range"` and `"NotEqual"`, whereas `kind.type` uses +`"range"` and `"not_equal"`. **Do not index `info` directly with `kind.type`** +when the ADJ uses those names: the current response does not normalize the keys. +For these conventional ADJ names, the correspondence is: + +| `kind.type` | ADJ metadata key | +| --- | --- | +| `above` | `Above` | +| `below` | `Below` | +| `equal` | `Equal` | +| `not_equal` | `NotEqual` | +| `range` | `Range` | + +Metadata is not synthesized for missing ADJ entries. In its text templates, +`{}` represents protection bounds and `%` the measured value. `text_time` is +omitted when the ADJ does not declare an alternative time-based template. + +### Measurement `kind` Variants + +Each measurement has exactly one of these objects as its `kind` value: + +Numeric: + +```jsonc +{ + "type": "numeric", + "wire_type": string +} +``` + +`wire_type` is one of `"uint8"`, `"uint16"`, `"uint32"`, `"uint64"`, +`"int8"`, `"int16"`, `"int32"`, `"int64"`, `"float32"`, or `"float64"`. + +Boolean: + +```jsonc +{ + "type": "boolean" +} +``` + +Enum: + +```jsonc +{ + "type": "enum", + "options": [string] +} +``` + +Numeric measurements do not carry separate safe/warning ranges; protection +definitions carry conditions and severity instead. `display_units` remains +present even when it is `""`. + +### Protection `kind` Variants + +Each protection has exactly one of these objects as its `kind` value: + +| Condition | JSON-shaped type template | +| --- | --- | +| Above a limit | `{"type": "above", "limit": number}` | +| Below a limit | `{"type": "below", "limit": number}` | +| Equal to a target | `{"type": "equal", "target": number}` | +| Not equal to a target | `{"type": "not_equal", "target": number}` | +| Outside a range | `{"type": "range", "min": number, "max": number}` | + +The protection `range` variant always has both bounds. \ No newline at end of file diff --git a/backend/crates/core/src/model/http/example/order.json b/backend/crates/core/src/model/http/example/order.json index 06d460bbe..2a7d30548 100644 --- a/backend/crates/core/src/model/http/example/order.json +++ b/backend/crates/core/src/model/http/example/order.json @@ -20,7 +20,7 @@ }, "protections": [ { - "id": 1, + "id": 11193, "kind": { "type": "range", "min": 0.0, @@ -29,7 +29,7 @@ "severity": "fault" }, { - "id": 2, + "id": 19385, "kind": { "type": "above", "limit": 40.0 diff --git a/backend/crates/core/src/model/http/example/protection.json b/backend/crates/core/src/model/http/example/protection.json index 4cb3cd0ba..1ea79e46b 100644 --- a/backend/crates/core/src/model/http/example/protection.json +++ b/backend/crates/core/src/model/http/example/protection.json @@ -6,48 +6,48 @@ "board_id": 1, "measurement_id": 3000, "kind": { - "type": "Range", + "type": "range", "min": 0.0, "max": 100.0 }, "severity": "fault", "time": "500ms" }, - { - "id": 19384, - "name": "LCU_temperature_1_protection_2", - "board_id": 1, - "measurement_id": 3000, - "kind": { - "type": "Below", - "limit": 10.0 - }, - "severity": "warning", - "time": "1s" - }, { "id": 11292, "name": "HVBMS_pack_voltage_protection_1", "board_id": 2, "measurement_id": 3100, "kind": { - "type": "Range", + "type": "range", "min": 300.0, "max": 500.0 }, "severity": "fault" + }, + { + "id": 19384, + "name": "LCU_temperature_1_protection_2", + "board_id": 1, + "measurement_id": 3000, + "kind": { + "type": "below", + "limit": 10.0 + }, + "severity": "warning", + "time": "1000ms" } ], "info": { - "Equal": { + "equal": { "range": false, "text": "Value is equal to {} (measured: %)" }, - "Range": { + "range": { "range": true, "text": "Value out of range {} (measured: %)" }, - "Below": { + "below": { "range": false, "text": "Value below {} (measured: %)" } From dbef8963482930c975e8b075f664379a712435ec Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Tue, 17 Nov 2026 01:38:52 +0100 Subject: [PATCH 133/225] fix(backend, http): update main --- backend/crates/station/src/main.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/backend/crates/station/src/main.rs b/backend/crates/station/src/main.rs index c3288c29d..fa81b031b 100644 --- a/backend/crates/station/src/main.rs +++ b/backend/crates/station/src/main.rs @@ -26,7 +26,7 @@ async fn main() -> std::io::Result<()> { // Just testing, not the actual address let listener = TcpListener::bind("127.0.0.1:8080").await?; - http::serve(listener, &adj).await?; + http::serve(listener, &adj, None).await?; tracing::info!("demo finalizada"); From ee2e3546302a46c0d0b0989b1c26e44253a2df90 Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Tue, 17 Nov 2026 18:43:21 +0100 Subject: [PATCH 134/225] fix(backend, git): clippy check --- backend/crates/core/src/git/update.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/backend/crates/core/src/git/update.rs b/backend/crates/core/src/git/update.rs index 65fe5655c..25e081d41 100644 --- a/backend/crates/core/src/git/update.rs +++ b/backend/crates/core/src/git/update.rs @@ -39,14 +39,14 @@ const ADJ_URL: &str = "https://github.com/Hyperloop-UPV/adj.git"; pub fn update_adj(path: Option, branch: &str) -> Result { let (repo, dir) = adj_exists_repo(path)?; - if check_internet_connection() && branch != "" { + if check_internet_connection() && !branch.is_empty() { info!(path = ?dir, branch, "starting ADJ update"); // Release repository handles before moving the existing cache directory. drop(repo); git_replace(&dir, branch, ADJ_URL) } else if let Some(repo) = repo { - if branch == "" { + if branch.is_empty() { warn!(path = ?dir, requested_branch = branch, "branch not specified; using cached ADJ with current branch"); From 62c9ea5160e201a3961d0e65a5d3cef6129acd80 Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Tue, 17 Nov 2026 18:49:11 +0100 Subject: [PATCH 135/225] fix(backend, http): clippy warings solved --- backend/crates/core/src/adj/http.rs | 23 ++++++++++++----------- 1 file changed, 12 insertions(+), 11 deletions(-) diff --git a/backend/crates/core/src/adj/http.rs b/backend/crates/core/src/adj/http.rs index 5feeca4a5..88ab5455c 100644 --- a/backend/crates/core/src/adj/http.rs +++ b/backend/crates/core/src/adj/http.rs @@ -118,7 +118,7 @@ impl Adj { id: AdjId((protection.id.0 << 13) | measurement.id.0), kind: protection.kind, severity: protection.severity, - time: protection_time_to_nanos(protection.time), + time: format_protection_time(protection.time), }) .collect(), }) @@ -170,7 +170,7 @@ impl Adj { measurement_id: measurement.id, kind: protection.kind, severity: protection.severity, - time: protection_time_to_nanos(protection.time), + time: format_protection_time(protection.time), }) }) .collect(); @@ -197,20 +197,21 @@ impl Adj { } // Returns Some("(time)xs") if the time is not 0 -fn protection_time_to_nanos(time: Duration) -> Option { +fn format_protection_time(time: Duration) -> Option { if time == Duration::new(0, 0) { None } else { // If the duration is in nanoseconds (default) - let mut res = format!("{}ns", time.as_nanos().to_string()); - - if time.as_millis() > 0 { - res = format!("{}ms", time.as_millis().to_string()); - } else if time.as_micros() > 0 { - res = format!("{}us", time.as_micros().to_string()); + let ns = time.as_nanos(); + + // Adjust the result + if ns.is_multiple_of(1_000_000) { + Some(format!("{}ms", ns / 1_000_000)) + } else if ns.is_multiple_of(1_000) { + Some(format!("{}us", ns / 1_000)) + } else { + Some(format!("{}ns", ns)) } - - Some(res) } } From 2fdd73d6c3f2eaf38701ffc171a13d1f43f59275 Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Tue, 17 Nov 2026 20:00:22 +0100 Subject: [PATCH 136/225] fix(backend, http): types in all the structures --- backend/crates/core/src/model/http/README.md | 112 ++++++++++++------ backend/crates/core/src/model/http/data.rs | 26 ++-- .../core/src/model/http/example/data.json | 19 +-- .../core/src/model/http/example/order.json | 9 +- .../src/model/http/example/protection.json | 6 +- backend/crates/core/src/model/http/order.rs | 6 +- .../crates/core/src/model/http/protection.rs | 2 +- backend/crates/core/src/utils/serialize.rs | 52 ++++++-- 8 files changed, 148 insertions(+), 84 deletions(-) diff --git a/backend/crates/core/src/model/http/README.md b/backend/crates/core/src/model/http/README.md index c099a5893..1f500cb49 100644 --- a/backend/crates/core/src/model/http/README.md +++ b/backend/crates/core/src/model/http/README.md @@ -58,7 +58,7 @@ These are documentation templates, not valid JSON payloads; see the linked Each array shows one representative item but can contain zero or more items. IDs are unsigned 16-bit integers, not strings or wrapper objects. The catalog templates show numeric measurements and range protections; -the other possible `kind` shapes are listed below. +the other possible `type` values are listed below. ### Data Catalog (`DataResponse`) @@ -79,10 +79,7 @@ the other possible `kind` shapes are listed below. "alias": string, "name": string, "display_units": string, - "kind": { - "type": "numeric", - "wire_type": string - } + "type": string // A numeric wire type, such as "float32", or "boolean"; see enum form below. } ] } @@ -114,14 +111,11 @@ internal ADJ definitions declare protections. "alias": string, "name": string, "display_units": string, - "kind": { - "type": "numeric", - "wire_type": string - }, + "type": string, // A numeric wire type, such as "float32", or "boolean"; see enum form below. "protections": [ { "id": number, // Compound ID, not the local position (1–7). - "kind": { + "type": { "type": "range", "min": number, "max": number @@ -153,7 +147,7 @@ a parameter with no declared protections has `protections: []`. "name": string, "board_id": number, "measurement_id": number, - "kind": { + "type": { "type": "range", "min": number, "max": number @@ -173,12 +167,14 @@ a parameter with no declared protections has `protections: []`. ``` `info` comes from `general_info.json`'s `protectionTypes`. Its keys preserve the -ADJ names, such as `"Range"` and `"NotEqual"`, whereas `kind.type` uses -`"range"` and `"not_equal"`. **Do not index `info` directly with `kind.type`** -when the ADJ uses those names: the current response does not normalize the keys. -For these conventional ADJ names, the correspondence is: - -| `kind.type` | ADJ metadata key | +ADJ names exactly, whereas the inner protection discriminator uses snake_case. +For example, a protection has `protection.type.type === "range"`, but the +metadata key may be `"Range"` or `"range"`, depending on the ADJ. +Direct access such as `response.info[protection.type.type]` only works when +those keys match: the builder does not normalize them. For the conventional +capitalized ADJ names, the correspondence is: + +| `protection.type.type` | Capitalized ADJ metadata key | | --- | --- | | `above` | `Above` | | `below` | `Below` | @@ -190,23 +186,25 @@ Metadata is not synthesized for missing ADJ entries. In its text templates, `{}` represents protection bounds and `%` the measured value. `text_time` is omitted when the ADJ does not declare an alternative time-based template. -### Measurement `kind` Variants +### Measurement `type` Values -Each measurement has exactly one of these objects as its `kind` value: +The Rust field is called `kind`, but is serialized as the JSON property `type` +in both data and order measurements. Its value is a string for numeric and +boolean measurements, or an object for enums. There is no separate `wire_type` +property in the JSON. -Numeric: +Numeric measurement (field excerpt): ```jsonc { - "type": "numeric", - "wire_type": string + "type": string // One of the numeric wire types listed below, e.g. "float32". } ``` -`wire_type` is one of `"uint8"`, `"uint16"`, `"uint32"`, `"uint64"`, +Numeric `type` is one of `"uint8"`, `"uint16"`, `"uint32"`, `"uint64"`, `"int8"`, `"int16"`, `"int32"`, `"int64"`, `"float32"`, or `"float64"`. -Boolean: +Boolean measurement (field excerpt): ```jsonc { @@ -214,12 +212,14 @@ Boolean: } ``` -Enum: +Enum measurement (field excerpt): ```jsonc { - "type": "enum", - "options": [string] + "type": { + "type": "enum", + "options": [string] + } } ``` @@ -227,16 +227,58 @@ Numeric measurements do not carry separate safe/warning ranges; protection definitions carry conditions and severity instead. `display_units` remains present even when it is `""`. -### Protection `kind` Variants +### Protection `type` Values -Each protection has exactly one of these objects as its `kind` value: +The Rust protection field is also called `kind`, but is serialized as `type`. +Unlike numeric and boolean measurement types, its JSON value is always an +object, with its own `type` discriminator and the condition's bound(s). +The following are field excerpts from a protection object: | Condition | JSON-shaped type template | | --- | --- | -| Above a limit | `{"type": "above", "limit": number}` | -| Below a limit | `{"type": "below", "limit": number}` | -| Equal to a target | `{"type": "equal", "target": number}` | -| Not equal to a target | `{"type": "not_equal", "target": number}` | -| Outside a range | `{"type": "range", "min": number, "max": number}` | +| Above a limit | `{"type": {"type": "above", "limit": number}}` | +| Below a limit | `{"type": {"type": "below", "limit": number}}` | +| Equal to a target | `{"type": {"type": "equal", "target": number}}` | +| Not equal to a target | `{"type": {"type": "not_equal", "target": number}}` | +| Outside a range | `{"type": {"type": "range", "min": number, "max": number}}` | + +The protection `range` variant always has both bounds. + +## IDs, Ordering, and Optional Fields + +- Protection IDs in both order and protection responses are composed as + `(position << 13) | measurement_id`: the high 3 bits hold the one-based + position (`1–7`), and the low 13 bits hold the measurement ID. For measurement + `3001`, the first two protections are `11193` and `19385`. The internal + `Protection::id` still stores only the local position. +- Boards are sorted by ID; their data packets or orders are sorted by ID. + Boards without matching packets/orders are retained with an empty array. +- Measurement order, enum option order, and order-parameter protection order + follow the ADJ. The flat protection catalog is sorted by compound packet ID, + then board ID; the keys of `info` have no guaranteed order. +- Catalog arrays remain present even when empty. An empty ADJ yields + `{"boards": []}` for data and orders, and + `{"protections": [], "info": {}}` for protections. + +### Protection Duration (`time`) + +`time` is a duration string, not a timestamp. It is omitted for +`Duration::ZERO`, not serialized as `null` or `"0ns"`. + +For positive durations, the formatter chooses an exact integer representation: + +1. Milliseconds (`ms`) when the nanosecond count is divisible by `1_000_000`. +2. Otherwise microseconds (`us`) when it is divisible by `1_000`. +3. Otherwise nanoseconds (`ns`). + +No precision is discarded during this formatting step. For example: + +| Duration | Serialized `time` | +| --- | --- | +| Zero | Property omitted | +| 1 second | `"1000ms"` | +| 1500 microseconds | `"1500us"` | +| 1500 nanoseconds | `"1500ns"` | -The protection `range` variant always has both bounds. \ No newline at end of file +This rule applies to protection `time`, not to the metadata template string +`text_time`, which is copied from the ADJ and omitted when absent. diff --git a/backend/crates/core/src/model/http/data.rs b/backend/crates/core/src/model/http/data.rs index dbb1778dc..d739e82a2 100644 --- a/backend/crates/core/src/model/http/data.rs +++ b/backend/crates/core/src/model/http/data.rs @@ -4,7 +4,7 @@ use serde::Serialize; use crate::{ model::{AdjId, BoardId, NumericKind}, - utils::serialize::{serialize_adj_id, serialize_board_id, serialize_numeric_kind}, + utils::serialize::{serialize_adj_id, serialize_board_id, serialize_data_measurement_type}, }; /// Data packet definitions grouped by board. @@ -56,25 +56,29 @@ pub struct DataMeasurementResponse { pub name: String, /// Unit label displayed to the user. pub display_units: String, - /// Numeric, boolean or enum metadata. + /// Measurement type metadata, serialized under the JSON key `type`. + /// Numeric and boolean types are strings; enums are objects with options. + #[serde(rename = "type", serialize_with = "serialize_data_measurement_type")] pub kind: DataMeasurementKind, } -/// Measurement metadata tagged with an explicit `type` field in JSON. -#[derive(Debug, Clone, PartialEq, Serialize)] -#[serde(tag = "type", rename_all = "snake_case")] +/// Measurement type metadata used by the custom response serializer. +/// +/// As a measurement's JSON `type` value, numeric types become their ADJ wire +/// type name, booleans become `"boolean"`, and enums become an object with +/// `"type": "enum"` and an `options` array. +#[derive(Debug, Clone, PartialEq)] pub enum DataMeasurementKind { - /// Numeric measurement, including its binary representation. + /// Numeric measurement, serialized as a wire type string such as `"float32"`. Numeric { - /// Wire type, serialized with its ADJ name, e.g. `float32`. - #[serde(serialize_with = "serialize_numeric_kind")] + /// Selects the ADJ type name; no separate `wire_type` JSON field is emitted. wire_type: NumericKind, }, - /// Boolean measurement, serialized as `{"type":"boolean"}`. + /// Boolean measurement, serialized as the string `"boolean"`. Boolean, - /// Enumeration with variants in ADJ order. + /// Enumeration, serialized as `{"type":"enum","options":[...]}`. Enum { - /// Allowed variant names. + /// Allowed variant names, preserved in ADJ order. options: Vec, }, } diff --git a/backend/crates/core/src/model/http/example/data.json b/backend/crates/core/src/model/http/example/data.json index e383f07eb..08d2f8461 100644 --- a/backend/crates/core/src/model/http/example/data.json +++ b/backend/crates/core/src/model/http/example/data.json @@ -14,10 +14,7 @@ "alias": "temperature_1", "name": "Motor temperature", "display_units": "ºC", - "kind": { - "type": "numeric", - "wire_type": "float32" - } + "type": "float32" } ] }, @@ -31,10 +28,7 @@ "alias": "levitation_distance", "name": "Levitation distance", "display_units": "mm", - "kind": { - "type": "numeric", - "wire_type": "float32" - } + "type": "float32" } ] } @@ -54,10 +48,7 @@ "alias": "pack_voltage", "name": "Pack voltage", "display_units": "V", - "kind": { - "type": "numeric", - "wire_type": "float32" - } + "type": "float32" } ] }, @@ -71,9 +62,7 @@ "alias": "contactor_closed", "name": "Contactor closed", "display_units": "", - "kind": { - "type": "boolean" - } + "type": "boolean" } ] } diff --git a/backend/crates/core/src/model/http/example/order.json b/backend/crates/core/src/model/http/example/order.json index 2a7d30548..63f9bedfb 100644 --- a/backend/crates/core/src/model/http/example/order.json +++ b/backend/crates/core/src/model/http/example/order.json @@ -14,14 +14,11 @@ "alias": "target_speed", "name": "Target speed", "display_units": "m/s", - "kind": { - "type": "numeric", - "wire_type": "float32" - }, + "type": "float32", "protections": [ { "id": 11193, - "kind": { + "type": { "type": "range", "min": 0.0, "max": 50.0 @@ -30,7 +27,7 @@ }, { "id": 19385, - "kind": { + "type": { "type": "above", "limit": 40.0 }, diff --git a/backend/crates/core/src/model/http/example/protection.json b/backend/crates/core/src/model/http/example/protection.json index 1ea79e46b..778e1a6d0 100644 --- a/backend/crates/core/src/model/http/example/protection.json +++ b/backend/crates/core/src/model/http/example/protection.json @@ -5,7 +5,7 @@ "name": "LCU_temperature_1_protection_1", "board_id": 1, "measurement_id": 3000, - "kind": { + "type": { "type": "range", "min": 0.0, "max": 100.0 @@ -18,7 +18,7 @@ "name": "HVBMS_pack_voltage_protection_1", "board_id": 2, "measurement_id": 3100, - "kind": { + "type": { "type": "range", "min": 300.0, "max": 500.0 @@ -30,7 +30,7 @@ "name": "LCU_temperature_1_protection_2", "board_id": 1, "measurement_id": 3000, - "kind": { + "type": { "type": "below", "limit": 10.0 }, diff --git a/backend/crates/core/src/model/http/order.rs b/backend/crates/core/src/model/http/order.rs index feb7d8614..964d442e6 100644 --- a/backend/crates/core/src/model/http/order.rs +++ b/backend/crates/core/src/model/http/order.rs @@ -5,7 +5,8 @@ use serde::Serialize; use crate::{ model::{AdjId, BoardId, ProtectionKind, Severity}, utils::serialize::{ - serialize_adj_id, serialize_board_id, serialize_protection_kind, serialize_severity, + serialize_adj_id, serialize_board_id, serialize_data_measurement_type, + serialize_protection_kind, serialize_severity, }, }; @@ -58,6 +59,7 @@ pub struct OrderMeasurementResponse { /// Unit label displayed to the user. pub display_units: String, /// Same numeric, boolean or enum metadata used by data measurements. + #[serde(rename = "type", serialize_with = "serialize_data_measurement_type")] pub kind: DataMeasurementKind, /// Protection definitions in ADJ order; empty when none are declared. pub protections: Vec, @@ -70,7 +72,7 @@ pub struct OrderProtectionResponse { #[serde(serialize_with = "serialize_adj_id")] pub id: AdjId, /// Trigger condition, serialized with its type and named bounds. - #[serde(serialize_with = "serialize_protection_kind")] + #[serde(rename = "type", serialize_with = "serialize_protection_kind")] pub kind: ProtectionKind, /// Severity serialized as `fault` or `warning`. #[serde(serialize_with = "serialize_severity")] diff --git a/backend/crates/core/src/model/http/protection.rs b/backend/crates/core/src/model/http/protection.rs index 132f4e66d..8e55e9477 100644 --- a/backend/crates/core/src/model/http/protection.rs +++ b/backend/crates/core/src/model/http/protection.rs @@ -37,7 +37,7 @@ pub struct ProtectionInfoResponse { #[serde(serialize_with = "serialize_adj_id")] pub measurement_id: AdjId, /// Trigger condition; `type` preserves the ADJ name to index `info` directly. - #[serde(serialize_with = "serialize_protection_kind")] + #[serde(rename = "type", serialize_with = "serialize_protection_kind")] pub kind: ProtectionKind, /// Severity serialized as `fault` or `warning`. #[serde(serialize_with = "serialize_severity")] diff --git a/backend/crates/core/src/utils/serialize.rs b/backend/crates/core/src/utils/serialize.rs index 1a8e3354d..58e2ad00b 100644 --- a/backend/crates/core/src/utils/serialize.rs +++ b/backend/crates/core/src/utils/serialize.rs @@ -1,16 +1,20 @@ -use crate::model::{AdjId, BoardId, NumericKind, ProtectionKind, Severity}; +use crate::{ + model::{ + AdjId, BoardId, NumericKind, ProtectionKind, Severity, http::data::DataMeasurementKind, + } +}; use serde::{Serialize, Serializer}; -// EXPLANATION OF THE OBJECT SERIALIZER +// EXPLANATION OF THE OBJECT SERIALIZER // When using the macro #[serde(serialize_with = "")] you specify a function // which takes to arguments: // - 1st with the type of the atribute you apply the object // - 2nd with the type `Serializer` // The second one is just for setting the specified value obtained in the function // when the serialization occurs. Very simple. -// +// // If you want to serialize a structure you have to implement the trait Serialize, -// which +// which // Serialize domain types locally without changing the internal model. pub(crate) fn serialize_board_id( @@ -28,11 +32,8 @@ pub(crate) fn serialize_adj_id( } // Serialize numeric kind to match ADJv3 types. -pub(crate) fn serialize_numeric_kind( - kind: &NumericKind, - serializer: S, -) -> Result { - let name = match kind { +pub(crate) fn get_numeric_kind(kind: &NumericKind) -> &str { + match kind { NumericKind::U8 => "uint8", NumericKind::U16 => "uint16", NumericKind::U32 => "uint32", @@ -43,8 +44,7 @@ pub(crate) fn serialize_numeric_kind( NumericKind::I64 => "int64", NumericKind::F32 => "float32", NumericKind::F64 => "float64", - }; - serializer.serialize_str(name) + } } // A remote derive keeps the JSON representation here, without changing model. @@ -76,3 +76,33 @@ pub(crate) fn serialize_severity( Severity::Warning => "warning", }) } + +// Little helper for serialize the data measurement type +#[derive(Serialize)] +struct EnumKind { + #[serde(rename = "type")] + type_kind: String, + options: Vec, +} + +pub(crate) fn serialize_data_measurement_type( + kind: &DataMeasurementKind, + serializer: S, +) -> Result { + match kind { + DataMeasurementKind::Numeric { wire_type } => { + serializer.serialize_str(get_numeric_kind(wire_type)) + } + DataMeasurementKind::Boolean => serializer.serialize_str("boolean"), + DataMeasurementKind::Enum { options } => { + let options = options.clone(); + + let enum_kind = EnumKind { + type_kind: "enum".to_string(), + options, + }; + + EnumKind::serialize(&enum_kind, serializer) + } + } +} \ No newline at end of file From ad236e056f159c72342b6ac9a82ba6e7938c8cd3 Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Tue, 17 Nov 2026 20:16:19 +0100 Subject: [PATCH 137/225] docs(backend, http): comment some more --- backend/crates/core/src/adj/http.rs | 5 +++-- backend/crates/core/src/utils/serialize.rs | 14 +++++++------- backend/crates/station/src/http.rs | 6 +----- backend/crates/station/src/http/handlers.rs | 1 + 4 files changed, 12 insertions(+), 14 deletions(-) diff --git a/backend/crates/core/src/adj/http.rs b/backend/crates/core/src/adj/http.rs index 88ab5455c..8fcc13af5 100644 --- a/backend/crates/core/src/adj/http.rs +++ b/backend/crates/core/src/adj/http.rs @@ -79,8 +79,7 @@ impl Adj { /// Builds the order catalog without modifying or consuming the ADJ. /// /// Boards and orders are sorted by id. Boards without orders are retained with - /// an empty list. Parameters and their protections keep their ADJ order; - /// protection ids remain their one-based positions within each measurement. + /// an empty list. Parameters and their protections keep their ADJ order. pub fn order_response(&self) -> OrderResponse { let mut boards: Vec = self .pod_data @@ -105,6 +104,7 @@ impl Adj { packet_type: "order".to_string(), measurements: measurements .iter() + // Convert each parameter into its HTTP response representation .map(|measurement| OrderMeasurementResponse { id: measurement.id, alias: measurement.alias.clone(), @@ -114,6 +114,7 @@ impl Adj { protections: measurement .protections .iter() + // Convert each protection .map(|protection| OrderProtectionResponse { id: AdjId((protection.id.0 << 13) | measurement.id.0), kind: protection.kind, diff --git a/backend/crates/core/src/utils/serialize.rs b/backend/crates/core/src/utils/serialize.rs index 58e2ad00b..02418e970 100644 --- a/backend/crates/core/src/utils/serialize.rs +++ b/backend/crates/core/src/utils/serialize.rs @@ -1,7 +1,5 @@ -use crate::{ - model::{ - AdjId, BoardId, NumericKind, ProtectionKind, Severity, http::data::DataMeasurementKind, - } +use crate::model::{ + AdjId, BoardId, NumericKind, ProtectionKind, Severity, http::data::DataMeasurementKind, }; use serde::{Serialize, Serializer}; @@ -13,8 +11,7 @@ use serde::{Serialize, Serializer}; // The second one is just for setting the specified value obtained in the function // when the serialization occurs. Very simple. // -// If you want to serialize a structure you have to implement the trait Serialize, -// which +// Serialize delegates the value's representation to a generic Serializer. // Serialize domain types locally without changing the internal model. pub(crate) fn serialize_board_id( @@ -90,10 +87,13 @@ pub(crate) fn serialize_data_measurement_type( serializer: S, ) -> Result { match kind { + // for example: NumericKind::F32 -> "type": "float32" DataMeasurementKind::Numeric { wire_type } => { serializer.serialize_str(get_numeric_kind(wire_type)) } + // "type": "boolean" DataMeasurementKind::Boolean => serializer.serialize_str("boolean"), + // Enum types become an object containing "type": "enum" and the declared options. DataMeasurementKind::Enum { options } => { let options = options.clone(); @@ -105,4 +105,4 @@ pub(crate) fn serialize_data_measurement_type( EnumKind::serialize(&enum_kind, serializer) } } -} \ No newline at end of file +} diff --git a/backend/crates/station/src/http.rs b/backend/crates/station/src/http.rs index 50183c88e..30c91003a 100644 --- a/backend/crates/station/src/http.rs +++ b/backend/crates/station/src/http.rs @@ -15,11 +15,7 @@ use crate::http::server::setup_router; mod handlers; mod server; -/// Serves the catalogs without connecting a WebSocket consumer yet. -/// -/// Preserves the entry point used by the test startup code. Upgrade requests -/// to `/backend` receive `503` until [`serve_with_websocket`] is used with a -/// channel connected to the future WebSocket module. +/// Serves the ADJ catalogs and the WebSocket upgrade endpoint. pub async fn serve( listener: TcpListener, adj: &Adj, diff --git a/backend/crates/station/src/http/handlers.rs b/backend/crates/station/src/http/handlers.rs index 52ca92c01..05ce0efa5 100644 --- a/backend/crates/station/src/http/handlers.rs +++ b/backend/crates/station/src/http/handlers.rs @@ -86,6 +86,7 @@ pub(super) async fn websocket( }) } +// Builds an HTTP JSON response from already serialized bytes. fn json_response(body: Bytes) -> Response { // Do not wrap these bytes in Json: that would serialize the content again. ([(header::CONTENT_TYPE, "application/json")], body).into_response() From f6d632df492700683c705775775875d726d689e0 Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Tue, 17 Nov 2026 20:36:41 +0100 Subject: [PATCH 138/225] fix(backend, http): comment little things --- backend/crates/core/src/utils.rs | 1 - backend/crates/core/src/utils/serialize.rs | 1 + backend/crates/station/src/http/handlers.rs | 2 ++ 3 files changed, 3 insertions(+), 1 deletion(-) diff --git a/backend/crates/core/src/utils.rs b/backend/crates/core/src/utils.rs index 8e32a77ad..0063520a7 100644 --- a/backend/crates/core/src/utils.rs +++ b/backend/crates/core/src/utils.rs @@ -1,2 +1 @@ -#[cfg(feature = "http")] pub(crate) mod serialize; \ No newline at end of file diff --git a/backend/crates/core/src/utils/serialize.rs b/backend/crates/core/src/utils/serialize.rs index 02418e970..1abf05513 100644 --- a/backend/crates/core/src/utils/serialize.rs +++ b/backend/crates/core/src/utils/serialize.rs @@ -82,6 +82,7 @@ struct EnumKind { options: Vec, } +// Serializes the type of the data of the measurement, depends on each kind of measurement pub(crate) fn serialize_data_measurement_type( kind: &DataMeasurementKind, serializer: S, diff --git a/backend/crates/station/src/http/handlers.rs b/backend/crates/station/src/http/handlers.rs index 05ce0efa5..aabd23741 100644 --- a/backend/crates/station/src/http/handlers.rs +++ b/backend/crates/station/src/http/handlers.rs @@ -13,7 +13,9 @@ use tokio::sync::mpsc; /// Immutable state shared by all requests without a mutex. pub(super) struct HttpState { + // the three response JSON pre-serialized responses: Responses, + // the websocket channel websocket_connections: Option>, } From f5e9ee6682bc0a1141f8f95ee13c0310fe73d40d Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Tue, 17 Nov 2026 20:40:19 +0100 Subject: [PATCH 139/225] fix(backend, http): revert changes to main.rs --- backend/crates/station/src/main.rs | 26 +------------------------- 1 file changed, 1 insertion(+), 25 deletions(-) diff --git a/backend/crates/station/src/main.rs b/backend/crates/station/src/main.rs index fa81b031b..d872008d1 100644 --- a/backend/crates/station/src/main.rs +++ b/backend/crates/station/src/main.rs @@ -1,37 +1,13 @@ //! Ejecutable mínimo para demostrar la integración con `software-core`. -use tokio::net::TcpListener; use tracing_subscriber::EnvFilter; -#[tokio::main] -async fn main() -> std::io::Result<()> { +fn main() { let filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info")); tracing_subscriber::fmt().with_env_filter(filter).init(); tracing::info!("iniciando demo de station"); let name = std::env::args().nth(1).unwrap_or_else(|| "World".into()); let _greeting = software_core::hello_world::greet(&name); - - let adj_path = - std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../core/src/adj/test/adj"); - let adj = match software_core::adj::load_from_dir(&adj_path) { - Ok(adj) => adj, - Err(err) => { - tracing::error!(%err, "no se pudo cargar el ADJ de prueba"); - std::process::exit(1); - } - }; - tracing::info!(boards = adj.pod_data.boards.len(), "adj de prueba cargado"); - - // Just testing, not the actual address - let listener = TcpListener::bind("127.0.0.1:8080").await?; - - http::serve(listener, &adj, None).await?; - tracing::info!("demo finalizada"); - - Ok(()) } - -mod http; -mod vehicle; \ No newline at end of file From ba36feab3769aabe1c6f24e345c48890c97e9e38 Mon Sep 17 00:00:00 2001 From: GaziH Date: Tue, 17 Nov 2026 22:21:44 +0100 Subject: [PATCH 140/225] Feat(backend, net, udp): Amended implementation to ditch the use of a ring buffer. --- backend/crates/core/src/net/udp.rs | 232 ++++++++++------------------- 1 file changed, 81 insertions(+), 151 deletions(-) diff --git a/backend/crates/core/src/net/udp.rs b/backend/crates/core/src/net/udp.rs index 069219dfc..c85972214 100644 --- a/backend/crates/core/src/net/udp.rs +++ b/backend/crates/core/src/net/udp.rs @@ -6,23 +6,6 @@ //! One socket bound to the backend's own address, carrying `Data` packets //! from every board. Nothing is ever sent from it. //! -//! # Architecture: two-stage receive with bounded channel -//! -//! Boards send thousands of packets per second, sometimes in bursts that -//! overwhelm a single processing loop. To handle this, the module uses a -//! two-stage design: -//! -//! 1. **Receive loop** — a fast task that only reads datagrams from the -//! socket and pushes them into a bounded `mpsc` channel. -//! 2. **Processing loop** — drains the channel, decodes each datagram -//! using [`crate::protocol::udp::decode_datagram`], resolves the board -//! id, and reports through [`super::Reporter`]. -//! -//! The channel (`RING_CAPACITY` = 8192) absorbs bursts so the receive -//! loop stays responsive. If the channel fills, the receive loop waits for -//! space rather than dropping — the kernel socket buffer (`SO_RCVBUF`) is -//! the first line of defense, and this channel is the second. -//! //! # Entry point //! //! [`spawn`], taking [`Config`], an `Arc` and a @@ -37,7 +20,7 @@ //! none of [`super::tcp`]'s buffer applies here. Read into one reused //! 64 KiB buffer and a datagram can never be silently truncated, //! whatever the ADJ grows to. -//! - The processing loop does three things and nothing else: decode with +//! - The loop does three things and nothing else: decode with //! [`crate::protocol::udp::decode_datagram`], resolve the board, report. //! No disk, no WebSocket, no aggregation. //! - [`super::Notification::board`] comes from the decoded packet's id, @@ -72,7 +55,6 @@ use crate::model::Packet; use crate::protocol::{DecodeError, Index}; use std::net::SocketAddr; use std::sync::Arc; -use tokio::sync::mpsc; use tokio::task::JoinHandle; use tracing::{error, warn}; @@ -93,52 +75,25 @@ pub struct Config { pub recv_buffer: usize, } -/// A queued datagram entry: raw payload bytes and the sender's address. -#[derive(Debug)] -struct Datagram { - /// The raw datagram bytes copied from the socket receive buffer. - bytes: Box<[u8]>, - /// The sender's socket address (used for error attribution if decoding fails). - from: SocketAddr, -} - -/// Channel capacity — the number of datagrams that can be queued -/// between the fast receive loop and the decode/report path. -/// -/// Boards send thousands of packets per second. This buffer absorbs -/// bursts so the receive loop stays responsive while `SO_RCVBUF` acts -/// as the first line of defense in the OS kernel. -const RING_CAPACITY: usize = 8192; - -/// Binds the shared socket and spawns the receive and processing loops. +/// Binds the shared socket and spawns the receive loop. /// /// Binding happens here, **before** the task, so that a bad address is a /// startup failure handed back to whoever is composing the backend rather /// than something reported once everything is already running. /// +/// `adj` is the only part of the ADJ this module needs: it maps a decoded +/// id to its [`crate::model::PacketDef`], for the decode itself and for +/// the `board` every [`super::Notification`] carries. `station` owns it +/// and hands out clones; it is read-only here, and a reload of the ADJ is +/// a new [`Index`] with a new task, never a mutation of this one. +/// /// # Errors /// /// [`Error::Bind`] only — every later failure goes out through /// `reporter`, since by then there is nobody left to return it to. pub fn spawn(config: Config, adj: Arc, reporter: Reporter) -> Result, Error> { - // 1. Bind the UDP socket synchronously before spawning async tasks. let socket = bind_socket(config)?; - - // 2. Create the bounded channel connecting the receive loop to the processor. - let (ring_tx, ring_rx) = mpsc::channel(RING_CAPACITY); - - let recv_reporter = reporter.clone(); - - // 3. Spawn a supervising task that runs both the receiver and processor, - // ensuring clean shutdown of the processor when the receiver exits. - let handle = tokio::spawn(async move { - let processor = tokio::spawn(process_loop(ring_rx, adj, reporter)); - receive_loop(socket, ring_tx, recv_reporter).await; - // Once receive_loop exits, `ring_tx` is dropped, causing `process_loop` - // to drain remaining items and finish. - let _ = processor.await; - }); - + let handle = tokio::spawn(run_loop(socket, adj, reporter)); Ok(handle) } @@ -162,7 +117,6 @@ fn bind_socket(config: Config) -> Result { source, })?; - // Attempt to enlarge the kernel's SO_RCVBUF to handle high-frequency telemetry bursts. let sock_ref = socket2::SockRef::from(&socket); if let Err(e) = sock_ref.set_recv_buffer_size(config.recv_buffer) { warn!( @@ -176,27 +130,20 @@ fn bind_socket(config: Config) -> Result { Ok(socket) } -/// Fast receive loop: reads raw datagrams from the socket and pushes them into the channel. -async fn receive_loop( +/// Main UDP loop: reads datagrams into a reusable 64 KiB buffer, decodes in-place, and reports. +async fn run_loop( socket: tokio::net::UdpSocket, - ring_tx: mpsc::Sender, + adj: Arc, reporter: Reporter, ) { - // Allocate a single 64 KiB buffer (maximum possible UDP datagram size) - // so no incoming packet can ever be truncated. + // Reusable 64 KiB buffer — a datagram can never be silently truncated. let mut buf = vec![0u8; 64 * 1024]; loop { match socket.recv_from(&mut buf).await { Ok((len, from)) => { - // Copy only the valid bytes of this datagram into a boxed slice. - let datagram = Datagram { - bytes: buf[..len].into(), - from, - }; - - // Forward to the processing task. If the receiver dropped, exit cleanly. - if ring_tx.send(datagram).await.is_err() { + if !handle_datagram(&buf[..len], from, &adj, &reporter).await { + // Downstream channels closed; exit cleanly. break; } } @@ -211,49 +158,35 @@ async fn receive_loop( } } -/// Processing loop: drains the channel, decodes datagrams against the ADJ `Index`, and notifies downstream. -async fn process_loop( - mut ring_rx: mpsc::Receiver, - adj: Arc, - reporter: Reporter, -) { - // Pull datagrams one by one until `ring_tx` is closed and the queue is empty. - while let Some(datagram) = ring_rx.recv().await { - let Datagram { bytes, from } = datagram; - - // Decode raw bytes into a DataPacket using the ADJ lookup index. - let packet = match crate::protocol::udp::decode_datagram(&bytes, &adj) { - Ok(p) => p, - Err(source) => { - // A decode failure indicates an ADJ mismatch; report it to the error channel - // and continue draining subsequent packets. - let error = Error::Decode { from, source }; - error!(%error, "UDP decode error"); - if reporter.report(error).await.is_err() { - break; - } - continue; - } - }; +/// Decodes a single datagram slice against `adj` and forwards the result or error to `reporter`. +/// +/// Returns `false` if the downstream `reporter` channels have closed and the loop should stop. +async fn handle_datagram( + bytes: &[u8], + from: SocketAddr, + adj: &Index, + reporter: &Reporter, +) -> bool { + let packet = match crate::protocol::udp::decode_datagram(bytes, adj) { + Ok(p) => p, + Err(source) => { + let error = Error::Decode { from, source }; + error!(%error, "UDP decode error"); + return reporter.report(error).await.is_ok(); + } + }; - // Look up the packet definition to find out which board sent this packet. - let Some(packet_def) = adj.packet(packet.id) else { - warn!(id = ?packet.id, "decoded packet id not in index"); - continue; - }; + let Some(packet_def) = adj.packet(packet.id) else { + warn!(id = ?packet.id, "decoded packet id not in index"); + return true; + }; - let board = packet_def.board; + let board = packet_def.board; - // Broadcast the decoded telemetry packet to the event bus. - if reporter - .notify(board, super::Event::Received(Packet::Data(packet))) - .await - .is_err() - { - // Downstream event receiver closed; exit loop. - break; - } - } + reporter + .notify(board, super::Event::Received(Packet::Data(packet))) + .await + .is_ok() } /// Something that went wrong on the shared UDP socket. @@ -298,6 +231,22 @@ pub enum Error { impl Error { /// Whether this error means the pod has to be sent to fault. + /// + /// "Fatal" is about the **pod**, not about this process: the backend + /// stays up — still reading, still serving the frontend, still + /// recording — so that whoever is operating the pod can see what + /// happened. Nothing here ever calls `std::process::exit`. + /// + /// Both runtime failures of this socket qualify, and for the same + /// reason: neither can be true of a single datagram. + /// [`Error::Decode`] means the loaded ADJ does not describe what the + /// boards are sending, and [`Error::Recv`] means the socket itself is + /// no longer usable, which is every board's telemetry gone at once. + /// Neither is something a retry fixes. + /// + /// [`Error::Bind`] never reaches this: binding happens before the + /// task is spawned, so it is a startup failure handed back to + /// whoever composes the backend. pub fn is_fatal(&self) -> bool { match self { Error::Bind { .. } | Error::Recv { .. } | Error::Decode { .. } => true, @@ -312,7 +261,6 @@ mod tests { use std::collections::HashMap; use std::net::IpAddr; - /// Helper returning a dummy sender SocketAddr for tests. fn peer() -> SocketAddr { SocketAddr::new(IpAddr::from([192, 168, 1, 3]), 50400) } @@ -324,8 +272,6 @@ mod tests { source: crate::protocol::DecodeError::UnknownId(AdjId(9999)), }; - // Nothing corrupts a datagram in flight, so this is a mismatched - // ADJ, not noise to skip over. assert!(error.is_fatal()); } @@ -335,7 +281,6 @@ mod tests { source: std::io::Error::from(std::io::ErrorKind::ConnectionReset), }; - // Every board's telemetry at once. assert!(error.is_fatal()); } @@ -346,8 +291,6 @@ mod tests { source: crate::protocol::DecodeError::UnknownId(AdjId(9999)), }; - // The only identity it has: there is no board to attribute an - // undeclared id to. assert!(error.to_string().contains("192.168.1.3:50400")); } @@ -369,58 +312,45 @@ mod tests { let pod_data = PodData { boards: HashMap::from([(board.id, board)]), }; - Index::new(&pod_data) // I am not sure what to do here - } - - #[test] - fn ring_capacity_is_positive() { - // Sanity: the channel must hold at least one entry. - assert!(RING_CAPACITY > 0); + Index::new(&pod_data, None) } #[tokio::test] - async fn process_loop_reports_error_on_unknown_id() { + async fn handle_datagram_decodes_valid_packet_and_notifies() { let (reporter, mut sinks) = Reporter::channels(16, 16); - let index = Arc::new(sample_index()); - let (ring_tx, ring_rx) = mpsc::channel(RING_CAPACITY); + let index = sample_index(); - let processor = tokio::spawn(process_loop(ring_rx, index, reporter)); + // 1000 in little-endian u16 is [0xE8, 0x03], with 0 measurements. + let keep_going = handle_datagram(&[0xE8, 0x03], peer(), &index, &reporter).await; + assert!(keep_going); - // Send a datagram with an unknown id (0xFFFF = 65535) — should trigger a decode error. - let datagram = Datagram { - bytes: vec![0xFF, 0xFF].into(), - from: peer(), - }; - ring_tx.send(datagram).await.expect("processor is alive"); + let notification = sinks.notifications.recv().await; + assert!(notification.is_some(), "should have emitted a packet event"); + assert!(sinks.errors.try_recv().is_err(), "should not have reported an error"); + } + + #[tokio::test] + async fn handle_datagram_reports_error_on_unknown_id() { + let (reporter, mut sinks) = Reporter::channels(16, 16); + let index = sample_index(); - // Drop the sender so the processor exits. - drop(ring_tx); - processor.await.expect("processor should finish"); + // Unknown ID 0xFFFF (65535) + let keep_going = handle_datagram(&[0xFF, 0xFF], peer(), &index, &reporter).await; + assert!(keep_going); - // The processor should have reported a decode error. let error_report = sinks.errors.recv().await; assert!(error_report.is_some(), "should have reported a decode error"); } #[tokio::test] - async fn process_loop_exits_when_ring_closes() { + async fn handle_datagram_stops_when_sinks_are_dropped() { let (reporter, sinks) = Reporter::channels(16, 16); - let index = Arc::new(sample_index()); - let (ring_tx, ring_rx) = mpsc::channel(RING_CAPACITY); - - let processor = tokio::spawn(process_loop(ring_rx, index, reporter)); - - // Send an incomplete 1-byte datagram (fails with UnexpectedEof), then close the channel. - let datagram = Datagram { - bytes: vec![0x00].into(), - from: peer(), - }; - ring_tx.send(datagram).await.expect("processor is alive"); - drop(ring_tx); - - // Wait for the processor to finish cleanly. - processor.await.expect("processor should finish cleanly"); + let index = sample_index(); drop(sinks); + + // With receivers dropped, reporting should signal the loop to exit (false). + let keep_going = handle_datagram(&[0xFF, 0xFF], peer(), &index, &reporter).await; + assert!(!keep_going); } #[test] From 8f2b89c10077fa79dd0702b86a41b0d46913f275 Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Tue, 17 Nov 2026 23:17:31 +0100 Subject: [PATCH 141/225] fix(backend, http): fix feature imports and usage --- backend/crates/core/src/utils/serialize.rs | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/backend/crates/core/src/utils/serialize.rs b/backend/crates/core/src/utils/serialize.rs index 1abf05513..cb61543b9 100644 --- a/backend/crates/core/src/utils/serialize.rs +++ b/backend/crates/core/src/utils/serialize.rs @@ -1,8 +1,9 @@ -use crate::model::{ - AdjId, BoardId, NumericKind, ProtectionKind, Severity, http::data::DataMeasurementKind, -}; +use crate::model::{AdjId, BoardId, NumericKind, ProtectionKind, Severity}; use serde::{Serialize, Serializer}; +#[cfg(feature = "http")] +use crate::model::http::data::DataMeasurementKind; + // EXPLANATION OF THE OBJECT SERIALIZER // When using the macro #[serde(serialize_with = "")] you specify a function // which takes to arguments: @@ -82,6 +83,7 @@ struct EnumKind { options: Vec, } +#[cfg(feature = "http")] // Serializes the type of the data of the measurement, depends on each kind of measurement pub(crate) fn serialize_data_measurement_type( kind: &DataMeasurementKind, From ada7456ab716564716c96caaacfc4cb6cfd23b46 Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Tue, 17 Nov 2026 23:32:20 +0100 Subject: [PATCH 142/225] fix(backend, Cargo.lock): fix duplicated dependencies --- backend/Cargo.lock | 6 ------ 1 file changed, 6 deletions(-) diff --git a/backend/Cargo.lock b/backend/Cargo.lock index 554d047d5..5ed9308bd 100644 --- a/backend/Cargo.lock +++ b/backend/Cargo.lock @@ -3737,12 +3737,6 @@ version = "0.57.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" -[[package]] -name = "wit-bindgen" -version = "0.57.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" - [[package]] name = "writeable" version = "0.6.4" From 74b08446511f2c633245ab0f83d3b2e278ba42ac Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Tue, 24 Nov 2026 11:39:17 +0100 Subject: [PATCH 143/225] wip(backend, websocket): initial module structure --- backend/crates/station/src/main.rs | 4 ++++ backend/crates/station/src/websocket.rs | 6 ++++++ backend/crates/station/src/websocket/broker.rs | 0 backend/crates/station/src/websocket/handler.rs | 0 backend/crates/station/src/websocket/receiver.rs | 0 backend/crates/station/src/websocket/sender.rs | 0 6 files changed, 10 insertions(+) create mode 100644 backend/crates/station/src/websocket.rs create mode 100644 backend/crates/station/src/websocket/broker.rs create mode 100644 backend/crates/station/src/websocket/handler.rs create mode 100644 backend/crates/station/src/websocket/receiver.rs create mode 100644 backend/crates/station/src/websocket/sender.rs diff --git a/backend/crates/station/src/main.rs b/backend/crates/station/src/main.rs index d872008d1..9fa834996 100644 --- a/backend/crates/station/src/main.rs +++ b/backend/crates/station/src/main.rs @@ -11,3 +11,7 @@ fn main() { let _greeting = software_core::hello_world::greet(&name); tracing::info!("demo finalizada"); } + +mod http; +mod vehicle; +mod websocket; diff --git a/backend/crates/station/src/websocket.rs b/backend/crates/station/src/websocket.rs new file mode 100644 index 000000000..d789e536d --- /dev/null +++ b/backend/crates/station/src/websocket.rs @@ -0,0 +1,6 @@ +mod handler; +mod receiver; +mod sender; +mod broker; + + diff --git a/backend/crates/station/src/websocket/broker.rs b/backend/crates/station/src/websocket/broker.rs new file mode 100644 index 000000000..e69de29bb diff --git a/backend/crates/station/src/websocket/handler.rs b/backend/crates/station/src/websocket/handler.rs new file mode 100644 index 000000000..e69de29bb diff --git a/backend/crates/station/src/websocket/receiver.rs b/backend/crates/station/src/websocket/receiver.rs new file mode 100644 index 000000000..e69de29bb diff --git a/backend/crates/station/src/websocket/sender.rs b/backend/crates/station/src/websocket/sender.rs new file mode 100644 index 000000000..e69de29bb From 8d8193408fe961fba8889fa3c70f697d9398d86e Mon Sep 17 00:00:00 2001 From: Gazi Al Saad Halawani Date: Tue, 24 Nov 2026 21:08:44 +0100 Subject: [PATCH 144/225] Feat(backend, pipeline): Add pipeline module so Javier can have a look --- backend/crates/core/src/lib.rs | 1 + backend/crates/core/src/pipeline/mod.rs | 1 + backend/crates/core/src/pipeline/pipeline.rs | 286 +++++++++++++++++++ 3 files changed, 288 insertions(+) create mode 100644 backend/crates/core/src/pipeline/mod.rs create mode 100644 backend/crates/core/src/pipeline/pipeline.rs diff --git a/backend/crates/core/src/lib.rs b/backend/crates/core/src/lib.rs index 573dd787e..92ce900f4 100644 --- a/backend/crates/core/src/lib.rs +++ b/backend/crates/core/src/lib.rs @@ -23,3 +23,4 @@ pub mod protocol; /// into [`protocol`] to decode. See [`net::tcp`], [`net::udp`]. #[cfg(feature = "net")] pub mod net; +pub mod pipeline; diff --git a/backend/crates/core/src/pipeline/mod.rs b/backend/crates/core/src/pipeline/mod.rs new file mode 100644 index 000000000..e979cae3b --- /dev/null +++ b/backend/crates/core/src/pipeline/mod.rs @@ -0,0 +1 @@ +pub mod pipeline; \ No newline at end of file diff --git a/backend/crates/core/src/pipeline/pipeline.rs b/backend/crates/core/src/pipeline/pipeline.rs new file mode 100644 index 000000000..a8c92f0f7 --- /dev/null +++ b/backend/crates/core/src/pipeline/pipeline.rs @@ -0,0 +1,286 @@ +//! Central routing and fan-out stage between `net` and downstream consumers. +//! +//! # What this module is +//! +//! The single consumer of [`crate::net::Sinks`]. Everything that comes off the +//! wire (UDP telemetry, TCP orders/messages, connection transitions, and +//! transport errors) enters here once and is distributed to whoever needs it: +//! live observers (WebSocket/frontend, protection checks), optional disk +//! recording, and the pod fault supervisor. +//! +//! # Entry point +//! +//! [`spawn`], taking [`Config`], [`crate::net::Sinks`], and an optional +//! recorder channel. Returns a [`Pipeline`] handle exposing live telemetry +//! subscriptions, the single-shot fault receiver, and the task's `JoinHandle`. +//! +//! # Contract +//! +//! - **Never backpressure `net`.** Both `sinks.notifications` and +//! `sinks.errors` are drained continuously in a single `tokio::select!` loop. +//! A slow frontend or stalled disk writer must never block UDP/TCP ingestion: +//! live consumers use a [`tokio::sync::broadcast`] channel (lagging receivers +//! skip old frames), and optional disk recording uses non-blocking `try_send`. +//! - **Single "fault once" guard.** Transport modules (`net::udp`, `net::tcp`) +//! report every error and keep running without acting on it. This module +//! checks [`NetError::is_fatal`] and emits **at most one** fault trigger on +//! [`Pipeline::faults`] so `station` sends the pod to fault once—even if a +//! mismatched ADJ produces thousands of decode errors per second. +//! - **Stay alive after fault.** Faulting is about the **pod**, not this +//! process. After emitting a fault trigger, the loop keeps routing packets +//! and draining errors so operators can inspect telemetry and logs. +//! - **Zero-copy fan-out.** Each [`Notification`] is wrapped in an `Arc` once +//! and shared across all subscribers rather than cloned per consumer. +//! - **Clean shutdown.** Disables closed `select!` branches to avoid busy +//! spinning and exits once both upstream `net` channels have closed. + +use crate::net::{Error as NetError, Notification, Sinks}; +use std::sync::Arc; +use tokio::sync::mpsc::error::TrySendError; +use tokio::sync::{broadcast, mpsc}; +use tokio::task::JoinHandle; +use tracing::{error, warn}; + +/// Sizing parameters for the pipeline's internal channels. +/// +/// Resolved by `station` before spawning; this module reads no config files. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Config { + /// Capacity of the live [`broadcast`] channel shared by subscribers + /// (WebSocket server, state aggregator, protections). + /// + /// A subscriber falling more than this many notifications behind receives + /// `RecvError::Lagged` and jumps to the latest frame instead of stalling + /// the network receive loops. + pub broadcast_capacity: usize, +} + +impl Default for Config { + fn default() -> Self { + Self { + broadcast_capacity: 1024, + } + } +} + +/// Handle to a running pipeline task. +pub struct Pipeline { + telemetry_tx: broadcast::Sender>, + /// Fires at most once when the first fatal transport error arrives. + /// + /// `station` listens here to command the pod into fault state. + pub faults: mpsc::Receiver, + /// Handle to the background routing task. + pub handle: JoinHandle<()>, +} + +impl Pipeline { + /// Subscribes a new live consumer (e.g. WebSocket broadcaster or state + /// cache) to every [`Notification`] flowing through the pipeline. + pub fn subscribe(&self) -> broadcast::Receiver> { + self.telemetry_tx.subscribe() + } +} + +/// Spawns the pipeline routing task. +/// +/// `recorder` is optional: pass `Some(tx)` when disk recording is enabled, or +/// `None` in lightweight demos/tests. Recording uses `try_send` so a full disk +/// buffer drops frames with a warning rather than stalling `net`. +/// +/// TODO(review): Confirm whether protections (ADJv3 range/limit checks) should +/// run inline in `handle_notification` before fan-out, or as a separate task +/// calling `pipeline.subscribe()`. +pub fn spawn( + config: Config, + sinks: Sinks, + recorder: Option>>, +) -> Pipeline { + let (telemetry_tx, _) = broadcast::channel(config.broadcast_capacity); + // Capacity 1 is enough: the fault-once guard sends at most one fatal error. + let (fault_tx, fault_rx) = mpsc::channel(1); + + let handle = tokio::spawn(run_loop(sinks, telemetry_tx.clone(), fault_tx, recorder)); + + Pipeline { + telemetry_tx, + faults: fault_rx, + handle, + } +} + +/// Main routing loop: drains both `net` channels until upstream closes. +async fn run_loop( + mut sinks: Sinks, + telemetry_tx: broadcast::Sender>, + fault_tx: mpsc::Sender, + mut recorder: Option>>, +) { + let mut faulted = false; + let mut notifications_open = true; + let mut errors_open = true; + + while notifications_open || errors_open { + tokio::select! { + res = sinks.notifications.recv(), if notifications_open => { + match res { + Some(notification) => { + handle_notification(notification, &telemetry_tx, &mut recorder); + } + None => notifications_open = false, + } + } + res = sinks.errors.recv(), if errors_open => { + match res { + Some(err) => { + handle_error(err, &mut faulted, &fault_tx); + } + None => errors_open = false, + } + } + } + } +} + +/// Fans a single notification out to live subscribers and the optional recorder. +fn handle_notification( + notification: Notification, + telemetry_tx: &broadcast::Sender>, + recorder: &mut Option>>, +) { + let shared = Arc::new(notification); + + // TODO(review): If state aggregation / rate throttling for the frontend + // belongs inside `pipeline` rather than downstream, hook it in here. + + // Broadcast returns Err only when there are zero active subscribers, which + // is expected during startup or headless runs. + let _ = telemetry_tx.send(Arc::clone(&shared)); + + if let Some(tx) = recorder.as_ref() { + match tx.try_send(shared) { + Ok(()) => {} + Err(TrySendError::Full(_)) => { + // TODO(review): Consider rate-limiting this warning or tracking + // a dropped-frame counter if high-rate telemetry overflows disk. + warn!("recorder channel full, dropping notification to avoid stalling net"); + } + Err(TrySendError::Closed(_)) => { + warn!("recorder channel closed, disabling recording sink"); + *recorder = None; + } + } + } +} + +/// Evaluates a transport error against the fault-once guard. +fn handle_error(err: NetError, faulted: &mut bool, fault_tx: &mpsc::Sender) { + if !err.is_fatal() { + warn!(%err, "non-fatal network error"); + return; + } + + if *faulted { + // Already triggered a pod fault; keep draining silently so `sinks.errors` + // never fills up and deadlocks the transport tasks. + return; + } + + *faulted = true; + error!(%err, "fatal network error — triggering pod fault"); + + if let Err(send_err) = fault_tx.try_send(err) { + error!(%send_err, "could not deliver fault trigger to supervisor"); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::model::{AdjId, BoardId, DataOrderPacket, Packet}; + use crate::net::{udp, Event, Reporter}; + use crate::protocol::DecodeError; + use std::net::{IpAddr, SocketAddr}; + + fn sample_notification() -> (BoardId, Event) { + let packet = DataOrderPacket::new(AdjId(551), vec![]); + (BoardId(5), Event::Received(Packet::Data(packet))) + } + + fn fatal_udp_error() -> udp::Error { + udp::Error::Decode { + from: SocketAddr::new(IpAddr::from([192, 168, 1, 3]), 50400), + source: DecodeError::UnknownId(AdjId(9999)), + } + } + + #[tokio::test] + async fn fans_out_notifications_to_multiple_subscribers_and_recorder() { + let (reporter, sinks) = Reporter::channels(16, 16); + let (rec_tx, mut rec_rx) = mpsc::channel(16); + + let pipeline = spawn(Config::default(), sinks, Some(rec_tx)); + let mut sub_a = pipeline.subscribe(); + let mut sub_b = pipeline.subscribe(); + + let (board, event) = sample_notification(); + reporter.notify(board, event).await.unwrap(); + + let a = sub_a.recv().await.unwrap(); + let b = sub_b.recv().await.unwrap(); + let rec = rec_rx.recv().await.unwrap(); + + assert_eq!(a.board, BoardId(5)); + assert_eq!(b.board, BoardId(5)); + assert_eq!(rec.board, BoardId(5)); + + drop(reporter); + pipeline.handle.await.unwrap(); + } + + #[tokio::test] + async fn fatal_errors_trigger_fault_only_once_and_keep_draining() { + let (reporter, sinks) = Reporter::channels(16, 4); + let mut pipeline = spawn(Config::default(), sinks, None); + let mut sub = pipeline.subscribe(); + + // Flood more fatal errors than the error channel capacity (4) to verify + // the pipeline keeps draining without deadlocking. + for _ in 0..20 { + reporter.report(fatal_udp_error()).await.unwrap(); + } + + // Exactly one fault trigger should be emitted. + let first_fault = pipeline.faults.recv().await; + assert!(first_fault.is_some()); + + // Telemetry must still flow after faulting. + let (board, event) = sample_notification(); + reporter.notify(board, event).await.unwrap(); + let received = sub.recv().await.unwrap(); + assert_eq!(received.board, BoardId(5)); + + drop(reporter); + pipeline.handle.await.unwrap(); + + // No second fault trigger was queued. + assert!(pipeline.faults.try_recv().is_err()); + } + + #[tokio::test] + async fn full_recorder_does_not_block_live_subscribers() { + let (reporter, sinks) = Reporter::channels(16, 16); + // Recorder with capacity 1 that nobody reads from. + let (rec_tx, _rec_rx) = mpsc::channel(1); + + let pipeline = spawn(Config::default(), sinks, Some(rec_tx)); + let mut sub = pipeline.subscribe(); + + for _ in 0..5 { + let (board, event) = sample_notification(); + reporter.notify(board, event).await.unwrap(); + } + + for _ in 0..5 { + let msg = sub.recv().await.unwrap(); + assert_eq!(msg \ No newline at end of file From 95640427d1cb17d75e8af01c548f6e1e8de94b98 Mon Sep 17 00:00:00 2001 From: Gazi Al Saad Halawani Date: Tue, 24 Nov 2026 21:09:30 +0100 Subject: [PATCH 145/225] Feat(backend, pipeline): added missing lines. --- backend/crates/core/src/pipeline/pipeline.rs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/backend/crates/core/src/pipeline/pipeline.rs b/backend/crates/core/src/pipeline/pipeline.rs index a8c92f0f7..2c68a6a47 100644 --- a/backend/crates/core/src/pipeline/pipeline.rs +++ b/backend/crates/core/src/pipeline/pipeline.rs @@ -283,4 +283,10 @@ mod tests { for _ in 0..5 { let msg = sub.recv().await.unwrap(); - assert_eq!(msg \ No newline at end of file + assert_eq!(msg.board, BoardId(5)); + } + + drop(reporter); + pipeline.handle.await.unwrap(); + } +} \ No newline at end of file From 5ce19d26d074509acf6d4d744b7c951194afd715 Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Tue, 24 Nov 2026 23:58:32 +0100 Subject: [PATCH 146/225] feat(backend, model): websocket payloads and examples --- backend/crates/core/src/model.rs | 3 + backend/crates/core/src/model/websocket.rs | 26 +++++ .../core/src/model/websocket/connection.rs | 16 ++++ .../crates/core/src/model/websocket/data.rs | 42 ++++++++ .../model/websocket/example/connection.json | 13 +++ .../src/model/websocket/example/data.json | 35 +++++++ .../websocket/example/logger_enable.json | 4 + .../websocket/example/logger_response.json | 4 + .../websocket/example/logger_variables.json | 8 ++ .../src/model/websocket/example/message.json | 18 ++++ .../src/model/websocket/example/order.json | 13 +++ .../model/websocket/example/protection.json | 13 +++ .../model/websocket/example/state_orders.json | 10 ++ .../core/src/model/websocket/message.rs | 88 +++++++++++++++++ .../crates/core/src/model/websocket/order.rs | 32 +++++++ .../core/src/model/websocket/protection.rs | 95 +++++++++++++++++++ backend/crates/core/src/utils/serialize.rs | 21 ++++ 17 files changed, 441 insertions(+) create mode 100644 backend/crates/core/src/model/websocket.rs create mode 100644 backend/crates/core/src/model/websocket/connection.rs create mode 100644 backend/crates/core/src/model/websocket/data.rs create mode 100644 backend/crates/core/src/model/websocket/example/connection.json create mode 100644 backend/crates/core/src/model/websocket/example/data.json create mode 100644 backend/crates/core/src/model/websocket/example/logger_enable.json create mode 100644 backend/crates/core/src/model/websocket/example/logger_response.json create mode 100644 backend/crates/core/src/model/websocket/example/logger_variables.json create mode 100644 backend/crates/core/src/model/websocket/example/message.json create mode 100644 backend/crates/core/src/model/websocket/example/order.json create mode 100644 backend/crates/core/src/model/websocket/example/protection.json create mode 100644 backend/crates/core/src/model/websocket/example/state_orders.json create mode 100644 backend/crates/core/src/model/websocket/message.rs create mode 100644 backend/crates/core/src/model/websocket/order.rs create mode 100644 backend/crates/core/src/model/websocket/protection.rs diff --git a/backend/crates/core/src/model.rs b/backend/crates/core/src/model.rs index 74b79b99a..80ec948a2 100644 --- a/backend/crates/core/src/model.rs +++ b/backend/crates/core/src/model.rs @@ -20,6 +20,9 @@ mod value; #[cfg(feature = "http")] pub mod http; +#[cfg(feature = "websocket")] +pub mod websocket; + pub use board::{Board, PacketDef, PacketType, PodData}; pub use id::{AdjId, BoardId, MacAddress, Port}; pub use measurement::{Measurement, MeasurementKind, NumericKind, Range}; diff --git a/backend/crates/core/src/model/websocket.rs b/backend/crates/core/src/model/websocket.rs new file mode 100644 index 000000000..4fe844983 --- /dev/null +++ b/backend/crates/core/src/model/websocket.rs @@ -0,0 +1,26 @@ +//! JSON payloads for frontend WebSocket topics (feature `websocket`). +//! +//! Existing topics preserve the Go backend's JSON shapes; `protection/update` +//! adds a compact event. Socket handling, subscriptions and publication belong +//! to `station`. See `websocket/README.md`. + +mod connection; +mod data; +mod message; +mod order; +mod protection; + +pub use connection::{Connection, ConnectionUpdate}; +pub use data::{DataPacketUpdate, DataUpdate, MeasurementUpdate}; +pub use message::{MessageKind, MessagePayload, MessageTimestamp, MessageUpdate}; +pub use order::{OrderField, OrderSend, StateOrdersUpdate}; +pub use protection::{ProtectionPayload, ProtectionUpdate}; + +/// Payload of `logger/enable`: the requested recording state. +pub type LoggerEnable = bool; + +/// Payload of `logger/response`: the actual recording state. +pub type LoggerResponse = bool; + +/// Payload of `logger/variables`: selected measurement names. +pub type LoggerVariables = Vec; diff --git a/backend/crates/core/src/model/websocket/connection.rs b/backend/crates/core/src/model/websocket/connection.rs new file mode 100644 index 000000000..2e4a2d8c7 --- /dev/null +++ b/backend/crates/core/src/model/websocket/connection.rs @@ -0,0 +1,16 @@ +use std::collections::HashMap; + +use serde::Serialize; + +/// Payload of `connection/update`, keyed by board name. +pub type ConnectionUpdate = HashMap; + +/// Whether a board is connected to the backend. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Connection { + /// Board name, also used as the key in `ConnectionUpdate`. + pub name: String, + /// Current connection state. + pub is_connected: bool, +} diff --git a/backend/crates/core/src/model/websocket/data.rs b/backend/crates/core/src/model/websocket/data.rs new file mode 100644 index 000000000..8901f7e26 --- /dev/null +++ b/backend/crates/core/src/model/websocket/data.rs @@ -0,0 +1,42 @@ +use std::collections::HashMap; + +use serde::Serialize; + +use crate::{model::AdjId, utils::serialize::serialize_adj_id}; + +/// Payload of `podData/update`, keyed by packet id (JSON object keys are strings). +pub type DataUpdate = HashMap; + +/// Current telemetry and statistics for one packet. +#[derive(Debug, Clone, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct DataPacketUpdate { + /// ADJ packet id, serialized as a number. + #[serde(serialize_with = "serialize_adj_id")] + pub id: AdjId, + /// Hexadecimal representation of the received packet. + pub hex_value: String, + /// Number of packets received under this id. + pub count: u64, + /// Averaged interval between packets, in the legacy timestamp's units. + pub cycle_time: u64, + /// Updates keyed by the measurement's textual alias. + pub measurement_updates: HashMap, +} + +/// A number carries statistics; booleans and enums are JSON primitives. +#[derive(Debug, Clone, PartialEq, Serialize)] +#[serde(untagged)] +pub enum MeasurementUpdate { + /// Numeric measurement and its moving average. + Numeric { + /// Most recently received value. + last: f64, + /// Moving average of the received values. + average: f64, + }, + /// Most recently received boolean. + Boolean(bool), + /// Most recently received enum variant. + Enum(String), +} diff --git a/backend/crates/core/src/model/websocket/example/connection.json b/backend/crates/core/src/model/websocket/example/connection.json new file mode 100644 index 000000000..ab23a4751 --- /dev/null +++ b/backend/crates/core/src/model/websocket/example/connection.json @@ -0,0 +1,13 @@ +{ + "topic": "connection/update", + "payload": { + "LCU": { + "name": "LCU", + "isConnected": true + }, + "HVBMS": { + "name": "HVBMS", + "isConnected": false + } + } +} diff --git a/backend/crates/core/src/model/websocket/example/data.json b/backend/crates/core/src/model/websocket/example/data.json new file mode 100644 index 000000000..312fdc7ba --- /dev/null +++ b/backend/crates/core/src/model/websocket/example/data.json @@ -0,0 +1,35 @@ +{ + "topic": "podData/update", + "payload": { + "936": { + "id": 936, + "hexValue": "a80300000e42", + "count": 124, + "cycleTime": 100000000, + "measurementUpdates": { + "temperature_1": { + "last": 35.5, + "average": 35.0 + } + } + }, + "1201": { + "id": 1201, + "hexValue": "b10401", + "count": 58, + "cycleTime": 100000000, + "measurementUpdates": { + "contactor_closed": true + } + }, + "1202": { + "id": 1202, + "hexValue": "b20401", + "count": 58, + "cycleTime": 100000000, + "measurementUpdates": { + "state": "Operational" + } + } + } +} diff --git a/backend/crates/core/src/model/websocket/example/logger_enable.json b/backend/crates/core/src/model/websocket/example/logger_enable.json new file mode 100644 index 000000000..a63e1bf11 --- /dev/null +++ b/backend/crates/core/src/model/websocket/example/logger_enable.json @@ -0,0 +1,4 @@ +{ + "topic": "logger/enable", + "payload": true +} diff --git a/backend/crates/core/src/model/websocket/example/logger_response.json b/backend/crates/core/src/model/websocket/example/logger_response.json new file mode 100644 index 000000000..fc7277b4c --- /dev/null +++ b/backend/crates/core/src/model/websocket/example/logger_response.json @@ -0,0 +1,4 @@ +{ + "topic": "logger/response", + "payload": true +} diff --git a/backend/crates/core/src/model/websocket/example/logger_variables.json b/backend/crates/core/src/model/websocket/example/logger_variables.json new file mode 100644 index 000000000..6fb7698f8 --- /dev/null +++ b/backend/crates/core/src/model/websocket/example/logger_variables.json @@ -0,0 +1,8 @@ +{ + "topic": "logger/variables", + "payload": [ + "temperature_1", + "contactor_closed", + "state" + ] +} diff --git a/backend/crates/core/src/model/websocket/example/message.json b/backend/crates/core/src/model/websocket/example/message.json new file mode 100644 index 000000000..65d1f75cb --- /dev/null +++ b/backend/crates/core/src/model/websocket/example/message.json @@ -0,0 +1,18 @@ +{ + "topic": "message/update", + "payload": { + "kind": "info", + "payload": "Order Sent", + "board": "LCU", + "name": "1001", + "timestamp": { + "counter": 0, + "second": 5, + "minute": 30, + "hour": 12, + "day": 24, + "month": 11, + "year": 2026 + } + } +} diff --git a/backend/crates/core/src/model/websocket/example/order.json b/backend/crates/core/src/model/websocket/example/order.json new file mode 100644 index 000000000..853111e21 --- /dev/null +++ b/backend/crates/core/src/model/websocket/example/order.json @@ -0,0 +1,13 @@ +{ + "topic": "order/send", + "payload": { + "id": 1001, + "fields": { + "target_speed": { + "value": 12.5, + "isEnabled": true, + "type": "float32" + } + } + } +} diff --git a/backend/crates/core/src/model/websocket/example/protection.json b/backend/crates/core/src/model/websocket/example/protection.json new file mode 100644 index 000000000..8ae2375a1 --- /dev/null +++ b/backend/crates/core/src/model/websocket/example/protection.json @@ -0,0 +1,13 @@ +{ + "topic": "protection/update", + "payload": { + "id": 11192, + "value": 105.5, + "timestamp": { + "hour": 12, + "minute": 30, + "second": 6, + "subsecond": 0 + } + } +} diff --git a/backend/crates/core/src/model/websocket/example/state_orders.json b/backend/crates/core/src/model/websocket/example/state_orders.json new file mode 100644 index 000000000..0ee68edda --- /dev/null +++ b/backend/crates/core/src/model/websocket/example/state_orders.json @@ -0,0 +1,10 @@ +{ + "topic": "order/stateOrders", + "payload": { + "LCU": [ + 1001, + 1002 + ], + "HVBMS": [] + } +} diff --git a/backend/crates/core/src/model/websocket/message.rs b/backend/crates/core/src/model/websocket/message.rs new file mode 100644 index 000000000..f6ce745bb --- /dev/null +++ b/backend/crates/core/src/model/websocket/message.rs @@ -0,0 +1,88 @@ +use serde::Serialize; + +use crate::model::{MessageLevel, Severity}; + +use super::ProtectionPayload; + +/// Payload of `message/update`, preserving the legacy event envelope. +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct MessageUpdate { + /// Event severity, represented by the legacy JSON field `kind`. + pub kind: MessageKind, + /// Text or protection details. + pub payload: MessagePayload, + /// Name of the board that produced the event. + pub board: String, + /// Display name of the event; order-sent notices use the order id as text. + pub name: String, + /// Original RTC fields, without a timezone conversion. + pub timestamp: MessageTimestamp, +} + +/// Both message shapes accepted by the existing frontend. +#[derive(Debug, Clone, PartialEq, Serialize)] +#[serde(untagged)] +pub enum MessagePayload { + /// An informational notice or a board's free-text message. + Text(String), + /// Protection details, as published on `message/update` by Go. + Protection(ProtectionPayload), +} + +/// Event severity: legacy values plus ADJv3's `panic` message level. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "lowercase")] +pub enum MessageKind { + /// Informational message. + Info, + /// Unexpected condition. + Warning, + /// Fault condition. + Fault, + /// A legacy protection returned to its appropriate range. + Ok, + /// Unrecoverable firmware error. + Panic, +} + +impl From for MessageKind { + fn from(level: MessageLevel) -> Self { + match level { + MessageLevel::Fault => Self::Fault, + MessageLevel::Warning => Self::Warning, + MessageLevel::Info => Self::Info, + MessageLevel::Panic => Self::Panic, + } + } +} + +impl From for MessageKind { + fn from(severity: Severity) -> Self { + match severity { + Severity::Fault => Self::Fault, + Severity::Warning => Self::Warning, + } + } +} + +/// Legacy RTC timestamp used by the frontend's event display. +/// +/// This is not `ShortTimestamp`: the latter has no date and its subsecond unit +/// is unresolved. Event construction must supply the date and counter explicitly. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +pub struct MessageTimestamp { + /// RTC counter; kept separate from `ShortTimestamp::subsecond`. + pub counter: u16, + /// Second of the minute. + pub second: u8, + /// Minute of the hour. + pub minute: u8, + /// Hour of the day. + pub hour: u8, + /// Day of the month. + pub day: u8, + /// Month of the year. + pub month: u8, + /// Calendar year. + pub year: u16, +} diff --git a/backend/crates/core/src/model/websocket/order.rs b/backend/crates/core/src/model/websocket/order.rs new file mode 100644 index 000000000..5b8cb221f --- /dev/null +++ b/backend/crates/core/src/model/websocket/order.rs @@ -0,0 +1,32 @@ +use std::collections::HashMap; + +use serde::Deserialize; + +use crate::{model::AdjId, utils::serialize::deserialize_adj_id}; + +/// Payload of `order/send`; conversion to an `OrderPacket` requires the ADJ. +#[derive(Debug, Clone, PartialEq, Deserialize)] +pub struct OrderSend { + /// Requested order's ADJ id. + #[serde(deserialize_with = "deserialize_adj_id")] + pub id: AdjId, + /// Parameters keyed by their textual aliases, rather than wire position. + pub fields: HashMap, +} + +/// One parameter supplied by the frontend. +#[derive(Debug, Clone, PartialEq, Deserialize)] +pub struct OrderField { + /// Raw JSON value; its type and range must be checked against the ADJ. + /// Keeping it raw also preserves integer precision before validation. + pub value: serde_json::Value, + /// Whether the frontend enables this parameter. + #[serde(rename = "isEnabled")] + pub is_enabled: bool, + /// Legacy type name, such as `uint16`, `float32`, `bool` or `enum`. + #[serde(rename = "type")] + pub field_type: String, +} + +/// Payload of `order/stateOrders`: board names mapped to enabled order ids. +pub type StateOrdersUpdate = HashMap>; diff --git a/backend/crates/core/src/model/websocket/protection.rs b/backend/crates/core/src/model/websocket/protection.rs new file mode 100644 index 000000000..6dbd1cafa --- /dev/null +++ b/backend/crates/core/src/model/websocket/protection.rs @@ -0,0 +1,95 @@ +use serde::Serialize; +use serde_json::Value as JsonValue; + +use crate::{ + model::{AdjId, ProtectionPacket, ShortTimestamp, Value}, + utils::serialize::{serialize_adj_id, serialize_value}, +}; + +/// Payload of `protection/update`: the triggered id, measured value and time. +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct ProtectionUpdate { + /// Compound protection id; its definition is available in the ADJ catalog. + #[serde(serialize_with = "serialize_adj_id")] + pub id: AdjId, + /// Value that triggered the protection, serialized as a JSON primitive. + #[serde(serialize_with = "serialize_value")] + pub value: Value, + /// Time received from the board, preserving the raw subsecond byte. + #[serde(with = "ShortTimestampJson")] + pub timestamp: ShortTimestamp, +} + +impl From for ProtectionUpdate { + fn from(packet: ProtectionPacket) -> Self { + Self { + id: packet.id, + value: packet.value, + timestamp: packet.timestamp, + } + } +} + +#[derive(Serialize)] +#[serde(remote = "ShortTimestamp")] +struct ShortTimestampJson { + hour: u8, + minute: u8, + second: u8, + subsecond: u8, +} + +/// Legacy protection details used only by `message/update`. +/// +/// Values retain their JSON number or boolean representation. ADJ validation +/// and conversion from domain packets belong to the publisher. +#[derive(Debug, Clone, PartialEq, Serialize)] +#[serde(tag = "kind", content = "data", rename_all = "SCREAMING_SNAKE_CASE")] +pub enum ProtectionPayload { + /// A value dropped below its lower bound. + LowerBound { + /// Lower bound. + bound: JsonValue, + /// Value that triggered the protection. + value: JsonValue, + }, + /// A value exceeded its upper bound. + UpperBound { + /// Upper bound. + bound: JsonValue, + /// Value that triggered the protection. + value: JsonValue, + }, + /// A value left the allowed interval. + OutOfBounds { + /// Lower and upper bounds, in that order. + bounds: [JsonValue; 2], + /// Value that triggered the protection. + value: JsonValue, + }, + /// A value matched the protected value. + Equals { + /// Value that triggered the protection. + value: JsonValue, + }, + /// A value differed from the expected value. + NotEquals { + /// Expected value. + want: JsonValue, + /// Value that triggered the protection. + value: JsonValue, + }, + /// The legacy time-accumulation protection. + TimeAccumulation { + /// Value that triggered the protection. + value: JsonValue, + /// Threshold. + bound: JsonValue, + /// Time limit in seconds. + timelimit: f32, + }, + /// Legacy firmware error text. + ErrorHandler(String), + /// Legacy warning text. + Warning(String), +} diff --git a/backend/crates/core/src/utils/serialize.rs b/backend/crates/core/src/utils/serialize.rs index cb61543b9..9c57bb7b3 100644 --- a/backend/crates/core/src/utils/serialize.rs +++ b/backend/crates/core/src/utils/serialize.rs @@ -1,4 +1,6 @@ +use crate::model::Value; use crate::model::{AdjId, BoardId, NumericKind, ProtectionKind, Severity}; +use serde::{Deserialize, Deserializer}; use serde::{Serialize, Serializer}; #[cfg(feature = "http")] @@ -29,6 +31,25 @@ pub(crate) fn serialize_adj_id( serializer.serialize_u16(id.0) } +// Deserializer works the other way around as Serializer +pub(crate) fn deserialize_adj_id<'de, D: Deserializer<'de>>( + deserializer: D, +) -> Result { + u16::deserialize(deserializer).map(AdjId) +} + +// Serializes the value of a protection message +pub(crate) fn serialize_value( + value: &Value, + serializer: S, +) -> Result { + match value { + Value::Number(value) => serializer.serialize_f64(*value), + Value::Bool(value) => serializer.serialize_bool(*value), + Value::Enum(value) => serializer.serialize_str(value), + } +} + // Serialize numeric kind to match ADJv3 types. pub(crate) fn get_numeric_kind(kind: &NumericKind) -> &str { match kind { From 91d744deaa3423e404ef9175fd9bd2963962e934 Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Tue, 24 Nov 2026 23:59:18 +0100 Subject: [PATCH 147/225] docs(backend, model): update READMEs adding submodule and feature websocket --- backend/crates/core/Cargo.toml | 2 + backend/crates/core/src/model/README.md | 14 + .../crates/core/src/model/websocket/README.md | 279 ++++++++++++++++++ 3 files changed, 295 insertions(+) create mode 100644 backend/crates/core/src/model/websocket/README.md diff --git a/backend/crates/core/Cargo.toml b/backend/crates/core/Cargo.toml index ac855d65f..7042ba762 100644 --- a/backend/crates/core/Cargo.toml +++ b/backend/crates/core/Cargo.toml @@ -33,6 +33,8 @@ host = ["logger", "dep:whoami", "dep:rlimit"] trace = ["dep:tracing-subscriber", "dep:tracing-appender"] # Structure responses for HTTP petitions http = [] +# JSON payloads for frontend WebSocket topics; no socket or runtime dependency. +websocket = [] [dependencies] bytes.workspace = true diff --git a/backend/crates/core/src/model/README.md b/backend/crates/core/src/model/README.md index 40001c283..ff64eb94e 100644 --- a/backend/crates/core/src/model/README.md +++ b/backend/crates/core/src/model/README.md @@ -8,6 +8,9 @@ The domain types describe vehicle definitions and decoded packets. With the `http` feature enabled, `model::http` also exposes separate, serializable catalog response models; see [section 7](#7-http-http-feature). +With the `websocket` feature, `model::websocket` exposes the live-update and +request payloads used by the frontend; see [section 8](#8-websocket-websocket-feature). + ## 1. `board.rs` All structs and enums needed for the Pod can be found defined in this file. ### 1.1 `PacketType` @@ -301,3 +304,14 @@ This module defines no HTTP server, routes, CORS, or cache policy. See the [HTTP response models README](http/README.md) for usage, JSON type notation, field omission rules, and concrete examples. + +## 8. `websocket` (`websocket` feature) + +`model/websocket.rs` publicly re-exports the payload types for telemetry, +connections, orders, messages, protection events, and logger control. +Published structures implement `serde::Serialize`; order requests implement +`serde::Deserialize`. These models describe the payload inside a +`{topic, payload}` message; socket handling and the broker belong to `station`. + +See the [WebSocket message models README](websocket/README.md) for the topic +list, usage, JSON type notation, and complete message examples. diff --git a/backend/crates/core/src/model/websocket/README.md b/backend/crates/core/src/model/websocket/README.md new file mode 100644 index 000000000..6947c9117 --- /dev/null +++ b/backend/crates/core/src/model/websocket/README.md @@ -0,0 +1,279 @@ +# WebSocket Message Models (`model::websocket`) + +JSON models for telemetry, connections, orders, messages, protection events +and logger control. The `websocket` feature enables the types in +`model/websocket.rs` and `model/websocket/`. + +The Rust types describe the payload of each topic. Messages sent over the +WebSocket wrap that payload in `{topic, payload}`, as shown in the templates +and example files below. Connections, subscriptions, channels and the broker +belong to the application (`station`). + +## Topics + +| Topic | Payload type | Direction | JSON example | +| --- | --- | --- | --- | +| `podData/update` | `DataUpdate` | Backend → frontend | [data.json](example/data.json) | +| `connection/update` | `ConnectionUpdate` | Backend → frontend | [connection.json](example/connection.json) | +| `order/send` | `OrderSend` | Frontend → backend | [order.json](example/order.json) | +| `order/stateOrders` | `StateOrdersUpdate` | Backend → frontend | [state_orders.json](example/state_orders.json) | +| `message/update` | `MessageUpdate` | Backend → frontend | [message.json](example/message.json) | +| `protection/update` | `ProtectionUpdate` | Backend → frontend | [protection.json](example/protection.json) | +| `logger/enable` | `LoggerEnable` | Frontend → backend | [logger_enable.json](example/logger_enable.json) | +| `logger/response` | `LoggerResponse` | Backend → frontend | [logger_response.json](example/logger_response.json) | +| `logger/variables` | `LoggerVariables` | Frontend → backend | [logger_variables.json](example/logger_variables.json) | + +Directions describe the topic's data flow. A subscription request is handled +separately by the broker. Each example is an illustrative complete message, +independent of the bundled ADJ fixture and HTTP catalog examples. + +## Usage + +Enable the feature in the application's dependency: + +```bash +cargo add software-core -F websocket +``` + +With a decoded `packet: ProtectionPacket`: + +```rust +use software_core::model::websocket::{OrderSend, ProtectionUpdate}; + +let request: OrderSend = serde_json::from_str(r#"{"id":1002,"fields":{}}"#)?; +let protection = ProtectionUpdate::from(packet); +let payload_json = serde_json::to_string(&protection)?; +``` + +Published structures implement `serde::Serialize`; `OrderSend` and `OrderField` +implement `serde::Deserialize`. The logger aliases use the primitive types' +Serde implementations. All payload types are re-exported from +`model::websocket`. + +Deserializing an order checks its JSON structure. Parameter types, ranges and +their correspondence with the ADJ must be validated by the application before +converting it to an `OrderPacket`. + +## JSON Structure Templates + +These templates keep the JSON object and array structure, replacing values +with their types: `number`, `string`, or `boolean`. Quoted topic names and +discriminators are literals; keys in angle brackets represent map entries. +Comments describe alternative values and constraints. These are documentation +templates, not valid JSON messages; the linked `.json` files contain concrete +values. + +Maps and arrays show representative entries and may be empty. Numeric IDs +are unsigned 16-bit integers. When an ID is an object key, JSON represents +it as a string. + +### Telemetry (`DataUpdate`) + +```jsonc +{ + "topic": "podData/update", + "payload": { + "": { + "id": number, + "hexValue": string, + "count": number, + "cycleTime": number, + "measurementUpdates": { + "": { + "last": number, + "average": number + }, + "": boolean, + "": string + } + } + } +} +``` + +The outer key matches the packet's `id`. `count` is the received packet count; +`cycleTime` is the averaged interval between packet receptions. The publisher +supplies these statistics and the hexadecimal packet representation. + +`MeasurementUpdate` has three JSON forms: `{last, average}` for a number, +a boolean, or an enum variant string. There is no additional discriminator +around a measurement value. + +### Connections (`ConnectionUpdate`) + +```jsonc +{ + "topic": "connection/update", + "payload": { + "": { + "name": string, + "isConnected": boolean + } + } +} +``` + +The map key matches `name`. The state describes the connection between the +backend and the board. + +### Send Order (`OrderSend`) + +```jsonc +{ + "topic": "order/send", + "payload": { + "id": number, + "fields": { + "": { + "value": number, // A boolean or enum string is also possible. + "isEnabled": boolean, + "type": string + } + } + } +} +``` + +An order without parameters has `fields: {}`. Parameter names are aliases; +the application uses the ADJ to place their values in wire order. The `value` +field remains raw JSON until validation, preserving integer precision. + +Numeric `type` names are `"uint8"`, `"uint16"`, `"uint32"`, `"uint64"`, +`"int8"`, `"int16"`, `"int32"`, `"int64"`, `"float32"` and `"float64"`. +Boolean and enum parameters use `"bool"` and `"enum"`, respectively. + +### Enabled Orders (`StateOrdersUpdate`) + +```jsonc +{ + "topic": "order/stateOrders", + "payload": { + "": [number] + } +} +``` + +Each array contains the IDs of the board's currently enabled orders. A board +with no enabled orders is represented by an empty array. + +### Messages (`MessageUpdate`) + +```jsonc +{ + "topic": "message/update", + "payload": { + "kind": string, // "info", "warning", "fault", "ok" or "panic". + "payload": string, // Alternatively, the detailed object shown below. + "board": string, + "name": string, + "timestamp": { + "counter": number, + "second": number, + "minute": number, + "hour": number, + "day": number, + "month": number, + "year": number + } + } +} +``` + +`MessagePayload::Text` is a JSON string. `MessagePayload::Protection` is an +object with its own `kind` and `data`. The outer `kind` always describes +severity; the inner `kind` describes the condition: + +```jsonc +{ + "kind": "UPPER_BOUND", + "data": { + "bound": number, + "value": number + } +} +``` + +The detailed forms are: + +| Inner `kind` | `data` template | +| --- | --- | +| `LOWER_BOUND` | `{"bound": number, "value": number}` | +| `UPPER_BOUND` | `{"bound": number, "value": number}` | +| `OUT_OF_BOUNDS` | `{"bounds": [number, number], "value": number}` | +| `EQUALS` | `{"value": number}` | +| `NOT_EQUALS` | `{"want": number, "value": number}` | +| `TIME_ACCUMULATION` | `{"value": number, "bound": number, "timelimit": number}` | +| `ERROR_HANDLER` | `string` | +| `WARNING` | `string` | + +Measured values and thresholds can also be booleans when appropriate for +the condition. `bounds` contains exactly two elements, lower then upper; +`timelimit` is expressed in seconds. The application validates the detailed +values against the ADJ. + +### Protection Events (`ProtectionUpdate`) + +```jsonc +{ + "topic": "protection/update", + "payload": { + "id": number, + "value": number, // A boolean or enum string is also possible. + "timestamp": { + "hour": number, + "minute": number, + "second": number, + "subsecond": number + } + } +} +``` + +The payload contains only the compound protection ID, the value that triggered +it and the board's timestamp. The ADJ catalog supplies the protection's name, +condition and severity. `ProtectionUpdate::from(packet)` builds this payload +directly from a domain `ProtectionPacket`. + +### Logger Control (`LoggerEnable`, `LoggerResponse`, `LoggerVariables`) + +Request the desired recording state: + +```jsonc +{ + "topic": "logger/enable", + "payload": boolean +} +``` + +Report the actual recording state: + +```jsonc +{ + "topic": "logger/response", + "payload": boolean +} +``` + +Select the measurement names to record: + +```jsonc +{ + "topic": "logger/variables", + "payload": [string] +} +``` + +## IDs, Ordering, and Timestamps + +- Protection IDs are composed as `(position << 13) | measurement_id`. + The high 3 bits hold the one-based protection position (`1–7`); the low + 13 bits identify the watched measurement. +- Map keys have no guaranteed order. An empty map is `{}` and an empty + list is `[]`. Declared structure fields remain present. +- `message/update` uses `MessageTimestamp`, with RTC counter and calendar + fields. These values are represented without timezone conversion. +- `protection/update` uses `ShortTimestamp`, containing the time of day and + a raw `subsecond` byte. That byte's unit is unresolved and is not converted + to milliseconds. It carries no calendar date. +- Constructing a `MessageTimestamp` from a `ShortTimestamp` requires receive + context for the date and an explicit policy for the counter. From 19b00a4e9c737595cf963fa63409354a7c5263b9 Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Wed, 25 Nov 2026 01:09:32 +0100 Subject: [PATCH 148/225] fix(backend, model -> websocket): move payloads to websocket in station and broker in progress --- backend/Cargo.lock | 1 + backend/crates/core/Cargo.toml | 2 - backend/crates/core/src/model.rs | 3 - backend/crates/core/src/model/README.md | 14 -- backend/crates/core/src/utils/serialize.rs | 19 --- backend/crates/station/Cargo.toml | 4 + backend/crates/station/src/http/server.rs | 118 +++++++++++++- backend/crates/station/src/websocket.rs | 44 +++++- .../crates/station/src/websocket/broker.rs | 145 ++++++++++++++++++ backend/crates/station/src/websocket/error.rs | 16 ++ .../crates/station/src/websocket/handler.rs | 19 +++ .../src/websocket/payload.rs} | 1 + .../src/websocket/payload}/README.md | 24 ++- .../src/websocket/payload}/connection.rs | 3 +- .../src/websocket/payload}/data.rs | 7 +- .../payload}/example/connection.json | 0 .../src/websocket/payload}/example/data.json | 0 .../payload}/example/logger_enable.json | 0 .../payload}/example/logger_response.json | 0 .../payload}/example/logger_variables.json | 0 .../websocket/payload}/example/message.json | 0 .../src/websocket/payload}/example/order.json | 1 - .../payload}/example/protection.json | 0 .../payload}/example/state_orders.json | 0 .../src/websocket/payload}/message.rs | 6 +- .../src/websocket/payload}/order.rs | 10 +- .../src/websocket/payload}/protection.rs | 8 +- .../src/websocket/payload/serialize.rs | 28 ++++ .../crates/station/src/websocket/receiver.rs | 126 +++++++++++++++ .../crates/station/src/websocket/sender.rs | 41 +++++ 30 files changed, 563 insertions(+), 77 deletions(-) create mode 100644 backend/crates/station/src/websocket/error.rs rename backend/crates/{core/src/model/websocket.rs => station/src/websocket/payload.rs} (98%) rename backend/crates/{core/src/model/websocket => station/src/websocket/payload}/README.md (92%) rename backend/crates/{core/src/model/websocket => station/src/websocket/payload}/connection.rs (99%) rename backend/crates/{core/src/model/websocket => station/src/websocket/payload}/data.rs (94%) rename backend/crates/{core/src/model/websocket => station/src/websocket/payload}/example/connection.json (100%) rename backend/crates/{core/src/model/websocket => station/src/websocket/payload}/example/data.json (100%) rename backend/crates/{core/src/model/websocket => station/src/websocket/payload}/example/logger_enable.json (100%) rename backend/crates/{core/src/model/websocket => station/src/websocket/payload}/example/logger_response.json (100%) rename backend/crates/{core/src/model/websocket => station/src/websocket/payload}/example/logger_variables.json (100%) rename backend/crates/{core/src/model/websocket => station/src/websocket/payload}/example/message.json (100%) rename backend/crates/{core/src/model/websocket => station/src/websocket/payload}/example/order.json (86%) rename backend/crates/{core/src/model/websocket => station/src/websocket/payload}/example/protection.json (100%) rename backend/crates/{core/src/model/websocket => station/src/websocket/payload}/example/state_orders.json (100%) rename backend/crates/{core/src/model/websocket => station/src/websocket/payload}/message.rs (98%) rename backend/crates/{core/src/model/websocket => station/src/websocket/payload}/order.rs (84%) rename backend/crates/{core/src/model/websocket => station/src/websocket/payload}/protection.rs (94%) create mode 100644 backend/crates/station/src/websocket/payload/serialize.rs diff --git a/backend/Cargo.lock b/backend/Cargo.lock index 5ed9308bd..356fa5ac0 100644 --- a/backend/Cargo.lock +++ b/backend/Cargo.lock @@ -2958,6 +2958,7 @@ name = "station" version = "0.1.0" dependencies = [ "axum", + "futures-util", "serde", "serde_json", "software-core", diff --git a/backend/crates/core/Cargo.toml b/backend/crates/core/Cargo.toml index 7042ba762..ac855d65f 100644 --- a/backend/crates/core/Cargo.toml +++ b/backend/crates/core/Cargo.toml @@ -33,8 +33,6 @@ host = ["logger", "dep:whoami", "dep:rlimit"] trace = ["dep:tracing-subscriber", "dep:tracing-appender"] # Structure responses for HTTP petitions http = [] -# JSON payloads for frontend WebSocket topics; no socket or runtime dependency. -websocket = [] [dependencies] bytes.workspace = true diff --git a/backend/crates/core/src/model.rs b/backend/crates/core/src/model.rs index 80ec948a2..74b79b99a 100644 --- a/backend/crates/core/src/model.rs +++ b/backend/crates/core/src/model.rs @@ -20,9 +20,6 @@ mod value; #[cfg(feature = "http")] pub mod http; -#[cfg(feature = "websocket")] -pub mod websocket; - pub use board::{Board, PacketDef, PacketType, PodData}; pub use id::{AdjId, BoardId, MacAddress, Port}; pub use measurement::{Measurement, MeasurementKind, NumericKind, Range}; diff --git a/backend/crates/core/src/model/README.md b/backend/crates/core/src/model/README.md index ff64eb94e..40001c283 100644 --- a/backend/crates/core/src/model/README.md +++ b/backend/crates/core/src/model/README.md @@ -8,9 +8,6 @@ The domain types describe vehicle definitions and decoded packets. With the `http` feature enabled, `model::http` also exposes separate, serializable catalog response models; see [section 7](#7-http-http-feature). -With the `websocket` feature, `model::websocket` exposes the live-update and -request payloads used by the frontend; see [section 8](#8-websocket-websocket-feature). - ## 1. `board.rs` All structs and enums needed for the Pod can be found defined in this file. ### 1.1 `PacketType` @@ -304,14 +301,3 @@ This module defines no HTTP server, routes, CORS, or cache policy. See the [HTTP response models README](http/README.md) for usage, JSON type notation, field omission rules, and concrete examples. - -## 8. `websocket` (`websocket` feature) - -`model/websocket.rs` publicly re-exports the payload types for telemetry, -connections, orders, messages, protection events, and logger control. -Published structures implement `serde::Serialize`; order requests implement -`serde::Deserialize`. These models describe the payload inside a -`{topic, payload}` message; socket handling and the broker belong to `station`. - -See the [WebSocket message models README](websocket/README.md) for the topic -list, usage, JSON type notation, and complete message examples. diff --git a/backend/crates/core/src/utils/serialize.rs b/backend/crates/core/src/utils/serialize.rs index 9c57bb7b3..62c544ae8 100644 --- a/backend/crates/core/src/utils/serialize.rs +++ b/backend/crates/core/src/utils/serialize.rs @@ -31,25 +31,6 @@ pub(crate) fn serialize_adj_id( serializer.serialize_u16(id.0) } -// Deserializer works the other way around as Serializer -pub(crate) fn deserialize_adj_id<'de, D: Deserializer<'de>>( - deserializer: D, -) -> Result { - u16::deserialize(deserializer).map(AdjId) -} - -// Serializes the value of a protection message -pub(crate) fn serialize_value( - value: &Value, - serializer: S, -) -> Result { - match value { - Value::Number(value) => serializer.serialize_f64(*value), - Value::Bool(value) => serializer.serialize_bool(*value), - Value::Enum(value) => serializer.serialize_str(value), - } -} - // Serialize numeric kind to match ADJv3 types. pub(crate) fn get_numeric_kind(kind: &NumericKind) -> &str { match kind { diff --git a/backend/crates/station/Cargo.toml b/backend/crates/station/Cargo.toml index 9eed62cbe..d481d8fb2 100644 --- a/backend/crates/station/Cargo.toml +++ b/backend/crates/station/Cargo.toml @@ -17,9 +17,13 @@ toml.workspace = true tracing.workspace = true tracing-subscriber.workspace = true serde_json.workspace = true +futures-util = { version = "0.3", default-features = false, features = ["std", "sink"] } tower = "0.5.3" axum = { version = "0.8.9", features = ["ws", "http1", "http2"] } tower-http = { version = "0.6.11", features = ["cors", "set-header"] } +[dev-dependencies] +tokio = { workspace = true, features = ["test-util"] } + [lints] workspace = true diff --git a/backend/crates/station/src/http/server.rs b/backend/crates/station/src/http/server.rs index 0bb27dedf..3526a44b0 100644 --- a/backend/crates/station/src/http/server.rs +++ b/backend/crates/station/src/http/server.rs @@ -57,7 +57,7 @@ pub(super) mod tests { }; use software_core::adj::{Adj, load_from_dir}; use tokio::{ - io::{AsyncBufReadExt, AsyncWriteExt, BufReader}, + io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader}, net::{TcpListener, TcpStream}, sync::{mpsc, oneshot}, time::timeout, @@ -279,6 +279,122 @@ pub(super) mod tests { Ok(()) } + #[tokio::test] + async fn websocket_subscription_receives_connection_snapshots() + -> Result<(), Box> { + use super::super::super::websocket::payload::Connection; + + let (broker, client) = crate::websocket::broker::Broker::new(); + let broker_worker = tokio::spawn(broker.run()); + let (connections, receiver) = mpsc::channel(1); + let worker = tokio::spawn(crate::websocket::run(receiver, client.clone())); + let app = setup_router(&Adj::default(), Some(connections))?; + let (headers, mut first) = handshake(app.clone()).await?; + assert!(headers.starts_with("HTTP/1.1 101 Switching Protocols\r\n")); + let (_headers, mut second) = handshake(app).await?; + + timeout(Duration::from_secs(5), async { + send_text( + &mut first, + r#"{"topic":"connection/heartbeat","payload":{}}"#, + ) + .await?; + // Other frontend topics can be added incrementally without closing the socket. + send_text( + &mut first, + r#"{"topic":"podData/update","payload":{"subscribe":true}}"#, + ) + .await?; + send_text( + &mut first, + r#"{"topic":"connection/update","payload":{"subscribe":true}}"#, + ) + .await?; + assert_eq!( + read_json(&mut first).await?, + serde_json::json!({ + "topic": "connection/update", "payload": {} + }) + ); + + client + .publish_connection(Connection { + name: "LCU".into(), + is_connected: true, + }) + .await?; + let expected = serde_json::json!({ + "topic": "connection/update", + "payload": {"LCU": {"name": "LCU", "isConnected": true}} + }); + assert_eq!(read_json(&mut first).await?, expected); + + // A client receives nothing before subscribing, then receives the current map. + assert!( + timeout(Duration::from_millis(50), second.read_u8()) + .await + .is_err() + ); + send_text(&mut second, r#"{"topic":"connection/update","payload":{}}"#).await?; + assert_eq!(read_json(&mut second).await?, expected); + + client + .publish_connection(Connection { + name: "HVBMS".into(), + is_connected: false, + }) + .await?; + let expected = serde_json::json!({ + "topic": "connection/update", + "payload": { + "LCU": {"name": "LCU", "isConnected": true}, + "HVBMS": {"name": "HVBMS", "isConnected": false} + } + }); + assert_eq!(read_json(&mut first).await?, expected); + assert_eq!(read_json(&mut second).await?, expected); + + for socket in [&mut first, &mut second] { + socket.write_all(&[0x88, 0x80, 0, 0, 0, 0]).await?; + assert_eq!(socket.read_u8().await?, 0x88); + } + Ok::<_, Box>(()) + }) + .await??; + drop(client); + worker.await?; + timeout(Duration::from_secs(5), broker_worker).await??; + Ok(()) + } + + async fn send_text( + client: &mut TcpStream, + text: &str, + ) -> Result<(), Box> { + // Test requests fit a short masked frame; a zero mask leaves the JSON unchanged. + let length = u8::try_from(text.len())?; + assert!(length < 126); + client.write_all(&[0x81, 0x80 | length, 0, 0, 0, 0]).await?; + client.write_all(text.as_bytes()).await?; + Ok(()) + } + + async fn read_json( + client: &mut TcpStream, + ) -> Result> { + assert_eq!(client.read_u8().await?, 0x81); + let header = client.read_u8().await?; + assert_eq!(header & 0x80, 0, "server frames must not be masked"); + let length = match header { + 126 => usize::from(client.read_u16().await?), + 127 => usize::try_from(client.read_u64().await?)?, + length => usize::from(length), + }; + let mut body = vec![0; length]; + client.read_exact(&mut body).await?; + Ok(serde_json::from_slice(&body)?) + } + #[tokio::test] async fn websocket_without_a_consumer_returns_unavailable() -> Result<(), Box> { diff --git a/backend/crates/station/src/websocket.rs b/backend/crates/station/src/websocket.rs index d789e536d..7071721bd 100644 --- a/backend/crates/station/src/websocket.rs +++ b/backend/crates/station/src/websocket.rs @@ -1,6 +1,48 @@ +//! Connects upgraded HTTP sockets to broker subscriptions. + +use axum::extract::ws::WebSocket; +use serde::{Deserialize, Serialize}; +use tokio::sync::mpsc; + +use self::broker::BrokerClient; + +pub mod broker; +mod error; mod handler; mod receiver; mod sender; -mod broker; +pub(super) mod payload; + +const CONNECTION_UPDATE: &str = "connection/update"; +const HEARTBEAT: &str = "connection/heartbeat"; +/// JSON envelope shared with the frontend. +#[derive(Debug, Serialize, Deserialize)] +pub struct WsMessage { + /// Topic of the message, can be: + /// - order/send + /// - podData/update + /// - connection/update + /// - order/stateOrders + /// - message/update + /// - protection/update + /// - logger/enable + /// - logger/response + /// - logger/variables + pub topic: String, + /// Topic-specific JSON payload + pub payload: serde_json::Value, +} +/// Handles each connection independently while HTTP keeps accepting sockets. +pub async fn run(mut connections: mpsc::Receiver, broker: BrokerClient) { + // Spawn one tokio task per Websocket connection + while let Some(socket) = connections.recv().await { + let broker = broker.clone(); + tokio::spawn(async move { + if let Err(error) = handler::handle(socket, broker).await { + tracing::warn!(%error, "WebSocket connection ended with an error"); + } + }); + } +} diff --git a/backend/crates/station/src/websocket/broker.rs b/backend/crates/station/src/websocket/broker.rs index e69de29bb..a9d9275ac 100644 --- a/backend/crates/station/src/websocket/broker.rs +++ b/backend/crates/station/src/websocket/broker.rs @@ -0,0 +1,145 @@ +//! Publishes the current board connection state to subscribers. + +use super::payload::{Connection, ConnectionUpdate}; +use tokio::sync::{mpsc, watch}; + +pub use super::error::Error; + +/// Owns the connection state and processes incoming updates. +#[derive(Debug)] +pub struct Broker { + updates: mpsc::Receiver, + connections: watch::Sender, +} + +/// Clonable access to connection publication and subscriptions. +#[derive(Debug, Clone)] +pub struct BrokerClient { + updates: mpsc::Sender, + connections: watch::Receiver, +} + +impl Broker { + /// Creates a broker and its client, initially with no known connections. + pub fn new() -> (Self, BrokerClient) { + let (updates, receiver) = mpsc::channel(32); + let (connections, state) = watch::channel(ConnectionUpdate::new()); + ( + Self { + updates: receiver, + connections, + }, + BrokerClient { + updates, + connections: state, + }, + ) + } + + /// Processes updates until all publishing clients have been dropped. + pub async fn run(mut self) { + while let Some(connection) = self.updates.recv().await { + self.connections.send_modify(|state| { + state.insert(connection.name.clone(), connection); + }); + } + } +} + +impl BrokerClient { + /// Queues a board connection update, waiting if the input channel is full. + pub async fn publish_connection(&self, connection: Connection) -> Result<(), Error> { + self.updates + .send(connection) + .await + .map_err(|_| Error::BrokerClosed) + } + + /// Subscribes to the complete connection map, starting at its current state. + /// Read that state with `borrow_and_update()`, then wait on `changed()`. + pub fn subscribe_connections(&self) -> watch::Receiver { + let mut receiver = self.connections.clone(); + receiver.borrow_and_update(); + receiver + } +} + +#[cfg(test)] +mod tests { + use std::time::Duration; + + use tokio::time::timeout; + + use super::*; + + #[tokio::test] + async fn subscribers_receive_complete_state_and_late_subscribers_start_current() + -> Result<(), Box> { + let (broker, client) = Broker::new(); + let publisher = client.clone(); + let mut first = client.subscribe_connections(); + let mut second = client.subscribe_connections(); + assert!(first.borrow_and_update().is_empty()); + assert!(second.borrow_and_update().is_empty()); + let worker = tokio::spawn(broker.run()); + + for (name, is_connected) in [("LCU", true), ("HVBMS", true), ("LCU", false)] { + publisher + .publish_connection(Connection { + name: name.into(), + is_connected, + }) + .await?; + timeout(Duration::from_secs(1), first.changed()).await??; + timeout(Duration::from_secs(1), second.changed()).await??; + let state = first.borrow_and_update().clone(); + assert_eq!(state, *second.borrow_and_update()); + assert_eq!(state[name].is_connected, is_connected); + assert_eq!(state[name].name, name); + } + + let mut late = client.subscribe_connections(); + assert!(!late.has_changed()?); + let state = late.borrow_and_update().clone(); + assert_eq!(state.len(), 2); + assert!(!state["LCU"].is_connected); + assert!(state["HVBMS"].is_connected); + + drop(publisher); + drop(client); + timeout(Duration::from_secs(1), worker).await??; + assert!(late.changed().await.is_err()); + Ok(()) + } + + #[tokio::test] + async fn publication_fails_when_broker_is_closed() { + let (broker, client) = Broker::new(); + drop(broker); + let result = client + .publish_connection(Connection { + name: "LCU".into(), + is_connected: true, + }) + .await; + assert!(matches!(result, Err(Error::BrokerClosed))); + } + + #[tokio::test] + async fn broker_drains_queued_updates_before_stopping() -> Result<(), Box> + { + let (broker, client) = Broker::new(); + let state = client.subscribe_connections(); + client + .publish_connection(Connection { + name: "LCU".into(), + is_connected: true, + }) + .await?; + drop(client); + + timeout(Duration::from_secs(1), broker.run()).await?; + assert!(state.borrow()["LCU"].is_connected); + Ok(()) + } +} diff --git a/backend/crates/station/src/websocket/error.rs b/backend/crates/station/src/websocket/error.rs new file mode 100644 index 000000000..5fc0f3eb8 --- /dev/null +++ b/backend/crates/station/src/websocket/error.rs @@ -0,0 +1,16 @@ +/// Errors handling WebSocket connections and broker communication. +#[derive(Debug, thiserror::Error)] +pub enum Error { + /// The broker no longer accepts updates. + #[error("WebSocket broker is closed")] + BrokerClosed, + /// Reading or writing the socket failed. + #[error("WebSocket I/O failed: {0}")] + Socket(#[from] axum::Error), + /// The message or its payload could not be converted to JSON models. + #[error("invalid WebSocket JSON: {0}")] + Json(#[from] serde_json::Error), + /// No valid application message arrived before the deadline. + #[error("WebSocket heartbeat timed out")] + HeartbeatTimeout, +} diff --git a/backend/crates/station/src/websocket/handler.rs b/backend/crates/station/src/websocket/handler.rs index e69de29bb..e6422f457 100644 --- a/backend/crates/station/src/websocket/handler.rs +++ b/backend/crates/station/src/websocket/handler.rs @@ -0,0 +1,19 @@ +use std::time::Duration; + +use axum::extract::ws::WebSocket; +use futures_util::{SinkExt, StreamExt}; +use tokio::{sync::watch, time::timeout}; + +use super::{broker::BrokerClient, error::Error, receiver, sender}; + +/// Runs reading and writing together; either side finishing ends the session. +pub(super) async fn handle(socket: WebSocket, broker: BrokerClient) -> Result<(), Error> { + let (mut write, read) = socket.split(); + let (subscription, subscribed) = watch::channel(false); + let result = tokio::select! { + result = receiver::run(read, subscription) => result, + result = sender::run(&mut write, &broker, subscribed) => result, + }; + let _ = timeout(Duration::from_secs(1), write.close()).await; + result +} diff --git a/backend/crates/core/src/model/websocket.rs b/backend/crates/station/src/websocket/payload.rs similarity index 98% rename from backend/crates/core/src/model/websocket.rs rename to backend/crates/station/src/websocket/payload.rs index 4fe844983..4f840cb68 100644 --- a/backend/crates/core/src/model/websocket.rs +++ b/backend/crates/station/src/websocket/payload.rs @@ -9,6 +9,7 @@ mod data; mod message; mod order; mod protection; +mod serialize; pub use connection::{Connection, ConnectionUpdate}; pub use data::{DataPacketUpdate, DataUpdate, MeasurementUpdate}; diff --git a/backend/crates/core/src/model/websocket/README.md b/backend/crates/station/src/websocket/payload/README.md similarity index 92% rename from backend/crates/core/src/model/websocket/README.md rename to backend/crates/station/src/websocket/payload/README.md index 6947c9117..b57f3bba4 100644 --- a/backend/crates/core/src/model/websocket/README.md +++ b/backend/crates/station/src/websocket/payload/README.md @@ -1,13 +1,15 @@ -# WebSocket Message Models (`model::websocket`) +# WebSocket Message Models (`websocket::payload`) JSON models for telemetry, connections, orders, messages, protection events -and logger control. The `websocket` feature enables the types in -`model/websocket.rs` and `model/websocket/`. +and logger control. The types live in station's `websocket/payload.rs` and +`websocket/payload/`, alongside the WebSocket implementation. The Rust types describe the payload of each topic. Messages sent over the WebSocket wrap that payload in `{topic, payload}`, as shown in the templates and example files below. Connections, subscriptions, channels and the broker -belong to the application (`station`). +are handled by the surrounding [WebSocket module](../README.md). Shared +serialization helpers live in [serialize.rs](serialize.rs), and domain types +such as `AdjId`, `Value` and `ProtectionPacket` come from `software_core::model`. ## Topics @@ -29,16 +31,11 @@ independent of the bundled ADJ fixture and HTTP catalog examples. ## Usage -Enable the feature in the application's dependency: - -```bash -cargo add software-core -F websocket -``` - -With a decoded `packet: ProtectionPacket`: +The payload module is compiled as part of station, without a separate feature. +Within station, with a decoded `packet: software_core::model::ProtectionPacket`: ```rust -use software_core::model::websocket::{OrderSend, ProtectionUpdate}; +use crate::websocket::payload::{OrderSend, ProtectionUpdate}; let request: OrderSend = serde_json::from_str(r#"{"id":1002,"fields":{}}"#)?; let protection = ProtectionUpdate::from(packet); @@ -48,7 +45,7 @@ let payload_json = serde_json::to_string(&protection)?; Published structures implement `serde::Serialize`; `OrderSend` and `OrderField` implement `serde::Deserialize`. The logger aliases use the primitive types' Serde implementations. All payload types are re-exported from -`model::websocket`. +`crate::websocket::payload` within station. Deserializing an order checks its JSON structure. Parameter types, ranges and their correspondence with the ADJ must be validated by the application before @@ -126,7 +123,6 @@ backend and the board. "fields": { "": { "value": number, // A boolean or enum string is also possible. - "isEnabled": boolean, "type": string } } diff --git a/backend/crates/core/src/model/websocket/connection.rs b/backend/crates/station/src/websocket/payload/connection.rs similarity index 99% rename from backend/crates/core/src/model/websocket/connection.rs rename to backend/crates/station/src/websocket/payload/connection.rs index 2e4a2d8c7..4fbe97955 100644 --- a/backend/crates/core/src/model/websocket/connection.rs +++ b/backend/crates/station/src/websocket/payload/connection.rs @@ -1,6 +1,5 @@ -use std::collections::HashMap; - use serde::Serialize; +use std::collections::HashMap; /// Payload of `connection/update`, keyed by board name. pub type ConnectionUpdate = HashMap; diff --git a/backend/crates/core/src/model/websocket/data.rs b/backend/crates/station/src/websocket/payload/data.rs similarity index 94% rename from backend/crates/core/src/model/websocket/data.rs rename to backend/crates/station/src/websocket/payload/data.rs index 8901f7e26..702081784 100644 --- a/backend/crates/core/src/model/websocket/data.rs +++ b/backend/crates/station/src/websocket/payload/data.rs @@ -1,8 +1,7 @@ -use std::collections::HashMap; - +use super::serialize::serialize_adj_id; use serde::Serialize; - -use crate::{model::AdjId, utils::serialize::serialize_adj_id}; +use software_core::model::AdjId; +use std::collections::HashMap; /// Payload of `podData/update`, keyed by packet id (JSON object keys are strings). pub type DataUpdate = HashMap; diff --git a/backend/crates/core/src/model/websocket/example/connection.json b/backend/crates/station/src/websocket/payload/example/connection.json similarity index 100% rename from backend/crates/core/src/model/websocket/example/connection.json rename to backend/crates/station/src/websocket/payload/example/connection.json diff --git a/backend/crates/core/src/model/websocket/example/data.json b/backend/crates/station/src/websocket/payload/example/data.json similarity index 100% rename from backend/crates/core/src/model/websocket/example/data.json rename to backend/crates/station/src/websocket/payload/example/data.json diff --git a/backend/crates/core/src/model/websocket/example/logger_enable.json b/backend/crates/station/src/websocket/payload/example/logger_enable.json similarity index 100% rename from backend/crates/core/src/model/websocket/example/logger_enable.json rename to backend/crates/station/src/websocket/payload/example/logger_enable.json diff --git a/backend/crates/core/src/model/websocket/example/logger_response.json b/backend/crates/station/src/websocket/payload/example/logger_response.json similarity index 100% rename from backend/crates/core/src/model/websocket/example/logger_response.json rename to backend/crates/station/src/websocket/payload/example/logger_response.json diff --git a/backend/crates/core/src/model/websocket/example/logger_variables.json b/backend/crates/station/src/websocket/payload/example/logger_variables.json similarity index 100% rename from backend/crates/core/src/model/websocket/example/logger_variables.json rename to backend/crates/station/src/websocket/payload/example/logger_variables.json diff --git a/backend/crates/core/src/model/websocket/example/message.json b/backend/crates/station/src/websocket/payload/example/message.json similarity index 100% rename from backend/crates/core/src/model/websocket/example/message.json rename to backend/crates/station/src/websocket/payload/example/message.json diff --git a/backend/crates/core/src/model/websocket/example/order.json b/backend/crates/station/src/websocket/payload/example/order.json similarity index 86% rename from backend/crates/core/src/model/websocket/example/order.json rename to backend/crates/station/src/websocket/payload/example/order.json index 853111e21..0aa349cb0 100644 --- a/backend/crates/core/src/model/websocket/example/order.json +++ b/backend/crates/station/src/websocket/payload/example/order.json @@ -5,7 +5,6 @@ "fields": { "target_speed": { "value": 12.5, - "isEnabled": true, "type": "float32" } } diff --git a/backend/crates/core/src/model/websocket/example/protection.json b/backend/crates/station/src/websocket/payload/example/protection.json similarity index 100% rename from backend/crates/core/src/model/websocket/example/protection.json rename to backend/crates/station/src/websocket/payload/example/protection.json diff --git a/backend/crates/core/src/model/websocket/example/state_orders.json b/backend/crates/station/src/websocket/payload/example/state_orders.json similarity index 100% rename from backend/crates/core/src/model/websocket/example/state_orders.json rename to backend/crates/station/src/websocket/payload/example/state_orders.json diff --git a/backend/crates/core/src/model/websocket/message.rs b/backend/crates/station/src/websocket/payload/message.rs similarity index 98% rename from backend/crates/core/src/model/websocket/message.rs rename to backend/crates/station/src/websocket/payload/message.rs index f6ce745bb..deee233e8 100644 --- a/backend/crates/core/src/model/websocket/message.rs +++ b/backend/crates/station/src/websocket/payload/message.rs @@ -1,8 +1,6 @@ -use serde::Serialize; - -use crate::model::{MessageLevel, Severity}; - use super::ProtectionPayload; +use serde::Serialize; +use software_core::model::{MessageLevel, Severity}; /// Payload of `message/update`, preserving the legacy event envelope. #[derive(Debug, Clone, PartialEq, Serialize)] diff --git a/backend/crates/core/src/model/websocket/order.rs b/backend/crates/station/src/websocket/payload/order.rs similarity index 84% rename from backend/crates/core/src/model/websocket/order.rs rename to backend/crates/station/src/websocket/payload/order.rs index 5b8cb221f..ed6453df1 100644 --- a/backend/crates/core/src/model/websocket/order.rs +++ b/backend/crates/station/src/websocket/payload/order.rs @@ -1,8 +1,7 @@ -use std::collections::HashMap; - +use super::serialize::deserialize_adj_id; use serde::Deserialize; - -use crate::{model::AdjId, utils::serialize::deserialize_adj_id}; +use software_core::model::AdjId; +use std::collections::HashMap; /// Payload of `order/send`; conversion to an `OrderPacket` requires the ADJ. #[derive(Debug, Clone, PartialEq, Deserialize)] @@ -20,9 +19,6 @@ pub struct OrderField { /// Raw JSON value; its type and range must be checked against the ADJ. /// Keeping it raw also preserves integer precision before validation. pub value: serde_json::Value, - /// Whether the frontend enables this parameter. - #[serde(rename = "isEnabled")] - pub is_enabled: bool, /// Legacy type name, such as `uint16`, `float32`, `bool` or `enum`. #[serde(rename = "type")] pub field_type: String, diff --git a/backend/crates/core/src/model/websocket/protection.rs b/backend/crates/station/src/websocket/payload/protection.rs similarity index 94% rename from backend/crates/core/src/model/websocket/protection.rs rename to backend/crates/station/src/websocket/payload/protection.rs index 6dbd1cafa..fddde0c71 100644 --- a/backend/crates/core/src/model/websocket/protection.rs +++ b/backend/crates/station/src/websocket/payload/protection.rs @@ -1,10 +1,8 @@ -use serde::Serialize; +use super::serialize::{serialize_adj_id, serialize_value}; +use serde::{Serialize}; use serde_json::Value as JsonValue; -use crate::{ - model::{AdjId, ProtectionPacket, ShortTimestamp, Value}, - utils::serialize::{serialize_adj_id, serialize_value}, -}; +use software_core::model::{AdjId, ProtectionPacket, ShortTimestamp, Value}; /// Payload of `protection/update`: the triggered id, measured value and time. #[derive(Debug, Clone, PartialEq, Serialize)] diff --git a/backend/crates/station/src/websocket/payload/serialize.rs b/backend/crates/station/src/websocket/payload/serialize.rs new file mode 100644 index 000000000..2d26e35ee --- /dev/null +++ b/backend/crates/station/src/websocket/payload/serialize.rs @@ -0,0 +1,28 @@ +use serde::{Deserialize, Deserializer, Serializer}; +use software_core::model::{AdjId, Value}; + +// Serializes the value of a protection message +pub(super) fn serialize_value( + value: &Value, + serializer: S, +) -> Result { + match value { + Value::Number(value) => serializer.serialize_f64(*value), + Value::Bool(value) => serializer.serialize_bool(*value), + Value::Enum(value) => serializer.serialize_str(value), + } +} + +// Deserializer works the other way around as Serializer +pub(super) fn deserialize_adj_id<'de, D: Deserializer<'de>>( + deserializer: D, +) -> Result { + u16::deserialize(deserializer).map(AdjId) +} + +pub(super) fn serialize_adj_id( + id: &AdjId, + serializer: S, +) -> Result { + serializer.serialize_u16(id.0) +} diff --git a/backend/crates/station/src/websocket/receiver.rs b/backend/crates/station/src/websocket/receiver.rs index e69de29bb..cc03c0541 100644 --- a/backend/crates/station/src/websocket/receiver.rs +++ b/backend/crates/station/src/websocket/receiver.rs @@ -0,0 +1,126 @@ +use std::time::Duration; + +use axum::extract::ws::Message as Frame; +use futures_util::{Stream, StreamExt}; +use serde::Deserialize; +use tokio::{ + sync::watch, + time::{Instant, timeout_at}, +}; + +use super::{CONNECTION_UPDATE, HEARTBEAT, WsMessage, error::Error}; + +const HEARTBEAT_TIMEOUT: Duration = Duration::from_secs(3); + +#[derive(Deserialize)] +struct Subscription { + subscribe: Option, +} + +/// Handles subscriptions and renews the deadline on each valid JSON message. +pub(super) async fn run( + mut read: impl Stream> + Unpin, + subscription: watch::Sender, +) -> Result<(), Error> { + let mut deadline = Instant::now() + HEARTBEAT_TIMEOUT; + loop { + let frame = timeout_at(deadline, read.next()) + .await + .map_err(|_| Error::HeartbeatTimeout)?; + let Some(frame) = frame else { + return Ok(()); + }; + match frame? { + Frame::Text(text) => { + let message: WsMessage = serde_json::from_str(&text)?; + match message.topic.as_str() { + CONNECTION_UPDATE => { + let request: Subscription = serde_json::from_value(message.payload)?; + let subscribed = request.subscribe.unwrap_or(true); + subscription.send_if_modified(|current| { + let changed = *current != subscribed; + *current = subscribed; + changed + }); + } + HEARTBEAT => {} + topic => tracing::warn!(topic, "unsupported WebSocket topic"), + } + deadline = Instant::now() + HEARTBEAT_TIMEOUT; + } + Frame::Close(_) => return Ok(()), + _ => {} + } + } +} + +#[cfg(test)] +mod tests { + use futures_util::stream; + use tokio::time::advance; + + use super::*; + + #[tokio::test(start_paused = true)] + async fn inactivity_expires() { + let (subscription, _state) = watch::channel(false); + assert!(matches!( + run(stream::pending(), subscription).await, + Err(Error::HeartbeatTimeout) + )); + } + + #[tokio::test(start_paused = true)] + async fn subscription_messages_also_renew_the_deadline() + -> Result<(), Box> { + let (input, mut frames) = tokio::sync::mpsc::channel(1); + let read = stream::poll_fn(move |cx| frames.poll_recv(cx)); + let (subscription, mut state) = watch::channel(false); + let worker = tokio::spawn(run(read, subscription)); + tokio::task::yield_now().await; + + advance(Duration::from_secs(2)).await; + input + .send(Ok(Frame::Text( + r#"{"topic":"connection/update","payload":{"subscribe":true}}"#.into(), + ))) + .await?; + state.changed().await?; + advance(Duration::from_secs(2)).await; + assert!(!worker.is_finished()); + advance(Duration::from_secs(1)).await; + assert!(matches!(worker.await?, Err(Error::HeartbeatTimeout))); + Ok(()) + } + + #[tokio::test] + async fn heartbeats_do_not_subscribe_or_publish() -> Result<(), Error> { + let (subscription, state) = watch::channel(false); + let frames = stream::iter([ + Ok(Frame::Text( + r#"{"topic":"connection/heartbeat","payload":{}}"#.into(), + )), + Ok(Frame::Close(None)), + ]); + run(frames, subscription).await?; + assert!(!*state.borrow()); + Ok(()) + } + + #[tokio::test] + async fn subscription_requests_can_unsubscribe() -> Result<(), Error> { + let (subscription, state) = watch::channel(false); + let frames = stream::iter([ + Ok(Frame::Text( + r#"{"topic":"connection/update","payload":{}}"#.into(), + )), + Ok(Frame::Text( + r#"{"topic":"connection/update","payload":{"subscribe":false}}"#.into(), + )), + Ok(Frame::Close(None)), + ]); + run(frames, subscription).await?; + assert!(!*state.borrow()); + Ok(()) + } +} diff --git a/backend/crates/station/src/websocket/sender.rs b/backend/crates/station/src/websocket/sender.rs index e69de29bb..432de565e 100644 --- a/backend/crates/station/src/websocket/sender.rs +++ b/backend/crates/station/src/websocket/sender.rs @@ -0,0 +1,41 @@ +use axum::extract::ws::{Message as Frame, WebSocket}; +use futures_util::{SinkExt, stream::SplitSink}; +use tokio::sync::watch; + +use super::{CONNECTION_UPDATE, WsMessage, broker::BrokerClient, error::Error}; + +/// Sends the current state on subscription, followed by complete state updates. +pub(super) async fn run( + write: &mut SplitSink, + broker: &BrokerClient, + mut subscribed: watch::Receiver, +) -> Result<(), Error> { + let mut connections = broker.subscribe_connections(); + loop { + if !*subscribed.borrow_and_update() { + if subscribed.changed().await.is_err() { + return Ok(()); + } + continue; + } + + let payload = serde_json::to_value(&*connections.borrow_and_update())?; + let message = WsMessage { + topic: CONNECTION_UPDATE.into(), + payload, + }; + write + .send(Frame::Text(serde_json::to_string(&message)?.into())) + .await?; + + tokio::select! { + biased; + result = subscribed.changed() => { + if result.is_err() { return Ok(()); } + } + result = connections.changed() => { + result.map_err(|_| Error::BrokerClosed)?; + } + } + } +} From 4e6d5b82267f749b313d9f75a06b2ecfd2a17471 Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Wed, 25 Nov 2026 01:38:17 +0100 Subject: [PATCH 149/225] fmt(backend, websocket): format --- backend/crates/station/src/websocket/payload/protection.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/backend/crates/station/src/websocket/payload/protection.rs b/backend/crates/station/src/websocket/payload/protection.rs index fddde0c71..42e9e9496 100644 --- a/backend/crates/station/src/websocket/payload/protection.rs +++ b/backend/crates/station/src/websocket/payload/protection.rs @@ -1,5 +1,5 @@ use super::serialize::{serialize_adj_id, serialize_value}; -use serde::{Serialize}; +use serde::Serialize; use serde_json::Value as JsonValue; use software_core::model::{AdjId, ProtectionPacket, ShortTimestamp, Value}; From 3cf93d67f102794642d9772b17c35b32f53a0f3c Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Wed, 25 Nov 2026 01:38:53 +0100 Subject: [PATCH 150/225] feat(backend, websocket): add topic subscriptions and validated order forwarding and some tests in http --- backend/crates/station/src/http/server.rs | 353 +++++++++++++++++- backend/crates/station/src/websocket.rs | 54 ++- .../crates/station/src/websocket/broker.rs | 284 +++++++++++++- backend/crates/station/src/websocket/error.rs | 31 ++ .../crates/station/src/websocket/handler.rs | 16 +- backend/crates/station/src/websocket/order.rs | 180 +++++++++ .../crates/station/src/websocket/receiver.rs | 175 +++++++-- .../crates/station/src/websocket/sender.rs | 141 +++++-- 8 files changed, 1146 insertions(+), 88 deletions(-) create mode 100644 backend/crates/station/src/websocket/order.rs diff --git a/backend/crates/station/src/http/server.rs b/backend/crates/station/src/http/server.rs index 3526a44b0..1f5584852 100644 --- a/backend/crates/station/src/http/server.rs +++ b/backend/crates/station/src/http/server.rs @@ -282,12 +282,12 @@ pub(super) mod tests { #[tokio::test] async fn websocket_subscription_receives_connection_snapshots() -> Result<(), Box> { - use super::super::super::websocket::payload::Connection; + use crate::websocket::payload::{Connection, StateOrdersUpdate}; let (broker, client) = crate::websocket::broker::Broker::new(); let broker_worker = tokio::spawn(broker.run()); let (connections, receiver) = mpsc::channel(1); - let worker = tokio::spawn(crate::websocket::run(receiver, client.clone())); + let worker = tokio::spawn(crate::websocket::run(receiver, client.clone(), None)); let app = setup_router(&Adj::default(), Some(connections))?; let (headers, mut first) = handshake(app.clone()).await?; assert!(headers.starts_with("HTTP/1.1 101 Switching Protocols\r\n")); @@ -302,7 +302,7 @@ pub(super) mod tests { // Other frontend topics can be added incrementally without closing the socket. send_text( &mut first, - r#"{"topic":"podData/update","payload":{"subscribe":true}}"#, + r#"{"topic":"not-a-topic","payload":{"subscribe":true}}"#, ) .await?; send_text( @@ -354,6 +354,175 @@ pub(super) mod tests { assert_eq!(read_json(&mut first).await?, expected); assert_eq!(read_json(&mut second).await?, expected); + send_text( + &mut first, + r#"{"topic":"order/stateOrders","payload":{"subscribe":true}}"#, + ) + .await?; + assert_eq!( + read_json(&mut first).await?, + serde_json::json!({ + "topic": "order/stateOrders", "payload": {} + }) + ); + send_text( + &mut second, + r#"{"topic":"logger/response","payload":{"subscribe":true}}"#, + ) + .await?; + assert_eq!( + read_json(&mut second).await?, + serde_json::json!({ + "topic": "logger/response", "payload": false + }) + ); + + client + .publish_state_orders(StateOrdersUpdate::from([("LCU".into(), vec![1001])])) + .await?; + assert_eq!( + read_json(&mut first).await?, + serde_json::json!({ + "topic": "order/stateOrders", "payload": {"LCU": [1001]} + }) + ); + assert!( + timeout(Duration::from_millis(50), second.read_u8()) + .await + .is_err() + ); + + client.publish_logger(true).await?; + assert_eq!( + read_json(&mut second).await?, + serde_json::json!({ + "topic": "logger/response", "payload": true + }) + ); + assert!( + timeout(Duration::from_millis(50), first.read_u8()) + .await + .is_err() + ); + + // The logger snapshot confirms the preceding unsubscribe was handled. + send_text( + &mut first, + r#"{"topic":"order/stateOrders","payload":{"subscribe":false}}"#, + ) + .await?; + send_text( + &mut first, + r#"{"topic":"logger/response","payload":{"subscribe":true}}"#, + ) + .await?; + assert_eq!( + read_json(&mut first).await?, + serde_json::json!({ + "topic": "logger/response", "payload": true + }) + ); + client + .publish_state_orders(StateOrdersUpdate::from([("LCU".into(), vec![])])) + .await?; + assert!( + timeout(Duration::from_millis(50), first.read_u8()) + .await + .is_err() + ); + + // Resubscribing recovers the latest full state, including empty lists. + send_text(&mut first, r#"{"topic":"order/stateOrders","payload":{}}"#).await?; + assert_eq!( + read_json(&mut first).await?, + serde_json::json!({ + "topic": "order/stateOrders", "payload": {"LCU": []} + }) + ); + client.publish_logger(false).await?; + let expected = serde_json::json!({"topic": "logger/response", "payload": false}); + assert_eq!(read_json(&mut first).await?, expected); + assert_eq!(read_json(&mut second).await?, expected); + + for socket in [&mut first, &mut second] { + socket.write_all(&[0x88, 0x80, 0, 0, 0, 0]).await?; + assert_eq!(socket.read_u8().await?, 0x88); + } + Ok::<_, Box>(()) + }) + .await??; + drop(client); + worker.await?; + timeout(Duration::from_secs(5), broker_worker).await??; + Ok(()) + } + + #[tokio::test] + async fn websocket_telemetry_sends_complete_snapshots() -> Result<(), Box> + { + use crate::websocket::payload::{DataPacketUpdate, MeasurementUpdate}; + use software_core::model::AdjId; + + let (broker, client) = crate::websocket::broker::Broker::new(); + let broker_worker = tokio::spawn(broker.run()); + let (connections, receiver) = mpsc::channel(1); + let worker = tokio::spawn(crate::websocket::run(receiver, client.clone(), None)); + let app = setup_router(&Adj::default(), Some(connections))?; + let (_, mut first) = handshake(app.clone()).await?; + let (_, mut second) = handshake(app).await?; + + timeout(Duration::from_secs(5), async { + send_text( + &mut first, + r#"{"topic":"podData/update","payload":{"subscribe":true}}"#, + ) + .await?; + assert_eq!( + read_json(&mut first).await?, + serde_json::json!({ + "topic": "podData/update", "payload": {} + }) + ); + + let packet = DataPacketUpdate { + id: AdjId(1000), + hex_value: "e8030000bc41".into(), + count: 1, + cycle_time: 100_000_000, + measurement_updates: std::collections::HashMap::from([( + "temperature".into(), + MeasurementUpdate::Numeric { + last: 23.5, + average: 23.0, + }, + )]), + }; + client.publish_data(packet.clone()).await?; + let expected = serde_json::json!({ + "topic": "podData/update", + "payload": {"1000": { + "id": 1000, "hexValue": "e8030000bc41", "count": 1, "cycleTime": 100_000_000, + "measurementUpdates": {"temperature": {"last": 23.5, "average": 23.0}} + }} + }); + assert_eq!(read_json(&mut first).await?, expected); + + send_text(&mut second, r#"{"topic":"podData/update","payload":{}}"#).await?; + assert_eq!(read_json(&mut second).await?, expected); + client + .publish_data(DataPacketUpdate { + id: AdjId(1001), + hex_value: "e9030000bc41".into(), + ..packet + }) + .await?; + let updated = read_json(&mut first).await?; + assert_eq!(updated["topic"], "podData/update"); + assert_eq!(updated["payload"].as_object().map(|map| map.len()), Some(2)); + assert_eq!(updated["payload"]["1000"], expected["payload"]["1000"]); + assert_eq!(updated["payload"]["1001"]["id"], 1001); + assert_eq!(read_json(&mut second).await?, updated); + for socket in [&mut first, &mut second] { socket.write_all(&[0x88, 0x80, 0, 0, 0, 0]).await?; assert_eq!(socket.read_u8().await?, 0x88); @@ -367,14 +536,184 @@ pub(super) mod tests { Ok(()) } + #[tokio::test] + async fn websocket_event_subscriptions_deliver_live_payloads() + -> Result<(), Box> { + use crate::websocket::{ + broker::Broker, + payload::{ + MessageKind, MessagePayload, MessageTimestamp, MessageUpdate, ProtectionUpdate, + }, + }; + use serde_json::json; + use software_core::model::{AdjId, ShortTimestamp, Value}; + + let (broker, client) = Broker::new(); + let broker_worker = tokio::spawn(broker.run()); + let (sockets, receiver) = mpsc::channel(1); + let worker = tokio::spawn(crate::websocket::run(receiver, client.clone(), None)); + let message = MessageUpdate { + kind: MessageKind::Info, + payload: MessagePayload::Text("Order Sent".into()), + board: "LCU".into(), + name: "1001".into(), + timestamp: MessageTimestamp { + counter: 0, + second: 5, + minute: 30, + hour: 12, + day: 24, + month: 11, + year: 2026, + }, + }; + let protection = ProtectionUpdate { + id: AdjId(11192), + value: Value::Number(105.5), + timestamp: ShortTimestamp { + hour: 12, + minute: 30, + second: 6, + subsecond: 0, + }, + }; + let expected_message: serde_json::Value = + serde_json::from_str(include_str!("../websocket/payload/example/message.json"))?; + let expected_protection: serde_json::Value = + serde_json::from_str(include_str!("../websocket/payload/example/protection.json"))?; + let (_, mut socket) = handshake(setup_router(&Adj::default(), Some(sockets))?).await?; + + timeout(Duration::from_secs(5), async { + let mut logger = client.subscribe_logger(); + client + .publish_message(MessageUpdate { + payload: MessagePayload::Text("Before subscribing".into()), + ..message.clone() + }) + .await?; + client.publish_logger(true).await?; + logger.changed().await?; + send_text(&mut socket, r#"{"topic":"message/update","payload":{}}"#).await?; + send_text( + &mut socket, + r#"{"topic":"protection/update","payload":{"subscribe":true}}"#, + ) + .await?; + // The state snapshot confirms the preceding subscriptions were processed. + send_text(&mut socket, r#"{"topic":"logger/response","payload":{}}"#).await?; + assert_eq!( + read_json(&mut socket).await?, + json!({"topic": "logger/response", "payload": true}) + ); + + client.publish_message(message.clone()).await?; + assert_eq!(read_json(&mut socket).await?, expected_message); + client.publish_protection(protection.clone()).await?; + assert_eq!(read_json(&mut socket).await?, expected_protection); + + send_text( + &mut socket, + r#"{"topic":"message/update","payload":{"subscribe":false}}"#, + ) + .await?; + send_text(&mut socket, r#"{"topic":"connection/update","payload":{}}"#).await?; + assert_eq!( + read_json(&mut socket).await?, + json!({"topic": "connection/update", "payload": {}}) + ); + client + .publish_message(MessageUpdate { + payload: MessagePayload::Text("While unsubscribed".into()), + ..message + }) + .await?; + client.publish_protection(protection).await?; + assert_eq!(read_json(&mut socket).await?, expected_protection); + assert!( + timeout(Duration::from_millis(50), socket.read_u8()) + .await + .is_err() + ); + + socket.write_all(&[0x88, 0x80, 0, 0, 0, 0]).await?; + assert_eq!(socket.read_u8().await?, 0x88); + Ok::<_, Box>(()) + }) + .await??; + drop(client); + worker.await?; + timeout(Duration::from_secs(5), broker_worker).await??; + Ok(()) + } + + #[tokio::test] + async fn websocket_forwards_validated_orders_in_adj_order() + -> Result<(), Box> { + use crate::websocket::{OrderForwarder, broker::Broker}; + use software_core::{ + model::{AdjId, OrderPacket, Value}, + protocol::Index, + }; + use std::sync::Arc; + + let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("../core/src/adj/test/adj"); + let adj = load_from_dir(&path)?; + let index = Arc::new(Index::new(&adj.pod_data, None)); + let (order_tx, mut orders) = mpsc::channel(1); + let forwarder = OrderForwarder::new(index, order_tx); + let (broker, client) = Broker::new(); + let broker_worker = tokio::spawn(broker.run()); + let (connections, receiver) = mpsc::channel(1); + let worker = tokio::spawn(crate::websocket::run(receiver, client, Some(forwarder))); + let (_, mut socket) = handshake(setup_router(&adj, Some(connections))?).await?; + + timeout(Duration::from_secs(5), async { + for invalid in [ + r#"{"topic":"order/send","payload":{"id":65535,"fields":{}}}"#, + r#"{"topic":"order/send","payload":{"id":809,"fields":{}}}"#, + r#"{"topic":"order/send","payload":{"id":801,"fields":{"extra":{"value":0,"type":"uint8"}}}}"#, + r#"{"topic":"order/send","payload":{"id":809,"fields":{"desired_current":{"value":12.5,"type":"float64"},"lpu_id":{"value":2,"type":"uint32"}}}}"#, + r#"{"topic":"order/send","payload":{"id":809,"fields":{"desired_current":{"value":12.5,"type":"float32"},"lpu_id":{"value":2.5,"type":"uint32"}}}}"#, + ] { + send_text(&mut socket, invalid).await?; + } + send_text(&mut socket, r#"{"topic":"order/send","payload":{"id":809,"fields":{"desired_current":{"value":12.5,"type":"float32"},"lpu_id":{"value":2,"type":"uint32"}}}}"#).await?; + let stop = r#"{"topic":"order/send","payload":{"id":801,"fields":{}}}"#; + send_text(&mut socket, stop).await?; + + // The snapshot confirms both requests reached the receiver before we free the queue. + send_text(&mut socket, r#"{"topic":"connection/update","payload":{}}"#).await?; + assert_eq!(read_json(&mut socket).await?["topic"], "connection/update"); + assert_eq!(orders.recv().await, Some(OrderPacket::new( + AdjId(809), vec![Value::Number(2.0), Value::Number(12.5)], + ))); + assert!(matches!(orders.try_recv(), Err(mpsc::error::TryRecvError::Empty))); + + send_text(&mut socket, stop).await?; + assert_eq!(orders.recv().await, Some(OrderPacket::new(AdjId(801), vec![]))); + + socket.write_all(&[0x88, 0x80, 0, 0, 0, 0]).await?; + assert_eq!(socket.read_u8().await?, 0x88); + Ok::<_, Box>(()) + }).await??; + worker.await?; + timeout(Duration::from_secs(5), broker_worker).await??; + Ok(()) + } + async fn send_text( client: &mut TcpStream, text: &str, ) -> Result<(), Box> { - // Test requests fit a short masked frame; a zero mask leaves the JSON unchanged. - let length = u8::try_from(text.len())?; - assert!(length < 126); - client.write_all(&[0x81, 0x80 | length, 0, 0, 0, 0]).await?; + // A zero mask leaves the test JSON unchanged. + let length = u16::try_from(text.len())?; + if length < 126 { + client.write_all(&[0x81, 0x80 | length as u8]).await?; + } else { + client.write_all(&[0x81, 0xfe]).await?; + client.write_u16(length).await?; + } + client.write_all(&[0; 4]).await?; client.write_all(text.as_bytes()).await?; Ok(()) } diff --git a/backend/crates/station/src/websocket.rs b/backend/crates/station/src/websocket.rs index 7071721bd..0fce10c17 100644 --- a/backend/crates/station/src/websocket.rs +++ b/backend/crates/station/src/websocket.rs @@ -5,17 +5,60 @@ use serde::{Deserialize, Serialize}; use tokio::sync::mpsc; use self::broker::BrokerClient; +pub(crate) use self::order::OrderForwarder; pub mod broker; mod error; mod handler; +mod order; +pub(super) mod payload; mod receiver; mod sender; -pub(super) mod payload; const CONNECTION_UPDATE: &str = "connection/update"; +const STATE_ORDERS: &str = "order/stateOrders"; +const LOGGER_RESPONSE: &str = "logger/response"; +const DATA_UPDATE: &str = "podData/update"; +const MESSAGE_UPDATE: &str = "message/update"; +const PROTECTION_UPDATE: &str = "protection/update"; +const ORDER_SEND: &str = "order/send"; const HEARTBEAT: &str = "connection/heartbeat"; +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +enum Topic { + Connections, + StateOrders, + Logger, + Data, + Messages, + Protections, +} + +impl Topic { + fn from_name(name: &str) -> Option { + match name { + CONNECTION_UPDATE => Some(Self::Connections), + STATE_ORDERS => Some(Self::StateOrders), + LOGGER_RESPONSE => Some(Self::Logger), + DATA_UPDATE => Some(Self::Data), + MESSAGE_UPDATE => Some(Self::Messages), + PROTECTION_UPDATE => Some(Self::Protections), + _ => None, + } + } + + fn name(self) -> &'static str { + match self { + Self::Connections => CONNECTION_UPDATE, + Self::StateOrders => STATE_ORDERS, + Self::Logger => LOGGER_RESPONSE, + Self::Data => DATA_UPDATE, + Self::Messages => MESSAGE_UPDATE, + Self::Protections => PROTECTION_UPDATE, + } + } +} + /// JSON envelope shared with the frontend. #[derive(Debug, Serialize, Deserialize)] pub struct WsMessage { @@ -35,12 +78,17 @@ pub struct WsMessage { } /// Handles each connection independently while HTTP keeps accepting sockets. -pub async fn run(mut connections: mpsc::Receiver, broker: BrokerClient) { +pub async fn run( + mut connections: mpsc::Receiver, + broker: BrokerClient, + orders: Option, +) { // Spawn one tokio task per Websocket connection while let Some(socket) = connections.recv().await { let broker = broker.clone(); + let orders = orders.clone(); tokio::spawn(async move { - if let Err(error) = handler::handle(socket, broker).await { + if let Err(error) = handler::handle(socket, broker, orders.as_ref()).await { tracing::warn!(%error, "WebSocket connection ended with an error"); } }); diff --git a/backend/crates/station/src/websocket/broker.rs b/backend/crates/station/src/websocket/broker.rs index a9d9275ac..64079557e 100644 --- a/backend/crates/station/src/websocket/broker.rs +++ b/backend/crates/station/src/websocket/broker.rs @@ -1,47 +1,120 @@ -//! Publishes the current board connection state to subscribers. +//! Publishes current state and forwards messages and protection events. -use super::payload::{Connection, ConnectionUpdate}; -use tokio::sync::{mpsc, watch}; +use std::time::Duration; + +use super::payload::{ + Connection, ConnectionUpdate, DataPacketUpdate, DataUpdate, LoggerResponse, MessageUpdate, + ProtectionUpdate, StateOrdersUpdate, +}; +use tokio::{ + sync::{broadcast, mpsc, watch}, + time::{Instant, MissedTickBehavior, interval_at}, +}; pub use super::error::Error; -/// Owns the connection state and processes incoming updates. +const EVENT_CAPACITY: usize = 128; + +#[derive(Debug)] +enum Update { + Connection(Connection), + StateOrders(StateOrdersUpdate), + Logger(LoggerResponse), + Data(DataPacketUpdate), + Message(MessageUpdate), + Protection(ProtectionUpdate), +} + +/// Owns the topic states and processes incoming updates. #[derive(Debug)] pub struct Broker { - updates: mpsc::Receiver, + updates: mpsc::Receiver, connections: watch::Sender, + state_orders: watch::Sender, + logger: watch::Sender, + data: watch::Sender, + messages: broadcast::Sender, + protections: broadcast::Sender, } -/// Clonable access to connection publication and subscriptions. +/// Clonable access to publication and subscriptions. #[derive(Debug, Clone)] pub struct BrokerClient { - updates: mpsc::Sender, + updates: mpsc::Sender, connections: watch::Receiver, + state_orders: watch::Receiver, + logger: watch::Receiver, + data: watch::Receiver, + messages: broadcast::WeakSender, + protections: broadcast::WeakSender, } impl Broker { - /// Creates a broker and its client, initially with no known connections. + /// Starts with empty state maps and a stopped logger. pub fn new() -> (Self, BrokerClient) { let (updates, receiver) = mpsc::channel(32); let (connections, state) = watch::channel(ConnectionUpdate::new()); + let (state_orders, orders) = watch::channel(StateOrdersUpdate::new()); + let (logger, recording) = watch::channel(false); + let (data, telemetry) = watch::channel(DataUpdate::new()); + let (messages, _) = broadcast::channel(EVENT_CAPACITY); + let (protections, _) = broadcast::channel(EVENT_CAPACITY); + let message_topic = messages.downgrade(); + let protection_topic = protections.downgrade(); ( Self { updates: receiver, connections, + state_orders, + logger, + data, + messages, + protections, }, BrokerClient { updates, connections: state, + state_orders: orders, + logger: recording, + data: telemetry, + messages: message_topic, + protections: protection_topic, }, ) } /// Processes updates until all publishing clients have been dropped. pub async fn run(mut self) { - while let Some(connection) = self.updates.recv().await { - self.connections.send_modify(|state| { - state.insert(connection.name.clone(), connection); - }); + let period = Duration::from_millis(100); + let mut tick = interval_at(Instant::now() + period, period); + tick.set_missed_tick_behavior(MissedTickBehavior::Skip); + let mut pending = DataUpdate::new(); + loop { + tokio::select! { + update = self.updates.recv() => { + match update { + Some(Update::Connection(connection)) => self.connections.send_modify(|state| { + state.insert(connection.name.clone(), connection); + }), + Some(Update::StateOrders(orders)) => { self.state_orders.send_replace(orders); } + Some(Update::Logger(recording)) => { self.logger.send_replace(recording); } + Some(Update::Data(packet)) => { pending.insert(packet.id.0, packet); } + Some(Update::Message(message)) => { let _ = self.messages.send(message); } + Some(Update::Protection(protection)) => { let _ = self.protections.send(protection); } + None => { + self.flush_data(&mut pending); + return; + } + } + } + _ = tick.tick() => self.flush_data(&mut pending), + } + } + } + + fn flush_data(&self, pending: &mut DataUpdate) { + if !pending.is_empty() { + self.data.send_modify(|state| state.extend(pending.drain())); } } } @@ -49,8 +122,37 @@ impl Broker { impl BrokerClient { /// Queues a board connection update, waiting if the input channel is full. pub async fn publish_connection(&self, connection: Connection) -> Result<(), Error> { + self.publish(Update::Connection(connection)).await + } + + /// Queues the complete map of enabled orders, replacing the previous map. + pub async fn publish_state_orders(&self, orders: StateOrdersUpdate) -> Result<(), Error> { + self.publish(Update::StateOrders(orders)).await + } + + /// Queues the actual logger state reported by the backend. + pub async fn publish_logger(&self, recording: LoggerResponse) -> Result<(), Error> { + self.publish(Update::Logger(recording)).await + } + + /// Queues a complete, prepared packet update for the next 100 ms batch. + pub async fn publish_data(&self, packet: DataPacketUpdate) -> Result<(), Error> { + self.publish(Update::Data(packet)).await + } + + /// Queues a message for current subscribers. + pub async fn publish_message(&self, message: MessageUpdate) -> Result<(), Error> { + self.publish(Update::Message(message)).await + } + + /// Queues a protection event for current subscribers. + pub async fn publish_protection(&self, protection: ProtectionUpdate) -> Result<(), Error> { + self.publish(Update::Protection(protection)).await + } + + async fn publish(&self, update: Update) -> Result<(), Error> { self.updates - .send(connection) + .send(update) .await .map_err(|_| Error::BrokerClosed) } @@ -58,17 +160,48 @@ impl BrokerClient { /// Subscribes to the complete connection map, starting at its current state. /// Read that state with `borrow_and_update()`, then wait on `changed()`. pub fn subscribe_connections(&self) -> watch::Receiver { - let mut receiver = self.connections.clone(); - receiver.borrow_and_update(); - receiver + subscribe(&self.connections) + } + + /// Subscribes to the complete map of enabled order ids by board name. + pub fn subscribe_state_orders(&self) -> watch::Receiver { + subscribe(&self.state_orders) + } + + /// Subscribes to the actual recording state, initially `false`. + pub fn subscribe_logger(&self) -> watch::Receiver { + subscribe(&self.logger) } + + /// Subscribes to the complete telemetry map, initially empty. + pub fn subscribe_data(&self) -> watch::Receiver { + subscribe(&self.data) + } + + /// Subscribes to future messages. + pub fn subscribe_messages(&self) -> Result, Error> { + let sender = self.messages.upgrade().ok_or(Error::BrokerClosed)?; + Ok(sender.subscribe()) + } + + /// Subscribes to future protection events. + pub fn subscribe_protections(&self) -> Result, Error> { + let sender = self.protections.upgrade().ok_or(Error::BrokerClosed)?; + Ok(sender.subscribe()) + } +} + +fn subscribe(state: &watch::Receiver) -> watch::Receiver { + let mut receiver = state.clone(); + receiver.borrow_and_update(); + receiver } #[cfg(test)] mod tests { use std::time::Duration; - use tokio::time::timeout; + use tokio::time::{advance, timeout}; use super::*; @@ -123,6 +256,102 @@ mod tests { }) .await; assert!(matches!(result, Err(Error::BrokerClosed))); + assert!(matches!( + client.publish_state_orders(StateOrdersUpdate::new()).await, + Err(Error::BrokerClosed) + )); + assert!(matches!( + client.publish_logger(true).await, + Err(Error::BrokerClosed) + )); + assert!(matches!( + client.publish_data(packet(1000, 1)).await, + Err(Error::BrokerClosed) + )); + } + + #[tokio::test(start_paused = true)] + async fn telemetry_batches_latest_packets_and_keeps_the_complete_state() + -> Result<(), Box> { + let (broker, client) = Broker::new(); + let mut data = client.subscribe_data(); + let mut logger = client.subscribe_logger(); + assert!(data.borrow_and_update().is_empty()); + let worker = tokio::spawn(broker.run()); + tokio::task::yield_now().await; + + client.publish_data(packet(1000, 1)).await?; + client.publish_data(packet(2000, 1)).await?; + client.publish_data(packet(1000, 2)).await?; + // The logger update is a barrier: the preceding inputs have been processed. + client.publish_logger(true).await?; + logger.changed().await?; + assert!(!data.has_changed()?); + advance(Duration::from_millis(99)).await; + assert!(!data.has_changed()?); + advance(Duration::from_millis(1)).await; + timeout(Duration::from_millis(1), data.changed()).await??; + let snapshot = data.borrow_and_update().clone(); + assert_eq!(snapshot.len(), 2); + assert_eq!(snapshot[&1000].count, 2); + assert_eq!(snapshot[&2000].count, 1); + + let late = client.subscribe_data(); + assert_eq!(*late.borrow(), snapshot); + assert!(!late.has_changed()?); + advance(Duration::from_millis(100)).await; + tokio::task::yield_now().await; + assert!(!data.has_changed()?, "idle ticks must not publish"); + + client.publish_data(packet(2000, 2)).await?; + client.publish_logger(false).await?; + logger.changed().await?; + advance(Duration::from_millis(100)).await; + timeout(Duration::from_millis(1), data.changed()).await??; + assert_eq!(data.borrow()[&1000].count, 2); + assert_eq!(data.borrow()[&2000].count, 2); + + drop(client); + timeout(Duration::from_secs(1), worker).await??; + Ok(()) + } + + #[tokio::test] + async fn orders_and_logger_keep_independent_current_states() + -> Result<(), Box> { + let (broker, client) = Broker::new(); + let mut orders = client.subscribe_state_orders(); + let mut logger = client.subscribe_logger(); + assert!(orders.borrow_and_update().is_empty()); + assert!(!*logger.borrow_and_update()); + let worker = tokio::spawn(broker.run()); + + let initial = StateOrdersUpdate::from([("LCU".into(), vec![1001, 1002])]); + client.publish_state_orders(initial.clone()).await?; + timeout(Duration::from_secs(1), orders.changed()).await??; + assert_eq!(*orders.borrow_and_update(), initial); + assert!(!logger.has_changed()?); + + client.publish_logger(true).await?; + timeout(Duration::from_secs(1), logger.changed()).await??; + assert!(*logger.borrow_and_update()); + assert!(!orders.has_changed()?); + + // A full snapshot replaces previous boards and can clear enabled orders. + let current = StateOrdersUpdate::from([("HVBMS".into(), vec![])]); + client.publish_state_orders(current.clone()).await?; + timeout(Duration::from_secs(1), orders.changed()).await??; + assert_eq!(*orders.borrow_and_update(), current); + let late_orders = client.subscribe_state_orders(); + let late_logger = client.subscribe_logger(); + assert_eq!(*late_orders.borrow(), current); + assert!(*late_logger.borrow()); + assert!(!late_orders.has_changed()?); + assert!(!late_logger.has_changed()?); + + drop(client); + timeout(Duration::from_secs(1), worker).await??; + Ok(()) } #[tokio::test] @@ -136,10 +365,31 @@ mod tests { is_connected: true, }) .await?; + let orders = client.subscribe_state_orders(); + let logger = client.subscribe_logger(); + client + .publish_state_orders(StateOrdersUpdate::from([("LCU".into(), vec![1001])])) + .await?; + client.publish_logger(true).await?; + let data = client.subscribe_data(); + client.publish_data(packet(1000, 1)).await?; drop(client); timeout(Duration::from_secs(1), broker.run()).await?; assert!(state.borrow()["LCU"].is_connected); + assert_eq!(orders.borrow()["LCU"], [1001]); + assert!(*logger.borrow()); + assert_eq!(data.borrow()[&1000].count, 1); Ok(()) } + + fn packet(id: u16, count: u64) -> DataPacketUpdate { + DataPacketUpdate { + id: software_core::model::AdjId(id), + hex_value: String::new(), + count, + cycle_time: 100_000_000, + measurement_updates: Default::default(), + } + } } diff --git a/backend/crates/station/src/websocket/error.rs b/backend/crates/station/src/websocket/error.rs index 5fc0f3eb8..bfe127d9b 100644 --- a/backend/crates/station/src/websocket/error.rs +++ b/backend/crates/station/src/websocket/error.rs @@ -1,9 +1,17 @@ +use software_core::model::AdjId; + /// Errors handling WebSocket connections and broker communication. #[derive(Debug, thiserror::Error)] pub enum Error { /// The broker no longer accepts updates. #[error("WebSocket broker is closed")] BrokerClosed, + /// The socket writer fell behind the subscription requests. + #[error("WebSocket subscription queue is full")] + SubscriptionQueueFull, + /// The client fell behind on an event topic. + #[error("WebSocket subscriber missed {missed} events on {topic}")] + EventLagged { topic: &'static str, missed: u64 }, /// Reading or writing the socket failed. #[error("WebSocket I/O failed: {0}")] Socket(#[from] axum::Error), @@ -14,3 +22,26 @@ pub enum Error { #[error("WebSocket heartbeat timed out")] HeartbeatTimeout, } + +#[derive(Debug, thiserror::Error)] +pub(super) enum OrderError { + #[error("invalid order payload: {0}")] + Json(#[from] serde_json::Error), + #[error("unknown order id {0:?}")] + UnknownOrder(AdjId), + #[error("missing order field {0:?}")] + MissingField(String), + #[error("unexpected order field {0:?}")] + UnexpectedField(String), + #[error("order field {field:?} must have type {expected}")] + WrongFieldType { + field: String, + expected: &'static str, + }, + #[error("invalid value for order field {0:?}")] + InvalidValue(String), + #[error("vehicle order queue is full")] + QueueFull, + #[error("vehicle order receiver is unavailable")] + VehicleUnavailable, +} diff --git a/backend/crates/station/src/websocket/handler.rs b/backend/crates/station/src/websocket/handler.rs index e6422f457..aca901803 100644 --- a/backend/crates/station/src/websocket/handler.rs +++ b/backend/crates/station/src/websocket/handler.rs @@ -2,17 +2,21 @@ use std::time::Duration; use axum::extract::ws::WebSocket; use futures_util::{SinkExt, StreamExt}; -use tokio::{sync::watch, time::timeout}; +use tokio::{sync::mpsc, time::timeout}; -use super::{broker::BrokerClient, error::Error, receiver, sender}; +use super::{OrderForwarder, broker::BrokerClient, error::Error, receiver, sender}; /// Runs reading and writing together; either side finishing ends the session. -pub(super) async fn handle(socket: WebSocket, broker: BrokerClient) -> Result<(), Error> { +pub(super) async fn handle( + socket: WebSocket, + broker: BrokerClient, + orders: Option<&OrderForwarder>, +) -> Result<(), Error> { let (mut write, read) = socket.split(); - let (subscription, subscribed) = watch::channel(false); + let (changes, subscriptions) = mpsc::channel(16); let result = tokio::select! { - result = receiver::run(read, subscription) => result, - result = sender::run(&mut write, &broker, subscribed) => result, + result = receiver::run(read, &broker, orders, changes) => result, + result = sender::run(&mut write, subscriptions) => result, }; let _ = timeout(Duration::from_secs(1), write.close()).await; result diff --git a/backend/crates/station/src/websocket/order.rs b/backend/crates/station/src/websocket/order.rs new file mode 100644 index 000000000..7cc3655a4 --- /dev/null +++ b/backend/crates/station/src/websocket/order.rs @@ -0,0 +1,180 @@ +use super::error::OrderError; +use serde_json::Value as JsonValue; +use software_core::{ + model::{MeasurementKind, NumericKind, OrderPacket, PacketType, Value}, + protocol::{Index, wire}, +}; +use std::sync::Arc; +use tokio::sync::mpsc; + +use super::payload::{OrderField, OrderSend}; + +/// Validates frontend requests against the ADJ and forwards them to the vehicle. +#[derive(Debug, Clone)] +pub(crate) struct OrderForwarder { + index: Arc, + orders: mpsc::Sender, +} + +impl OrderForwarder { + pub(crate) fn new(index: Arc, orders: mpsc::Sender) -> Self { + Self { index, orders } + } + + pub(super) fn forward(&self, payload: JsonValue) -> Result<(), OrderError> { + let request = serde_json::from_value(payload)?; + let packet = to_packet(request, &self.index)?; + self.orders.try_send(packet).map_err(|error| match error { + mpsc::error::TrySendError::Full(_) => OrderError::QueueFull, + mpsc::error::TrySendError::Closed(_) => OrderError::VehicleUnavailable, + }) + } +} + +fn to_packet(mut request: OrderSend, index: &Index) -> Result { + let Some(PacketType::Order(measurements)) = + index.packet(request.id).map(|packet| &packet.packet_type) + else { + return Err(OrderError::UnknownOrder(request.id)); + }; + + let mut values = Vec::with_capacity(measurements.len()); + for measurement in measurements { + let alias = &measurement.alias; + let field = request + .fields + .remove(alias) + .ok_or_else(|| OrderError::MissingField(alias.clone()))?; + values.push(field_value(&field, alias, &measurement.kind)?); + } + if let Some(extra) = request.fields.into_keys().next() { + return Err(OrderError::UnexpectedField(extra)); + } + Ok(OrderPacket::new(request.id, values)) +} + +fn field_value( + field: &OrderField, + alias: &str, + kind: &MeasurementKind, +) -> Result { + let expected = match kind { + MeasurementKind::Numeric { wire_type } => numeric_type_name(*wire_type), + MeasurementKind::Boolean => "bool", + MeasurementKind::Enum { .. } => "enum", + }; + if field.field_type != expected { + return Err(OrderError::WrongFieldType { + field: alias.into(), + expected, + }); + } + + let value = match kind { + MeasurementKind::Numeric { wire_type } => { + number(&field.value, *wire_type).map(Value::Number) + } + MeasurementKind::Boolean => field.value.as_bool().map(Value::Bool), + MeasurementKind::Enum { options } => field.value.as_str().and_then(|name| { + let index = options.iter().position(|option| option == name)?; + // The order encoder takes the one-byte index into the ADJ's options. + u8::try_from(index) + .ok() + .map(|index| Value::Number(f64::from(index))) + }), + } + .ok_or_else(|| OrderError::InvalidValue(alias.into()))?; + + wire::encode_value(&value, kind).map_err(|_| OrderError::InvalidValue(alias.into()))?; + Ok(value) +} + +fn number(value: &JsonValue, kind: NumericKind) -> Option { + let JsonValue::Number(raw) = value else { + return None; + }; + let number = raw.as_f64()?; + if matches!(kind, NumericKind::F32 | NumericKind::F64) { + return Some(number); + } + + let integer = raw + .as_i64() + .map(i128::from) + .or_else(|| raw.as_u64().map(i128::from)); + if let Some(integer) = integer { + // OrderPacket stores numbers as f64. Avoid changing a large integer in transit. + if number as i128 != integer { + return None; + } + } else if number.fract() != 0.0 || number.abs() >= (1_u64 << 53) as f64 { + return None; + } + // The 64-bit upper bounds round up when represented as f64. + match kind { + NumericKind::U64 if number >= u64::MAX as f64 => None, + NumericKind::I64 if number >= i64::MAX as f64 => None, + _ => Some(number), + } +} + +fn numeric_type_name(kind: NumericKind) -> &'static str { + match kind { + NumericKind::U8 => "uint8", + NumericKind::U16 => "uint16", + NumericKind::U32 => "uint32", + NumericKind::U64 => "uint64", + NumericKind::I8 => "int8", + NumericKind::I16 => "int16", + NumericKind::I32 => "int32", + NumericKind::I64 => "int64", + NumericKind::F32 => "float32", + NumericKind::F64 => "float64", + } +} + +#[cfg(test)] +mod tests { + use serde_json::json; + + use super::*; + + #[test] + fn integer_fields_reject_values_the_packet_or_wire_would_change() { + let cases = [ + (NumericKind::U32, json!(2.5)), + (NumericKind::I64, json!(1_u64 << 63)), + (NumericKind::U64, json!((1_u64 << 53) + 1)), + (NumericKind::U64, json!(u64::MAX)), + ]; + for (kind, value) in cases { + assert!(number(&value, kind).is_none()); + } + assert_eq!(number(&json!(2.0), NumericKind::U32), Some(2.0)); + assert_eq!( + number(&json!(1_u64 << 63), NumericKind::U64), + Some((1_u64 << 63) as f64) + ); + } + + #[test] + fn enum_order_field_is_converted_to_the_encoder_index() -> Result<(), OrderError> { + let kind = MeasurementKind::Enum { + options: vec!["idle".into(), "ready".into()], + }; + let field = OrderField { + value: json!("ready"), + field_type: "enum".into(), + }; + assert_eq!(field_value(&field, "mode", &kind)?, Value::Number(1.0)); + let unknown = OrderField { + value: json!("unknown"), + ..field + }; + assert!(matches!( + field_value(&unknown, "mode", &kind), + Err(OrderError::InvalidValue(_)) + )); + Ok(()) + } +} diff --git a/backend/crates/station/src/websocket/receiver.rs b/backend/crates/station/src/websocket/receiver.rs index cc03c0541..e9d16adeb 100644 --- a/backend/crates/station/src/websocket/receiver.rs +++ b/backend/crates/station/src/websocket/receiver.rs @@ -1,14 +1,21 @@ -use std::time::Duration; - use axum::extract::ws::Message as Frame; use futures_util::{Stream, StreamExt}; use serde::Deserialize; +use std::{collections::HashSet, time::Duration}; use tokio::{ - sync::watch, + sync::{broadcast, mpsc, watch}, time::{Instant, timeout_at}, }; -use super::{CONNECTION_UPDATE, HEARTBEAT, WsMessage, error::Error}; +use super::{ + HEARTBEAT, ORDER_SEND, OrderForwarder, Topic, WsMessage, + broker::BrokerClient, + error::{Error, OrderError}, + payload::{ + ConnectionUpdate, DataUpdate, LoggerResponse, MessageUpdate, ProtectionUpdate, + StateOrdersUpdate, + }, +}; const HEARTBEAT_TIMEOUT: Duration = Duration::from_secs(3); @@ -17,11 +24,48 @@ struct Subscription { subscribe: Option, } -/// Handles subscriptions and renews the deadline on each valid JSON message. +/// Carries a new topic receiver, or `None` to unsubscribe. +#[derive(Debug)] +pub(super) enum SubscriptionChange { + Connections(Option>), + StateOrders(Option>), + Logger(Option>), + Data(Option>), + Messages(Option>), + Protections(Option>), +} + +impl SubscriptionChange { + fn new(broker: &BrokerClient, topic: Topic, enabled: bool) -> Result { + Ok(match topic { + Topic::Connections => { + Self::Connections(enabled.then(|| broker.subscribe_connections())) + } + Topic::StateOrders => { + Self::StateOrders(enabled.then(|| broker.subscribe_state_orders())) + } + Topic::Logger => Self::Logger(enabled.then(|| broker.subscribe_logger())), + Topic::Data => Self::Data(enabled.then(|| broker.subscribe_data())), + Topic::Messages => { + Self::Messages(enabled.then(|| broker.subscribe_messages()).transpose()?) + } + Topic::Protections => Self::Protections( + enabled + .then(|| broker.subscribe_protections()) + .transpose()?, + ), + }) + } +} + +/// Handles frontend requests and renews the deadline on each valid JSON message. pub(super) async fn run( mut read: impl Stream> + Unpin, - subscription: watch::Sender, + broker: &BrokerClient, + orders: Option<&OrderForwarder>, + changes: mpsc::Sender, ) -> Result<(), Error> { + let mut subscriptions = HashSet::new(); let mut deadline = Instant::now() + HEARTBEAT_TIMEOUT; loop { let frame = timeout_at(deadline, read.next()) @@ -33,18 +77,34 @@ pub(super) async fn run( match frame? { Frame::Text(text) => { let message: WsMessage = serde_json::from_str(&text)?; - match message.topic.as_str() { - CONNECTION_UPDATE => { - let request: Subscription = serde_json::from_value(message.payload)?; - let subscribed = request.subscribe.unwrap_or(true); - subscription.send_if_modified(|current| { - let changed = *current != subscribed; - *current = subscribed; - changed - }); + if message.topic == ORDER_SEND { + let result = orders + .ok_or(OrderError::VehicleUnavailable) + .and_then(|orders| orders.forward(message.payload)); + if let Err(error) = result { + tracing::warn!(topic = ORDER_SEND, %error, "order rejected"); + } + } else if let Some(topic) = Topic::from_name(&message.topic) { + let request: Subscription = serde_json::from_value(message.payload)?; + let enabled = request.subscribe.unwrap_or(true); + let changed = if enabled { + subscriptions.insert(topic) + } else { + subscriptions.remove(&topic) + }; + if changed { + // Start buffering events as soon as the request is accepted. + let change = SubscriptionChange::new(broker, topic, enabled)?; + match changes.try_send(change) { + Ok(()) => {} + Err(mpsc::error::TrySendError::Full(_)) => { + return Err(Error::SubscriptionQueueFull); + } + Err(mpsc::error::TrySendError::Closed(_)) => return Ok(()), + } } - HEARTBEAT => {} - topic => tracing::warn!(topic, "unsupported WebSocket topic"), + } else if message.topic != HEARTBEAT { + tracing::warn!(topic = %message.topic, "unsupported WebSocket topic"); } deadline = Instant::now() + HEARTBEAT_TIMEOUT; } @@ -60,12 +120,14 @@ mod tests { use tokio::time::advance; use super::*; + use crate::websocket::broker::Broker; #[tokio::test(start_paused = true)] async fn inactivity_expires() { - let (subscription, _state) = watch::channel(false); + let (_broker, client) = Broker::new(); + let (changes, _subscriptions) = mpsc::channel(1); assert!(matches!( - run(stream::pending(), subscription).await, + run(stream::pending(), &client, None, changes).await, Err(Error::HeartbeatTimeout) )); } @@ -75,8 +137,9 @@ mod tests { -> Result<(), Box> { let (input, mut frames) = tokio::sync::mpsc::channel(1); let read = stream::poll_fn(move |cx| frames.poll_recv(cx)); - let (subscription, mut state) = watch::channel(false); - let worker = tokio::spawn(run(read, subscription)); + let (_broker, client) = Broker::new(); + let (changes, mut subscriptions) = mpsc::channel(1); + let worker = tokio::spawn(async move { run(read, &client, None, changes).await }); tokio::task::yield_now().await; advance(Duration::from_secs(2)).await; @@ -85,7 +148,10 @@ mod tests { r#"{"topic":"connection/update","payload":{"subscribe":true}}"#.into(), ))) .await?; - state.changed().await?; + assert!(matches!( + subscriptions.recv().await, + Some(SubscriptionChange::Connections(Some(_))) + )); advance(Duration::from_secs(2)).await; assert!(!worker.is_finished()); advance(Duration::from_secs(1)).await; @@ -95,21 +161,23 @@ mod tests { #[tokio::test] async fn heartbeats_do_not_subscribe_or_publish() -> Result<(), Error> { - let (subscription, state) = watch::channel(false); + let (_broker, client) = Broker::new(); + let (changes, mut subscriptions) = mpsc::channel(1); let frames = stream::iter([ Ok(Frame::Text( r#"{"topic":"connection/heartbeat","payload":{}}"#.into(), )), Ok(Frame::Close(None)), ]); - run(frames, subscription).await?; - assert!(!*state.borrow()); + run(frames, &client, None, changes).await?; + assert!(subscriptions.recv().await.is_none()); Ok(()) } #[tokio::test] async fn subscription_requests_can_unsubscribe() -> Result<(), Error> { - let (subscription, state) = watch::channel(false); + let (_broker, client) = Broker::new(); + let (changes, mut subscriptions) = mpsc::channel(2); let frames = stream::iter([ Ok(Frame::Text( r#"{"topic":"connection/update","payload":{}}"#.into(), @@ -119,8 +187,59 @@ mod tests { )), Ok(Frame::Close(None)), ]); - run(frames, subscription).await?; - assert!(!*state.borrow()); + run(frames, &client, None, changes).await?; + assert!(matches!( + subscriptions.recv().await, + Some(SubscriptionChange::Connections(Some(_))) + )); + assert!(matches!( + subscriptions.recv().await, + Some(SubscriptionChange::Connections(None)) + )); + assert!(subscriptions.recv().await.is_none()); + Ok(()) + } + + #[tokio::test] + async fn repeated_event_subscriptions_keep_the_existing_receiver() -> Result<(), Error> { + let (_broker, client) = Broker::new(); + let (changes, mut subscriptions) = mpsc::channel(4); + let frames = stream::iter([ + Ok(Frame::Text( + r#"{"topic":"message/update","payload":{}}"#.into(), + )), + Ok(Frame::Text( + r#"{"topic":"protection/update","payload":{"subscribe":true}}"#.into(), + )), + Ok(Frame::Text( + r#"{"topic":"message/update","payload":{"subscribe":true}}"#.into(), + )), + Ok(Frame::Text( + r#"{"topic":"message/update","payload":{"subscribe":false}}"#.into(), + )), + Ok(Frame::Text( + r#"{"topic":"message/update","payload":{"subscribe":true}}"#.into(), + )), + Ok(Frame::Close(None)), + ]); + run(frames, &client, None, changes).await?; + assert!(matches!( + subscriptions.recv().await, + Some(SubscriptionChange::Messages(Some(_))) + )); + assert!(matches!( + subscriptions.recv().await, + Some(SubscriptionChange::Protections(Some(_))) + )); + assert!(matches!( + subscriptions.recv().await, + Some(SubscriptionChange::Messages(None)) + )); + assert!(matches!( + subscriptions.recv().await, + Some(SubscriptionChange::Messages(Some(_))) + )); + assert!(subscriptions.recv().await.is_none()); Ok(()) } } diff --git a/backend/crates/station/src/websocket/sender.rs b/backend/crates/station/src/websocket/sender.rs index 432de565e..a537641a3 100644 --- a/backend/crates/station/src/websocket/sender.rs +++ b/backend/crates/station/src/websocket/sender.rs @@ -1,41 +1,128 @@ +use std::future::pending; + use axum::extract::ws::{Message as Frame, WebSocket}; use futures_util::{SinkExt, stream::SplitSink}; -use tokio::sync::watch; +use serde::Serialize; +use tokio::sync::{broadcast, mpsc, watch}; -use super::{CONNECTION_UPDATE, WsMessage, broker::BrokerClient, error::Error}; +use super::{Topic, WsMessage, error::Error, receiver::SubscriptionChange}; -/// Sends the current state on subscription, followed by complete state updates. +/// Sends subscribed state snapshots and events over the socket. pub(super) async fn run( write: &mut SplitSink, - broker: &BrokerClient, - mut subscribed: watch::Receiver, + mut subscriptions: mpsc::Receiver, ) -> Result<(), Error> { - let mut connections = broker.subscribe_connections(); + let (mut connections, mut orders, mut logger, mut data) = (None, None, None, None); + let (mut messages, mut protections) = (None, None); loop { - if !*subscribed.borrow_and_update() { - if subscribed.changed().await.is_err() { - return Ok(()); + let frame = tokio::select! { + biased; + change = subscriptions.recv() => { + let Some(change) = change else { return Ok(()); }; + let snapshot = match change { + SubscriptionChange::Connections(next) => subscribe_state(Topic::Connections, &mut connections, next)?, + SubscriptionChange::StateOrders(next) => subscribe_state(Topic::StateOrders, &mut orders, next)?, + SubscriptionChange::Logger(next) => subscribe_state(Topic::Logger, &mut logger, next)?, + SubscriptionChange::Data(next) => subscribe_state(Topic::Data, &mut data, next)?, + SubscriptionChange::Messages(next) => { messages = next; None } + SubscriptionChange::Protections(next) => { protections = next; None } + }; + let Some(snapshot) = snapshot else { continue; }; + snapshot } - continue; - } - - let payload = serde_json::to_value(&*connections.borrow_and_update())?; - let message = WsMessage { - topic: CONNECTION_UPDATE.into(), - payload, + next = next_event(Topic::Protections, &mut protections) => next?, + next = next_event(Topic::Messages, &mut messages) => next?, + next = next_state(Topic::Connections, &mut connections) => next?, + next = next_state(Topic::StateOrders, &mut orders) => next?, + next = next_state(Topic::Logger, &mut logger) => next?, + next = next_state(Topic::Data, &mut data) => next?, }; - write - .send(Frame::Text(serde_json::to_string(&message)?.into())) - .await?; + write.send(frame).await?; + } +} - tokio::select! { - biased; - result = subscribed.changed() => { - if result.is_err() { return Ok(()); } - } - result = connections.changed() => { - result.map_err(|_| Error::BrokerClosed)?; - } +fn subscribe_state( + topic: Topic, + state: &mut Option>, + subscription: Option>, +) -> Result, Error> { + *state = subscription; + state + .as_mut() + .map(|state| state_frame(topic, state)) + .transpose() +} + +async fn next_state( + topic: Topic, + state: &mut Option>, +) -> Result { + let Some(state) = state else { + return pending().await; + }; + state.changed().await.map_err(|_| Error::BrokerClosed)?; + state_frame(topic, state) +} + +fn state_frame(topic: Topic, state: &mut watch::Receiver) -> Result { + encode(topic, &*state.borrow_and_update()) +} + +async fn next_event( + topic: Topic, + events: &mut Option>, +) -> Result { + let Some(events) = events else { + return pending().await; + }; + let event = events.recv().await.map_err(|error| match error { + broadcast::error::RecvError::Closed => Error::BrokerClosed, + broadcast::error::RecvError::Lagged(missed) => Error::EventLagged { + topic: topic.name(), + missed, + }, + })?; + encode(topic, &event) +} + +fn encode(topic: Topic, payload: &impl Serialize) -> Result { + let message = WsMessage { + topic: topic.name().into(), + payload: serde_json::to_value(payload)?, + }; + Ok(Frame::Text(serde_json::to_string(&message)?.into())) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[tokio::test] + async fn lagged_event_receiver_reports_its_loss_without_affecting_another_subscriber() + -> Result<(), Box> { + let (events, stalled) = broadcast::channel(2); + let mut stalled = Some(stalled); + let mut current = Some(events.subscribe()); + + for count in 1..=3 { + events.send(count)?; + let frame = next_event(Topic::Messages, &mut current).await?; + let message: WsMessage = serde_json::from_str(frame.to_text()?)?; + assert_eq!(message.payload, count); } + + assert!(matches!( + next_event(Topic::Messages, &mut stalled).await, + Err(Error::EventLagged { + topic: "message/update", + missed: 1 + }) + )); + drop(stalled); + events.send(4)?; + let frame = next_event(Topic::Messages, &mut current).await?; + let message: WsMessage = serde_json::from_str(frame.to_text()?)?; + assert_eq!(message.payload, 4); + Ok(()) } } From c11853cff8cbe98d7f18215ee378ea8b38008706 Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Wed, 25 Nov 2026 02:16:30 +0100 Subject: [PATCH 151/225] refactor(backend, udp) --- backend/crates/core/src/net.rs | 2 +- backend/crates/core/src/net/README.md | 32 +- backend/crates/core/src/net/error.rs | 2 +- backend/crates/core/src/net/report.rs | 12 +- backend/crates/core/src/net/udp.rs | 462 +++++++++++------- .../crates/core/src/net/udp/manual_tests.rs | 225 +++++++++ .../crates/core/src/net/udp/test_support.rs | 129 +++++ backend/crates/core/src/net/udp/tests.rs | 327 +++++++++++++ 8 files changed, 988 insertions(+), 203 deletions(-) create mode 100644 backend/crates/core/src/net/udp/manual_tests.rs create mode 100644 backend/crates/core/src/net/udp/test_support.rs create mode 100644 backend/crates/core/src/net/udp/tests.rs diff --git a/backend/crates/core/src/net.rs b/backend/crates/core/src/net.rs index ff2824e13..3ba454472 100644 --- a/backend/crates/core/src/net.rs +++ b/backend/crates/core/src/net.rs @@ -33,7 +33,7 @@ //! //! Addresses are for the operator, not for the domain types: they show //! up interpolated in each submodule's error messages (`tcp::Error`, -//! `udp::Error`), which is where somebody actually reads them. +//! `udp::UdpError`), which is where somebody actually reads them. mod error; mod report; diff --git a/backend/crates/core/src/net/README.md b/backend/crates/core/src/net/README.md index f5f9cd5f3..dde1b5bd3 100644 --- a/backend/crates/core/src/net/README.md +++ b/backend/crates/core/src/net/README.md @@ -10,9 +10,10 @@ Two submodules do the I/O, and **this directory's shared part opens nothing**: net/ ├── net.rs # module root: docs and re-exports ├── report.rs # Event, Notification, ErrorReport, Reporter — what is reported -├── error.rs # Error — aggregates tcp::Error / udp::Error, nothing else +├── error.rs # Error — aggregates tcp::Error / udp::UdpError, nothing else ├── tcp.rs # the TCP client (not written yet: error type + contract) -└── udp.rs # the shared UDP socket (not written yet: error type + contract) +├── udp.rs # the shared UDP socket +└── udp/ # its tests: tests.rs, test_support.rs, manual_tests.rs (load probe) ``` ## The shared part @@ -35,7 +36,7 @@ And the board is all the identity there is: one connection per board, one shared socket for UDP, so nothing needs telling apart beyond it. Addresses are for the operator, not for the domain types: they show up -interpolated in `tcp::Error`/`udp::Error` messages, which is where somebody +interpolated in `tcp::Error`/`udp::UdpError` messages, which is where somebody actually reads them. ### `Event` and `Notification` — what happened, and when @@ -86,7 +87,7 @@ that it can afford to queue behind telemetry. failed lives inside the `Error` variant, which is the only place that always has it. A datagram that fails to decode resolves to no board at all — its id is not in the ADJ, so there is no `PacketDef` to ask — and all that can be said about it is -the address it came from, which is what `udp::Error::Decode` holds. +the address it came from, which is what `udp::UdpError::Decode` holds. ### `Error` — aggregation only @@ -102,14 +103,14 @@ submodule's own error: nobody outside knows which of its variants are fatal. | | `tcp` | `udp` | |---|---|---| -| Entry point | `spawn(Config, Arc, Reporter) -> Handles` | `spawn(Config, Arc, Reporter) -> Result, Error>` (binds first) | +| Entry point | `spawn(Config, Arc, Reporter) -> Handles` | `spawn_udp(UdpConfig, Arc, Reporter) -> Result, UdpError>` (binds first) | | Inputs | its `Config` (boards, timeouts, backoff, keep-alive) | its `Config` (bind address, `SO_RCVBUF`) | | Role | client only; one connection per board, one task each | one shared socket, receive-only, one task | | Framing | buffer + `&mut Cursor` + advance by `cursor.position()`; bail out past 374 bytes | none — `recv_from` delivers a whole datagram into a reused 64 KiB buffer | | Writing | yes (orders, keep-alive); a single writer task per connection | no | | On a decode error | report it; **fatal**, and close/reopen the connection (the stream cannot be resynchronised) | report it; **fatal**, and keep receiving | | `Connected`/`Disconnected` | per board | never | -| Fault | writes it: `Handles::propagate_fault()`, id 0 to every board | cannot write; only reports | +| Fault | writes it: `Handles::propagate_fault()`, id 0 to every board | cannot write; a received id 0 is reported as `UdpError::Fault`, before decoding | Both take the same two things besides their own `Config`: an `Arc` — the only part of the ADJ `net` needs, owned by `station` and read-only here — and a @@ -121,7 +122,9 @@ which is also what lets a test point it at a fake peer. reads `is_fatal()` and calls `Handles::propagate_fault()`, which puts the order with id 0 into every board's writer channel (the Go backend's `SendFault`). A *received* packet with id 0 is the same action requested by a board, and -`station` answers it the same way. +`station` answers it the same way. In `udp` it arrives on the error channel as +`UdpError::Fault { from }`: recognised by its id alone, before decoding, without +looking at the ADJ. Three rules both follow: @@ -131,18 +134,23 @@ Three rules both follow: ### What "fatal" means -`tcp::Error::is_fatal`/`udp::Error::is_fatal` are about the **pod**, not about -this process: it means the pod has to be sent to fault, and the backend -**stays up** — still reading, still serving the frontend, still recording — so the -operator can see why. Nothing in `net` ever calls `std::process::exit`. +`tcp::Error::is_fatal`/`udp::UdpError::is_fatal` are about the **pod**: they say +the pod has to be sent to fault. They are a hint, not a decision — what happens +next (the fault, closing the connections, shutting the backend down safely) is +decided by whoever consumes the error channel (`station`). Nothing in `net` ever +calls `std::process::exit`. -Only a decode failure is fatal, on either transport, and this is a deliberate +On either transport, a decode failure is fatal, and this is a deliberate departure from Go. Nothing corrupts a frame or a datagram in flight (both transports checksum, TCP retransmits, and the pod's network does not fragment), so something that will not decode means the loaded ADJ does not describe what the firmware is sending — which reconnecting cannot fix. A failed connect or write is *not* fatal: that is what the backoff is for. +Two more are fatal in `udp`: losing the socket (`UdpError::Recv`), which is every +board's telemetry gone at once, and a fault sent by a board (`UdpError::Fault`, +packet id 0), which is a board asking for exactly that. + `net` never raises the fault itself — neither transport does. It logs, it reports, and `is_fatal()` is the classification whoever consumes the error channel acts on. That is deliberate: a mismatched ADJ fails on every frame that follows, thousands diff --git a/backend/crates/core/src/net/error.rs b/backend/crates/core/src/net/error.rs index 64109a954..1588e2043 100644 --- a/backend/crates/core/src/net/error.rs +++ b/backend/crates/core/src/net/error.rs @@ -24,5 +24,5 @@ pub enum Error { Tcp(#[from] tcp::Error), /// On the shared UDP socket. #[error(transparent)] - Udp(#[from] udp::Error), + Udp(#[from] udp::UdpError), } diff --git a/backend/crates/core/src/net/report.rs b/backend/crates/core/src/net/report.rs index 35f7dc16c..7ff356f1f 100644 --- a/backend/crates/core/src/net/report.rs +++ b/backend/crates/core/src/net/report.rs @@ -57,7 +57,7 @@ pub struct Notification { /// board at all — its id is not in the ADJ, so there is no /// [`crate::model::PacketDef`] to ask — and all that can be said about /// it is the address it came from, which is exactly what -/// [`super::udp::Error::Decode`] holds. +/// [`super::udp::UdpError::Decode`] holds. #[derive(Debug)] pub struct ErrorReport { /// The instant the failure was reported, on the same clock as @@ -207,8 +207,8 @@ mod tests { Event::Received(Packet::Data(DataPacket::new(AdjId(1000), vec![]))) } - fn an_error() -> udp::Error { - udp::Error::Recv { + fn an_error() -> udp::UdpError { + udp::UdpError::Recv { source: std::io::Error::from(std::io::ErrorKind::ConnectionReset), } } @@ -333,7 +333,7 @@ mod tests { let Some(report) = sinks.errors.recv().await else { unreachable!("exactly one error was reported"); }; - let Error::Udp(udp::Error::Recv { .. }) = report.error else { + let Error::Udp(udp::UdpError::Recv { .. }) = report.error else { unreachable!("a udp error should arrive as Error::Udp"); }; // Nothing reached the notification channel. @@ -343,14 +343,14 @@ mod tests { #[test] fn a_udp_decode_error_keeps_the_address_it_cannot_resolve_to_a_board() { let addr = SocketAddr::new(IpAddr::from([192, 168, 1, 3]), 50400); - let error = udp::Error::Decode { + let error = udp::UdpError::Decode { from: addr, source: crate::protocol::DecodeError::UnknownId(AdjId(9999)), }; // The whole reason an error report carries no board: this one has // an address, and no board to attribute it to. - let Error::Udp(udp::Error::Decode { from, .. }) = Error::from(error) else { + let Error::Udp(udp::UdpError::Decode { from, .. }) = Error::from(error) else { unreachable!("a decode error should convert into Error::Udp"); }; assert_eq!(from, addr); diff --git a/backend/crates/core/src/net/udp.rs b/backend/crates/core/src/net/udp.rs index c85972214..e1be8f6cb 100644 --- a/backend/crates/core/src/net/udp.rs +++ b/backend/crates/core/src/net/udp.rs @@ -4,11 +4,12 @@ //! # What this module is //! //! One socket bound to the backend's own address, carrying `Data` packets -//! from every board. Nothing is ever sent from it. +//! from every board, and the fault (packet id 0) any of them may send. +//! Nothing is ever sent from it. //! //! # Entry point //! -//! [`spawn`], taking [`Config`], an `Arc` and a +//! [`spawn_udp`], taking [`UdpConfig`], an `Arc` and a //! [`super::Reporter`] — written out with its reasoning on the items //! themselves. No handle comes back beyond the `JoinHandle`: there is no //! writing side. @@ -21,57 +22,117 @@ //! 64 KiB buffer and a datagram can never be silently truncated, //! whatever the ADJ grows to. //! - The loop does three things and nothing else: decode with -//! [`crate::protocol::udp::decode_datagram`], resolve the board, report. -//! No disk, no WebSocket, no aggregation. +//! [`crate::protocol::udp::decode_datagram`], resolve the board, report +//! (a fault skips the first two, see below). No disk, no WebSocket, no +//! aggregation. +//! - **Packet id 0 is a fault** ([`UdpError::Fault`]): what a board sends +//! when it has detected an error. It is recognised by its id alone, +//! **before** decoding: it is not in the ADJ, the [`crate::protocol::Index`] +//! is not consulted and nothing after the id is read. It goes down the +//! error channel with the address it came from, the only thing that +//! says which board sent it. //! - [`super::Notification::board`] comes from the decoded packet's id, //! through [`crate::protocol::Index`] — every //! [`crate::model::PacketDef`] carries its `board` — so that a //! notification looks the same whichever transport brought it. That is //! one `HashMap` lookup per datagram, done here once rather than //! repeated by every consumer downstream. -//! - **A decode failure is fatal**: see [`Error::is_fatal`]. Nothing -//! corrupts a datagram in flight — UDP checksums it and the pod's -//! network does not fragment it — so a datagram that will not decode -//! means the ADJ this backend loaded does not describe what the boards -//! are actually sending, and every datagram after it is suspect for the -//! same reason. So: log it and report it on the error channel, exactly -//! as [`super::tcp`] does — and that is all. This socket writes -//! nothing, and sending the pod to fault is not `net`'s call anyway: -//! whoever consumes the error channel reads [`Error::is_fatal`] and -//! decides, which also keeps the "fault once" guard in one place -//! rather than one per transport. Keep receiving meanwhile: a -//! mismatched ADJ fails on every datagram that follows, several -//! thousand a second, and each one is reported, not acted on. +//! - **A decode failure is reported as fatal** (see [`UdpError::is_fatal`]), +//! but acting on it is not this module's call. Nothing corrupts a +//! datagram in flight — UDP checksums it and the pod's network does not +//! fragment it — so a datagram that will not decode most likely means +//! the ADJ this backend loaded does not describe what the boards are +//! actually sending. This module traces it and reports it on the error +//! channel, exactly as [`super::tcp`] does — and that is all. Whoever +//! consumes the error channel decides what happens next (sending the +//! pod to fault, shutting down), which also keeps the "fault once" guard +//! in one place rather than one per transport. +//! - **Every failure is reported, but the trace is rate-limited.** A +//! mismatched ADJ fails on every datagram that follows, several thousand +//! a second. Each one still goes down the error channel, so the consumer +//! sees them all; the trace gets the first one and then at most one line +//! a second, carrying how many were left out since the previous line. +//! Decode failures and faults are limited separately, so a burst of one +//! never hides the other. //! - [`super::Event::Connected`]/[`super::Event::Disconnected`] are never //! emitted: there is no connection to come up or go down. //! - Binding happens **before** the task is spawned, so a bad address is //! a startup failure returned to whoever is composing the backend -//! (`station::vehicle::bootstrap`), not something reported once +//! (`station`), not something reported once //! everything is already running. Hence the entry point returns -//! `Result, Error>`. +//! `Result, UdpError>`. +//! +//! # Stopping +//! +//! The loop stops on its own when a report fails because the consumer is +//! gone — but it only finds out the next time it has something to report, +//! that is, on the next datagram. With no telemetry arriving (boards off, +//! cable out), closing the [`super::Sinks`] alone leaves the task waiting +//! on the socket. +//! +//! To stop it at a moment of the caller's choosing (a shutdown), call +//! [`JoinHandle::abort`] on the handle [`spawn_udp`] returns. That is safe: +//! the task holds nothing that needs flushing, and all that is lost is +//! whatever was still sitting in the kernel's receive buffer. +//! +//! # Tests +//! +//! Kept out of this file, next to it in `udp/`: +//! +//! - `tests.rs` — unit tests, and tests through a real socket on loopback. +//! - `test_support.rs` — the fixtures both share: a minimal ADJ index, +//! loopback sockets, and waits on the reporter's channels that fail +//! instead of hanging. +//! - `manual_tests.rs` — `manual_udp_load`, an ignored load probe that +//! checks the loop keeps up with 25 Mbit/s of 76-byte datagrams: +//! +//! ```sh +//! cargo test -p software-core --features net --release manual_udp_load -- --ignored --nocapture +//! ``` use super::Reporter; use crate::model::Packet; use crate::protocol::{DecodeError, Index}; use std::net::SocketAddr; use std::sync::Arc; +use std::time::{Duration, Instant}; use tokio::task::JoinHandle; -use tracing::{error, warn}; +use tracing::{error, info, warn}; /// How to set the shared socket up. /// /// Everything here is resolved by `station` before `net` is reached: this /// module reads no config file and no ADJ of its own. #[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct Config { - /// Where to bind: the backend's own address, `backend_ip` + - /// `ports["UDP"]` in the ADJ's general info. +pub struct UdpConfig { + /// Where to bind: the backend's own address, `addresses["backend"]` + /// and `ports["UDP"]` in the ADJ's `general_info.json`. pub addr: SocketAddr, - /// `SO_RCVBUF`, in bytes. + /// `SO_RCVBUF` to request, in bytes. /// /// The only thing absorbing a stall of the receive loop, since the - /// kernel drops the tail silently once it is full: 2 MiB is about - /// 0.8 s of margin at 20 Mbit/s. + /// kernel drops the tail silently once it is full. + /// + /// The margin it buys is counted in **datagrams**, not bytes: the + /// kernel charges each datagram its bookkeeping on top of its payload. + /// Measured on Linux over loopback, a 76-byte datagram (the average of + /// the H11 packets) takes about 960 bytes of buffer, so 2 MiB requested + /// (4 MiB granted, see below) holds about 4,400 datagrams — roughly + /// 0.1 s at 25 Mbit/s of 76-byte datagrams (~41,000 a second). A real + /// network card's driver may charge a different amount; measure on the + /// station's own machine. + /// + /// **This margin can be widened** by requesting more and raising the OS + /// limit so that the request is granted. On Linux, with + /// `sudo sysctl -w net.core.rmem_max=16777216` (16 MiB) and 16 MiB + /// requested here, 32 MiB are granted: by the figure above about 35,000 + /// datagrams, roughly 0.8 s at that rate. `sysctl -w` is lost on reboot; + /// to keep it, put `net.core.rmem_max = 16777216` in a file under + /// `/etc/sysctl.d/`. The limits on Windows and macOS have not been checked. + /// + /// The operating system may grant less than this — Linux silently caps + /// it at `net.core.rmem_max` — so [`spawn_udp`] reads the granted size back + /// and warns when it is smaller than requested. pub recv_buffer: usize, } @@ -87,69 +148,110 @@ pub struct Config { /// and hands out clones; it is read-only here, and a reload of the ADJ is /// a new [`Index`] with a new task, never a mutation of this one. /// +/// The returned handle is also how to stop the task: see the module's +/// "Stopping" section. +/// /// # Errors /// -/// [`Error::Bind`] only — every later failure goes out through +/// [`UdpError::Bind`] only — every later failure goes out through /// `reporter`, since by then there is nobody left to return it to. -pub fn spawn(config: Config, adj: Arc, reporter: Reporter) -> Result, Error> { - let socket = bind_socket(config)?; - let handle = tokio::spawn(run_loop(socket, adj, reporter)); +pub fn spawn_udp( + config: UdpConfig, + adj: Arc, + reporter: Reporter, +) -> Result, UdpError> { + let socket = bind_telemetry_socket(config)?; + let handle = tokio::spawn(receive_telemetry(socket, adj, reporter)); Ok(handle) } /// Binds a UDP socket and configures its OS-level receive buffer size (`SO_RCVBUF`). -fn bind_socket(config: Config) -> Result { +fn bind_telemetry_socket(config: UdpConfig) -> Result { // Bind using the standard library socket first so we can configure non-blocking mode. - let std_socket = std::net::UdpSocket::bind(config.addr).map_err(|source| Error::Bind { + let std_socket = std::net::UdpSocket::bind(config.addr).map_err(|source| UdpError::Bind { addr: config.addr, source, })?; // Tokio requires the underlying std socket to be in non-blocking mode. - std_socket.set_nonblocking(true).map_err(|source| Error::Bind { - addr: config.addr, - source, - })?; + std_socket + .set_nonblocking(true) + .map_err(|source| UdpError::Bind { + addr: config.addr, + source, + })?; // Convert the standard socket into an async Tokio UdpSocket. - let socket = tokio::net::UdpSocket::from_std(std_socket).map_err(|source| Error::Bind { + let socket = tokio::net::UdpSocket::from_std(std_socket).map_err(|source| UdpError::Bind { addr: config.addr, source, })?; + // Asking is not getting: Linux caps the request at `net.core.rmem_max` + // without returning an error, so the size actually granted has to be + // read back. Linux also reports back twice what it granted (it reserves + // the other half for bookkeeping, see socket(7)): with `rmem_max` at + // 4 MiB, asking for 2 MiB reads back 4 MiB and asking for 16 MiB reads + // back 8 MiB. So on Linux a full grant reads back as twice the request, + // and anything less means the request was capped. Elsewhere the value + // read back is compared with the request as is. + let full_grant = if cfg!(target_os = "linux") { + config.recv_buffer.saturating_mul(2) + } else { + config.recv_buffer + }; let sock_ref = socket2::SockRef::from(&socket); - if let Err(e) = sock_ref.set_recv_buffer_size(config.recv_buffer) { - warn!( - %config.addr, - buffer = config.recv_buffer, - %e, - "could not set SO_RCVBUF, using system default" - ); + let granted = sock_ref + .set_recv_buffer_size(config.recv_buffer) + .and_then(|()| sock_ref.recv_buffer_size()); + match granted { + Ok(granted) if granted >= full_grant => { + info!( + addr = %config.addr, + requested = config.recv_buffer, + granted, + "SO_RCVBUF set" + ); + } + Ok(granted) => { + warn!( + addr = %config.addr, + requested = config.recv_buffer, + granted, + "SO_RCVBUF is smaller than requested, so a stall loses datagrams sooner; \ + raise the OS limit (net.core.rmem_max on Linux) for more margin" + ); + } + Err(e) => { + warn!( + addr = %config.addr, + requested = config.recv_buffer, + %e, + "could not set SO_RCVBUF, using system default" + ); + } } Ok(socket) } /// Main UDP loop: reads datagrams into a reusable 64 KiB buffer, decodes in-place, and reports. -async fn run_loop( - socket: tokio::net::UdpSocket, - adj: Arc, - reporter: Reporter, -) { +async fn receive_telemetry(socket: tokio::net::UdpSocket, adj: Arc, reporter: Reporter) { // Reusable 64 KiB buffer — a datagram can never be silently truncated. let mut buf = vec![0u8; 64 * 1024]; + let mut traces = ReceiveTraces::default(); loop { match socket.recv_from(&mut buf).await { Ok((len, from)) => { - if !handle_datagram(&buf[..len], from, &adj, &reporter).await { + if !decode_and_report(&buf[..len], from, &adj, &reporter, &mut traces).await { // Downstream channels closed; exit cleanly. break; } } Err(source) => { // Socket-level receive failure: log, report as fatal to the backend, and stop. - let err = Error::Recv { source }; + let err = UdpError::Recv { source }; error!(%err, "UDP receive error"); let _ = reporter.report(err).await; break; @@ -158,24 +260,51 @@ async fn run_loop( } } +/// The first two bytes of a fault datagram: packet id 0, little-endian +/// like every id on the wire. +/// +/// A board that has detected an error sends it. It is not declared in the +/// ADJ, and the Go backend broadcasts the same id to every board when it +/// raises a fault itself (`SendFault`). +const FAULT_ID: [u8; 2] = 0u16.to_le_bytes(); + /// Decodes a single datagram slice against `adj` and forwards the result or error to `reporter`. /// +/// A fault (packet id 0, see [`FAULT_ID`]) is reported before any of that, +/// without looking at `adj`. +/// /// Returns `false` if the downstream `reporter` channels have closed and the loop should stop. -async fn handle_datagram( +async fn decode_and_report( bytes: &[u8], from: SocketAddr, adj: &Index, reporter: &Reporter, + traces: &mut ReceiveTraces, ) -> bool { + if bytes.starts_with(&FAULT_ID) { + if let Some(suppressed) = traces.fault.should_trace(Instant::now()) { + error!(%from, suppressed, "a board signalled a fault (packet id 0)"); + } + return reporter.report(UdpError::Fault { from }).await.is_ok(); + } + let packet = match crate::protocol::udp::decode_datagram(bytes, adj) { Ok(p) => p, Err(source) => { - let error = Error::Decode { from, source }; - error!(%error, "UDP decode error"); + if let Some(suppressed) = traces.decode.should_trace(Instant::now()) { + error!(%from, %source, suppressed, "UDP datagram could not be decoded"); + } + let error = UdpError::Decode { from, source }; return reporter.report(error).await.is_ok(); } }; + // A second lookup of the id `decode_datagram` has just resolved: it + // returns the packet, not its definition. Decoding already rejected + // any id the index does not know, so this branch is not expected to + // run; it is handled rather than unwrapped because the decode lives + // in another module. One extra `HashMap` lookup per datagram is not + // worth changing `protocol`'s API to avoid. let Some(packet_def) = adj.packet(packet.id) else { warn!(id = ?packet.id, "decoded packet id not in index"); return true; @@ -189,14 +318,65 @@ async fn handle_datagram( .is_ok() } -/// Something that went wrong on the shared UDP socket. +/// How often, at most, each kind of failure reaches the trace. +const TRACE_INTERVAL: Duration = Duration::from_secs(1); + +/// The receive loop's trace rate limits, one per kind of failure, so that +/// a burst of decode failures never hides a fault from the trace, nor the +/// other way round. +#[derive(Debug, Default)] +struct ReceiveTraces { + /// Datagrams that would not decode. + decode: TraceRateLimit, + /// Faults (packet id 0). + fault: TraceRateLimit, +} + +/// Rate limit for tracing one kind of failure. +/// +/// Only the trace is limited: every failure is still reported down the +/// error channel. A burst that stops is summed up by the next failure +/// that gets traced, so if no further failure ever comes, its count is +/// only in the error channel — which already had every one of them. +#[derive(Debug, Default)] +struct TraceRateLimit { + /// Failures not traced since the last one that was. + suppressed: u64, + /// When a failure was last traced. + last: Option, +} + +impl TraceRateLimit { + /// Decides whether the failure seen at `now` is traced. + /// + /// `Some(n)` means trace it, `n` being how many were left out since the + /// previous traced one (`0` for the first). `None` means count it + /// only. `now` is a parameter rather than read here so that the + /// decision can be tested without waiting for real time to pass. + fn should_trace(&mut self, now: Instant) -> Option { + match self.last { + Some(last) if now.saturating_duration_since(last) < TRACE_INTERVAL => { + self.suppressed += 1; + None + } + _ => { + self.last = Some(now); + Some(std::mem::take(&mut self.suppressed)) + } + } + } +} + +/// Something that went wrong on the shared UDP socket, or that a board +/// says went wrong ([`UdpError::Fault`]). /// /// No [`crate::model::BoardId`] in any variant, on purpose: the socket /// belongs to no board, and a datagram that fails to decode may not -/// resolve to one at all — [`Error::Decode`] carries the address it came -/// from, which is the only identity that always exists. +/// resolve to one at all — [`UdpError::Decode`] and [`UdpError::Fault`] +/// carry the address the datagram came from, which is the only identity +/// that always exists. #[derive(Debug, thiserror::Error)] -pub enum Error { +pub enum UdpError { /// The socket could not be bound, so no telemetry will arrive at all. #[error("could not bind the shared UDP socket to {addr}")] Bind { @@ -215,9 +395,9 @@ pub enum Error { source: std::io::Error, }, - /// A datagram could not be decoded, which means the loaded ADJ does - /// not describe what the boards are sending. Fatal: see - /// [`Error::is_fatal`]. + /// A datagram could not be decoded, which most likely means the loaded + /// ADJ does not describe what the boards are sending. See + /// [`UdpError::is_fatal`]. #[error("could not decode a datagram from {from}")] Decode { /// Where the datagram came from — there may be no board to @@ -227,141 +407,57 @@ pub enum Error { #[source] source: DecodeError, }, + + /// A board has detected an error and said so with a fault: a datagram + /// whose packet id is 0. Not a failure of this socket — the datagram + /// arrived fine — but the pod telling the backend it is in trouble. + #[error("the board at {from} signalled a fault (packet id 0)")] + Fault { + /// Where the fault came from: the board's address, since a fault + /// carries nothing else that says which board sent it. + from: SocketAddr, + }, } -impl Error { - /// Whether this error means the pod has to be sent to fault. +impl UdpError { + /// Whether this module considers the error serious enough to send the + /// pod to fault. /// - /// "Fatal" is about the **pod**, not about this process: the backend - /// stays up — still reading, still serving the frontend, still - /// recording — so that whoever is operating the pod can see what - /// happened. Nothing here ever calls `std::process::exit`. + /// A **hint** for whoever consumes the error channel, not a decision: + /// `net` never raises the fault and never stops the process. What to + /// do about a fatal error — sending the pod to fault, shutting the + /// backend down, or something else — is decided by the application + /// (`station`), which may also look at the error's details (such as + /// the [`DecodeError`] variant) rather than at this answer alone. /// /// Both runtime failures of this socket qualify, and for the same /// reason: neither can be true of a single datagram. - /// [`Error::Decode`] means the loaded ADJ does not describe what the - /// boards are sending, and [`Error::Recv`] means the socket itself is - /// no longer usable, which is every board's telemetry gone at once. - /// Neither is something a retry fixes. + /// [`UdpError::Decode`] most likely means the loaded ADJ does not describe + /// what the boards are sending, and [`UdpError::Recv`] means the socket + /// itself is no longer usable, which is every board's telemetry gone + /// at once. Neither is something a retry fixes. + /// + /// [`UdpError::Fault`] is fatal by definition: it is a board asking for + /// the pod to go to fault. /// - /// [`Error::Bind`] never reaches this: binding happens before the - /// task is spawned, so it is a startup failure handed back to - /// whoever composes the backend. + /// [`UdpError::Bind`] never reaches the error channel: binding happens + /// before the task is spawned, so it is a startup failure handed back + /// to whoever composes the backend. pub fn is_fatal(&self) -> bool { match self { - Error::Bind { .. } | Error::Recv { .. } | Error::Decode { .. } => true, + UdpError::Bind { .. } + | UdpError::Recv { .. } + | UdpError::Decode { .. } + | UdpError::Fault { .. } => true, } } } #[cfg(test)] -mod tests { - use super::*; - use crate::model::{AdjId, Board, BoardId, MacAddress, MessageLevel, PacketDef, PacketType, PodData}; - use std::collections::HashMap; - use std::net::IpAddr; - - fn peer() -> SocketAddr { - SocketAddr::new(IpAddr::from([192, 168, 1, 3]), 50400) - } - - #[test] - fn a_datagram_that_will_not_decode_faults_the_pod() { - let error = Error::Decode { - from: peer(), - source: crate::protocol::DecodeError::UnknownId(AdjId(9999)), - }; - - assert!(error.is_fatal()); - } - - #[test] - fn losing_the_socket_faults_the_pod_too() { - let error = Error::Recv { - source: std::io::Error::from(std::io::ErrorKind::ConnectionReset), - }; - - assert!(error.is_fatal()); - } - - #[test] - fn a_decode_failure_says_where_it_came_from() { - let error = Error::Decode { - from: peer(), - source: crate::protocol::DecodeError::UnknownId(AdjId(9999)), - }; +mod manual_tests; - assert!(error.to_string().contains("192.168.1.3:50400")); - } - - /// Builds a minimal Index with one empty Data packet (ID 1000) on Board 1. - fn sample_index() -> Index { - let packet = PacketDef { - id: AdjId(1000), - board: BoardId(1), - name: "test_data".to_string(), - packet_type: PacketType::Message(MessageLevel::Info),// I don't know what packet type to use here - }; - let board = Board { - id: BoardId(1), - name: "TEST".to_string(), - ip: IpAddr::from([192, 168, 0, 10]), - mac: MacAddress([0; 6]), - packets: HashMap::from([(packet.id, packet)]), - }; - let pod_data = PodData { - boards: HashMap::from([(board.id, board)]), - }; - Index::new(&pod_data, None) - } - - #[tokio::test] - async fn handle_datagram_decodes_valid_packet_and_notifies() { - let (reporter, mut sinks) = Reporter::channels(16, 16); - let index = sample_index(); - - // 1000 in little-endian u16 is [0xE8, 0x03], with 0 measurements. - let keep_going = handle_datagram(&[0xE8, 0x03], peer(), &index, &reporter).await; - assert!(keep_going); - - let notification = sinks.notifications.recv().await; - assert!(notification.is_some(), "should have emitted a packet event"); - assert!(sinks.errors.try_recv().is_err(), "should not have reported an error"); - } - - #[tokio::test] - async fn handle_datagram_reports_error_on_unknown_id() { - let (reporter, mut sinks) = Reporter::channels(16, 16); - let index = sample_index(); - - // Unknown ID 0xFFFF (65535) - let keep_going = handle_datagram(&[0xFF, 0xFF], peer(), &index, &reporter).await; - assert!(keep_going); - - let error_report = sinks.errors.recv().await; - assert!(error_report.is_some(), "should have reported a decode error"); - } - - #[tokio::test] - async fn handle_datagram_stops_when_sinks_are_dropped() { - let (reporter, sinks) = Reporter::channels(16, 16); - let index = sample_index(); - drop(sinks); - - // With receivers dropped, reporting should signal the loop to exit (false). - let keep_going = handle_datagram(&[0xFF, 0xFF], peer(), &index, &reporter).await; - assert!(!keep_going); - } +#[cfg(test)] +mod test_support; - #[test] - fn config_is_copy() { - let config = Config { - addr: SocketAddr::new(IpAddr::from([127, 0, 0, 1]), 0), - recv_buffer: 2 * 1024 * 1024, - }; - let _copy = config; - // Config is still usable after assignment — it implements Copy. - let _addr = config.addr; - let _buf = config.recv_buffer; - } -} \ No newline at end of file +#[cfg(test)] +mod tests; diff --git a/backend/crates/core/src/net/udp/manual_tests.rs b/backend/crates/core/src/net/udp/manual_tests.rs new file mode 100644 index 000000000..eb890291d --- /dev/null +++ b/backend/crates/core/src/net/udp/manual_tests.rs @@ -0,0 +1,225 @@ +//! Manual load probe: can the receive loop keep up with the pod's +//! telemetry? +//! +//! Ignored by a normal `cargo test`. It sends 76-byte datagrams over +//! loopback at `UDP_LOAD_MBIT` Mbit/s (default 25, about 41,000 datagrams +//! a second) for `UDP_LOAD_SECS` seconds (default 10), through the real +//! socket, decode and reporter, into a consumer that only counts. It fails +//! if any datagram is lost or fails to decode. `UDP_LOAD_RCVBUF` sets the +//! `SO_RCVBUF` requested (default 2 MiB). Run it in release, which is how +//! the station runs: +//! +//! ```sh +//! cargo test -p software-core --features net --release manual_udp_load -- --ignored --nocapture +//! UDP_LOAD_MBIT=40 cargo test -p software-core --features net --release manual_udp_load -- --ignored --nocapture +//! ``` +//! +//! What it does **not** tell: the cost of the real consumer (`station`'s +//! event loop), which comes on top — a consumer that only adds a timer per +//! message was already enough to lose 0.7 % at 25 Mbit/s. And loopback is +//! not the pod's network: sender and receiver share this machine's CPUs, +//! and there is no network card. + +use super::test_support::{any_loopback_port, bind_on_loopback}; +use super::*; +use crate::model::{ + AdjId, Board, BoardId, DataPacket, MacAddress, Measurement, MeasurementKind, NumericKind, + PacketDef, PacketType, PodData, Value, +}; +use std::collections::HashMap; +use std::net::IpAddr; + +/// Bytes of one datagram in the probe: 2 of id and 74 of values. +const PROBE_DATAGRAM_LEN: usize = 76; + +fn measurement_with_id(id: u16, kind: MeasurementKind) -> Measurement { + Measurement { + id: AdjId(id), + alias: format!("m{id}"), + name: format!("measurement {id}"), + display_units: String::new(), + kind, + protections: vec![], + } +} + +/// An index with one `Data` packet (id 1000, board 1) whose datagram is +/// [`PROBE_DATAGRAM_LEN`] bytes, mixing value types the way board telemetry +/// does — floats, integers, enums (which decode into a `String`) and +/// booleans — together with the bytes of one such datagram. +fn telemetry_index_and_datagram() -> (Index, Vec) { + let mut measurements = Vec::new(); + let mut values = Vec::new(); + let mut add = |kind: MeasurementKind, value: Value, count: usize| { + for _ in 0..count { + let id = u16::try_from(measurements.len() + 1).unwrap_or(u16::MAX); + measurements.push(measurement_with_id(id, kind.clone())); + values.push(value.clone()); + } + }; + let numeric = |wire_type| MeasurementKind::Numeric { wire_type }; + let options = vec!["Idle".to_string(), "Running".into(), "Fault".into()]; + + add(numeric(NumericKind::F32), Value::Number(21.5), 14); // 56 bytes + add(numeric(NumericKind::U16), Value::Number(1234.0), 4); // 8 bytes + add(numeric(NumericKind::U8), Value::Number(7.0), 6); // 6 bytes + add(MeasurementKind::Enum { options }, Value::Number(1.0), 2); // 2 bytes + add(MeasurementKind::Boolean, Value::Bool(true), 2); // 2 bytes + + let packet = PacketDef { + id: AdjId(1000), + board: BoardId(1), + name: "telemetry".to_string(), + packet_type: PacketType::Data(measurements), + }; + let board = Board { + id: BoardId(1), + name: "TEST".to_string(), + ip: IpAddr::from([127, 0, 0, 1]), + mac: MacAddress([0; 6]), + packets: HashMap::from([(packet.id, packet)]), + }; + let index = Index::new( + &PodData { + boards: HashMap::from([(board.id, board)]), + }, + None, + ); + + let datagram = + crate::protocol::packet::data_order::encode(&DataPacket::new(AdjId(1000), values), &index); + let Ok(datagram) = datagram else { + unreachable!("the probe's telemetry packet should encode"); + }; + assert_eq!(datagram.len(), PROBE_DATAGRAM_LEN); + (index, datagram) +} + +/// Sends `datagram` to `to` at `per_second` for `duration`, paced in short +/// bursts as a board's network would deliver it. Returns how many were +/// sent and how many sends failed. +fn send_at_rate( + to: SocketAddr, + datagram: &[u8], + per_second: f64, + duration: Duration, +) -> (u64, u64) { + let Ok(socket) = std::net::UdpSocket::bind(any_loopback_port()) else { + unreachable!("binding the probe's sending socket should succeed"); + }; + let start = Instant::now(); + let (mut sent, mut failed) = (0u64, 0u64); + while start.elapsed() < duration { + let due = (start.elapsed().as_secs_f64() * per_second) as u64; + while sent + failed < due { + match socket.send_to(datagram, to) { + Ok(_) => sent += 1, + Err(_) => failed += 1, + } + } + std::thread::sleep(Duration::from_micros(200)); + } + (sent, failed) +} + +/// The kernel's count of UDP datagrams dropped for lack of receive buffer, +/// system-wide (`RcvbufErrors` in `/proc/net/snmp`). Linux only. +fn kernel_rcvbuf_errors() -> Option { + let snmp = std::fs::read_to_string("/proc/net/snmp").ok()?; + let mut udp = snmp.lines().filter(|line| line.starts_with("Udp:")); + let header = udp.next()?; + let values = udp.next()?; + let column = header + .split_whitespace() + .position(|c| c == "RcvbufErrors")?; + values.split_whitespace().nth(column)?.parse().ok() +} + +/// The environment variable `name` parsed as `T`, or `default`. +fn env_var_or(name: &str, default: T) -> T { + std::env::var(name) + .ok() + .and_then(|value| value.parse().ok()) + .unwrap_or(default) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[ignore = "load probe: run in release with --ignored --nocapture"] +async fn manual_udp_load() { + let mbit: f64 = env_var_or("UDP_LOAD_MBIT", 25.0); + let secs: u64 = env_var_or("UDP_LOAD_SECS", 10); + let recv_buffer: usize = env_var_or("UDP_LOAD_RCVBUF", 2 * 1024 * 1024); + let per_second = mbit * 1_000_000.0 / 8.0 / PROBE_DATAGRAM_LEN as f64; + let (index, datagram) = telemetry_index_and_datagram(); + + let (socket, addr) = bind_on_loopback(recv_buffer); + let granted = socket2::SockRef::from(&socket).recv_buffer_size().ok(); + let (reporter, mut sinks) = Reporter::channels(8192, 16); + let receiver = tokio::spawn(receive_telemetry(socket, Arc::new(index), reporter)); + + // Counts until told the sender is done, then drains what is left. No + // timer per message, so that the consumer costs as little as possible + // and what is measured is this module. + let (done_tx, mut done_rx) = tokio::sync::oneshot::channel::<()>(); + let consumer = tokio::spawn(async move { + let (mut received, mut errors) = (0u64, 0u64); + loop { + tokio::select! { + biased; + Some(_) = sinks.notifications.recv() => received += 1, + Some(_) = sinks.errors.recv() => errors += 1, + _ = &mut done_rx => break, + } + } + while let Ok(Some(_)) = + tokio::time::timeout(Duration::from_millis(200), sinks.notifications.recv()).await + { + received += 1; + } + while sinks.errors.try_recv().is_ok() { + errors += 1; + } + (received, errors) + }); + + let drops_before = kernel_rcvbuf_errors(); + let started = Instant::now(); + let sender = tokio::task::spawn_blocking(move || { + send_at_rate(addr, &datagram, per_second, Duration::from_secs(secs)) + }); + let Ok((sent, failed)) = sender.await else { + unreachable!("the sender thread should not panic"); + }; + let send_time = started.elapsed(); + let _ = done_tx.send(()); + let Ok((received, errors)) = consumer.await else { + unreachable!("the consumer task should not panic"); + }; + let drops = match (drops_before, kernel_rcvbuf_errors()) { + (Some(before), Some(after)) => format!("+{}", after.saturating_sub(before)), + _ => "unavailable".to_string(), + }; + receiver.abort(); + + let lost = sent.saturating_sub(received); + println!( + "UDP load probe: {mbit} Mbit/s in {PROBE_DATAGRAM_LEN}-byte datagrams \ + = {per_second:.0} datagrams/s, for {secs} s" + ); + println!( + " sent {sent} in {:.2} s ({:.0}/s), {failed} sends failed", + send_time.as_secs_f64(), + sent as f64 / send_time.as_secs_f64() + ); + println!( + " received {received}, lost {lost} ({:.4} %), decode errors {errors}", + 100.0 * lost as f64 / sent.max(1) as f64 + ); + println!( + " SO_RCVBUF requested {recv_buffer} bytes, read back {granted:?}; \ + kernel RcvbufErrors (system-wide): {drops}" + ); + + assert_eq!(errors, 0, "every datagram should decode"); + assert_eq!(lost, 0, "every datagram sent should be received"); +} diff --git a/backend/crates/core/src/net/udp/test_support.rs b/backend/crates/core/src/net/udp/test_support.rs new file mode 100644 index 000000000..aa8425133 --- /dev/null +++ b/backend/crates/core/src/net/udp/test_support.rs @@ -0,0 +1,129 @@ +//! Fixtures shared by `tests.rs` and `manual_tests.rs`: a minimal ADJ +//! index, loopback sockets, and waits on the reporter's channels that fail +//! instead of hanging. + +use super::*; +use crate::model::{AdjId, Board, BoardId, MacAddress, PacketDef, PacketType, PodData}; +use crate::net::{ErrorReport, Event, Notification, Sinks}; +use std::collections::HashMap; +use std::net::IpAddr; + +/// How long a test waits for something to arrive before failing, so that +/// a broken expectation fails instead of hanging forever. +pub(super) const RECEIVE_TIMEOUT: Duration = Duration::from_secs(1); + +/// Id 1000, little-endian, with no measurements after it: the one packet +/// [`index_with_empty_data_packet`] declares. +pub(super) const EMPTY_DATA_DATAGRAM: [u8; 2] = [0xE8, 0x03]; + +/// Id 0xFFFF, which [`index_with_empty_data_packet`] does not declare. +pub(super) const UNKNOWN_ID_DATAGRAM: [u8; 2] = [0xFF, 0xFF]; + +/// A fault: packet id 0, which [`index_with_empty_data_packet`] does not +/// declare either — a fault is recognised without the ADJ. +pub(super) const FAULT_DATAGRAM: [u8; 2] = [0x00, 0x00]; + +/// A board's address on the pod's network, for errors that carry one. +pub(super) fn example_board_addr() -> SocketAddr { + SocketAddr::new(IpAddr::from([192, 168, 1, 3]), 50400) +} + +/// `127.0.0.1` with port 0, so that the OS picks a free one. +pub(super) fn any_loopback_port() -> SocketAddr { + SocketAddr::new(IpAddr::from([127, 0, 0, 1]), 0) +} + +/// An index with a single `Data` packet, id 1000 on board 1, that carries +/// no measurements. +/// +/// It has to be `Data`: that is the only type a UDP datagram can carry, +/// and decoding rejects any other with `WrongPacketType`. +pub(super) fn index_with_empty_data_packet() -> Index { + let packet = PacketDef { + id: AdjId(1000), + board: BoardId(1), + name: "test_data".to_string(), + packet_type: PacketType::Data(vec![]), + }; + let board = Board { + id: BoardId(1), + name: "TEST".to_string(), + ip: IpAddr::from([192, 168, 0, 10]), + mac: MacAddress([0; 6]), + packets: HashMap::from([(packet.id, packet)]), + }; + let pod_data = PodData { + boards: HashMap::from([(board.id, board)]), + }; + Index::new(&pod_data, None) +} + +/// The next notification, or a test failure after [`RECEIVE_TIMEOUT`]. +pub(super) async fn receive_notification(sinks: &mut Sinks) -> Notification { + let Ok(Some(notification)) = + tokio::time::timeout(RECEIVE_TIMEOUT, sinks.notifications.recv()).await + else { + unreachable!("a notification should have arrived within {RECEIVE_TIMEOUT:?}"); + }; + notification +} + +/// The next error report, or a test failure after [`RECEIVE_TIMEOUT`]. +pub(super) async fn receive_error_report(sinks: &mut Sinks) -> ErrorReport { + let Ok(Some(report)) = tokio::time::timeout(RECEIVE_TIMEOUT, sinks.errors.recv()).await else { + unreachable!("an error report should have arrived within {RECEIVE_TIMEOUT:?}"); + }; + report +} + +/// Asserts that `notification` is what [`EMPTY_DATA_DATAGRAM`] decodes to. +pub(super) fn assert_is_empty_data_packet(notification: Notification) { + assert_eq!(notification.board, BoardId(1)); + let Event::Received(Packet::Data(packet)) = notification.event else { + unreachable!("a datagram should arrive as Event::Received(Packet::Data)"); + }; + assert_eq!(packet.id, AdjId(1000)); + assert!(packet.values.is_empty()); +} + +/// Binds the telemetry socket on a free loopback port, as [`spawn_udp`] does on +/// the backend's own address, and returns it with the port the OS picked. +pub(super) fn bind_on_loopback(recv_buffer: usize) -> (tokio::net::UdpSocket, SocketAddr) { + let config = UdpConfig { + addr: any_loopback_port(), + recv_buffer, + }; + let Ok(socket) = bind_telemetry_socket(config) else { + unreachable!("binding to a free loopback port should succeed"); + }; + let Ok(addr) = socket.local_addr() else { + unreachable!("a bound socket has a local address"); + }; + (socket, addr) +} + +/// Starts receiving on a free loopback port with +/// [`index_with_empty_data_packet`], as [`spawn_udp`] does, and returns the +/// address to send to along with the task's handle. +pub(super) fn start_receiving_on_loopback(reporter: Reporter) -> (SocketAddr, JoinHandle<()>) { + let (socket, addr) = bind_on_loopback(256 * 1024); + let index = Arc::new(index_with_empty_data_packet()); + let handle = tokio::spawn(receive_telemetry(socket, index, reporter)); + (addr, handle) +} + +/// A socket standing in for a board that sends telemetry. +pub(super) async fn bind_fake_board() -> tokio::net::UdpSocket { + let Ok(socket) = tokio::net::UdpSocket::bind(any_loopback_port()).await else { + unreachable!("binding the fake board's socket should succeed"); + }; + socket +} + +/// Sends `bytes` as one datagram from `from` to `to`. +pub(super) async fn send_datagram(from: &tokio::net::UdpSocket, bytes: &[u8], to: SocketAddr) { + let Ok(sent) = from.send_to(bytes, to).await else { + unreachable!("sending on loopback should succeed"); + }; + assert_eq!(sent, bytes.len()); +} diff --git a/backend/crates/core/src/net/udp/tests.rs b/backend/crates/core/src/net/udp/tests.rs new file mode 100644 index 000000000..b71efb004 --- /dev/null +++ b/backend/crates/core/src/net/udp/tests.rs @@ -0,0 +1,327 @@ +//! Unit tests of the receive path, and tests through a real socket on +//! loopback. Fixtures live in `test_support.rs`. + +use super::test_support::*; +use super::*; +use crate::model::AdjId; + +// --------------------------------------------------------------------------- +// Error classification +// --------------------------------------------------------------------------- + +#[test] +fn a_datagram_that_will_not_decode_faults_the_pod() { + let error = UdpError::Decode { + from: example_board_addr(), + source: DecodeError::UnknownId(AdjId(9999)), + }; + + assert!(error.is_fatal()); +} + +#[test] +fn losing_the_socket_faults_the_pod_too() { + let error = UdpError::Recv { + source: std::io::Error::from(std::io::ErrorKind::ConnectionReset), + }; + + assert!(error.is_fatal()); +} + +#[test] +fn a_decode_failure_says_where_it_came_from() { + let error = UdpError::Decode { + from: example_board_addr(), + source: DecodeError::UnknownId(AdjId(9999)), + }; + + assert!(error.to_string().contains("192.168.1.3:50400")); +} + +#[test] +fn a_board_signalling_a_fault_faults_the_pod() { + let error = UdpError::Fault { + from: example_board_addr(), + }; + + assert!(error.is_fatal()); +} + +#[test] +fn a_fault_says_where_it_came_from() { + let error = UdpError::Fault { + from: example_board_addr(), + }; + + assert!(error.to_string().contains("192.168.1.3:50400")); +} + +// --------------------------------------------------------------------------- +// decode_and_report, without a socket +// --------------------------------------------------------------------------- + +#[tokio::test] +async fn decode_and_report_notifies_a_valid_datagram() { + let (reporter, mut sinks) = Reporter::channels(16, 16); + let index = index_with_empty_data_packet(); + let mut traces = ReceiveTraces::default(); + + let keep_going = decode_and_report( + &EMPTY_DATA_DATAGRAM, + example_board_addr(), + &index, + &reporter, + &mut traces, + ) + .await; + assert!(keep_going); + + assert_is_empty_data_packet(receive_notification(&mut sinks).await); + assert!( + sinks.errors.try_recv().is_err(), + "should not have reported an error" + ); +} + +#[tokio::test] +async fn decode_and_report_reports_an_unknown_id() { + let (reporter, mut sinks) = Reporter::channels(16, 16); + let index = index_with_empty_data_packet(); + let mut traces = ReceiveTraces::default(); + + let keep_going = decode_and_report( + &UNKNOWN_ID_DATAGRAM, + example_board_addr(), + &index, + &reporter, + &mut traces, + ) + .await; + assert!(keep_going); + + let report = receive_error_report(&mut sinks).await; + let crate::net::Error::Udp(UdpError::Decode { from, source }) = report.error else { + unreachable!("an undecodable datagram should be reported as udp::UdpError::Decode"); + }; + assert_eq!(from, example_board_addr()); + assert!(matches!(source, DecodeError::UnknownId(AdjId(0xFFFF)))); + assert!( + sinks.notifications.try_recv().is_err(), + "should not have notified a packet" + ); +} + +#[tokio::test] +async fn decode_and_report_reports_a_fault_without_looking_at_the_adj() { + let (reporter, mut sinks) = Reporter::channels(16, 16); + // Declares id 1000 only: id 0 is unknown to it, and yet it is a fault. + let index = index_with_empty_data_packet(); + let mut traces = ReceiveTraces::default(); + + let keep_going = decode_and_report( + &FAULT_DATAGRAM, + example_board_addr(), + &index, + &reporter, + &mut traces, + ) + .await; + assert!(keep_going); + + let report = receive_error_report(&mut sinks).await; + let crate::net::Error::Udp(UdpError::Fault { from }) = report.error else { + unreachable!("a datagram with packet id 0 should be reported as udp::UdpError::Fault"); + }; + assert_eq!(from, example_board_addr()); + assert!( + sinks.notifications.try_recv().is_err(), + "should not have notified a packet" + ); +} + +#[tokio::test] +async fn whatever_follows_the_fault_id_is_not_read() { + let (reporter, mut sinks) = Reporter::channels(16, 16); + let index = index_with_empty_data_packet(); + let mut traces = ReceiveTraces::default(); + + decode_and_report( + &[0x00, 0x00, 0xAB, 0xCD], + example_board_addr(), + &index, + &reporter, + &mut traces, + ) + .await; + + let report = receive_error_report(&mut sinks).await; + assert!(matches!( + report.error, + crate::net::Error::Udp(UdpError::Fault { .. }) + )); +} + +#[tokio::test] +async fn a_single_zero_byte_is_not_a_fault() { + let (reporter, mut sinks) = Reporter::channels(16, 16); + let index = index_with_empty_data_packet(); + let mut traces = ReceiveTraces::default(); + + // An id takes two bytes: one zero byte is a truncated datagram. + decode_and_report( + &[0x00], + example_board_addr(), + &index, + &reporter, + &mut traces, + ) + .await; + + let report = receive_error_report(&mut sinks).await; + let crate::net::Error::Udp(UdpError::Decode { source, .. }) = report.error else { + unreachable!("a one-byte datagram should be a decode failure, not a fault"); + }; + assert!(matches!(source, DecodeError::UnexpectedEof)); +} + +#[tokio::test] +async fn decode_and_report_stops_once_nobody_listens() { + let (reporter, sinks) = Reporter::channels(16, 16); + let index = index_with_empty_data_packet(); + let mut traces = ReceiveTraces::default(); + drop(sinks); + + // With the receivers gone, reporting tells the loop to stop (false). + let keep_going = decode_and_report( + &UNKNOWN_ID_DATAGRAM, + example_board_addr(), + &index, + &reporter, + &mut traces, + ) + .await; + assert!(!keep_going); +} + +// --------------------------------------------------------------------------- +// Rate limit of the decode-failure trace +// --------------------------------------------------------------------------- + +#[test] +fn decode_failures_are_traced_at_most_once_a_second() { + let mut trace = TraceRateLimit::default(); + let t0 = Instant::now(); + let at = |ms: u64| t0 + Duration::from_millis(ms); + + assert_eq!( + trace.should_trace(at(0)), + Some(0), + "the first one is traced" + ); + assert_eq!( + trace.should_trace(at(300)), + None, + "within the second: counted" + ); + assert_eq!( + trace.should_trace(at(900)), + None, + "within the second: counted" + ); + assert_eq!( + trace.should_trace(at(1100)), + Some(2), + "after a second: traced, with the two left out" + ); + assert_eq!(trace.should_trace(at(1500)), None); + assert_eq!( + trace.should_trace(at(2200)), + Some(1), + "the window restarts at the last traced one" + ); +} + +// --------------------------------------------------------------------------- +// Through a real socket on loopback +// --------------------------------------------------------------------------- + +#[tokio::test] +async fn a_datagram_sent_to_the_socket_arrives_as_a_notification() { + let (reporter, mut sinks) = Reporter::channels(16, 16); + let (addr, handle) = start_receiving_on_loopback(reporter); + let board = bind_fake_board().await; + + send_datagram(&board, &EMPTY_DATA_DATAGRAM, addr).await; + + assert_is_empty_data_packet(receive_notification(&mut sinks).await); + handle.abort(); +} + +#[tokio::test] +async fn an_undecodable_datagram_is_reported_with_its_sender() { + let (reporter, mut sinks) = Reporter::channels(16, 16); + let (addr, handle) = start_receiving_on_loopback(reporter); + let board = bind_fake_board().await; + let Ok(board_addr) = board.local_addr() else { + unreachable!("a bound socket has a local address"); + }; + + send_datagram(&board, &UNKNOWN_ID_DATAGRAM, addr).await; + + let report = receive_error_report(&mut sinks).await; + let crate::net::Error::Udp(UdpError::Decode { from, .. }) = report.error else { + unreachable!("an undecodable datagram should be reported as udp::UdpError::Decode"); + }; + assert_eq!(from, board_addr); + handle.abort(); +} + +#[tokio::test] +async fn a_fault_sent_to_the_socket_is_reported_with_its_sender() { + let (reporter, mut sinks) = Reporter::channels(16, 16); + let (addr, handle) = start_receiving_on_loopback(reporter); + let board = bind_fake_board().await; + let Ok(board_addr) = board.local_addr() else { + unreachable!("a bound socket has a local address"); + }; + + send_datagram(&board, &FAULT_DATAGRAM, addr).await; + + let report = receive_error_report(&mut sinks).await; + let crate::net::Error::Udp(UdpError::Fault { from }) = report.error else { + unreachable!("a datagram with packet id 0 should be reported as udp::UdpError::Fault"); + }; + assert_eq!(from, board_addr); + handle.abort(); +} + +#[tokio::test] +async fn the_loop_stops_on_the_next_datagram_once_nobody_listens() { + let (reporter, sinks) = Reporter::channels(16, 16); + let (addr, handle) = start_receiving_on_loopback(reporter); + drop(sinks); + let board = bind_fake_board().await; + + // Without a datagram the loop would keep waiting on the socket: it only + // notices the consumer is gone when it tries to report. + send_datagram(&board, &EMPTY_DATA_DATAGRAM, addr).await; + + let Ok(Ok(())) = tokio::time::timeout(RECEIVE_TIMEOUT, handle).await else { + unreachable!("the loop should end once a report finds nobody listening"); + }; +} + +#[tokio::test] +async fn binding_an_address_already_in_use_is_a_bind_error() { + let (_first, taken) = bind_on_loopback(256 * 1024); + + let second = bind_telemetry_socket(UdpConfig { + addr: taken, + recv_buffer: 256 * 1024, + }); + + let Err(UdpError::Bind { addr, .. }) = second else { + unreachable!("binding an address already in use should fail with UdpError::Bind"); + }; + assert_eq!(addr, taken); +} From 0c586d7ca1ca4ad7791bebc24bddea0bbc4f8984 Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Wed, 25 Nov 2026 02:20:27 +0100 Subject: [PATCH 152/225] chore: update CI to test all features --- .github/workflows/rust-tests.yaml | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/.github/workflows/rust-tests.yaml b/.github/workflows/rust-tests.yaml index 6ab44a9ce..b3ebd6fc6 100644 --- a/.github/workflows/rust-tests.yaml +++ b/.github/workflows/rust-tests.yaml @@ -13,7 +13,14 @@ jobs: strategy: fail-fast: false matrix: - crate: [software-core, station] + include: + # software-core's modules sit behind features (net, git, logger, + # ntp, http...) that are all off by default: without + # --all-features none of their tests would run, UDP's included. + - crate: software-core + flags: --all-features + - crate: station + flags: "" steps: - uses: actions/checkout@v4 @@ -27,4 +34,4 @@ jobs: - name: Run tests working-directory: backend - run: cargo test --package ${{ matrix.crate }} + run: cargo test --package ${{ matrix.crate }} ${{ matrix.flags }} From c16a9df0ea4996baa6a9325b3e9e30000e908eb1 Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Wed, 25 Nov 2026 02:22:08 +0100 Subject: [PATCH 153/225] feat(backend, websocket): forward logger commands and make heartbeat timeout configurable --- backend/crates/station/src/http/server.rs | 540 +++--------------- backend/crates/station/src/websocket.rs | 53 +- .../crates/station/src/websocket/broker.rs | 12 +- backend/crates/station/src/websocket/error.rs | 18 +- .../crates/station/src/websocket/handler.rs | 10 +- backend/crates/station/src/websocket/order.rs | 5 + .../crates/station/src/websocket/payload.rs | 8 +- .../src/websocket/payload/connection.rs | 1 + .../station/src/websocket/payload/data.rs | 4 +- .../station/src/websocket/payload/message.rs | 8 +- .../station/src/websocket/payload/order.rs | 9 +- .../src/websocket/payload/protection.rs | 5 +- .../src/websocket/payload/serialize.rs | 5 +- .../crates/station/src/websocket/receiver.rs | 100 +++- .../crates/station/src/websocket/sender.rs | 4 + 15 files changed, 272 insertions(+), 510 deletions(-) diff --git a/backend/crates/station/src/http/server.rs b/backend/crates/station/src/http/server.rs index 1f5584852..ea6078ac0 100644 --- a/backend/crates/station/src/http/server.rs +++ b/backend/crates/station/src/http/server.rs @@ -48,14 +48,18 @@ pub(super) fn setup_router( } #[cfg(test)] -pub(super) mod tests { - use std::{io, path::Path, time::Duration}; +mod tests { + use std::{io, path::Path, sync::Arc, time::Duration}; use axum::{ body::{Body, to_bytes}, http::{Method, Request, StatusCode, header}, }; - use software_core::adj::{Adj, load_from_dir}; + use software_core::{ + adj::{Adj, load_from_dir}, + model::{AdjId, OrderPacket, ShortTimestamp, Value}, + protocol::Index, + }; use tokio::{ io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader}, net::{TcpListener, TcpStream}, @@ -65,6 +69,9 @@ pub(super) mod tests { use tower::ServiceExt; use super::setup_router; + use crate::websocket::{ + self, Commands, OrderForwarder, broker::Broker, payload::ProtectionUpdate, + }; pub(in crate::http) const PATHS: [&str; 3] = [ "/backend/adj/DataPackets", @@ -199,17 +206,10 @@ pub(super) mod tests { // Upgrades require a real HTTP connection: oneshot does not provide Hyper's // OnUpgrade extension. The server only runs for the duration of the test. - async fn handshake( + pub(super) async fn handshake( app: axum::Router, ) -> Result<(String, TcpStream), Box> { let listener = TcpListener::bind("127.0.0.1:0").await?; - handshake_on(listener, app).await - } - - pub(in crate::http) async fn handshake_on( - listener: TcpListener, - app: axum::Router, - ) -> Result<(String, TcpStream), Box> { let address = listener.local_addr()?; let (shutdown, stopped) = oneshot::channel(); let server = tokio::spawn(async move { @@ -280,490 +280,130 @@ pub(super) mod tests { } #[tokio::test] - async fn websocket_subscription_receives_connection_snapshots() + async fn websocket_delivers_protections_and_forwards_orders() -> Result<(), Box> { - use crate::websocket::payload::{Connection, StateOrdersUpdate}; - - let (broker, client) = crate::websocket::broker::Broker::new(); - let broker_worker = tokio::spawn(broker.run()); - let (connections, receiver) = mpsc::channel(1); - let worker = tokio::spawn(crate::websocket::run(receiver, client.clone(), None)); - let app = setup_router(&Adj::default(), Some(connections))?; - let (headers, mut first) = handshake(app.clone()).await?; + let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("../core/src/adj/test/adj"); + let adj = load_from_dir(&path)?; + let (order_tx, mut orders) = mpsc::channel(1); + let commands = Commands { + orders: Some(OrderForwarder::new( + Arc::new(Index::new(&adj.pod_data, None)), + order_tx, + )), + ..Commands::default() + }; + let (broker, client) = Broker::new(); + let broker_task = tokio::spawn(broker.run()); + let (sockets, receiver) = mpsc::channel(1); + let socket_task = tokio::spawn(websocket::run( + receiver, + client.clone(), + commands, + Duration::from_secs(10), + )); + let (headers, mut socket) = handshake(setup_router(&adj, Some(sockets))?).await?; assert!(headers.starts_with("HTTP/1.1 101 Switching Protocols\r\n")); - let (_headers, mut second) = handshake(app).await?; timeout(Duration::from_secs(5), async { - send_text( - &mut first, - r#"{"topic":"connection/heartbeat","payload":{}}"#, - ) - .await?; - // Other frontend topics can be added incrementally without closing the socket. - send_text( - &mut first, - r#"{"topic":"not-a-topic","payload":{"subscribe":true}}"#, - ) - .await?; - send_text( - &mut first, - r#"{"topic":"connection/update","payload":{"subscribe":true}}"#, - ) - .await?; - assert_eq!( - read_json(&mut first).await?, - serde_json::json!({ - "topic": "connection/update", "payload": {} - }) - ); - - client - .publish_connection(Connection { - name: "LCU".into(), - is_connected: true, - }) - .await?; - let expected = serde_json::json!({ - "topic": "connection/update", - "payload": {"LCU": {"name": "LCU", "isConnected": true}} - }); - assert_eq!(read_json(&mut first).await?, expected); - - // A client receives nothing before subscribing, then receives the current map. - assert!( - timeout(Duration::from_millis(50), second.read_u8()) - .await - .is_err() - ); - send_text(&mut second, r#"{"topic":"connection/update","payload":{}}"#).await?; - assert_eq!(read_json(&mut second).await?, expected); - - client - .publish_connection(Connection { - name: "HVBMS".into(), - is_connected: false, - }) - .await?; - let expected = serde_json::json!({ - "topic": "connection/update", - "payload": { - "LCU": {"name": "LCU", "isConnected": true}, - "HVBMS": {"name": "HVBMS", "isConnected": false} - } - }); - assert_eq!(read_json(&mut first).await?, expected); - assert_eq!(read_json(&mut second).await?, expected); - - send_text( - &mut first, - r#"{"topic":"order/stateOrders","payload":{"subscribe":true}}"#, - ) - .await?; - assert_eq!( - read_json(&mut first).await?, - serde_json::json!({ - "topic": "order/stateOrders", "payload": {} - }) - ); - send_text( - &mut second, - r#"{"topic":"logger/response","payload":{"subscribe":true}}"#, - ) - .await?; - assert_eq!( - read_json(&mut second).await?, - serde_json::json!({ - "topic": "logger/response", "payload": false - }) - ); - - client - .publish_state_orders(StateOrdersUpdate::from([("LCU".into(), vec![1001])])) - .await?; - assert_eq!( - read_json(&mut first).await?, - serde_json::json!({ - "topic": "order/stateOrders", "payload": {"LCU": [1001]} - }) - ); - assert!( - timeout(Duration::from_millis(50), second.read_u8()) - .await - .is_err() - ); - - client.publish_logger(true).await?; + send_text(&mut socket, r#"{"topic":"protection/update","payload":{}}"#).await?; + // Receiving the snapshot confirms the preceding event subscription is active. + send_text(&mut socket, r#"{"topic":"connection/update","payload":{}}"#).await?; assert_eq!( - read_json(&mut second).await?, - serde_json::json!({ - "topic": "logger/response", "payload": true - }) - ); - assert!( - timeout(Duration::from_millis(50), first.read_u8()) - .await - .is_err() + read_json(&mut socket).await?, + serde_json::json!({"topic": "connection/update", "payload": {}}) ); - // The logger snapshot confirms the preceding unsubscribe was handled. - send_text( - &mut first, - r#"{"topic":"order/stateOrders","payload":{"subscribe":false}}"#, - ) - .await?; - send_text( - &mut first, - r#"{"topic":"logger/response","payload":{"subscribe":true}}"#, - ) - .await?; - assert_eq!( - read_json(&mut first).await?, - serde_json::json!({ - "topic": "logger/response", "payload": true - }) - ); client - .publish_state_orders(StateOrdersUpdate::from([("LCU".into(), vec![])])) - .await?; - assert!( - timeout(Duration::from_millis(50), first.read_u8()) - .await - .is_err() - ); - - // Resubscribing recovers the latest full state, including empty lists. - send_text(&mut first, r#"{"topic":"order/stateOrders","payload":{}}"#).await?; - assert_eq!( - read_json(&mut first).await?, - serde_json::json!({ - "topic": "order/stateOrders", "payload": {"LCU": []} - }) - ); - client.publish_logger(false).await?; - let expected = serde_json::json!({"topic": "logger/response", "payload": false}); - assert_eq!(read_json(&mut first).await?, expected); - assert_eq!(read_json(&mut second).await?, expected); - - for socket in [&mut first, &mut second] { - socket.write_all(&[0x88, 0x80, 0, 0, 0, 0]).await?; - assert_eq!(socket.read_u8().await?, 0x88); - } - Ok::<_, Box>(()) - }) - .await??; - drop(client); - worker.await?; - timeout(Duration::from_secs(5), broker_worker).await??; - Ok(()) - } - - #[tokio::test] - async fn websocket_telemetry_sends_complete_snapshots() -> Result<(), Box> - { - use crate::websocket::payload::{DataPacketUpdate, MeasurementUpdate}; - use software_core::model::AdjId; - - let (broker, client) = crate::websocket::broker::Broker::new(); - let broker_worker = tokio::spawn(broker.run()); - let (connections, receiver) = mpsc::channel(1); - let worker = tokio::spawn(crate::websocket::run(receiver, client.clone(), None)); - let app = setup_router(&Adj::default(), Some(connections))?; - let (_, mut first) = handshake(app.clone()).await?; - let (_, mut second) = handshake(app).await?; - - timeout(Duration::from_secs(5), async { - send_text( - &mut first, - r#"{"topic":"podData/update","payload":{"subscribe":true}}"#, - ) - .await?; - assert_eq!( - read_json(&mut first).await?, - serde_json::json!({ - "topic": "podData/update", "payload": {} - }) - ); - - let packet = DataPacketUpdate { - id: AdjId(1000), - hex_value: "e8030000bc41".into(), - count: 1, - cycle_time: 100_000_000, - measurement_updates: std::collections::HashMap::from([( - "temperature".into(), - MeasurementUpdate::Numeric { - last: 23.5, - average: 23.0, + .publish_protection(ProtectionUpdate { + id: AdjId(11192), + value: Value::Number(105.5), + timestamp: ShortTimestamp { + hour: 12, + minute: 30, + second: 6, + subsecond: 0, }, - )]), - }; - client.publish_data(packet.clone()).await?; - let expected = serde_json::json!({ - "topic": "podData/update", - "payload": {"1000": { - "id": 1000, "hexValue": "e8030000bc41", "count": 1, "cycleTime": 100_000_000, - "measurementUpdates": {"temperature": {"last": 23.5, "average": 23.0}} - }} - }); - assert_eq!(read_json(&mut first).await?, expected); - - send_text(&mut second, r#"{"topic":"podData/update","payload":{}}"#).await?; - assert_eq!(read_json(&mut second).await?, expected); - client - .publish_data(DataPacketUpdate { - id: AdjId(1001), - hex_value: "e9030000bc41".into(), - ..packet - }) - .await?; - let updated = read_json(&mut first).await?; - assert_eq!(updated["topic"], "podData/update"); - assert_eq!(updated["payload"].as_object().map(|map| map.len()), Some(2)); - assert_eq!(updated["payload"]["1000"], expected["payload"]["1000"]); - assert_eq!(updated["payload"]["1001"]["id"], 1001); - assert_eq!(read_json(&mut second).await?, updated); - - for socket in [&mut first, &mut second] { - socket.write_all(&[0x88, 0x80, 0, 0, 0, 0]).await?; - assert_eq!(socket.read_u8().await?, 0x88); - } - Ok::<_, Box>(()) - }) - .await??; - drop(client); - worker.await?; - timeout(Duration::from_secs(5), broker_worker).await??; - Ok(()) - } - - #[tokio::test] - async fn websocket_event_subscriptions_deliver_live_payloads() - -> Result<(), Box> { - use crate::websocket::{ - broker::Broker, - payload::{ - MessageKind, MessagePayload, MessageTimestamp, MessageUpdate, ProtectionUpdate, - }, - }; - use serde_json::json; - use software_core::model::{AdjId, ShortTimestamp, Value}; - - let (broker, client) = Broker::new(); - let broker_worker = tokio::spawn(broker.run()); - let (sockets, receiver) = mpsc::channel(1); - let worker = tokio::spawn(crate::websocket::run(receiver, client.clone(), None)); - let message = MessageUpdate { - kind: MessageKind::Info, - payload: MessagePayload::Text("Order Sent".into()), - board: "LCU".into(), - name: "1001".into(), - timestamp: MessageTimestamp { - counter: 0, - second: 5, - minute: 30, - hour: 12, - day: 24, - month: 11, - year: 2026, - }, - }; - let protection = ProtectionUpdate { - id: AdjId(11192), - value: Value::Number(105.5), - timestamp: ShortTimestamp { - hour: 12, - minute: 30, - second: 6, - subsecond: 0, - }, - }; - let expected_message: serde_json::Value = - serde_json::from_str(include_str!("../websocket/payload/example/message.json"))?; - let expected_protection: serde_json::Value = - serde_json::from_str(include_str!("../websocket/payload/example/protection.json"))?; - let (_, mut socket) = handshake(setup_router(&Adj::default(), Some(sockets))?).await?; - - timeout(Duration::from_secs(5), async { - let mut logger = client.subscribe_logger(); - client - .publish_message(MessageUpdate { - payload: MessagePayload::Text("Before subscribing".into()), - ..message.clone() }) .await?; - client.publish_logger(true).await?; - logger.changed().await?; - send_text(&mut socket, r#"{"topic":"message/update","payload":{}}"#).await?; - send_text( - &mut socket, - r#"{"topic":"protection/update","payload":{"subscribe":true}}"#, - ) - .await?; - // The state snapshot confirms the preceding subscriptions were processed. - send_text(&mut socket, r#"{"topic":"logger/response","payload":{}}"#).await?; - assert_eq!( - read_json(&mut socket).await?, - json!({"topic": "logger/response", "payload": true}) - ); - - client.publish_message(message.clone()).await?; - assert_eq!(read_json(&mut socket).await?, expected_message); - client.publish_protection(protection.clone()).await?; - assert_eq!(read_json(&mut socket).await?, expected_protection); + let expected: serde_json::Value = serde_json::from_str(include_str!( + "../websocket/payload/example/protection.json" + ))?; + assert_eq!(read_json(&mut socket).await?, expected); send_text( &mut socket, - r#"{"topic":"message/update","payload":{"subscribe":false}}"#, + r#"{"topic":"order/send","payload":{"id":809,"fields":{"desired_current":{"value":12.5,"type":"float32"},"lpu_id":{"value":2,"type":"uint32"}}}}"#, ) .await?; - send_text(&mut socket, r#"{"topic":"connection/update","payload":{}}"#).await?; assert_eq!( - read_json(&mut socket).await?, - json!({"topic": "connection/update", "payload": {}}) - ); - client - .publish_message(MessageUpdate { - payload: MessagePayload::Text("While unsubscribed".into()), - ..message - }) - .await?; - client.publish_protection(protection).await?; - assert_eq!(read_json(&mut socket).await?, expected_protection); - assert!( - timeout(Duration::from_millis(50), socket.read_u8()) - .await - .is_err() + orders.recv().await, + Some(OrderPacket::new( + AdjId(809), + vec![Value::Number(2.0), Value::Number(12.5)], + )) ); - socket.write_all(&[0x88, 0x80, 0, 0, 0, 0]).await?; - assert_eq!(socket.read_u8().await?, 0x88); + drop(socket); + socket_task.await?; + drop(client); + broker_task.await?; Ok::<_, Box>(()) }) .await??; - drop(client); - worker.await?; - timeout(Duration::from_secs(5), broker_worker).await??; - Ok(()) - } - - #[tokio::test] - async fn websocket_forwards_validated_orders_in_adj_order() - -> Result<(), Box> { - use crate::websocket::{OrderForwarder, broker::Broker}; - use software_core::{ - model::{AdjId, OrderPacket, Value}, - protocol::Index, - }; - use std::sync::Arc; - - let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("../core/src/adj/test/adj"); - let adj = load_from_dir(&path)?; - let index = Arc::new(Index::new(&adj.pod_data, None)); - let (order_tx, mut orders) = mpsc::channel(1); - let forwarder = OrderForwarder::new(index, order_tx); - let (broker, client) = Broker::new(); - let broker_worker = tokio::spawn(broker.run()); - let (connections, receiver) = mpsc::channel(1); - let worker = tokio::spawn(crate::websocket::run(receiver, client, Some(forwarder))); - let (_, mut socket) = handshake(setup_router(&adj, Some(connections))?).await?; - - timeout(Duration::from_secs(5), async { - for invalid in [ - r#"{"topic":"order/send","payload":{"id":65535,"fields":{}}}"#, - r#"{"topic":"order/send","payload":{"id":809,"fields":{}}}"#, - r#"{"topic":"order/send","payload":{"id":801,"fields":{"extra":{"value":0,"type":"uint8"}}}}"#, - r#"{"topic":"order/send","payload":{"id":809,"fields":{"desired_current":{"value":12.5,"type":"float64"},"lpu_id":{"value":2,"type":"uint32"}}}}"#, - r#"{"topic":"order/send","payload":{"id":809,"fields":{"desired_current":{"value":12.5,"type":"float32"},"lpu_id":{"value":2.5,"type":"uint32"}}}}"#, - ] { - send_text(&mut socket, invalid).await?; - } - send_text(&mut socket, r#"{"topic":"order/send","payload":{"id":809,"fields":{"desired_current":{"value":12.5,"type":"float32"},"lpu_id":{"value":2,"type":"uint32"}}}}"#).await?; - let stop = r#"{"topic":"order/send","payload":{"id":801,"fields":{}}}"#; - send_text(&mut socket, stop).await?; - - // The snapshot confirms both requests reached the receiver before we free the queue. - send_text(&mut socket, r#"{"topic":"connection/update","payload":{}}"#).await?; - assert_eq!(read_json(&mut socket).await?["topic"], "connection/update"); - assert_eq!(orders.recv().await, Some(OrderPacket::new( - AdjId(809), vec![Value::Number(2.0), Value::Number(12.5)], - ))); - assert!(matches!(orders.try_recv(), Err(mpsc::error::TryRecvError::Empty))); - - send_text(&mut socket, stop).await?; - assert_eq!(orders.recv().await, Some(OrderPacket::new(AdjId(801), vec![]))); - - socket.write_all(&[0x88, 0x80, 0, 0, 0, 0]).await?; - assert_eq!(socket.read_u8().await?, 0x88); - Ok::<_, Box>(()) - }).await??; - worker.await?; - timeout(Duration::from_secs(5), broker_worker).await??; Ok(()) } async fn send_text( - client: &mut TcpStream, + socket: &mut TcpStream, text: &str, ) -> Result<(), Box> { - // A zero mask leaves the test JSON unchanged. let length = u16::try_from(text.len())?; if length < 126 { - client.write_all(&[0x81, 0x80 | length as u8]).await?; + socket.write_all(&[0x81, 0x80 | length as u8]).await?; } else { - client.write_all(&[0x81, 0xfe]).await?; - client.write_u16(length).await?; + socket.write_all(&[0x81, 0xfe]).await?; + socket.write_u16(length).await?; } - client.write_all(&[0; 4]).await?; - client.write_all(text.as_bytes()).await?; + // The zero mask keeps the test payload bytes unchanged. + socket.write_all(&[0; 4]).await?; + socket.write_all(text.as_bytes()).await?; Ok(()) } async fn read_json( - client: &mut TcpStream, + socket: &mut TcpStream, ) -> Result> { - assert_eq!(client.read_u8().await?, 0x81); - let header = client.read_u8().await?; - assert_eq!(header & 0x80, 0, "server frames must not be masked"); - let length = match header { - 126 => usize::from(client.read_u16().await?), - 127 => usize::try_from(client.read_u64().await?)?, - length => usize::from(length), + assert_eq!(socket.read_u8().await?, 0x81); + let length = match socket.read_u8().await? { + length @ 0..=125 => usize::from(length), + 126 => usize::from(socket.read_u16().await?), + _ => panic!("expected a short, unmasked server frame"), }; let mut body = vec![0; length]; - client.read_exact(&mut body).await?; + socket.read_exact(&mut body).await?; Ok(serde_json::from_slice(&body)?) } #[tokio::test] - async fn websocket_without_a_consumer_returns_unavailable() - -> Result<(), Box> { - let app = setup_router(&Adj::default(), None)?; - let (headers, _client) = handshake(app).await?; - assert!(headers.starts_with("HTTP/1.1 503 Service Unavailable\r\n")); - Ok(()) - } - - #[tokio::test] - async fn websocket_with_a_closed_channel_returns_unavailable() + async fn websocket_returns_unavailable_when_handoff_cannot_accept_a_socket() -> Result<(), Box> { - let (connections, receiver) = mpsc::channel(1); + let (closed, receiver) = mpsc::channel(1); drop(receiver); - let app = setup_router(&Adj::default(), Some(connections))?; - let (headers, _client) = handshake(app).await?; - assert!(headers.starts_with("HTTP/1.1 503 Service Unavailable\r\n")); - Ok(()) - } - - #[tokio::test] - async fn websocket_with_a_full_channel_returns_unavailable() - -> Result<(), Box> { - let (connections, _receiver) = mpsc::channel(1); - // Simulate an occupied slot without requiring another test socket. - let reservation = connections.clone().try_reserve_owned()?; - let app = setup_router(&Adj::default(), Some(connections))?; - let (headers, _client) = handshake(app).await?; - assert!(headers.starts_with("HTTP/1.1 503 Service Unavailable\r\n")); - drop(reservation); + let (full, _receiver) = mpsc::channel(1); + let _reservation = full.clone().try_reserve_owned()?; + + for (case, connections) in [ + ("missing", None), + ("closed", Some(closed)), + ("full", Some(full)), + ] { + let app = setup_router(&Adj::default(), connections)?; + let (headers, _client) = handshake(app).await?; + assert!( + headers.starts_with("HTTP/1.1 503 Service Unavailable\r\n"), + "expected 503 for {case} channel, got {headers}", + ); + } Ok(()) } diff --git a/backend/crates/station/src/websocket.rs b/backend/crates/station/src/websocket.rs index 0fce10c17..c98c72854 100644 --- a/backend/crates/station/src/websocket.rs +++ b/backend/crates/station/src/websocket.rs @@ -1,4 +1,9 @@ -//! Connects upgraded HTTP sockets to broker subscriptions. +//! Connects upgraded HTTP sockets to station's broker and command queues. +//! +//! Each connection has a reader that accepts subscriptions and commands and a +//! writer that turns the subscribed broker updates into JSON messages. + +use std::time::Duration; use axum::extract::ws::WebSocket; use serde::{Deserialize, Serialize}; @@ -6,6 +11,7 @@ use tokio::sync::mpsc; use self::broker::BrokerClient; pub(crate) use self::order::OrderForwarder; +use self::payload::{LoggerEnable, LoggerVariables}; pub mod broker; mod error; @@ -17,13 +23,32 @@ mod sender; const CONNECTION_UPDATE: &str = "connection/update"; const STATE_ORDERS: &str = "order/stateOrders"; +const LOGGER_ENABLE: &str = "logger/enable"; const LOGGER_RESPONSE: &str = "logger/response"; +const LOGGER_VARIABLES: &str = "logger/variables"; const DATA_UPDATE: &str = "podData/update"; const MESSAGE_UPDATE: &str = "message/update"; const PROTECTION_UPDATE: &str = "protection/update"; const ORDER_SEND: &str = "order/send"; const HEARTBEAT: &str = "connection/heartbeat"; +/// Requests queued for the logger. The logger publishes its applied state separately. +#[derive(Debug, PartialEq, Eq)] +pub(crate) enum LoggerCommand { + Enable(LoggerEnable), + Variables(LoggerVariables), +} + +/// Destinations for requests received over WebSocket. +#[derive(Debug, Clone, Default)] +pub(crate) struct Commands { + /// Validates frontend orders before queuing them for the vehicle. + pub(crate) orders: Option, + /// Queues recording and variable selection requests for the logger. + pub(crate) logger: Option>, +} + +/// Topics a frontend can subscribe to. Commands and heartbeats are routed by the reader. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] enum Topic { Connections, @@ -62,33 +87,25 @@ impl Topic { /// JSON envelope shared with the frontend. #[derive(Debug, Serialize, Deserialize)] pub struct WsMessage { - /// Topic of the message, can be: - /// - order/send - /// - podData/update - /// - connection/update - /// - order/stateOrders - /// - message/update - /// - protection/update - /// - logger/enable - /// - logger/response - /// - logger/variables + /// Wire name used to route the message, such as `connection/update`. pub topic: String, - /// Topic-specific JSON payload + /// Topic-specific JSON payload. pub payload: serde_json::Value, } -/// Handles each connection independently while HTTP keeps accepting sockets. -pub async fn run( +/// Runs one task per upgraded socket so a slow client stays isolated. +/// Closing the HTTP handoff channel ends socket intake. Existing sessions end independently. +pub(crate) async fn run( mut connections: mpsc::Receiver, broker: BrokerClient, - orders: Option, + commands: Commands, + heartbeat_timeout: Duration, ) { - // Spawn one tokio task per Websocket connection while let Some(socket) = connections.recv().await { let broker = broker.clone(); - let orders = orders.clone(); + let commands = commands.clone(); tokio::spawn(async move { - if let Err(error) = handler::handle(socket, broker, orders.as_ref()).await { + if let Err(error) = handler::handle(socket, broker, &commands, heartbeat_timeout).await { tracing::warn!(%error, "WebSocket connection ended with an error"); } }); diff --git a/backend/crates/station/src/websocket/broker.rs b/backend/crates/station/src/websocket/broker.rs index 64079557e..ba7ce289d 100644 --- a/backend/crates/station/src/websocket/broker.rs +++ b/backend/crates/station/src/websocket/broker.rs @@ -1,4 +1,7 @@ //! Publishes current state and forwards messages and protection events. +//! +//! Each `watch` topic holds a complete snapshot and may coalesce intermediate +//! updates. Each event topic has its own bounded `broadcast` backlog for live subscribers. use std::time::Duration; @@ -38,6 +41,7 @@ pub struct Broker { } /// Clonable access to publication and subscriptions. +/// A successful publish means the update entered the broker's input queue. #[derive(Debug, Clone)] pub struct BrokerClient { updates: mpsc::Sender, @@ -45,6 +49,7 @@ pub struct BrokerClient { state_orders: watch::Receiver, logger: watch::Receiver, data: watch::Receiver, + // Weak handles let event channels close when the broker exits. messages: broadcast::WeakSender, protections: broadcast::WeakSender, } @@ -83,10 +88,12 @@ impl Broker { ) } - /// Processes updates until all publishing clients have been dropped. + /// Processes updates as they arrive. After the last client drops, drains the input + /// queue and flushes any pending telemetry before exiting. pub async fn run(mut self) { let period = Duration::from_millis(100); let mut tick = interval_at(Instant::now() + period, period); + // Skip catch-up ticks and keep only the latest packet per ID in each batch. tick.set_missed_tick_behavior(MissedTickBehavior::Skip); let mut pending = DataUpdate::new(); loop { @@ -99,6 +106,7 @@ impl Broker { Some(Update::StateOrders(orders)) => { self.state_orders.send_replace(orders); } Some(Update::Logger(recording)) => { self.logger.send_replace(recording); } Some(Update::Data(packet)) => { pending.insert(packet.id.0, packet); } + // Zero subscribers is normal for a live event. Some(Update::Message(message)) => { let _ = self.messages.send(message); } Some(Update::Protection(protection)) => { let _ = self.protections.send(protection); } None => { @@ -114,6 +122,7 @@ impl Broker { fn flush_data(&self, pending: &mut DataUpdate) { if !pending.is_empty() { + // Preserve the last value for packets that were quiet during this batch. self.data.send_modify(|state| state.extend(pending.drain())); } } @@ -193,6 +202,7 @@ impl BrokerClient { fn subscribe(state: &watch::Receiver) -> watch::Receiver { let mut receiver = state.clone(); + // Callers read the initial snapshot directly. `changed()` then waits for a newer one. receiver.borrow_and_update(); receiver } diff --git a/backend/crates/station/src/websocket/error.rs b/backend/crates/station/src/websocket/error.rs index bfe127d9b..15b4889c8 100644 --- a/backend/crates/station/src/websocket/error.rs +++ b/backend/crates/station/src/websocket/error.rs @@ -6,16 +6,16 @@ pub enum Error { /// The broker no longer accepts updates. #[error("WebSocket broker is closed")] BrokerClosed, - /// The socket writer fell behind the subscription requests. + /// The session ends when the writer can no longer keep up with subscription changes. #[error("WebSocket subscription queue is full")] SubscriptionQueueFull, - /// The client fell behind on an event topic. + /// The event buffer overwrote unread events. The session logs the loss and closes. #[error("WebSocket subscriber missed {missed} events on {topic}")] EventLagged { topic: &'static str, missed: u64 }, /// Reading or writing the socket failed. #[error("WebSocket I/O failed: {0}")] Socket(#[from] axum::Error), - /// The message or its payload could not be converted to JSON models. + /// A WebSocket message or payload failed JSON encoding or decoding. #[error("invalid WebSocket JSON: {0}")] Json(#[from] serde_json::Error), /// No valid application message arrived before the deadline. @@ -23,6 +23,7 @@ pub enum Error { HeartbeatTimeout, } +/// Rejections of individual order requests. The reader logs these and keeps the session open. #[derive(Debug, thiserror::Error)] pub(super) enum OrderError { #[error("invalid order payload: {0}")] @@ -45,3 +46,14 @@ pub(super) enum OrderError { #[error("vehicle order receiver is unavailable")] VehicleUnavailable, } + +/// Rejections of individual logger requests. The reader logs these and keeps the session open. +#[derive(Debug, thiserror::Error)] +pub(super) enum LoggerError { + #[error("invalid logger payload: {0}")] + Json(#[from] serde_json::Error), + #[error("logger command queue is full")] + QueueFull, + #[error("logger command receiver is unavailable")] + Unavailable, +} diff --git a/backend/crates/station/src/websocket/handler.rs b/backend/crates/station/src/websocket/handler.rs index aca901803..f39e2bdd8 100644 --- a/backend/crates/station/src/websocket/handler.rs +++ b/backend/crates/station/src/websocket/handler.rs @@ -4,20 +4,22 @@ use axum::extract::ws::WebSocket; use futures_util::{SinkExt, StreamExt}; use tokio::{sync::mpsc, time::timeout}; -use super::{OrderForwarder, broker::BrokerClient, error::Error, receiver, sender}; +use super::{Commands, broker::BrokerClient, error::Error, receiver, sender}; -/// Runs reading and writing together; either side finishing ends the session. +/// Runs reading and writing concurrently. The first side to finish ends the session. pub(super) async fn handle( socket: WebSocket, broker: BrokerClient, - orders: Option<&OrderForwarder>, + commands: &Commands, + heartbeat_timeout: Duration ) -> Result<(), Error> { let (mut write, read) = socket.split(); let (changes, subscriptions) = mpsc::channel(16); let result = tokio::select! { - result = receiver::run(read, &broker, orders, changes) => result, + result = receiver::run(read, &broker, commands, changes, heartbeat_timeout) => result, result = sender::run(&mut write, subscriptions) => result, }; + // Bound the socket close and preserve the result that ended the session. let _ = timeout(Duration::from_secs(1), write.close()).await; result } diff --git a/backend/crates/station/src/websocket/order.rs b/backend/crates/station/src/websocket/order.rs index 7cc3655a4..c01f2c613 100644 --- a/backend/crates/station/src/websocket/order.rs +++ b/backend/crates/station/src/websocket/order.rs @@ -31,6 +31,7 @@ impl OrderForwarder { } } +/// Resolves aliases and emits values in the ADJ's wire order. fn to_packet(mut request: OrderSend, index: &Index) -> Result { let Some(PacketType::Order(measurements)) = index.packet(request.id).map(|packet| &packet.packet_type) @@ -47,6 +48,7 @@ fn to_packet(mut request: OrderSend, index: &Index) -> Result Option { let JsonValue::Number(raw) = value else { return None; @@ -108,6 +112,7 @@ fn number(value: &JsonValue, kind: NumericKind) -> Option { return None; } } else if number.fract() != 0.0 || number.abs() >= (1_u64 << 53) as f64 { + // Float-form integers must stay within the range where adjacent integers remain distinct. return None; } // The 64-bit upper bounds round up when represented as f64. diff --git a/backend/crates/station/src/websocket/payload.rs b/backend/crates/station/src/websocket/payload.rs index 4f840cb68..edcb33277 100644 --- a/backend/crates/station/src/websocket/payload.rs +++ b/backend/crates/station/src/websocket/payload.rs @@ -1,8 +1,8 @@ -//! JSON payloads for frontend WebSocket topics (feature `websocket`). +//! JSON payloads for station's frontend topics. //! -//! Existing topics preserve the Go backend's JSON shapes; `protection/update` -//! adds a compact event. Socket handling, subscriptions and publication belong -//! to `station`. See `websocket/README.md`. +//! Each model describes the `payload` inside a `{topic, payload}` message. +//! Serde adapters define the frontend JSON representation for shared domain types. +//! See `websocket/payload/README.md` for the wire shapes and examples. mod connection; mod data; diff --git a/backend/crates/station/src/websocket/payload/connection.rs b/backend/crates/station/src/websocket/payload/connection.rs index 4fbe97955..93ca602c2 100644 --- a/backend/crates/station/src/websocket/payload/connection.rs +++ b/backend/crates/station/src/websocket/payload/connection.rs @@ -2,6 +2,7 @@ use serde::Serialize; use std::collections::HashMap; /// Payload of `connection/update`, keyed by board name. +/// Boards remain in the snapshot with `isConnected: false` after a disconnect. pub type ConnectionUpdate = HashMap; /// Whether a board is connected to the backend. diff --git a/backend/crates/station/src/websocket/payload/data.rs b/backend/crates/station/src/websocket/payload/data.rs index 702081784..c410a1469 100644 --- a/backend/crates/station/src/websocket/payload/data.rs +++ b/backend/crates/station/src/websocket/payload/data.rs @@ -3,7 +3,7 @@ use serde::Serialize; use software_core::model::AdjId; use std::collections::HashMap; -/// Payload of `podData/update`, keyed by packet id (JSON object keys are strings). +/// Latest telemetry per packet for `podData/update`. Packet IDs are JSON object keys. pub type DataUpdate = HashMap; /// Current telemetry and statistics for one packet. @@ -23,7 +23,7 @@ pub struct DataPacketUpdate { pub measurement_updates: HashMap, } -/// A number carries statistics; booleans and enums are JSON primitives. +/// Numeric measurements carry statistics. Booleans and enum names use JSON primitives. #[derive(Debug, Clone, PartialEq, Serialize)] #[serde(untagged)] pub enum MeasurementUpdate { diff --git a/backend/crates/station/src/websocket/payload/message.rs b/backend/crates/station/src/websocket/payload/message.rs index deee233e8..8cb6496c8 100644 --- a/backend/crates/station/src/websocket/payload/message.rs +++ b/backend/crates/station/src/websocket/payload/message.rs @@ -63,13 +63,13 @@ impl From for MessageKind { } } -/// Legacy RTC timestamp used by the frontend's event display. +/// Calendar timestamp used by the frontend's event display. /// -/// This is not `ShortTimestamp`: the latter has no date and its subsecond unit -/// is unresolved. Event construction must supply the date and counter explicitly. +/// The event publisher supplies the date and RTC counter. The board's +/// `ShortTimestamp` contains the time of day and a raw subsecond byte. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] pub struct MessageTimestamp { - /// RTC counter; kept separate from `ShortTimestamp::subsecond`. + /// RTC counter supplied by the publisher. pub counter: u16, /// Second of the minute. pub second: u8, diff --git a/backend/crates/station/src/websocket/payload/order.rs b/backend/crates/station/src/websocket/payload/order.rs index ed6453df1..c40dbd6ea 100644 --- a/backend/crates/station/src/websocket/payload/order.rs +++ b/backend/crates/station/src/websocket/payload/order.rs @@ -3,23 +3,22 @@ use serde::Deserialize; use software_core::model::AdjId; use std::collections::HashMap; -/// Payload of `order/send`; conversion to an `OrderPacket` requires the ADJ. +/// Payload of `order/send`. The ADJ defines how to convert it to an `OrderPacket`. #[derive(Debug, Clone, PartialEq, Deserialize)] pub struct OrderSend { /// Requested order's ADJ id. #[serde(deserialize_with = "deserialize_adj_id")] pub id: AdjId, - /// Parameters keyed by their textual aliases, rather than wire position. + /// Parameters keyed by their ADJ aliases. The converter puts them in wire order. pub fields: HashMap, } /// One parameter supplied by the frontend. #[derive(Debug, Clone, PartialEq, Deserialize)] pub struct OrderField { - /// Raw JSON value; its type and range must be checked against the ADJ. - /// Keeping it raw also preserves integer precision before validation. + /// Raw JSON value retained so integer precision can be checked before conversion to `f64`. pub value: serde_json::Value, - /// Legacy type name, such as `uint16`, `float32`, `bool` or `enum`. + /// Frontend type name, such as `uint16` or `bool`. The converter checks it against the ADJ. #[serde(rename = "type")] pub field_type: String, } diff --git a/backend/crates/station/src/websocket/payload/protection.rs b/backend/crates/station/src/websocket/payload/protection.rs index 42e9e9496..d6eb1bd47 100644 --- a/backend/crates/station/src/websocket/payload/protection.rs +++ b/backend/crates/station/src/websocket/payload/protection.rs @@ -7,13 +7,13 @@ use software_core::model::{AdjId, ProtectionPacket, ShortTimestamp, Value}; /// Payload of `protection/update`: the triggered id, measured value and time. #[derive(Debug, Clone, PartialEq, Serialize)] pub struct ProtectionUpdate { - /// Compound protection id; its definition is available in the ADJ catalog. + /// Compound ID used to look up the protection definition in the ADJ catalog. #[serde(serialize_with = "serialize_adj_id")] pub id: AdjId, /// Value that triggered the protection, serialized as a JSON primitive. #[serde(serialize_with = "serialize_value")] pub value: Value, - /// Time received from the board, preserving the raw subsecond byte. + /// Time of day supplied by the board, with its original subsecond byte. #[serde(with = "ShortTimestampJson")] pub timestamp: ShortTimestamp, } @@ -28,6 +28,7 @@ impl From for ProtectionUpdate { } } +// Defines the frontend timestamp fields locally via Serde's remote derive. #[derive(Serialize)] #[serde(remote = "ShortTimestamp")] struct ShortTimestampJson { diff --git a/backend/crates/station/src/websocket/payload/serialize.rs b/backend/crates/station/src/websocket/payload/serialize.rs index 2d26e35ee..395f31bc4 100644 --- a/backend/crates/station/src/websocket/payload/serialize.rs +++ b/backend/crates/station/src/websocket/payload/serialize.rs @@ -1,7 +1,7 @@ use serde::{Deserialize, Deserializer, Serializer}; use software_core::model::{AdjId, Value}; -// Serializes the value of a protection message +/// Emits a scalar JSON value for a protection event. Enums use the variant name. pub(super) fn serialize_value( value: &Value, serializer: S, @@ -13,13 +13,14 @@ pub(super) fn serialize_value( } } -// Deserializer works the other way around as Serializer +/// Reads an ADJ ID from an unsigned 16-bit JSON integer. pub(super) fn deserialize_adj_id<'de, D: Deserializer<'de>>( deserializer: D, ) -> Result { u16::deserialize(deserializer).map(AdjId) } +/// Writes an ADJ ID as a JSON integer. pub(super) fn serialize_adj_id( id: &AdjId, serializer: S, diff --git a/backend/crates/station/src/websocket/receiver.rs b/backend/crates/station/src/websocket/receiver.rs index e9d16adeb..23bc28965 100644 --- a/backend/crates/station/src/websocket/receiver.rs +++ b/backend/crates/station/src/websocket/receiver.rs @@ -8,23 +8,23 @@ use tokio::{ }; use super::{ - HEARTBEAT, ORDER_SEND, OrderForwarder, Topic, WsMessage, + Commands, HEARTBEAT, LOGGER_ENABLE, LOGGER_VARIABLES, LoggerCommand, ORDER_SEND, Topic, + WsMessage, broker::BrokerClient, - error::{Error, OrderError}, + error::{Error, LoggerError, OrderError}, payload::{ ConnectionUpdate, DataUpdate, LoggerResponse, MessageUpdate, ProtectionUpdate, StateOrdersUpdate, }, }; -const HEARTBEAT_TIMEOUT: Duration = Duration::from_secs(3); - #[derive(Deserialize)] struct Subscription { + /// An empty object also opts in. `false` unsubscribes. subscribe: Option, } -/// Carries a new topic receiver, or `None` to unsubscribe. +/// Hands the writer an already-open topic receiver, or `None` to unsubscribe. #[derive(Debug)] pub(super) enum SubscriptionChange { Connections(Option>), @@ -58,15 +58,17 @@ impl SubscriptionChange { } } -/// Handles frontend requests and renews the deadline on each valid JSON message. +/// Routes frontend requests and tracks application-level liveness. pub(super) async fn run( mut read: impl Stream> + Unpin, broker: &BrokerClient, - orders: Option<&OrderForwarder>, + commands: &Commands, changes: mpsc::Sender, + heartbeat_timeout: Duration, ) -> Result<(), Error> { let mut subscriptions = HashSet::new(); - let mut deadline = Instant::now() + HEARTBEAT_TIMEOUT; + // Keep one deadline across frames. Only decoded application messages renew it. + let mut deadline = Instant::now() + heartbeat_timeout; loop { let frame = timeout_at(deadline, read.next()) .await @@ -77,16 +79,26 @@ pub(super) async fn run( match frame? { Frame::Text(text) => { let message: WsMessage = serde_json::from_str(&text)?; + // Nonblocking command queues keep heartbeat processing responsive. if message.topic == ORDER_SEND { - let result = orders + let result = commands + .orders + .as_ref() .ok_or(OrderError::VehicleUnavailable) .and_then(|orders| orders.forward(message.payload)); if let Err(error) = result { tracing::warn!(topic = ORDER_SEND, %error, "order rejected"); } + } else if matches!(message.topic.as_str(), LOGGER_ENABLE | LOGGER_VARIABLES) { + if let Err(error) = + forward_logger(commands.logger.as_ref(), &message.topic, message.payload) + { + tracing::warn!(topic = %message.topic, %error, "logger request rejected"); + } } else if let Some(topic) = Topic::from_name(&message.topic) { let request: Subscription = serde_json::from_value(message.payload)?; let enabled = request.subscribe.unwrap_or(true); + // Repeated requests keep the existing subscription and its cursor. let changed = if enabled { subscriptions.insert(topic) } else { @@ -106,7 +118,7 @@ pub(super) async fn run( } else if message.topic != HEARTBEAT { tracing::warn!(topic = %message.topic, "unsupported WebSocket topic"); } - deadline = Instant::now() + HEARTBEAT_TIMEOUT; + deadline = Instant::now() + heartbeat_timeout; } Frame::Close(_) => return Ok(()), _ => {} @@ -114,6 +126,25 @@ pub(super) async fn run( } } +fn forward_logger( + logger: Option<&mpsc::Sender>, + topic: &str, + payload: serde_json::Value, +) -> Result<(), LoggerError> { + let command = if topic == LOGGER_ENABLE { + LoggerCommand::Enable(serde_json::from_value(payload)?) + } else { + LoggerCommand::Variables(serde_json::from_value(payload)?) + }; + logger + .ok_or(LoggerError::Unavailable)? + .try_send(command) + .map_err(|error| match error { + mpsc::error::TrySendError::Full(_) => LoggerError::QueueFull, + mpsc::error::TrySendError::Closed(_) => LoggerError::Unavailable, + }) +} + #[cfg(test)] mod tests { use futures_util::stream; @@ -122,12 +153,21 @@ mod tests { use super::*; use crate::websocket::broker::Broker; + const HEARTBEAT_TIMEOUT: Duration = Duration::from_secs(3); + #[tokio::test(start_paused = true)] async fn inactivity_expires() { let (_broker, client) = Broker::new(); let (changes, _subscriptions) = mpsc::channel(1); assert!(matches!( - run(stream::pending(), &client, None, changes).await, + run( + stream::pending(), + &client, + &Commands::default(), + changes, + HEARTBEAT_TIMEOUT + ) + .await, Err(Error::HeartbeatTimeout) )); } @@ -139,7 +179,16 @@ mod tests { let read = stream::poll_fn(move |cx| frames.poll_recv(cx)); let (_broker, client) = Broker::new(); let (changes, mut subscriptions) = mpsc::channel(1); - let worker = tokio::spawn(async move { run(read, &client, None, changes).await }); + let worker = tokio::spawn(async move { + run( + read, + &client, + &Commands::default(), + changes, + HEARTBEAT_TIMEOUT, + ) + .await + }); tokio::task::yield_now().await; advance(Duration::from_secs(2)).await; @@ -169,7 +218,14 @@ mod tests { )), Ok(Frame::Close(None)), ]); - run(frames, &client, None, changes).await?; + run( + frames, + &client, + &Commands::default(), + changes, + HEARTBEAT_TIMEOUT, + ) + .await?; assert!(subscriptions.recv().await.is_none()); Ok(()) } @@ -187,7 +243,14 @@ mod tests { )), Ok(Frame::Close(None)), ]); - run(frames, &client, None, changes).await?; + run( + frames, + &client, + &Commands::default(), + changes, + HEARTBEAT_TIMEOUT, + ) + .await?; assert!(matches!( subscriptions.recv().await, Some(SubscriptionChange::Connections(Some(_))) @@ -222,7 +285,14 @@ mod tests { )), Ok(Frame::Close(None)), ]); - run(frames, &client, None, changes).await?; + run( + frames, + &client, + &Commands::default(), + changes, + HEARTBEAT_TIMEOUT, + ) + .await?; assert!(matches!( subscriptions.recv().await, Some(SubscriptionChange::Messages(Some(_))) diff --git a/backend/crates/station/src/websocket/sender.rs b/backend/crates/station/src/websocket/sender.rs index a537641a3..cbccbe07e 100644 --- a/backend/crates/station/src/websocket/sender.rs +++ b/backend/crates/station/src/websocket/sender.rs @@ -16,6 +16,7 @@ pub(super) async fn run( let (mut messages, mut protections) = (None, None); loop { let frame = tokio::select! { + // Apply subscription changes first, then give ready protection events priority. biased; change = subscriptions.recv() => { let Some(change) = change else { return Ok(()); }; @@ -41,6 +42,7 @@ pub(super) async fn run( } } +/// Installs a subscription and builds its initial snapshot, or drops it on unsubscribe. fn subscribe_state( topic: Topic, state: &mut Option>, @@ -58,6 +60,7 @@ async fn next_state( state: &mut Option>, ) -> Result { let Some(state) = state else { + // A disabled topic stays idle while select polls other branches. return pending().await; }; state.changed().await.map_err(|_| Error::BrokerClosed)?; @@ -65,6 +68,7 @@ async fn next_state( } fn state_frame(topic: Topic, state: &mut watch::Receiver) -> Result { + // Build an owned frame so the watch borrow ends before the socket write awaits. encode(topic, &*state.borrow_and_update()) } From be9130a05ae68a0312242525db22df977acfd4cb Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Wed, 25 Nov 2026 02:22:44 +0100 Subject: [PATCH 154/225] docs(backend, websocket): add websocket README and update payload one --- .../crates/station/src/websocket/README.md | 80 +++++++++++++++++++ .../station/src/websocket/payload/README.md | 8 +- 2 files changed, 85 insertions(+), 3 deletions(-) create mode 100644 backend/crates/station/src/websocket/README.md diff --git a/backend/crates/station/src/websocket/README.md b/backend/crates/station/src/websocket/README.md new file mode 100644 index 000000000..07d7c75f3 --- /dev/null +++ b/backend/crates/station/src/websocket/README.md @@ -0,0 +1,80 @@ +# WebSocket + +`broker.rs` provides `Broker` and the clonable `BrokerClient` for state and event topics, +using the types from `crate::websocket::payload`. +See the [payload models README](payload/README.md) for all topic payloads, +JSON templates, and complete message examples. Their serialization helpers +live in [`payload/serialize.rs`](payload/serialize.rs). + +| Topic | Publish through `BrokerClient` | Subscribe through `BrokerClient` | Initial state | +| --- | --- | --- | --- | +| `connection/update` | `publish_connection(connection)` | `subscribe_connections()` | `{}` | +| `order/stateOrders` | `publish_state_orders(orders)` | `subscribe_state_orders()` | `{}` | +| `logger/response` | `publish_logger(recording)` | `subscribe_logger()` | `false` | +| `podData/update` | `publish_data(packet)` | `subscribe_data()` | `{}` | +| `message/update` | `publish_message(message)` | `subscribe_messages()` | No initial event | +| `protection/update` | `publish_protection(protection)` | `subscribe_protections()` | No initial event | + +- `Broker::new()` creates both objects and the initial topic states. +- `Broker::run()` consumes a bounded `mpsc` channel of typed updates and + publishes state through `watch` and events through `broadcast`. It stops after all + `BrokerClient` instances are dropped and pending updates have been processed. +- Publication waits for capacity and returns `Error::BrokerClosed` if the + broker closed. Connection updates merge one board into the current map; + order updates replace the entire map, including empty lists or an empty map. +- State subscriptions return a `watch` receiver. Read the initial state with + `borrow_and_update()`, then await `changed()` and read again. Intermediate + changes may be coalesced; each value contains the complete current state. +- Each event topic has a separate `broadcast` buffer of 128 events. A + subscription starts with the next event. If a receiver reports `Lagged`, + the socket task logs the topic and number of missed events and closes that + session. + +`logger/enable` and `logger/variables` queue `LoggerCommand::Enable(bool)` and +`LoggerCommand::Variables(Vec)` for the logger. Both use the same +bounded `mpsc` queue. Invalid payloads and requests that cannot be queued are +logged, and the WebSocket session stays open. The logger reports its applied +state through `BrokerClient::publish_logger`, which feeds `logger/response`. + +`publish_data` accepts a complete, prepared `DataPacketUpdate`. The broker +buffers the latest update per packet id and merges it into the published +telemetry map every 100 ms when changes exist. Unchanged packets remain in +that map; repeated updates for one id within a batch are coalesced. Idle ticks +do not publish, and missed ticks are skipped rather than sent in a burst. +Pending telemetry is flushed when the broker finishes processing its input. +The publisher supplies packet counts, cycle times, measurement values and +averages; the broker preserves them as received. + +The station binary currently runs a greeting demo. To expose `/backend/ws`, +bind a listener and call `http::serve` with the sender of a bounded socket +channel. Start `Broker::run` and pass the channel receiver, a `BrokerClient`, +the command destinations, and a heartbeat timeout to `websocket::run`. +Each socket has independent reading and writing futures, coordinated by +`handler.rs`. Either future finishing closes the session. + +Connect to `/backend/ws` on the listener's address and port and send this +message to subscribe to `connection/update`. + +```json +{"topic":"connection/update","payload":{"subscribe":true}} +``` + +The same subscription format applies to all topics in the table. The sender +publishes the current state immediately for `watch` topics, then complete +updates. For event topics it sends events published after subscribing. +An empty payload `{}` also subscribes. Set `subscribe` to `false` to stop +receiving a topic. Duplicate requests to subscribe or unsubscribe are +idempotent. The receiver opens each topic subscription and passes it to the +socket writer through a bounded `mpsc` queue. A full queue closes that session. + +`receiver.rs` consumes `connection/heartbeat` without publishing a response. +It uses `timeout_at` with the caller's heartbeat timeout. Each valid JSON +application message renews the deadline. WebSocket ping/pong frames do not renew it. +Unknown topics are logged and ignored while their handlers are implemented. + +`sender.rs` releases each watch borrow before awaiting socket I/O. + +`order/send` checks parameter aliases, types and wire ranges against the ADJ. +It arranges values in ADJ order and queues the resulting `OrderPacket` for +the vehicle module. Rejected requests, including a full or closed order queue, +are logged and the WebSocket session stays open. diff --git a/backend/crates/station/src/websocket/payload/README.md b/backend/crates/station/src/websocket/payload/README.md index b57f3bba4..acb5d8a70 100644 --- a/backend/crates/station/src/websocket/payload/README.md +++ b/backend/crates/station/src/websocket/payload/README.md @@ -130,9 +130,11 @@ backend and the board. } ``` -An order without parameters has `fields: {}`. Parameter names are aliases; -the application uses the ADJ to place their values in wire order. The `value` -field remains raw JSON until validation, preserving integer precision. +An order without parameters has `fields: {}`. Parameter names are aliases. +The application uses the ADJ to place their values in wire order. The `value` +field remains raw JSON until validation. Integer fields must contain whole +numbers that fit both the wire type and the packet's `f64` representation. +Enum fields use the option name from the ADJ. Numeric `type` names are `"uint8"`, `"uint16"`, `"uint32"`, `"uint64"`, `"int8"`, `"int16"`, `"int32"`, `"int64"`, `"float32"` and `"float64"`. From a8e949552392e3f7db7c9a1fa84148dd57f1e268 Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Wed, 25 Nov 2026 17:27:52 +0100 Subject: [PATCH 155/225] feat(backend, websocket): add lib.rs to station --- backend/crates/core/src/utils/serialize.rs | 2 - backend/crates/station/README.md | 12 +- backend/crates/station/src/http/README.md | 122 ++++-------------- backend/crates/station/src/lib.rs | 3 + backend/crates/station/src/main.rs | 3 - backend/crates/station/src/websocket.rs | 4 +- .../crates/station/src/websocket/README.md | 12 +- .../crates/station/src/websocket/payload.rs | 4 +- .../station/src/websocket/payload/README.md | 3 +- 9 files changed, 46 insertions(+), 119 deletions(-) create mode 100644 backend/crates/station/src/lib.rs diff --git a/backend/crates/core/src/utils/serialize.rs b/backend/crates/core/src/utils/serialize.rs index 62c544ae8..cb61543b9 100644 --- a/backend/crates/core/src/utils/serialize.rs +++ b/backend/crates/core/src/utils/serialize.rs @@ -1,6 +1,4 @@ -use crate::model::Value; use crate::model::{AdjId, BoardId, NumericKind, ProtectionKind, Severity}; -use serde::{Deserialize, Deserializer}; use serde::{Serialize, Serializer}; #[cfg(feature = "http")] diff --git a/backend/crates/station/README.md b/backend/crates/station/README.md index 00e8661df..e0faef483 100644 --- a/backend/crates/station/README.md +++ b/backend/crates/station/README.md @@ -4,14 +4,16 @@ El backend de la Control Station de Hyperloop UPV: escucha a las placas del pod, decodifica sus paquetes, los reenvía a los frontends y guarda un registro en disco. Construido sobre [`software-core`](../core/README.md). -Ver [`../../ARCHITECTURE.md`](../../ARCHITECTURE.md) para el diseño completo. +La librería ([`lib.rs`](src/lib.rs)) expone los módulos [HTTP](src/http/README.md) +y [WebSocket](src/websocket/README.md) como `station::http` y +`station::websocket`. -## Arrancar +## Ejecutar la demo ```sh -cargo run -p station -- --config ./dev-config.toml +cargo run -p station -- "Hyperloop UPV" ``` -*(Pendiente: crear `dev-config.toml` y `config.toml`, portados de -`backend_old/cmd/`.)* +El binario ([`main.rs`](src/main.rs)) ejecuta la [demo de saludo](../../readme-demo.md). +El arranque del backend y la carga de la configuración quedan pendientes. diff --git a/backend/crates/station/src/http/README.md b/backend/crates/station/src/http/README.md index 9c905dbd2..d72fbee9a 100644 --- a/backend/crates/station/src/http/README.md +++ b/backend/crates/station/src/http/README.md @@ -7,14 +7,12 @@ from the frontend. It does not load the ADJ or handle WebSocket messages. | File | Responsibility | | --- | --- | -| [`../http.rs`](../http.rs) | Module entry points, with or without a WebSocket consumer. | -| [`configure.rs`](configure.rs) | Provisional HTTP configuration, validation, server preparation, and configuration tests. | -| [`server.rs`](server.rs) | Router construction, server execution, and route/WebSocket tests. | +| [`../http.rs`](../http.rs) | Server entry point, with an optional WebSocket consumer. | +| [`server.rs`](server.rs) | Router construction and HTTP and WebSocket tests. | | [`handlers.rs`](handlers.rs) | Shared state, pre-serialized catalog responses, and WebSocket handoff. | -The response models and transformations from `Adj` belong to -[`software_core::adj`](../../../core/src/adj.rs). Their JSON examples are in -[`core/src/adj/http/example`](../../../core/src/adj/http/example). +The server builds catalog responses from the given `Adj`. The +[HTTP models README](../../../core/src/model/http/README.md) contains the JSON examples. ## Routes @@ -23,7 +21,7 @@ The response models and transformations from `Adj` belong to | GET | `/backend/adj/DataPackets` | Boards and data packet definitions, without measurement protections. | | GET | `/backend/adj/OrderPackets` | Boards and order definitions, including parameter protections. | | GET | `/backend/adj/ProtectionPackets` | Flat protection catalog and protection-type display metadata. | -| GET with WebSocket upgrade headers | `/backend` | Upgrades the connection and hands the socket to the configured channel. | +| GET with WebSocket upgrade headers | `/backend/ws` | Upgrades the connection and hands the socket to the configured channel. | Catalog responses return `200 OK` with `Content-Type: application/json`. @@ -39,33 +37,29 @@ Each request clones the relevant `Bytes` handle and sends the existing JSON buffer. It does not rebuild the catalog, copy the whole buffer, or serialize the response again. No application-level mutex is needed for these reads. -The catalogs are a snapshot of the ADJ at startup; they are not refreshed -automatically. Serialization errors are propagated before requests are served. -This in-memory reuse is separate from browser caching. `configure_server` -applies the configured `Cache-Control` policy to the catalog routes. The older -listener-based entry points do not set an explicit cache policy. +The catalogs represent the ADJ loaded at startup. Serialization errors are +returned before requests are served. The router sets `Cache-Control: no-cache` +and uses permissive CORS. ## Starting the server -The caller supplies a bound `tokio::net::TcpListener` and an already-loaded -`&Adj`. The listener determines the address and port. Both entry points are -async and run until the server stops. +The caller passes a bound `tokio::net::TcpListener` and an already-loaded +`&Adj` to `station::http::serve`. The listener determines the address and port. +The function runs until the server stops. -Without a WebSocket consumer: +Pass `None` to serve the catalogs by themselves. ```rust -http::serve(listener, &adj).await?; +station::http::serve(listener, &adj, None).await?; ``` -With a bounded `tokio::sync::mpsc::Sender` whose -receiver belongs to the future WebSocket module: +To enable WebSocket upgrades, pass the sender of a bounded `tokio::sync::mpsc` +channel and give its receiver to [`station::websocket::run`](../websocket/README.md). ```rust -http::serve_with_websocket(listener, &adj, Some(sender)).await?; +station::http::serve(listener, &adj, Some(sender)).await?; ``` -Passing `None` to `serve_with_websocket` has the same behavior as `serve`. - ## WebSocket handoff The HTTP handler only performs the handshake and transfers ownership of the @@ -80,87 +74,17 @@ Before approving an upgrade, it reserves a slot in the bounded channel: capacity, it returns `503 Service Unavailable` instead of upgrading. - Invalid upgrade requests are rejected by Axum's `WebSocketUpgrade` extractor. -The future WebSocket module must consume the receiver and manage each socket's -lifetime, messages, and closure. Keeping a receiver alive without reading it -does not provide a functioning WebSocket service; the queue will eventually -fill. If the receiver disappears during the handoff, the socket is dropped. - -## Configuration - -`HttpConfig` is defined provisionally in `configure.rs` and reexported by `http`. -It does not depend on the future application configuration module or read files -and environment variables. - -| Field | Purpose | -| --- | --- | -| `bind_addr` | Explicit IP address and port to bind; port zero requests an available port. | -| `allowed_origins` | Exact HTTP(S) origins allowed by CORS; an empty list allows none. | -| `cache_policy` | Catalog policy: `NoStore`, `NoCache`, or `Unspecified`. | - -`HttpConfig::new(bind_addr)` uses no allowed CORS origins and defaults to -`CachePolicy::NoStore` (`Cache-Control: no-store`). `NoCache` allows storage -but requires revalidation before reuse; `Unspecified` sets no Cache-Control -header. These policies do not affect the server's reusable JSON buffers and -are not applied to WebSocket upgrades. - -The configuration path prepares the server without starting it: - -```rust -let mut config = http::HttpConfig::new("127.0.0.1:8080".parse()?); -config.allowed_origins = vec!["http://localhost:9000".into()]; - -let (listener, router) = http::configure_server(&config, &adj, None).await?; -axum::serve(listener, router).await?; -``` - -`configure_server` validates origins and serializes the catalogs before binding -the listener. Invalid settings and binding errors are returned to the caller; -there is no fallback to another address or port. To enable socket handoff, -replace `None` with `Some(sender)` as described above. - -CORS permits GET and HEAD from explicitly listed origins, handles preflight -requests, and does not enable credentials. Wildcards and origin URLs with -embedded credentials, paths (including a trailing slash), queries, fragments, -or invalid ports are rejected. The opaque origin `null` can be explicitly -listed for local-file clients, but it is not exclusive to Electron: other -opaque origins share it too. - -CORS controls browser access to responses; it is not HTTP authentication. -WebSocket Origin validation is still not implemented and is independent of -CORS. The existing `serve` and `serve_with_websocket` entry points remain -available for the current test startup and do not apply `HttpConfig` policies. - -## Manual checks - -From the backend workspace root, the current `main.rs` test startup can be run -with: - -```sh -cargo run -p station --locked -``` - -It currently loads the ADJ fixture and listens on `127.0.0.1:8080`. These are -temporary test settings, not configuration defaults. It uses `http::serve`, so -valid WebSocket upgrade requests receive `503` until a consumer is integrated. - -In another terminal: - -```sh -curl -i http://127.0.0.1:8080/backend/adj/DataPackets -curl -i http://127.0.0.1:8080/backend/adj/OrderPackets -curl -i http://127.0.0.1:8080/backend/adj/ProtectionPackets -``` +The WebSocket module consumes the receiver and manages each session. +If the receiver disappears during the handoff, the socket is dropped. ## Tests -From the backend workspace root: +Run the HTTP tests from the backend workspace root. ```sh -cargo test -p station http:: --locked +cargo test -p station --lib --locked http:: ``` -The tests cover catalog contents and repeated responses, empty catalogs, -configuration validation, binding errors, cache headers, CORS and preflight -handling, WebSocket upgrade and socket delivery over a real TCP connection, -unavailable channels (missing, closed, or full), and requests without upgrade -headers. +The tests cover catalog responses, cache headers, CORS, and WebSocket upgrades +over TCP. The end-to-end test checks that a protection event reaches the client +and a validated order reaches the vehicle queue. diff --git a/backend/crates/station/src/lib.rs b/backend/crates/station/src/lib.rs new file mode 100644 index 000000000..bcc30f85f --- /dev/null +++ b/backend/crates/station/src/lib.rs @@ -0,0 +1,3 @@ +pub mod http; +mod vehicle; +pub mod websocket; diff --git a/backend/crates/station/src/main.rs b/backend/crates/station/src/main.rs index 9fa834996..f7c37dc45 100644 --- a/backend/crates/station/src/main.rs +++ b/backend/crates/station/src/main.rs @@ -12,6 +12,3 @@ fn main() { tracing::info!("demo finalizada"); } -mod http; -mod vehicle; -mod websocket; diff --git a/backend/crates/station/src/websocket.rs b/backend/crates/station/src/websocket.rs index c98c72854..ba4b2cc57 100644 --- a/backend/crates/station/src/websocket.rs +++ b/backend/crates/station/src/websocket.rs @@ -41,7 +41,7 @@ pub(crate) enum LoggerCommand { /// Destinations for requests received over WebSocket. #[derive(Debug, Clone, Default)] -pub(crate) struct Commands { +pub struct Commands { /// Validates frontend orders before queuing them for the vehicle. pub(crate) orders: Option, /// Queues recording and variable selection requests for the logger. @@ -95,7 +95,7 @@ pub struct WsMessage { /// Runs one task per upgraded socket so a slow client stays isolated. /// Closing the HTTP handoff channel ends socket intake. Existing sessions end independently. -pub(crate) async fn run( +pub async fn run( mut connections: mpsc::Receiver, broker: BrokerClient, commands: Commands, diff --git a/backend/crates/station/src/websocket/README.md b/backend/crates/station/src/websocket/README.md index 07d7c75f3..acd385381 100644 --- a/backend/crates/station/src/websocket/README.md +++ b/backend/crates/station/src/websocket/README.md @@ -45,10 +45,14 @@ Pending telemetry is flushed when the broker finishes processing its input. The publisher supplies packet counts, cycle times, measurement values and averages; the broker preserves them as received. -The station binary currently runs a greeting demo. To expose `/backend/ws`, -bind a listener and call `http::serve` with the sender of a bounded socket -channel. Start `Broker::run` and pass the channel receiver, a `BrokerClient`, -the command destinations, and a heartbeat timeout to `websocket::run`. +The station binary currently runs a greeting demo. To expose `/backend/ws` +from a caller, bind a listener and pass it and the sender of a bounded socket +channel to `station::http::serve`. Create the broker and client with +`station::websocket::broker::Broker::new()` and start `broker.run()` as a Tokio task. +Pass the socket receiver, the `BrokerClient`, the command destinations, and a +heartbeat timeout to `station::websocket::run`. +`Commands::default()` leaves the order and logger destinations unset. + Each socket has independent reading and writing futures, coordinated by `handler.rs`. Either future finishing closes the session. diff --git a/backend/crates/station/src/websocket/payload.rs b/backend/crates/station/src/websocket/payload.rs index edcb33277..a2f6d5069 100644 --- a/backend/crates/station/src/websocket/payload.rs +++ b/backend/crates/station/src/websocket/payload.rs @@ -12,8 +12,8 @@ mod protection; mod serialize; pub use connection::{Connection, ConnectionUpdate}; -pub use data::{DataPacketUpdate, DataUpdate, MeasurementUpdate}; -pub use message::{MessageKind, MessagePayload, MessageTimestamp, MessageUpdate}; +pub use data::{DataPacketUpdate, DataUpdate}; +pub use message::{MessageUpdate}; pub use order::{OrderField, OrderSend, StateOrdersUpdate}; pub use protection::{ProtectionPayload, ProtectionUpdate}; diff --git a/backend/crates/station/src/websocket/payload/README.md b/backend/crates/station/src/websocket/payload/README.md index acb5d8a70..f5f2b2a48 100644 --- a/backend/crates/station/src/websocket/payload/README.md +++ b/backend/crates/station/src/websocket/payload/README.md @@ -44,8 +44,7 @@ let payload_json = serde_json::to_string(&protection)?; Published structures implement `serde::Serialize`; `OrderSend` and `OrderField` implement `serde::Deserialize`. The logger aliases use the primitive types' -Serde implementations. All payload types are re-exported from -`crate::websocket::payload` within station. +Serde implementations. The payload module is internal to the station library. Deserializing an order checks its JSON structure. Parameter types, ranges and their correspondence with the ADJ must be validated by the application before From a1faca9553874b547b54deeb451bc6e919e5b9c0 Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Wed, 25 Nov 2026 19:48:03 +0100 Subject: [PATCH 156/225] wip: event --- backend/crates/station/src/event.rs | 715 ++++++++++++++++++ backend/crates/station/src/event/README.md | 539 +++++++++++++ backend/crates/station/src/event/fault.rs | 77 ++ .../crates/station/src/event/manual_tests.rs | 88 +++ backend/crates/station/src/event/orders.rs | 65 ++ backend/crates/station/src/event/policy.rs | 238 ++++++ backend/crates/station/src/event/tests.rs | 499 ++++++++++++ 7 files changed, 2221 insertions(+) create mode 100644 backend/crates/station/src/event.rs create mode 100644 backend/crates/station/src/event/README.md create mode 100644 backend/crates/station/src/event/fault.rs create mode 100644 backend/crates/station/src/event/manual_tests.rs create mode 100644 backend/crates/station/src/event/orders.rs create mode 100644 backend/crates/station/src/event/policy.rs create mode 100644 backend/crates/station/src/event/tests.rs diff --git a/backend/crates/station/src/event.rs b/backend/crates/station/src/event.rs new file mode 100644 index 000000000..e28a64d55 --- /dev/null +++ b/backend/crates/station/src/event.rs @@ -0,0 +1,715 @@ +//! The communication between station's modules. +//! +//! Every module runs in its own task and only talks to the others through +//! queues. This module prepares every one of those queues, in one call +//! ([`channels`]), and routes what goes through them ([`spawn`]): +//! +//! - **towards the front**, the routing loop takes what `net` reports and +//! every error, and hands it to `logging` and `pipeline`, reading errors +//! first, then TCP, then UDP; +//! - **towards the boards**, two workers write the front's orders and the +//! fault to TCP, so the routing loop never waits on a socket. +//! +//! The full design (the queues and their numbers, the error procedures, +//! how it stops, the contract with the other modules) is in +//! `event/README.md`; the numbers ①–⑧ below refer to its table. + +mod fault; +mod orders; +mod policy; + +#[cfg(test)] +mod manual_tests; +#[cfg(test)] +mod tests; + +pub use policy::full_message; + +use std::collections::{HashMap, HashSet}; +use std::future::Future; +use std::net::IpAddr; +use std::pin::Pin; +use std::sync::Arc; +use std::time::{Duration, SystemTime}; + +use software_core::model::{BoardId, OrderPacket, PodData}; +use software_core::net::{ErrorReport, Notification, Reporter, Sinks}; +use tokio::sync::{mpsc, oneshot}; +use tokio::task::{JoinHandle, JoinSet}; +use tracing::{debug, error, warn}; + +use self::fault::{FAULT_QUEUE, FaultRequest}; +use self::policy::Action; + +/// A batch of notifications, shared by `logging` and `pipeline` without +/// copying it: one allocation per batch, freed when both have let go of it. +pub type Batch = Arc<[Notification]>; + +/// A future that can be sent to another task, boxed so that [`TcpLink`] can +/// be used as a trait object. +pub type BoxFuture<'a, T> = Pin + Send + 'a>>; + +/// What `event` needs from the TCP client: writing an order to its board, +/// and sending the fault to every board. +/// +/// A trait rather than `net::tcp`'s own type so that the workers can be +/// tested against a fake, and so that `event` does not depend on the TCP +/// client's API beyond these two calls. +pub trait TcpLink: Send + Sync { + /// Writes `order` to the board it belongs to. + /// + /// Returns that board **once the order is written**, not once it is + /// queued; fails right away, with the reason, if the board is not + /// connected. + fn send(&self, order: OrderPacket) -> BoxFuture<'_, Result>; + + /// Sends the fault to every board. Fails with the boards it did not + /// reach. + fn send_fault(&self) -> BoxFuture<'_, Result<(), Vec>>; +} + +/// Sizes of every queue, and the two settings of the error rules. +/// +/// Every size is clamped to at least 1. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct EventConfig { + /// Most notifications taken out of ③ or ④ at once. + pub batch: usize, + /// Slots in each of `net`'s error queues (①, one per transport). + pub errors_queue: usize, + /// Slots in ② (problems from station modules). + pub problems_queue: usize, + /// Slots in ③ (TCP notifications). + pub tcp_queue: usize, + /// Slots in ④ (UDP notifications). The only stretch of queue between the + /// UDP socket and the routing loop, so the widest. + pub udp_queue: usize, + /// Slots in ⑤, counted in **batches**, not notifications. + pub logging_queue: usize, + /// Slots in ⑥, counted in **batches**, not notifications. + pub pipeline_queue: usize, + /// Slots in ⑦ (orders from the front). + pub orders_queue: usize, + /// Forward a board's fault to the other boards. + pub forward_board_faults: bool, + /// How long a fatal stop waits for the fault to be sent. + pub fault_timeout: Duration, +} + +impl Default for EventConfig { + // Default config + fn default() -> Self { + Self { + batch: 512, + errors_queue: 16, + problems_queue: 16, + tcp_queue: 1024, + udp_queue: 8192, + logging_queue: 64, + pipeline_queue: 64, + orders_queue: 32, + forward_board_faults: true, + fault_timeout: Duration::from_secs(2), + } + } +} + +/// Something the operator has to see. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Problem { + /// When it was detected. + pub at: SystemTime, + /// The board, if known. + pub board: Option, + /// What it means for the backend. + pub kind: ProblemKind, + /// The message with all its causes: "could not X: because Y: because Z" + /// (see [`full_message`]). + pub text: String, +} + +impl Problem { + /// A problem detected now. + pub fn now(kind: ProblemKind, board: Option, text: impl Into) -> Self { + Self { + at: SystemTime::now(), + board, + kind, + text: text.into(), + } + } +} + +/// What a [`Problem`] means for the backend. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ProblemKind { + /// Shown on the front; the backend keeps running. + Shown, + /// Shown on the front; the fault is sent and the backend stops. + Fatal, + /// Only written to the trace: not shown, the backend keeps running. + Silent, +} + +/// What `logging` receives (⑤). +#[derive(Debug)] +pub enum ToLogging { + /// A batch of notifications, TCP or UDP. + Received(Batch), + /// An order TCP confirmed it wrote. + OrderSent { + /// When the write was confirmed. + at: SystemTime, + /// The board it was written to. + board: BoardId, + /// The order. + order: OrderPacket, + }, +} + +/// What `pipeline` receives (⑥). +#[derive(Debug)] +pub enum ToPipeline { + /// A batch of notifications, TCP or UDP. + Received(Batch), + /// Something the operator has to see. + Problem(Problem), + /// An order that did not go out. + OrderFailed { + /// When it failed. + at: SystemTime, + /// The order. + order: OrderPacket, + /// Why. + reason: String, + }, +} + +/// Why `event` ended. `main` reads it and shuts everything down in order. +#[derive(Debug)] +pub enum Stop { + /// A fatal error: shown on the front, fault sent (or attempted). + Fatal(Problem), + /// `net`'s queues closed: UDP and TCP were stopped. + NetGone, +} + +/// The boards as `event` needs them: who an IP belongs to, and what each +/// board is called. Built once from the ADJ. +#[derive(Debug, Clone, Default)] +pub struct Boards { + by_ip: HashMap, + names: HashMap, +} + +impl Boards { + /// Reads every board's IP and name. + pub fn from_pod_data(pod_data: &PodData) -> Self { + let by_ip = pod_data + .boards + .values() + .map(|board| (board.ip, board.id)) + .collect(); + let names = pod_data + .boards + .values() + .map(|board| (board.id, board.name.clone())) + .collect(); + Self { by_ip, names } + } + + /// The board at `ip`, if any. + pub fn by_ip(&self, ip: IpAddr) -> Option { + self.by_ip.get(&ip).copied() + } + + /// The board's name, or its id if the ADJ does not declare it. + pub fn name(&self, board: BoardId) -> String { + self.names + .get(&board) + .cloned() + .unwrap_or_else(|| format!("{board:?}")) + } +} + +/// Every queue between modules, as [`channels`] hands them out. +#[derive(Debug)] +pub struct Channels { + /// For `net::udp`: reports on ① and ④. + pub udp: Reporter, + /// For `net::tcp`: reports on ① and ③. Drop it if TCP is not started. + pub tcp: Reporter, + /// `event`'s own ends, for [`spawn`]. + pub event: EventEnds, + /// ⑦, for websocket's order forwarder. + pub orders: mpsc::Sender, + /// ②, cloned for every station module that reports problems. + pub problems: mpsc::Sender, + /// ⑤, for `logging`. + pub logging: mpsc::Receiver, + /// ⑥, for `pipeline`. + pub pipeline: mpsc::Receiver, +} + +/// `event`'s own ends of the queues: the reading side of ① ② ③ ④ ⑦ and the +/// writing side of ⑤ ⑥. Only [`spawn`] opens it. +#[derive(Debug)] +pub struct EventEnds { + udp: Sinks, + tcp: Sinks, + problems: mpsc::Receiver, + orders: mpsc::Receiver, + logging: mpsc::Sender, + pipeline: mpsc::Sender, + /// Capacities of ③ and ④: how much a fatal stop drains at most. + tcp_capacity: usize, + udp_capacity: usize, +} + +/// Creates every queue between modules. `main` calls it once, before +/// spawning anything, and hands each end to whoever uses it. +/// +/// `net`'s queues are built with `net`'s own [`Reporter::channels`], once per +/// transport: TCP and UDP each get their own notification queue, so that TCP +/// can be read first, and their own error queue. +pub fn channels(config: &EventConfig) -> Channels { + let errors = config.errors_queue.max(1); + let tcp_capacity = config.tcp_queue.max(1); + let udp_capacity = config.udp_queue.max(1); + + let (udp, udp_sinks) = Reporter::channels(udp_capacity, errors); + let (tcp, tcp_sinks) = Reporter::channels(tcp_capacity, errors); + let (problems_tx, problems_rx) = mpsc::channel(config.problems_queue.max(1)); + let (orders_tx, orders_rx) = mpsc::channel(config.orders_queue.max(1)); + let (logging_tx, logging_rx) = mpsc::channel(config.logging_queue.max(1)); + let (pipeline_tx, pipeline_rx) = mpsc::channel(config.pipeline_queue.max(1)); + + Channels { + udp, + tcp, + event: EventEnds { + udp: udp_sinks, + tcp: tcp_sinks, + problems: problems_rx, + orders: orders_rx, + logging: logging_tx, + pipeline: pipeline_tx, + tcp_capacity, + udp_capacity, + }, + orders: orders_tx, + problems: problems_tx, + logging: logging_rx, + pipeline: pipeline_rx, + } +} + +/// Starts the routing loop and the two workers. +/// +/// Without a TCP client (`tcp: None`), every order fails with "TCP not +/// available" and the fault is only traced. +/// +/// The returned task ends with the reason it stopped, once the workers have +/// been stopped too: by then every sender of ⑤ and ⑥ is gone, so `logging` +/// and `pipeline` finish what they have queued and end on their own. +pub fn spawn( + config: EventConfig, + ends: EventEnds, + boards: Boards, + tcp: Option>, +) -> JoinHandle { + tokio::spawn(run(config, ends, boards, tcp)) +} + +async fn run( + config: EventConfig, + ends: EventEnds, + boards: Boards, + tcp: Option>, +) -> Stop { + let boards = Arc::new(boards); + let (fault_tx, fault_rx) = mpsc::channel(FAULT_QUEUE); + + let mut workers = JoinSet::new(); + workers.spawn(fault::run( + fault_rx, + tcp.clone(), + ends.pipeline.clone(), + boards.clone(), + )); + workers.spawn(orders::run( + ends.orders, + tcp, + fault_tx.clone(), + ends.logging.clone(), + ends.pipeline.clone(), + )); + + let batch = config.batch.max(1); + let router = Router { + config, + batch, + boards, + udp: ends.udp, + tcp: ends.tcp, + problems: ends.problems, + logging: ends.logging, + pipeline: ends.pipeline, + fault: fault_tx, + open: Open::default(), + tcp_batch: Vec::with_capacity(batch), + udp_batch: Vec::with_capacity(batch), + tcp_capacity: ends.tcp_capacity, + udp_capacity: ends.udp_capacity, + faults_shown: HashSet::new(), + }; + + // The router's senders are dropped when `route` returns; the workers' + // when they are stopped here. + let stop = router.route().await; + workers.shutdown().await; + stop +} + +/// Which transport a notification queue belongs to. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Transport { + Tcp, + Udp, +} + +/// A consumer of the routing loop that has stopped. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Consumer { + Logging, + Pipeline, +} + +/// Why the routing loop has to stop, before it does it. +#[derive(Debug)] +enum Halt { + Fatal(Problem), + Gone(Consumer), +} + +/// What one round of the `select!` got. +enum Step { + NetError(Transport, Option), + Problem(Option), + Notifications(Transport, usize), +} + +/// Which input queues are still open. A closed queue answers "closed" +/// instantly, every time, so it is no longer watched: in fixed order it would +/// win every round and hide the queues below it. +#[derive(Debug, Clone, Copy)] +struct Open { + udp_errors: bool, + tcp_errors: bool, + problems: bool, + tcp_notifications: bool, + udp_notifications: bool, +} + +impl Default for Open { + fn default() -> Self { + Self { + udp_errors: true, + tcp_errors: true, + problems: true, + tcp_notifications: true, + udp_notifications: true, + } + } +} + +impl Open { + /// Whether any of `net`'s four queues is still open. The loop only ends + /// once all four are closed, so an error queued just before its + /// transport stopped is never lost. + fn net(&self) -> bool { + self.udp_errors || self.tcp_errors || self.tcp_notifications || self.udp_notifications + } +} + +/// The routing loop's state: everything towards the front. +struct Router { + config: EventConfig, + batch: usize, + boards: Arc, + udp: Sinks, + tcp: Sinks, + problems: mpsc::Receiver, + logging: mpsc::Sender, + pipeline: mpsc::Sender, + fault: mpsc::Sender, + open: Open, + /// One reused buffer per notification queue (the two are read in the + /// same `select!`, so they cannot share one). + tcp_batch: Vec, + udp_batch: Vec, + tcp_capacity: usize, + udp_capacity: usize, + /// The addresses whose fault has already been shown. + faults_shown: HashSet, +} + +impl Router { + async fn route(mut self) -> Stop { + loop { + if !self.open.net() { + return Stop::NetGone; + } + + let limit = self.batch; + let open = self.open; + // Fixed order: errors, then TCP, then UDP. + let step = tokio::select! { + biased; + report = self.udp.errors.recv(), if open.udp_errors => { + Step::NetError(Transport::Udp, report) + } + report = self.tcp.errors.recv(), if open.tcp_errors => { + Step::NetError(Transport::Tcp, report) + } + problem = self.problems.recv(), if open.problems => Step::Problem(problem), + n = self.tcp.notifications.recv_many(&mut self.tcp_batch, limit), + if open.tcp_notifications => Step::Notifications(Transport::Tcp, n), + n = self.udp.notifications.recv_many(&mut self.udp_batch, limit), + if open.udp_notifications => Step::Notifications(Transport::Udp, n), + else => return Stop::NetGone, + }; + + let handled = match step { + Step::NetError(Transport::Udp, None) => { + self.open.udp_errors = false; + Ok(()) + } + Step::NetError(Transport::Tcp, None) => { + self.open.tcp_errors = false; + Ok(()) + } + Step::NetError(_, Some(report)) => self.on_net_error(report).await, + Step::Problem(None) => { + self.open.problems = false; + Ok(()) + } + Step::Problem(Some(problem)) => self.on_problem(problem).await, + // 0 only once the queue is closed and empty. + Step::Notifications(Transport::Tcp, 0) => { + self.open.tcp_notifications = false; + Ok(()) + } + Step::Notifications(Transport::Udp, 0) => { + self.open.udp_notifications = false; + Ok(()) + } + Step::Notifications(transport, _) => { + self.forward(transport).await.map_err(Halt::Gone) + } + }; + + match handled { + Ok(()) => {} + Err(Halt::Fatal(problem)) => return self.stop_fatal(problem).await, + Err(Halt::Gone(consumer)) => return self.stop_consumer_gone(consumer).await, + } + } + } + + /// Sends the batch just taken from `transport`'s queue to both consumers, + /// as one shared copy. + async fn forward(&mut self, transport: Transport) -> Result<(), Consumer> { + let batch = match transport { + Transport::Tcp => &mut self.tcp_batch, + Transport::Udp => &mut self.udp_batch, + }; + // One allocation; the buffer keeps its capacity for the next batch. + let shared: Batch = batch.drain(..).collect(); + + self.logging + .send(ToLogging::Received(shared.clone())) + .await + .map_err(|_| Consumer::Logging)?; + self.pipeline + .send(ToPipeline::Received(shared)) + .await + .map_err(|_| Consumer::Pipeline) + } + + async fn on_net_error(&mut self, report: ErrorReport) -> Result<(), Halt> { + let action = policy::classify(&report.error); + let source = policy::source(&report.error); + let board = source + .board + .or_else(|| source.ip.and_then(|ip| self.boards.by_ip(ip))); + + // UDP errors only carry an address: put the board's name in front. + let mut text = full_message(&report.error); + if let (Some(board), Some(_)) = (board, source.ip) { + text = format!("{}: {text}", self.boards.name(board)); + } + + let kind = match action { + Action::Fatal => ProblemKind::Fatal, + Action::Silent => ProblemKind::Silent, + Action::Show | Action::BoardFault => ProblemKind::Shown, + }; + let problem = Problem { + at: report.at, + board, + kind, + text, + }; + + match action { + Action::Fatal => Err(Halt::Fatal(problem)), + Action::BoardFault => self.on_board_fault(problem, source.ip).await, + Action::Show => self.show(problem).await.map_err(Halt::Gone), + Action::Silent => { + self.trace_silent(&problem); + Ok(()) + } + } + } + + async fn on_problem(&mut self, problem: Problem) -> Result<(), Halt> { + match policy::for_problem(problem.kind) { + Action::Fatal => Err(Halt::Fatal(problem)), + Action::Silent => { + self.trace_silent(&problem); + Ok(()) + } + Action::Show | Action::BoardFault => self.show(problem).await.map_err(Halt::Gone), + } + } + + /// Procedure 1: written to the trace, and nothing else. + fn trace_silent(&self, problem: &Problem) { + let board = problem.board.map(|board| self.boards.name(board)); + warn!(board = ?board, problem = %problem.text, "problem not shown on the front"); + } + + /// The first fault from each address is shown and forwarded; repeats are + /// not (`net` already traces them, rate-limited). + async fn on_board_fault(&mut self, problem: Problem, ip: Option) -> Result<(), Halt> { + let first = ip.is_none_or(|ip| self.faults_shown.insert(ip)); + if !first { + return Ok(()); + } + + warn!(fault = %problem.text, "first fault from this board"); + self.show(problem).await.map_err(Halt::Gone)?; + + if self.config.forward_board_faults { + // Never waits: if the queue is full a request is already pending, + // and the fault goes out only once anyway. + if let Err(error) = self.fault.try_send(FaultRequest { done: None }) { + debug!(%error, "fault request not queued"); + } + } + Ok(()) + } + + async fn show(&self, problem: Problem) -> Result<(), Consumer> { + self.pipeline + .send(ToPipeline::Problem(problem)) + .await + .map_err(|_| Consumer::Pipeline) + } + + /// Procedure 3: show it, pass on what was already queued, send the fault, + /// stop. + async fn stop_fatal(mut self, problem: Problem) -> Stop { + error!(problem = %problem.text, "fatal error, stopping"); + + let pipeline_alive = self + .pipeline + .send(ToPipeline::Problem(problem.clone())) + .await + .is_ok(); + if pipeline_alive { + // Errors are read first, so this one has overtaken the data that + // arrived just before it: pass that on before stopping. If a + // consumer stops meanwhile, there is nothing left to do with it. + let _ = self.drain().await; + } + + self.send_fault_and_wait().await; + Stop::Fatal(problem) + } + + /// `logging` or `pipeline` stopped: nothing is recorded, or nothing is + /// shown. Fatal, without draining. + async fn stop_consumer_gone(self, consumer: Consumer) -> Stop { + let text = match consumer { + Consumer::Logging => "logging stopped: nothing is being recorded", + Consumer::Pipeline => "pipeline stopped: nothing reaches the front", + }; + let problem = Problem::now(ProblemKind::Fatal, None, text); + error!(problem = %problem.text, "fatal error, stopping"); + + if consumer == Consumer::Logging { + let _ = self + .pipeline + .send(ToPipeline::Problem(problem.clone())) + .await; + } + + self.send_fault_and_wait().await; + Stop::Fatal(problem) + } + + /// Passes on what is already in ③ and ④, at most their capacity each, so + /// that it cannot chase a queue that keeps filling up. + async fn drain(&mut self) -> Result<(), Consumer> { + for transport in [Transport::Tcp, Transport::Udp] { + let mut left = match transport { + Transport::Tcp => self.tcp_capacity, + Transport::Udp => self.udp_capacity, + }; + while left > 0 { + let (queue, batch) = match transport { + Transport::Tcp => (&mut self.tcp.notifications, &mut self.tcp_batch), + Transport::Udp => (&mut self.udp.notifications, &mut self.udp_batch), + }; + let limit = self.batch.min(left); + while batch.len() < limit { + match queue.try_recv() { + Ok(notification) => batch.push(notification), + Err(_) => break, + } + } + if batch.is_empty() { + break; + } + left -= batch.len(); + self.forward(transport).await?; + } + } + Ok(()) + } + + /// Asks the fault worker for the fault and waits until it has gone out + /// (or had gone out already), within [`Config::fault_timeout`]. + async fn send_fault_and_wait(&self) { + let (done_tx, done_rx) = oneshot::channel(); + let request = FaultRequest { + done: Some(done_tx), + }; + let wait = async { + if self.fault.send(request).await.is_ok() { + let _ = done_rx.await; + } + }; + if tokio::time::timeout(self.config.fault_timeout, wait) + .await + .is_err() + { + warn!( + timeout = ?self.config.fault_timeout, + "the fault was not confirmed in time; stopping anyway" + ); + } + } +} diff --git a/backend/crates/station/src/event/README.md b/backend/crates/station/src/event/README.md new file mode 100644 index 000000000..1ce4af010 --- /dev/null +++ b/backend/crates/station/src/event/README.md @@ -0,0 +1,539 @@ +# `event`: how station's modules talk to each other + +> `net::tcp` is not wired in yet: `main` starts `event` without a TCP client, +> so orders fail with "TCP not available" and the fault is only traced. + +Every module of the backend runs in **its own task**. A task is tokio's +lightweight thread: it runs on its own, at its own pace, and tokio spreads all +the tasks over a handful of OS threads (about one per CPU core). For this +document, think of each task as a thread. + +Modules **never call each other's functions** while running. They only talk +through **queues**: one module puts a message in, another takes it out. + +**`event` is that communication.** It is not "the UDP module" or "the orders +module": it is the switchboard every module goes through. It does two things: + +1. **It prepares every queue between modules**, in one place + ([`event::channels`](#who-creates-the-queues)), and `main` hands each end to + the module that uses it. +2. **It routes what goes through them**, in both directions: + - **towards the front**: what the boards send, and every error, goes to + `logging` (disk) and `pipeline` (front), in a fixed order of priority: + **errors, then TCP, then UDP**; + - **towards the boards**: orders from the front, and the fault, go to TCP. + +It does no work on the data. The real work (decoding, writing to disk, building +the front's JSON, writing to a socket) happens in the other tasks. + +## Overview + +`event` is three tasks: the **routing loop**, which handles everything going +towards the front, and two **workers**, which handle everything going towards +the boards. + +**Towards the front:** + +```text + ┌─ task ─────┐ ─① errors──────► ┌─ task ───────────────────┐ ─⑤─► ┌─ task ───┐ + │ net::udp │ ─④ UDP notif.──► │ event: routing loop │ │ logging │ → disk + └────────────┘ │ │ └──────────┘ + ┌─ task ─────┐ ─① errors──────► │ reads in this order: │ + │ net::tcp │ ─③ TCP notif.──► │ 1. ① ② errors │ ─⑥─► ┌─ task ───┐ + └────────────┘ │ 2. ③ TCP notifications │ │ pipeline │ → websocket → front + any station ─② problems─────► │ 3. ④ UDP notifications │ └──────────┘ + module └────────────┬─────────────┘ + │ ⑧ (fatal error, board fault) + ▼ + fault worker +``` + +**Towards the boards:** + +```text + front → websocket ─⑦ orders─► ┌─ task ──────────┐ ──► TCP: write to that board + │ orders worker │ ─⑤─► logging (sent) + │ one at a time │ ─⑥─► pipeline (failed) + └───────┬─────────┘ + │ ⑧ (order id 0 = fault) + ▼ + routing loop ─⑧─────────────► ┌─ task ──────────┐ ──► TCP: fault to every board + │ fault worker │ ─⑥─► pipeline (boards not reached) + │ "only once" │ + └─────────────────┘ + + main: calls event::channels(), spawns every task with its ends, + waits for event's Stop, then shuts everything down in order +``` + +The circled numbers are the queues in [The queues](#the-queues). + +Why it is built like this: + +- **A slow module does not hold up the others.** Each one works at its own + pace. The only time one waits for another is when a queue is full, and that + is on purpose (see "wait, don't drop" below). +- **The two directions never get in each other's way.** An order is never + stuck behind thousands of telemetry packets, and a slow board never holds up + the telemetry: orders and the fault have their own tasks. +- **Each module can be tested alone**: fill its input queue by hand and look at + what comes out of its output queue. No sockets, no other modules. +- **The boundaries are explicit.** What one module can tell another is exactly + the type of the queue between them, and nothing else. +- **All the decisions are in one module.** What to do about an error, when to + send the fault and when to stop live in `event`, not scattered across modules. + `net`, in particular, leaves all of that out on purpose. + +## Words used here + +- **Queue** (`tokio::sync::mpsc`): a line with a fixed number of slots between + two tasks. One puts messages in at one end (`Sender`), the other takes them + out at the other end (`Receiver`). Each queue has a single reader; it can + have several writers (the `Sender` is cloned). +- **`Reporter` and `Sinks`**: how `net` delivers what happens: the `Reporter` is + the putting end, held by the UDP or TCP task; the `Sinks` are the taking end, + held by `event`. They carry **notifications** (`Notification`: "this packet + arrived", "this board connected") and **errors** (`ErrorReport`). See + [`net/report.rs`](../../../core/src/net/report.rs). +- **Worker**: a task owned by `event` that does one slow thing (writing an order + to TCP, sending the fault), so that the routing loop never waits on a socket. +- **Batch**: several notifications taken out at once (`recv_many`) instead of + one at a time. +- **Wait, don't drop**: when a queue is full, whoever is putting into it waits + until there is a free slot. That wait travels back up to the socket, so the + only thing that can be lost is what the operating system has not handed over + yet, which has not been decoded yet. `net` works the same way. +- **Shared copy** (`Arc`): one piece of data in memory that several readers use + without copying it. It is freed when the last one lets go of it. +- **`select!` in fixed order** (`biased`): `select!` waits on several queues at + once. With `biased`, when more than one has something, the first one in the + list always wins. That is how priorities are done. + +## Files + +``` +event.rs # module root: channels, spawn, the routing loop, Stop +event/ +├── policy.rs # what to do with each error +├── orders.rs # the orders worker +├── fault.rs # the fault worker +├── tests.rs # the routing loop and the workers, with a fake TCP client +├── manual_tests.rs # throughput probe, ignored by default +└── README.md +``` + +## The queues + +| # | Queue | From → to | Carries | +|---|---|---|---| +| ① | net errors (one queue per transport) | `net::udp`, `net::tcp` → routing loop | `ErrorReport` | +| ② | problems | any station module → routing loop | `Problem` | +| ③ | TCP notifications | `net::tcp` → routing loop | `Notification` (protections, messages, connected/disconnected) | +| ④ | UDP notifications | `net::udp` → routing loop | `Notification` (data) | +| ⑤ | to logging | routing loop, orders worker → `logging` | `ToLogging` | +| ⑥ | to pipeline | routing loop, both workers → `pipeline` | `ToPipeline` | +| ⑦ | orders | `websocket` → orders worker | `OrderPacket` (id 0 = fault) | +| ⑧ | fault requests | routing loop, orders worker → fault worker | `FaultRequest` | + +**The routing loop reads ① to ④ in that order: errors, then TCP, then UDP.** + +- **Errors first**: an error is never stuck behind telemetry. +- **TCP before UDP**: a protection or a board's message is never stuck behind + thousands of telemetry packets. TCP carries little traffic, so reading it + first does not starve UDP. +- The order between a TCP and a UDP notification is not kept across the two + queues; each one carries the instant it was received (`at`), so anyone who + needs the real order can recover it. +- The order of priority applies **only towards the front**. Orders (⑦) go the + other way and are not read by the routing loop at all: the orders worker + reads them itself. + +## Who creates the queues + +**`event` does, all of them, in one call.** `main` calls it once before +spawning anything and hands each end to whoever uses it: + +```rust +let channels = event::channels(&config); + +spawn_udp(udp_config, index.clone(), channels.udp)?; // ① ④ +// the TCP client takes channels.tcp ① ③ +let boards = Boards::from_pod_data(&adj.pod_data); +let event = event::spawn(config, channels.event, boards, tcp); // tcp: Option> +logging::spawn(channels.logging, ...); // ⑤ +pipeline::spawn(channels.pipeline, broker_client, ...); // ⑥ +OrderForwarder::new(index, channels.orders); // ⑦ (websocket) +// channels.problems is cloned for every station module that reports errors ② +``` + +Why one place, instead of each module creating its own input queue: + +- There are **circles**: `event` sends to `logging`, and `logging` reports its + own failures back to `event` (②); `event` asks TCP to write, and TCP reports + back to `event` (① ③). If every module created its own queue, someone would + need the other's end before it existed. Creating everything first, in one + call, removes the problem. +- **`event` defines the types of all its queues**, including the ones going to + `logging` and `pipeline`. So it can be written and tested alone, and + `logging`/`pipeline` depend on `event`, never the other way round. +- The fault requests queue (⑧) is created inside `event::spawn`: nobody outside + `event` ever sees it. +- `net`'s queues are built with `net`'s own `Reporter::channels` (`core` + cannot depend on `station`), called **once per transport**: `net::udp` and + `net::tcp` each get their own `Reporter`, with its own notification queue + (so that TCP can be read first) and its own error queue. `net` needs no + change for it. + +## Towards the front + +| What arrives | `logging` | `pipeline` | fault worker | +|---|---|---|---| +| Batch of TCP notifications (③) | yes | yes | — | +| Batch of UDP notifications (④) | yes | yes | — | +| Problem to show (②, or a non-fatal error from ①) | no (trace only) | yes | — | +| Fatal error | no (trace only) | yes, before stopping | yes | +| Fault from a board (packet id 0, ①) | no (trace only) | yes, the first one from each board | yes, if forwarding is on | + +**How notifications travel.** The routing loop takes up to 512 at once from a +queue, puts them in **one shared copy** (`Arc<[Notification]>`) and sends that +same copy to both `logging` and `pipeline`. Nothing is duplicated in memory, +and each consumer takes what it needs (`logging` its selected measurements, +`pipeline` its counts and averages). `event` never looks inside. Each +`Notification` travels whole, so both times reach the consumers: when it was +received (`at`) and, for protections and messages, the board's own clock +(`ShortTimestamp`). + +**When ⑤ or ⑥ is full, `event` waits; it does not drop.** Everything decoded +reaches the disk, the same rule `net` follows. While the routing loop waits for +a free slot it does not handle errors either; this is accepted because the disk +is expected to keep up with the incoming rate (about 15–25 Mbit/s). + +## Towards the boards + +- **Orders.** `websocket` validates each order against the ADJ and puts it on + ⑦. The orders worker takes them **one at a time**: it writes the order and + waits for TCP to say it went out (or why not) before taking the next one. + - **"Sent" means written, not queued.** A sent order goes to `logging` (⑤) + only once TCP confirms the write. + - **A failed order goes to `pipeline`** (⑥), with the reason. An order for a + board that is not connected fails right away instead of waiting in a queue. +- **The fault.** The fault worker sends the fault (order id 0) to every board. + It gets requests on ⑧ from three places: the routing loop on a fatal error, + the routing loop on the first fault from each board (if forwarding is on), and the + orders worker when the front asks for one (an order with id 0). + - **Only once per session.** The fault worker sends it on the first request + and only acknowledges the later ones. It is the one place that keeps that + flag, whoever asks. + - **Boards it did not reach** go to `pipeline` (⑥): a fault that only half + landed is exactly what the operator has to know. +- **Without TCP** (no TCP client running), every order fails with "TCP not + available", shown on the front, and the fault is only traced. + +Neither worker is ever waited on by the routing loop, except when stopping on a +fatal error (see [Stopping](#stopping)): writing to a socket can take time (a +board that stops reading, a timeout), and the telemetry must not wait for it. + +## Errors + +**`event`** decides what an error means, not `net`: it looks at the error +itself and does not use `is_fatal()`. The decision lives in a function that +keeps no state between calls (`policy.rs`), so it can be tested on its own. + +There are three procedures, and every one of them ends up in the trace: + +1. **Not fatal, not shown**: trace only. Usually traced where it happens, + without reaching `event` (e.g. a failed reconnection with backoff); a + problem that does reach `event` this way is a `ProblemKind::Silent`, and + `event` only traces it. +2. **Not fatal, shown on the front**: e.g. an order to a board that is not + connected. +3. **Fatal, shown on the front**: send the fault, close TCP, shut the backend + down safely. + +| Error | What it means | Procedure | +|---|---|---| +| `UdpError::Decode` (any variant) | a datagram that cannot be decoded: the loaded ADJ does not match what the boards send | **3, fatal** | +| `UdpError::Recv` | the socket can no longer be read: telemetry from every board is gone | **3, fatal** | +| `UdpError::Fault { from }` | a board detected an error and says so (packet id 0) | **board fault**: shown, forwarded to the other boards; the backend **keeps running** | +| `UdpError::Bind` | the port could not be opened | never arrives: a startup failure, returned by `spawn_udp` | +| TCP frame that cannot be decoded | same as UDP | **3, fatal** | +| TCP fault (packet id 0 over TCP) | same as UDP | **board fault** | +| TCP connect or read failure | a board not up yet, or a connection that dropped | **1**, trace only; the `Disconnected` notification already tells the front | +| TCP keep-alive write failure | the keep-alive could not be written | **2, shown** | +| An order that could not be written | reported by the orders worker, not by `net` | **2, shown** | +| `Problem` from a station module (②) | whatever that module reports | what the module says: **1** (`Silent`), **2** (`Shown`) or **3** (`Fatal`) | +| `logging` or `pipeline` stops (⑤ or ⑥ closed) | nothing is recorded, or nothing is shown | **3, fatal** | + +Every decode error is fatal, not only an unknown id: a truncated datagram or an +enum value out of range also say the ADJ does not match the firmware, and +nothing corrupts a packet in flight. A dead `logging` means the run is not +recorded; a dead `pipeline` means the operator sees nothing. + +**Which board.** UDP errors carry the address the datagram came from (`from`), +not the board. At startup `event` gets an IP → `BoardId` map built from the ADJ +(every `Board` has its `ip`, see [`model/board.rs`](../../../core/src/model/board.rs)), +so the front says "HVSCU" rather than "127.0.0.7". An IP that belongs to no +board stays without a board, and the text carries the address. + +**Board faults on the front.** The first fault from each board is shown, as a +`Shown` problem whose text names the board; repeats are not, since `net` already traces them (at most one line a second, +with how many were skipped). Forwarding a board's fault to the others is +configurable and on by default. + +**Traces.** Every error ends up in the trace (`tracing`), but never twice: the +module where it happens traces it, and `event` only traces what it decides +itself ("fatal, stopping", "fault sent to every board", "first fault from +HVSCU") and the `Silent` problems it is sent. + +## Stopping + +**On a fatal error**, the routing loop: + +1. Sends the `Problem` to `pipeline`, so the operator sees it. +2. Empties whatever was already in ③ and ④ (at most their capacity) and passes + it on. Errors are read first, so the fatal error has overtaken the data that + arrived just before it, and that data is exactly what you want to understand + what happened. +3. Asks the fault worker to send the fault and waits for it to finish, with a + time limit (if it was already sent, the answer is immediate). +4. Ends by returning `Stop::Fatal(problem)`. + +If what stopped is `logging` or `pipeline`, step 2 is skipped. If it is +`logging`, `event` still tells `pipeline`. + +**On Ctrl+C:** `main` handles it, not `event`. `main` stops the UDP task +(`JoinHandle::abort`, see "Stopping" in [`net/udp.rs`](../../../core/src/net/udp.rs)) +and closes TCP. When those tasks end their `Reporter`s go with them, `net`'s +queues close, and the routing loop passes on whatever was left and ends with +`Stop::NetGone`. + +**Then `main` always does the same:** + +1. Stops UDP and closes TCP, if not done already. +2. When `event` ends, ⑤ and ⑥ close: `logging` and `pipeline` finish what they + have queued and end on their own (`logging` flushes its files to disk). +3. Waits for them, with a time limit of a few seconds. +4. Exits with code **1** after a fatal error and **0** after Ctrl+C. A + `Stop::NetGone` without Ctrl+C means `net` ended on its own, so that is 1 + as well. + +## Types + +```rust +/// A batch of notifications, shared by logging and pipeline without copying. +pub type Batch = Arc<[Notification]>; + +/// Creates every queue between modules. `main` calls it once, before spawning +/// anything, and hands each end to whoever uses it. +pub fn channels(config: &Config) -> Channels; + +pub struct Channels { + /// For net::udp: reports on ① and ④. + pub udp: Reporter, + /// For net::tcp: reports on ① and ③. Dropped if TCP is not started. + pub tcp: Reporter, + /// event's own ends (the reading side of ① ② ③ ④ ⑦, the writing side of + /// ⑤ ⑥), for `spawn`. Opaque. + pub event: EventEnds, + /// ⑦, for websocket's OrderForwarder. + pub orders: mpsc::Sender, + /// ②, cloned for every station module that reports problems. + pub problems: mpsc::Sender, + /// ⑤, for logging. + pub logging: mpsc::Receiver, + /// ⑥, for pipeline. + pub pipeline: mpsc::Receiver, +} + +/// Starts the routing loop and the two workers. Without a TCP client (`None`), +/// every order fails with "TCP not available" and the fault is only traced. +/// The task ends with the reason it stopped, once the workers have stopped +/// too, so that ⑤ and ⑥ close behind it. +pub fn spawn( + config: Config, + ends: EventEnds, + boards: Boards, + tcp: Option>, +) -> JoinHandle; + +/// What event needs from the TCP client. +pub trait TcpLink: Send + Sync { + /// Writes the order to its board; returns that board once written, or why + /// not (right away if the board is not connected). + fn send(&self, order: OrderPacket) -> BoxFuture<'_, Result>; + /// Sends the fault to every board; fails with the boards it did not reach. + fn send_fault(&self) -> BoxFuture<'_, Result<(), Vec>>; +} + +/// Who an IP belongs to and what each board is called, built from the ADJ. +pub struct Boards { /* ... */ } +impl Boards { + pub fn from_pod_data(pod_data: &PodData) -> Self; + pub fn by_ip(&self, ip: IpAddr) -> Option; + pub fn name(&self, board: BoardId) -> String; +} + +pub enum ToLogging { + Received(Batch), + /// An order TCP confirmed it wrote. + OrderSent { at: SystemTime, board: BoardId, order: OrderPacket }, +} + +pub enum ToPipeline { + Received(Batch), + Problem(Problem), + /// An order that did not go out, and why. + OrderFailed { at: SystemTime, order: OrderPacket, reason: String }, +} + +/// Something the operator has to see. `Problem::now(kind, board, text)` +/// builds one stamped with the current time. +pub struct Problem { + pub at: SystemTime, + /// The board, if known. + pub board: Option, + pub kind: ProblemKind, + /// The message with all its causes: "could not X: because Y: because Z" + /// (`event::full_message` builds it from any error). + pub text: String, +} + +pub enum ProblemKind { + /// Procedure 2: shown, the backend keeps running. + Shown, + /// Procedure 3: shown, the fault is sent and the backend stops. + Fatal, + /// Procedure 1: only traced, not shown; the backend keeps running. + Silent, +} + +/// Why event ended. `main` reads it and shuts down in order. +pub enum Stop { + Fatal(Problem), + /// `net`'s queues closed: UDP and TCP were stopped. + NetGone, +} + +/// `Config::default()` gives the sizes in brackets. Every size is clamped to +/// at least 1. +pub struct Config { + pub batch: usize, // most notifications per batch (512) + pub errors_queue: usize, // each of net's two error queues, ① (16) + pub problems_queue: usize, // ② (16) + pub tcp_queue: usize, // ③ (1,024) + pub udp_queue: usize, // ④ (8,192) + pub logging_queue: usize, // ⑤, in batches (64) + pub pipeline_queue: usize, // ⑥, in batches (64) + pub orders_queue: usize, // ⑦ (32) + pub forward_board_faults: bool, // (true) + pub fault_timeout: Duration, // how long a fatal stop waits for the fault (2 s) +} +``` + +`TcpLink` is a trait rather than `net::tcp`'s own type so that the workers can +be tested against a fake, and so that `event` depends on the TCP client for +these two calls only. `FaultRequest` (⑧) is private to `event`. + +## The routing loop + +```text +loop, select! in fixed order (closed queues are no longer watched): + 1. ① UDP errors, ① TCP errors, then ② problems -> policy: + fatal -> stop (see "Stopping") + board fault -> first from that board? Problem to ⑥ + forwarding on? request to ⑧ + shown -> Problem to ⑥ + silent -> trace only + 2. ③ TCP notifications.recv_many(batch, config.batch) -> forward + 3. ④ UDP notifications.recv_many(batch, config.batch) -> forward + all four of net's queues (① ① ③ ④) closed -> return Stop::NetGone + +forward: + shared = batch.drain(..).collect::>() + ⑤.send(Received(shared.clone())).await // on failure: fatal + ⑥.send(Received(shared)).await // on failure: fatal +``` + +`batch.drain(..).collect()` allocates once per batch, and the `batch` `Vec` +keeps its capacity for the next one. + +## Performance + +The requirement is **25 Mbit/s in 76-byte packets, about 41,000 a second**: +under 24 µs per notification, everything included. On loopback, UDP alone loses +nothing, but a reader with one timer per message already loses 0.7 %. **The +bottleneck is whoever reads `net`'s queues, that is, the routing loop.** Hence: + +- notifications in batches, one memory allocation per batch, not per + notification; +- no timer per notification; +- the routing loop does not look inside notifications: the expensive work + (picking measurements, computing averages, building JSON) is done by + `logging` and `pipeline`, each in its own task; +- anything that can wait on a socket is done by a worker, never by the routing + loop. + +## Contract with the other modules + +- **`net`** needs no change: each transport reports through the `Reporter` it + is given, and `event::channels` hands out one per transport. +- **`net::udp`** reports data on ④, errors on ①, and a fault (packet id 0) as + `UdpError::Fault` on ①, recognised before decoding. +- **`net::tcp`** reports protections, messages and connected/disconnected on ③, + errors on ①, and on top of that: + - recognises packet id 0 as a fault before decoding, like `net::udp`; + - does not report reconnection failures (procedure 1: it traces them); + - `send` fails right away if the board is not connected, and returns only + once the order is written; + - can send the fault to every board and say which ones it did not reach; + - has an explicit stop, for the safe shutdown; + - is handed to `event` as a `TcpLink`, directly or through a thin adapter. +- **`websocket`** validates each order against the ADJ and puts it on ⑦ + (`OrderForwarder` takes `channels.orders`). The front's logger requests + (`logger/enable`, variable selection) go straight to `logging`, not through + `event`. +- **`logging`** reads ⑤, picks which measurements to store following its own + selection, and reports its own failures (e.g. the disk) on ②. +- **`pipeline`** reads ⑥ and turns it into what the front shows: a batch into + per-packet updates (counts, cycle time, averages) or protection and message + updates, a `Problem` or a failed order into a message. It waits instead of + dropping and does not decide anything about errors. + +## Implementation notes + +- **`main` keeps no copy of a `Reporter`**: each one is moved into its task, + and `channels.tcp` is dropped if TCP is not started. A `Reporter` left alive + keeps its queues open, and the routing loop never ends. +- **A closed queue is no longer watched** in the `select!`. A closed queue + answers "closed" instantly, every time, so in fixed order it would win every + round and the queues below it would never be reached. Each branch has a + condition (`if open.udp_errors`, and so on). This does happen: at shutdown ① closes once both + `Reporter`s are gone while ④ may still have items in it, and without TCP ③ + is closed from the start. + +## Tests + +- `policy.rs`: the decision table, one test per row. +- `tests.rs`: the routing loop and the workers, with real queues and a fake + `TcpLink`, no sockets. Covers the order of priority, the shared batch, the + fatal stop (and that what was queued before the error still gets through), + board faults shown once per board and the fault sent once, orders with and + without TCP, order id 0, a consumer that stops, `net` closing, and a fault + that never finishes sending. Every wait is bounded, so a broken expectation + fails instead of hanging. +- `manual_tests.rs`: `manual_event_throughput`, ignored by default. It pushes + a million notifications through a `Reporter` into `event` and two readers + that only count. On a development machine, in release: about 4.9 million a + second, over 100 times the requirement. + + ```sh + cargo test -p station --release manual_event -- --ignored --nocapture + ``` + +## Open questions + +- **Fault from the front.** `websocket` validates orders against the ADJ, and id + 0 is not in it, so today a fault asked for from the front is rejected before + reaching ⑦. +- **Order echo.** Whether a sent order is also shown on the front, not only + logged. diff --git a/backend/crates/station/src/event/fault.rs b/backend/crates/station/src/event/fault.rs new file mode 100644 index 000000000..e3a143cd8 --- /dev/null +++ b/backend/crates/station/src/event/fault.rs @@ -0,0 +1,77 @@ +//! The fault worker: sends the fault (order id 0) to every board, once per +//! session, whoever asks for it. + +use std::sync::Arc; + +use software_core::model::AdjId; +use tokio::sync::{mpsc, oneshot}; +use tracing::{error, info, warn}; + +use super::{Boards, Problem, ProblemKind, TcpLink, ToPipeline}; + +/// The fault's id on the wire: what a board sends when it detects an error, +/// and what the backend sends to every board to put the pod in fault. +pub(super) const FAULT_ID: AdjId = AdjId(0); + +/// Slots in the fault requests queue (⑧). Requests are rare, and once the +/// fault has been sent every later one is a no-op, so a full queue only +/// means a request is already pending. +pub(super) const FAULT_QUEUE: usize = 8; + +/// A request to send the fault. +#[derive(Debug)] +pub(super) struct FaultRequest { + /// Told once the fault has been sent, or was already sent before: the + /// routing loop waits on it before stopping on a fatal error. + pub(super) done: Option>, +} + +/// Runs the worker until its queue closes (or `event` stops it). +/// +/// The "only once" flag lives here and nowhere else: a fatal error, a board's +/// fault and the front all end up in this queue. A request that arrives while +/// the fault is being sent waits behind it, so it is only acknowledged once +/// the fault has really gone out. +pub(super) async fn run( + mut requests: mpsc::Receiver, + tcp: Option>, + pipeline: mpsc::Sender, + boards: Arc, +) { + let mut sent = false; + while let Some(request) = requests.recv().await { + if !sent { + sent = true; + send_fault(tcp.as_deref(), &pipeline, &boards).await; + } + if let Some(done) = request.done { + // The one waiting may have given up already (its time limit). + let _ = done.send(()); + } + } +} + +/// Sends the fault and tells the front about the boards it did not reach. +async fn send_fault( + tcp: Option<&dyn TcpLink>, + pipeline: &mpsc::Sender, + boards: &Boards, +) { + let Some(tcp) = tcp else { + warn!("the fault was not sent to the boards: TCP not available"); + return; + }; + + match tcp.send_fault().await { + Ok(()) => info!("fault sent to every board"), + Err(unreached) => { + let names: Vec = unreached.iter().map(|&board| boards.name(board)).collect(); + let text = format!("the fault did not reach these boards: {}", names.join(", ")); + error!(%text); + // A fault that only half landed is exactly what the operator has + // to know. If pipeline is gone, event is stopping anyway. + let problem = Problem::now(ProblemKind::Shown, None, text); + let _ = pipeline.send(ToPipeline::Problem(problem)).await; + } + } +} diff --git a/backend/crates/station/src/event/manual_tests.rs b/backend/crates/station/src/event/manual_tests.rs new file mode 100644 index 000000000..3c3da9895 --- /dev/null +++ b/backend/crates/station/src/event/manual_tests.rs @@ -0,0 +1,88 @@ +//! A throughput probe for the routing loop, ignored by default: +//! +//! ```sh +//! cargo test -p station --release manual_event -- --ignored --nocapture +//! ``` +//! +//! The requirement is 25 Mbit/s in 76-byte packets, about 41,000 +//! notifications a second, and the routing loop is the bottleneck: on +//! loopback the UDP socket alone loses nothing. This pushes notifications +//! straight through a `Reporter`, with no socket, so what it measures is the +//! routing loop and its two queues. + +use super::*; +use software_core::model::{AdjId, DataPacket, Packet}; +use software_core::net::Event; +use std::error::Error; +use std::time::Instant; + +const NOTIFICATIONS: usize = 1_000_000; +const REQUIRED_PER_SECOND: f64 = 41_000.0; + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[ignore = "load probe: run it by hand, in release"] +async fn manual_event_throughput() -> Result<(), Box> { + let config = EventConfig::default(); + let Channels { + udp, + tcp, + event, + orders, + problems, + mut logging, + mut pipeline, + } = channels(&config); + drop((tcp, orders, problems)); + let event = spawn(config, event, Boards::default(), None); + + let logged = tokio::spawn(async move { + let mut count = 0; + while let Some(message) = logging.recv().await { + if let ToLogging::Received(batch) = message { + count += batch.len(); + } + } + count + }); + let shown = tokio::spawn(async move { + let mut count = 0; + while let Some(message) = pipeline.recv().await { + if let ToPipeline::Received(batch) = message { + count += batch.len(); + } + } + count + }); + + let start = Instant::now(); + let producer = tokio::spawn(async move { + for _ in 0..NOTIFICATIONS { + let packet = DataPacket::new(AdjId(1000), vec![]); + if udp + .notify(BoardId(1), Event::Received(Packet::Data(packet))) + .await + .is_err() + { + break; + } + } + // `udp` is dropped here: event passes on what is left and stops. + }); + producer.await?; + let stop = event.await?; + let (logged, shown) = (logged.await?, shown.await?); + let elapsed = start.elapsed(); + + let per_second = NOTIFICATIONS as f64 / elapsed.as_secs_f64(); + println!( + "{NOTIFICATIONS} notifications in {elapsed:.2?}: {per_second:.0}/s \ + ({:.1}x the required {REQUIRED_PER_SECOND:.0}/s)", + per_second / REQUIRED_PER_SECOND + ); + + assert!(matches!(stop, Stop::NetGone)); + assert_eq!(logged, NOTIFICATIONS, "logging got every notification"); + assert_eq!(shown, NOTIFICATIONS, "pipeline got every notification"); + assert!(per_second > REQUIRED_PER_SECOND); + Ok(()) +} diff --git a/backend/crates/station/src/event/orders.rs b/backend/crates/station/src/event/orders.rs new file mode 100644 index 000000000..f3b2a6303 --- /dev/null +++ b/backend/crates/station/src/event/orders.rs @@ -0,0 +1,65 @@ +//! The orders worker: takes the front's orders (⑦) one at a time and writes +//! them to TCP, so that the routing loop never waits on a socket. + +use std::sync::Arc; +use std::time::SystemTime; + +use software_core::model::OrderPacket; +use tokio::sync::mpsc; +use tracing::{info, warn}; + +use super::fault::{FAULT_ID, FaultRequest}; +use super::{TcpLink, ToLogging, ToPipeline}; + +/// The reason given for every order when no TCP client is running. +pub(super) const TCP_NOT_AVAILABLE: &str = "TCP not available"; + +/// Runs the worker until its queue closes (or `event` stops it). +/// +/// - An order with id 0 is the fault: it goes to the fault worker (⑧). +/// - Any other order is written and waited for before the next one is +/// taken. Written: it goes to `logging` (⑤). Not written: it goes to +/// `pipeline` (⑥) with the reason, and to the trace. +pub(super) async fn run( + mut orders: mpsc::Receiver, + tcp: Option>, + fault: mpsc::Sender, + logging: mpsc::Sender, + pipeline: mpsc::Sender, +) { + while let Some(order) = orders.recv().await { + if order.id == FAULT_ID { + info!("the front asked for the fault"); + if fault.send(FaultRequest { done: None }).await.is_err() { + break; + } + continue; + } + + let outcome = match &tcp { + Some(tcp) => tcp.send(order.clone()).await, + None => Err(TCP_NOT_AVAILABLE.to_string()), + }; + + // Stamped once the outcome is known: "sent" means written. + let at = SystemTime::now(); + let delivered = match outcome { + Ok(board) => logging + .send(ToLogging::OrderSent { at, board, order }) + .await + .is_ok(), + Err(reason) => { + warn!(id = ?order.id, %reason, "order not sent"); + pipeline + .send(ToPipeline::OrderFailed { at, order, reason }) + .await + .is_ok() + } + }; + + // Nobody left to tell: event is stopping. + if !delivered { + break; + } + } +} diff --git a/backend/crates/station/src/event/policy.rs b/backend/crates/station/src/event/policy.rs new file mode 100644 index 000000000..4fb8d2b86 --- /dev/null +++ b/backend/crates/station/src/event/policy.rs @@ -0,0 +1,238 @@ +//! What each error means: the decision table of the README's "Errors" +//! section, as functions that keep no state, so it can be tested on its own. + +use std::error::Error; +use std::net::IpAddr; + +use software_core::model::BoardId; +use software_core::net::{self, tcp, udp::UdpError}; + +use super::ProblemKind; + +/// What the routing loop does about an error. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(super) enum Action { + /// Procedure 3: show it, send the fault, stop. + Fatal, + /// A board sent a fault: show the first one from that board, forward + /// it to the others if configured, keep running. + BoardFault, + /// Procedure 2: show it, keep running. + Show, + /// Procedure 1: only written to the trace; not shown, keep running. + Silent, +} + +/// Decides what a `net` error means. `is_fatal()` is not consulted: the +/// decision is `event`'s, and it is made here, from the error itself. +pub(super) fn classify(error: &net::Error) -> Action { + match error { + net::Error::Udp(error) => match error { + // Nothing corrupts a datagram in flight, so any decode failure + // means the loaded ADJ does not match the firmware, whatever the + // variant: an unknown id, a truncated datagram, an enum value out + // of range. + UdpError::Decode { .. } => Action::Fatal, + // The socket is gone: every board's telemetry at once. + UdpError::Recv { .. } => Action::Fatal, + UdpError::Fault { .. } => Action::BoardFault, + // Never reaches the error queue (binding happens before the task + // starts). If it ever did, there would be no telemetry at all. + UdpError::Bind { .. } => Action::Fatal, + }, + net::Error::Tcp(error) => match error { + tcp::Error::Decode { .. } => Action::Fatal, + // A board not up yet: what the reconnection backoff is for. + tcp::Error::Connect { .. } => Action::Silent, + tcp::Error::Write { .. } => Action::Show, + }, + } +} + +/// Decides what a [`super::Problem`] from a station module means: whatever +/// the module that sent it says. +pub(super) fn for_problem(kind: ProblemKind) -> Action { + match kind { + ProblemKind::Fatal => Action::Fatal, + ProblemKind::Shown => Action::Show, + ProblemKind::Silent => Action::Silent, + } +} + +/// Where an error comes from, as far as the error itself says. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(super) struct Source { + /// The board, when the error names it (TCP errors do). + pub(super) board: Option, + /// The address a datagram came from, when that is all there is (UDP). + pub(super) ip: Option, +} + +/// Reads [`Source`] off an error. +pub(super) fn source(error: &net::Error) -> Source { + match error { + net::Error::Udp(error) => match error { + UdpError::Decode { from, .. } | UdpError::Fault { from } => Source { + board: None, + ip: Some(from.ip()), + }, + UdpError::Recv { .. } | UdpError::Bind { .. } => Source { + board: None, + ip: None, + }, + }, + net::Error::Tcp(error) => match error { + tcp::Error::Connect { board, .. } + | tcp::Error::Decode { board, .. } + | tcp::Error::Write { board, .. } => Source { + board: Some(*board), + ip: None, + }, + }, + } +} + +/// The error with all its causes: "could not X: because Y: because Z". +/// +/// Some errors already include their cause in their own message and others +/// do not, so a cause that already appears is not repeated. +pub fn full_message(error: &dyn Error) -> String { + let mut message = error.to_string(); + let mut source = error.source(); + while let Some(cause) = source { + let text = cause.to_string(); + if !message.contains(&text) { + message.push_str(": "); + message.push_str(&text); + } + source = cause.source(); + } + message +} + +#[cfg(test)] +mod tests { + use super::*; + use software_core::model::AdjId; + use software_core::protocol::DecodeError; + use std::net::SocketAddr; + + fn from() -> SocketAddr { + SocketAddr::new(IpAddr::from([127, 0, 0, 7]), 50400) + } + + fn io_error() -> std::io::Error { + std::io::Error::from(std::io::ErrorKind::ConnectionReset) + } + + fn udp(error: UdpError) -> net::Error { + net::Error::Udp(error) + } + + fn tcp(error: tcp::Error) -> net::Error { + net::Error::Tcp(error) + } + + #[test] + fn every_udp_decode_error_is_fatal_not_only_an_unknown_id() { + for source in [ + DecodeError::UnknownId(AdjId(9999)), + DecodeError::UnexpectedEof, + DecodeError::InvalidEnumValue { + index: 7, + options: 2, + }, + ] { + let error = udp(UdpError::Decode { + from: from(), + source, + }); + assert_eq!(classify(&error), Action::Fatal, "{error}"); + } + } + + #[test] + fn losing_the_udp_socket_is_fatal() { + let error = udp(UdpError::Recv { source: io_error() }); + assert_eq!(classify(&error), Action::Fatal); + } + + #[test] + fn a_fault_from_a_board_does_not_stop_the_backend() { + let error = udp(UdpError::Fault { from: from() }); + assert_eq!(classify(&error), Action::BoardFault); + } + + #[test] + fn tcp_errors_follow_the_three_procedures() { + let decode = tcp(tcp::Error::Decode { + board: BoardId(3), + source: DecodeError::UnknownId(AdjId(9999)), + }); + let connect = tcp(tcp::Error::Connect { + board: BoardId(3), + source: io_error(), + }); + let write = tcp(tcp::Error::Write { + board: BoardId(3), + source: io_error(), + }); + + assert_eq!(classify(&decode), Action::Fatal); + assert_eq!(classify(&connect), Action::Silent); + assert_eq!(classify(&write), Action::Show); + } + + #[test] + fn a_problem_means_what_its_module_says() { + assert_eq!(for_problem(ProblemKind::Fatal), Action::Fatal); + assert_eq!(for_problem(ProblemKind::Shown), Action::Show); + assert_eq!(for_problem(ProblemKind::Silent), Action::Silent); + } + + #[test] + fn udp_errors_carry_an_address_and_tcp_errors_a_board() { + let fault = udp(UdpError::Fault { from: from() }); + assert_eq!( + source(&fault), + Source { + board: None, + ip: Some(from().ip()) + } + ); + + let recv = udp(UdpError::Recv { source: io_error() }); + assert_eq!( + source(&recv), + Source { + board: None, + ip: None + } + ); + + let write = tcp(tcp::Error::Write { + board: BoardId(3), + source: io_error(), + }); + assert_eq!( + source(&write), + Source { + board: Some(BoardId(3)), + ip: None + } + ); + } + + #[test] + fn the_full_message_carries_every_cause_once() { + let error = udp(UdpError::Decode { + from: from(), + source: DecodeError::UnknownId(AdjId(9999)), + }); + + let message = full_message(&error); + assert!(message.contains("127.0.0.7:50400"), "{message}"); + assert!(message.contains("unknown packet id"), "{message}"); + assert_eq!(message.matches("unknown packet id").count(), 1); + } +} diff --git a/backend/crates/station/src/event/tests.rs b/backend/crates/station/src/event/tests.rs new file mode 100644 index 000000000..b32518285 --- /dev/null +++ b/backend/crates/station/src/event/tests.rs @@ -0,0 +1,499 @@ +//! Tests of the routing loop and the workers, with real queues and a fake +//! TCP client. No sockets. +//! +//! Every wait is bounded ([`next`], [`stops`], [`eventually`]), so that a +//! broken expectation fails instead of hanging. + +use super::*; +use software_core::model::{AdjId, Board, DataPacket, MacAddress, Packet}; +use software_core::net::Event; +use software_core::net::udp::UdpError; +use software_core::protocol::DecodeError; +use std::error::Error; +use std::net::SocketAddr; +use std::sync::atomic::{AtomicUsize, Ordering}; +use tokio::time::{sleep, timeout}; + +type TestResult = Result<(), Box>; + +const WAIT: Duration = Duration::from_secs(1); +const HVSCU: BoardId = BoardId(1); +const VCU: BoardId = BoardId(2); + +fn hvscu_addr() -> SocketAddr { + SocketAddr::new(IpAddr::from([127, 0, 0, 7]), 50400) +} + +fn vcu_addr() -> SocketAddr { + SocketAddr::new(IpAddr::from([127, 0, 0, 8]), 50400) +} + +fn board(id: BoardId, name: &str, addr: SocketAddr) -> Board { + Board { + id, + name: name.to_string(), + ip: addr.ip(), + mac: MacAddress([0; 6]), + packets: HashMap::new(), + } +} + +fn boards() -> Boards { + let pod_data = PodData { + boards: HashMap::from([ + (HVSCU, board(HVSCU, "HVSCU", hvscu_addr())), + (VCU, board(VCU, "VCU", vcu_addr())), + ]), + }; + Boards::from_pod_data(&pod_data) +} + +fn data() -> Event { + Event::Received(Packet::Data(DataPacket::new(AdjId(1000), vec![]))) +} + +fn fault_from(from: SocketAddr) -> UdpError { + UdpError::Fault { from } +} + +fn decode_error() -> UdpError { + UdpError::Decode { + from: hvscu_addr(), + source: DecodeError::UnknownId(AdjId(9999)), + } +} + +fn order(id: u16) -> OrderPacket { + OrderPacket::new(AdjId(id), vec![]) +} + +/// The next message on `queue`, failing if none arrives within [`WAIT`]. +async fn next(queue: &mut mpsc::Receiver) -> Result> { + timeout(WAIT, queue.recv()) + .await? + .ok_or_else(|| "the queue closed".into()) +} + +/// How `event` stopped, failing if it does not within [`WAIT`]. +async fn stops(event: JoinHandle) -> Result> { + Ok(timeout(WAIT, event).await??) +} + +/// Waits until `condition` holds, failing after [`WAIT`]. +async fn eventually(condition: impl Fn() -> bool) -> TestResult { + timeout(WAIT, async { + while !condition() { + sleep(Duration::from_millis(5)).await; + } + }) + .await?; + Ok(()) +} + +/// A TCP client that counts what it is asked to do. +#[derive(Debug, Default)] +struct FakeTcp { + orders: AtomicUsize, + faults: AtomicUsize, + /// Every order fails with this reason. + refuse_orders: Option<&'static str>, + /// The fault does not reach these boards. + unreachable: Vec, + /// The fault never finishes sending. + fault_hangs: bool, +} + +impl TcpLink for FakeTcp { + fn send(&self, _order: OrderPacket) -> BoxFuture<'_, Result> { + Box::pin(async move { + self.orders.fetch_add(1, Ordering::SeqCst); + match self.refuse_orders { + Some(reason) => Err(reason.to_string()), + None => Ok(HVSCU), + } + }) + } + + fn send_fault(&self) -> BoxFuture<'_, Result<(), Vec>> { + Box::pin(async move { + self.faults.fetch_add(1, Ordering::SeqCst); + if self.fault_hangs { + std::future::pending::<()>().await; + } + if self.unreachable.is_empty() { + Ok(()) + } else { + Err(self.unreachable.clone()) + } + }) + } +} + +fn as_link(fake: &Arc) -> Option> { + let link: Arc = fake.clone(); + Some(link) +} + +#[tokio::test] +async fn a_batch_reaches_logging_and_pipeline_as_the_same_copy() -> TestResult { + let config = EventConfig::default(); + let mut channels = channels(&config); + for _ in 0..3 { + channels.udp.notify(HVSCU, data()).await?; + } + let _event = spawn(config, channels.event, boards(), None); + + let ToLogging::Received(logged) = next(&mut channels.logging).await? else { + unreachable!("the first thing logging gets is the batch"); + }; + let ToPipeline::Received(shown) = next(&mut channels.pipeline).await? else { + unreachable!("the first thing pipeline gets is the batch"); + }; + assert_eq!(logged.len(), 3); + assert!(Arc::ptr_eq(&logged, &shown), "one copy, shared"); + Ok(()) +} + +#[tokio::test] +async fn errors_come_first_then_tcp_then_udp() -> TestResult { + let config = EventConfig::default(); + let mut channels = channels(&config); + // Queued in the opposite order to the one they must come out in. + channels.udp.notify(HVSCU, data()).await?; + channels.tcp.notify(VCU, Event::Connected).await?; + channels.udp.report(fault_from(hvscu_addr())).await?; + let _event = spawn(config, channels.event, boards(), None); + + let ToPipeline::Problem(problem) = next(&mut channels.pipeline).await? else { + unreachable!("the error comes first"); + }; + assert!( + problem.text.contains("signalled a fault"), + "{}", + problem.text + ); + + let ToPipeline::Received(tcp) = next(&mut channels.pipeline).await? else { + unreachable!("then the TCP notification"); + }; + assert!(matches!(tcp[0].event, Event::Connected)); + + let ToPipeline::Received(udp) = next(&mut channels.pipeline).await? else { + unreachable!("then the UDP notification"); + }; + assert!(matches!(udp[0].event, Event::Received(Packet::Data(_)))); + Ok(()) +} + +#[tokio::test] +async fn a_fatal_error_passes_on_what_was_queued_and_stops() -> TestResult { + let config = EventConfig::default(); + let mut channels = channels(&config); + channels.udp.notify(HVSCU, data()).await?; + channels.udp.notify(HVSCU, data()).await?; + channels.udp.report(decode_error()).await?; + let event = spawn(config, channels.event, boards(), None); + + let ToPipeline::Problem(problem) = next(&mut channels.pipeline).await? else { + unreachable!("the fatal error is shown first"); + }; + assert_eq!(problem.kind, ProblemKind::Fatal); + assert_eq!(problem.board, Some(HVSCU), "resolved from the address"); + assert!(problem.text.starts_with("HVSCU: "), "{}", problem.text); + + // The data that arrived before the error still gets through. + let ToPipeline::Received(shown) = next(&mut channels.pipeline).await? else { + unreachable!("then what was queued"); + }; + let ToLogging::Received(logged) = next(&mut channels.logging).await? else { + unreachable!("logging gets what was queued too"); + }; + assert_eq!(shown.len(), 2); + assert_eq!(logged.len(), 2); + + let Stop::Fatal(stopped_by) = stops(event).await? else { + unreachable!("a decode error is fatal"); + }; + assert_eq!(stopped_by, problem); + Ok(()) +} + +#[tokio::test] +async fn a_board_fault_is_shown_once_per_board_and_the_fault_sent_once() -> TestResult { + let config = EventConfig::default(); + let mut channels = channels(&config); + let fake = Arc::new(FakeTcp::default()); + let event = spawn(config, channels.event, boards(), as_link(&fake)); + + for _ in 0..3 { + channels.udp.report(fault_from(hvscu_addr())).await?; + } + channels.udp.report(fault_from(vcu_addr())).await?; + // A marker: whatever comes before it on pipeline is all there is. + channels.udp.notify(HVSCU, data()).await?; + + let ToPipeline::Problem(first) = next(&mut channels.pipeline).await? else { + unreachable!("HVSCU's first fault is shown"); + }; + let ToPipeline::Problem(second) = next(&mut channels.pipeline).await? else { + unreachable!("VCU's first fault is shown"); + }; + let ToPipeline::Received(_) = next(&mut channels.pipeline).await? else { + unreachable!("HVSCU's repeats are not shown"); + }; + assert_eq!(first.board, Some(HVSCU)); + assert_eq!(second.board, Some(VCU)); + assert_eq!(first.kind, ProblemKind::Shown); + + eventually(|| fake.faults.load(Ordering::SeqCst) == 1).await?; + sleep(Duration::from_millis(50)).await; + assert_eq!( + fake.faults.load(Ordering::SeqCst), + 1, + "the fault goes out once" + ); + assert!( + !event.is_finished(), + "a board fault does not stop the backend" + ); + Ok(()) +} + +#[tokio::test] +async fn forwarding_a_board_fault_can_be_turned_off() -> TestResult { + let config = EventConfig { + forward_board_faults: false, + ..EventConfig::default() + }; + let mut channels = channels(&config); + let fake = Arc::new(FakeTcp::default()); + let _event = spawn(config, channels.event, boards(), as_link(&fake)); + + channels.udp.report(fault_from(hvscu_addr())).await?; + let ToPipeline::Problem(_) = next(&mut channels.pipeline).await? else { + unreachable!("the fault is still shown"); + }; + sleep(Duration::from_millis(50)).await; + assert_eq!(fake.faults.load(Ordering::SeqCst), 0); + Ok(()) +} + +#[tokio::test] +async fn closed_queues_do_not_hide_the_others() -> TestResult { + let config = EventConfig::default(); + let Channels { + udp, + tcp, + event, + orders, + problems, + mut logging, + pipeline: _pipeline, + } = channels(&config); + drop((tcp, orders, problems)); + let _event = spawn(config, event, boards(), None); + + udp.notify(HVSCU, data()).await?; + let ToLogging::Received(batch) = next(&mut logging).await? else { + unreachable!("the UDP notification gets through"); + }; + assert_eq!(batch.len(), 1); + Ok(()) +} + +#[tokio::test] +async fn without_tcp_an_order_fails() -> TestResult { + let config = EventConfig::default(); + let mut channels = channels(&config); + let _event = spawn(config, channels.event, boards(), None); + + channels.orders.send(order(5)).await?; + let ToPipeline::OrderFailed { order, reason, .. } = next(&mut channels.pipeline).await? else { + unreachable!("the order fails"); + }; + assert_eq!(order.id, AdjId(5)); + assert_eq!(reason, orders::TCP_NOT_AVAILABLE); + Ok(()) +} + +#[tokio::test] +async fn a_written_order_is_logged() -> TestResult { + let config = EventConfig::default(); + let mut channels = channels(&config); + let fake = Arc::new(FakeTcp::default()); + let _event = spawn(config, channels.event, boards(), as_link(&fake)); + + channels.orders.send(order(5)).await?; + let ToLogging::OrderSent { board, order, .. } = next(&mut channels.logging).await? else { + unreachable!("the order is logged"); + }; + assert_eq!(board, HVSCU); + assert_eq!(order.id, AdjId(5)); + Ok(()) +} + +#[tokio::test] +async fn an_order_that_was_not_written_is_shown() -> TestResult { + let config = EventConfig::default(); + let mut channels = channels(&config); + let fake = Arc::new(FakeTcp { + refuse_orders: Some("board not connected"), + ..FakeTcp::default() + }); + let _event = spawn(config, channels.event, boards(), as_link(&fake)); + + channels.orders.send(order(5)).await?; + let ToPipeline::OrderFailed { reason, .. } = next(&mut channels.pipeline).await? else { + unreachable!("the order is shown as failed"); + }; + assert_eq!(reason, "board not connected"); + Ok(()) +} + +#[tokio::test] +async fn order_id_0_is_the_fault() -> TestResult { + let config = EventConfig::default(); + let channels = channels(&config); + let fake = Arc::new(FakeTcp::default()); + let _event = spawn(config, channels.event, boards(), as_link(&fake)); + + channels.orders.send(order(0)).await?; + eventually(|| fake.faults.load(Ordering::SeqCst) == 1).await?; + assert_eq!( + fake.orders.load(Ordering::SeqCst), + 0, + "not written as an order" + ); + Ok(()) +} + +#[tokio::test] +async fn a_fault_that_misses_boards_is_shown() -> TestResult { + let config = EventConfig::default(); + let mut channels = channels(&config); + let fake = Arc::new(FakeTcp { + unreachable: vec![VCU], + ..FakeTcp::default() + }); + let _event = spawn(config, channels.event, boards(), as_link(&fake)); + + channels.udp.report(fault_from(hvscu_addr())).await?; + let ToPipeline::Problem(fault) = next(&mut channels.pipeline).await? else { + unreachable!("the board's fault is shown"); + }; + let ToPipeline::Problem(missed) = next(&mut channels.pipeline).await? else { + unreachable!("then the boards the fault did not reach"); + }; + assert!(fault.text.contains("signalled a fault"), "{}", fault.text); + assert_eq!(missed.kind, ProblemKind::Shown); + assert!(missed.text.contains("VCU"), "{}", missed.text); + Ok(()) +} + +#[tokio::test] +async fn a_station_problem_is_traced_shown_or_stops_as_its_module_says() -> TestResult { + let config = EventConfig::default(); + let mut channels = channels(&config); + let event = spawn(config, channels.event, boards(), None); + + let silent = Problem::now(ProblemKind::Silent, None, "only for the trace"); + let shown = Problem::now(ProblemKind::Shown, None, "something to show"); + channels.problems.send(silent).await?; + channels.problems.send(shown.clone()).await?; + let ToPipeline::Problem(problem) = next(&mut channels.pipeline).await? else { + unreachable!("a shown problem reaches pipeline"); + }; + // The silent one went first, but only to the trace. + assert_eq!(problem, shown); + + let fatal = Problem::now(ProblemKind::Fatal, None, "the disk is full"); + channels.problems.send(fatal.clone()).await?; + let Stop::Fatal(stopped_by) = stops(event).await? else { + unreachable!("a fatal problem stops event"); + }; + assert_eq!(stopped_by, fatal); + Ok(()) +} + +#[tokio::test] +async fn when_logging_stops_event_stops_and_tells_pipeline() -> TestResult { + let config = EventConfig::default(); + let Channels { + udp, + tcp: _tcp, + event, + orders: _orders, + problems: _problems, + logging, + mut pipeline, + } = channels(&config); + drop(logging); + let event = spawn(config, event, boards(), None); + + udp.notify(HVSCU, data()).await?; + let ToPipeline::Problem(problem) = next(&mut pipeline).await? else { + unreachable!("pipeline is told that logging stopped"); + }; + assert_eq!(problem.kind, ProblemKind::Fatal); + assert!(problem.text.contains("logging"), "{}", problem.text); + + let Stop::Fatal(_) = stops(event).await? else { + unreachable!("losing logging is fatal"); + }; + Ok(()) +} + +#[tokio::test] +async fn when_net_closes_what_was_left_is_passed_on_and_event_stops() -> TestResult { + let config = EventConfig::default(); + let Channels { + udp, + tcp, + event, + orders: _orders, + problems: _problems, + mut logging, + pipeline: _pipeline, + } = channels(&config); + udp.notify(HVSCU, data()).await?; + udp.notify(HVSCU, data()).await?; + drop((udp, tcp)); + let event = spawn(config, event, boards(), None); + + let ToLogging::Received(batch) = next(&mut logging).await? else { + unreachable!("what was queued gets through"); + }; + assert_eq!(batch.len(), 2); + + let Stop::NetGone = stops(event).await? else { + unreachable!("both transports are gone"); + }; + // Once event has stopped, logging's queue closes: logging can finish. + assert!(timeout(WAIT, logging.recv()).await?.is_none()); + Ok(()) +} + +#[tokio::test] +async fn a_fault_that_never_goes_out_does_not_block_the_stop() -> TestResult { + let config = EventConfig { + fault_timeout: Duration::from_millis(50), + ..EventConfig::default() + }; + let channels = channels(&config); + let fake = Arc::new(FakeTcp { + fault_hangs: true, + ..FakeTcp::default() + }); + let event = spawn(config, channels.event, boards(), as_link(&fake)); + + channels.udp.report(decode_error()).await?; + let Stop::Fatal(_) = stops(event).await? else { + unreachable!("a decode error is fatal"); + }; + assert_eq!( + fake.faults.load(Ordering::SeqCst), + 1, + "the fault was attempted" + ); + Ok(()) +} From cf536764aa0229655ae9ae03a9ea3fc1295a41e6 Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Wed, 25 Nov 2026 20:13:58 +0100 Subject: [PATCH 157/225] feat(backend, websocket): detect loss of the last frontend and send "event" --- backend/crates/station/src/http/server.rs | 14 +- backend/crates/station/src/main.rs | 3 +- backend/crates/station/src/websocket.rs | 126 ++++++++++++++++-- .../crates/station/src/websocket/README.md | 6 + .../crates/station/src/websocket/handler.rs | 29 +++- 5 files changed, 157 insertions(+), 21 deletions(-) diff --git a/backend/crates/station/src/http/server.rs b/backend/crates/station/src/http/server.rs index ea6078ac0..7feb0abb8 100644 --- a/backend/crates/station/src/http/server.rs +++ b/backend/crates/station/src/http/server.rs @@ -64,7 +64,7 @@ mod tests { io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader}, net::{TcpListener, TcpStream}, sync::{mpsc, oneshot}, - time::timeout, + time::{Instant, timeout}, }; use tower::ServiceExt; @@ -280,7 +280,7 @@ mod tests { } #[tokio::test] - async fn websocket_delivers_protections_and_forwards_orders() + async fn websocket_routes_messages_until_the_last_frontend_disconnects() -> Result<(), Box> { let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("../core/src/adj/test/adj"); let adj = load_from_dir(&path)?; @@ -295,13 +295,14 @@ mod tests { let (broker, client) = Broker::new(); let broker_task = tokio::spawn(broker.run()); let (sockets, receiver) = mpsc::channel(1); + let heartbeat_timeout = Duration::from_secs(3); let socket_task = tokio::spawn(websocket::run( receiver, client.clone(), commands, - Duration::from_secs(10), + heartbeat_timeout, )); - let (headers, mut socket) = handshake(setup_router(&adj, Some(sockets))?).await?; + let (headers, mut socket) = handshake(setup_router(&adj, Some(sockets.clone()))?).await?; assert!(headers.starts_with("HTTP/1.1 101 Switching Protocols\r\n")); timeout(Duration::from_secs(5), async { @@ -343,8 +344,11 @@ mod tests { )) ); + let disconnected_at = Instant::now(); drop(socket); - socket_task.await?; + assert_eq!(socket_task.await?, Err(websocket::FrontendDisconnected)); + assert!(disconnected_at.elapsed() >= heartbeat_timeout); + drop(sockets); drop(client); broker_task.await?; Ok::<_, Box>(()) diff --git a/backend/crates/station/src/main.rs b/backend/crates/station/src/main.rs index f7c37dc45..40cba4f65 100644 --- a/backend/crates/station/src/main.rs +++ b/backend/crates/station/src/main.rs @@ -6,9 +6,10 @@ fn main() { let filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info")); tracing_subscriber::fmt().with_env_filter(filter).init(); + // TODO(event): When starting the backend here, convert FrontendDisconnected + // into a ProblemKind::Fatal with no board and send it on channels.problems. tracing::info!("iniciando demo de station"); let name = std::env::args().nth(1).unwrap_or_else(|| "World".into()); let _greeting = software_core::hello_world::greet(&name); tracing::info!("demo finalizada"); } - diff --git a/backend/crates/station/src/websocket.rs b/backend/crates/station/src/websocket.rs index ba4b2cc57..3c002f914 100644 --- a/backend/crates/station/src/websocket.rs +++ b/backend/crates/station/src/websocket.rs @@ -7,9 +7,13 @@ use std::time::Duration; use axum::extract::ws::WebSocket; use serde::{Deserialize, Serialize}; -use tokio::sync::mpsc; +use tokio::{ + sync::mpsc, + time::{Instant, sleep_until}, +}; use self::broker::BrokerClient; +use self::handler::SessionEnd; pub(crate) use self::order::OrderForwarder; use self::payload::{LoggerEnable, LoggerVariables}; @@ -93,21 +97,123 @@ pub struct WsMessage { pub payload: serde_json::Value, } +/// The last frontend's heartbeat or reconnect deadline expired. +#[derive(Debug, PartialEq, Eq, thiserror::Error)] +#[error("lost connection to the last frontend")] +pub struct FrontendDisconnected; + /// Runs one task per upgraded socket so a slow client stays isolated. -/// Closing the HTTP handoff channel ends socket intake. Existing sessions end independently. +/// +/// Returns `FrontendDisconnected` after the last session times out or the +/// reconnect window expires. Closing the HTTP handoff channel ends socket +/// intake. Existing sessions end independently. +/// +/// The caller should report `FrontendDisconnected` to `event` when station +/// wires the two modules together. pub async fn run( mut connections: mpsc::Receiver, broker: BrokerClient, commands: Commands, heartbeat_timeout: Duration, -) { - while let Some(socket) = connections.recv().await { - let broker = broker.clone(); - let commands = commands.clone(); - tokio::spawn(async move { - if let Err(error) = handler::handle(socket, broker, &commands, heartbeat_timeout).await { - tracing::warn!(%error, "WebSocket connection ended with an error"); +) -> Result<(), FrontendDisconnected> { + let (session_ends, mut ended) = mpsc::channel(16); + let mut sessions = FrontendSessions::default(); + + loop { + tokio::select! { + biased; + _ = async { + if let Some(deadline) = sessions.reconnect_deadline { + sleep_until(deadline).await; + } + }, if sessions.reconnect_deadline.is_some() => return Err(FrontendDisconnected), + socket = connections.recv() => { + let Some(socket) = socket else { return Ok(()); }; + sessions.connected(); + let broker = broker.clone(); + let commands = commands.clone(); + let session_ends = session_ends.clone(); + tokio::spawn(async move { + handler::handle(socket, broker, &commands, heartbeat_timeout, session_ends).await; + }); + } + Some(end) = ended.recv() => { + sessions.ended(end, heartbeat_timeout)?; + } + } + } +} + +/// Tracks the active frontend sessions and the reconnect window after the last one ends. +#[derive(Default)] +struct FrontendSessions { + /// Sessions accepted by the supervisor whose handlers have yet to report an end. + active: usize, + /// Set after the last session reports `SessionEnd::Closed` and cleared on reconnect. + reconnect_deadline: Option, +} + +impl FrontendSessions { + fn connected(&mut self) { + self.active += 1; + self.reconnect_deadline = None; + } + + fn ended( + &mut self, + end: SessionEnd, + reconnect_window: Duration, + ) -> Result<(), FrontendDisconnected> { + self.active -= 1; + if self.active > 0 { + return Ok(()); + } + match end { + SessionEnd::HeartbeatTimeout => Err(FrontendDisconnected), + SessionEnd::Closed(at) => { + self.reconnect_deadline = Some(at + reconnect_window); + Ok(()) } - }); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const HEARTBEAT_TIMEOUT: Duration = Duration::from_secs(3); + + #[test] + fn reconnect_cancels_the_deadline_after_the_last_socket_closes() + -> Result<(), FrontendDisconnected> { + let mut sessions = FrontendSessions::default(); + let at = Instant::now(); + + assert_eq!(sessions.reconnect_deadline, None); + sessions.connected(); + sessions.connected(); + sessions.ended(SessionEnd::Closed(at), HEARTBEAT_TIMEOUT)?; + assert_eq!(sessions.reconnect_deadline, None); + sessions.ended(SessionEnd::Closed(at), HEARTBEAT_TIMEOUT)?; + assert_eq!(sessions.reconnect_deadline, Some(at + HEARTBEAT_TIMEOUT)); + + sessions.connected(); + assert_eq!(sessions.reconnect_deadline, None); + Ok(()) + } + + #[test] + fn the_last_heartbeat_timeout_is_fatal_immediately() -> Result<(), FrontendDisconnected> { + let mut sessions = FrontendSessions::default(); + sessions.connected(); + sessions.connected(); + + sessions.ended(SessionEnd::HeartbeatTimeout, HEARTBEAT_TIMEOUT)?; + assert_eq!( + sessions.ended(SessionEnd::HeartbeatTimeout, HEARTBEAT_TIMEOUT), + Err(FrontendDisconnected) + ); + Ok(()) } } diff --git a/backend/crates/station/src/websocket/README.md b/backend/crates/station/src/websocket/README.md index acd385381..7c77a2463 100644 --- a/backend/crates/station/src/websocket/README.md +++ b/backend/crates/station/src/websocket/README.md @@ -56,6 +56,12 @@ heartbeat timeout to `station::websocket::run`. Each socket has independent reading and writing futures, coordinated by `handler.rs`. Either future finishing closes the session. +With a heartbeat timeout of three seconds, the loss of the last frontend makes +`websocket::run` return `FrontendDisconnected`. A heartbeat timeout already +satisfies that period. Other socket closures allow three seconds to reconnect. +The station startup task can report this error as a `ProblemKind::Fatal` on +`channels.problems` so `event` requests the fault and stops the backend. + Connect to `/backend/ws` on the listener's address and port and send this message to subscribe to `connection/update`. diff --git a/backend/crates/station/src/websocket/handler.rs b/backend/crates/station/src/websocket/handler.rs index f39e2bdd8..b8b80d00e 100644 --- a/backend/crates/station/src/websocket/handler.rs +++ b/backend/crates/station/src/websocket/handler.rs @@ -2,24 +2,43 @@ use std::time::Duration; use axum::extract::ws::WebSocket; use futures_util::{SinkExt, StreamExt}; -use tokio::{sync::mpsc, time::timeout}; +use tokio::{ + sync::mpsc, + time::{Instant, timeout}, +}; use super::{Commands, broker::BrokerClient, error::Error, receiver, sender}; +/// Reports why a session ended before the handler closes the socket. +pub(super) enum SessionEnd { + /// The full heartbeat timeout elapsed while waiting for an application message. + HeartbeatTimeout, + /// The session ended at this instant. For the last session, this starts the reconnect window. + Closed(Instant), +} + /// Runs reading and writing concurrently. The first side to finish ends the session. pub(super) async fn handle( socket: WebSocket, broker: BrokerClient, commands: &Commands, - heartbeat_timeout: Duration -) -> Result<(), Error> { + heartbeat_timeout: Duration, + session_ends: mpsc::Sender, +) { let (mut write, read) = socket.split(); let (changes, subscriptions) = mpsc::channel(16); let result = tokio::select! { result = receiver::run(read, &broker, commands, changes, heartbeat_timeout) => result, result = sender::run(&mut write, subscriptions) => result, }; - // Bound the socket close and preserve the result that ended the session. + let end = match result { + Err(Error::HeartbeatTimeout) => SessionEnd::HeartbeatTimeout, + _ => SessionEnd::Closed(Instant::now()), + }; + // Report the end of the session before waiting on socket I/O. + let _ = session_ends.send(end).await; + if let Err(error) = result { + tracing::warn!(%error, "WebSocket connection ended with an error"); + } let _ = timeout(Duration::from_secs(1), write.close()).await; - result } From eb988305278e14cb972bb7e9243524d1bdde4064 Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Wed, 25 Nov 2026 23:59:48 +0100 Subject: [PATCH 158/225] fix(frontend-kit): new websocket endpoint --- frontend/frontend-kit/kit/src/core/websocket.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/frontend/frontend-kit/kit/src/core/websocket.ts b/frontend/frontend-kit/kit/src/core/websocket.ts index 859c6ef70..d9a619810 100644 --- a/frontend/frontend-kit/kit/src/core/websocket.ts +++ b/frontend/frontend-kit/kit/src/core/websocket.ts @@ -26,7 +26,7 @@ import { type SocketConfig, type TopicOptions } from "./types"; const DEFAULT_CONFIG = { host: "127.0.0.1", port: 4000, - path: "/backend", + path: "/backend/ws", secure: false, heartbeatIntervalMs: 1000, } as const; From 37f4c5afab8cc5b5707b38d6f1d1105e65401c4b Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Thu, 26 Nov 2026 00:06:10 +0100 Subject: [PATCH 159/225] fix(backend, payload): create module payload --- backend/crates/station/src/http/server.rs | 7 ++++--- backend/crates/station/src/lib.rs | 1 + backend/crates/station/src/{websocket => }/payload.rs | 0 .../crates/station/src/{websocket => }/payload/README.md | 0 .../station/src/{websocket => }/payload/connection.rs | 0 .../crates/station/src/{websocket => }/payload/data.rs | 0 .../src/{websocket => }/payload/example/connection.json | 0 .../src/{websocket => }/payload/example/data.json | 0 .../{websocket => }/payload/example/logger_enable.json | 0 .../{websocket => }/payload/example/logger_response.json | 0 .../payload/example/logger_variables.json | 0 .../src/{websocket => }/payload/example/message.json | 0 .../src/{websocket => }/payload/example/order.json | 0 .../src/{websocket => }/payload/example/protection.json | 0 .../{websocket => }/payload/example/state_orders.json | 0 .../station/src/{websocket => }/payload/message.rs | 0 .../crates/station/src/{websocket => }/payload/order.rs | 0 .../station/src/{websocket => }/payload/protection.rs | 0 .../station/src/{websocket => }/payload/serialize.rs | 0 backend/crates/station/src/websocket.rs | 3 +-- backend/crates/station/src/websocket/broker.rs | 2 +- backend/crates/station/src/websocket/order.rs | 2 +- backend/crates/station/src/websocket/receiver.rs | 9 +++++---- 23 files changed, 13 insertions(+), 11 deletions(-) rename backend/crates/station/src/{websocket => }/payload.rs (100%) rename backend/crates/station/src/{websocket => }/payload/README.md (100%) rename backend/crates/station/src/{websocket => }/payload/connection.rs (100%) rename backend/crates/station/src/{websocket => }/payload/data.rs (100%) rename backend/crates/station/src/{websocket => }/payload/example/connection.json (100%) rename backend/crates/station/src/{websocket => }/payload/example/data.json (100%) rename backend/crates/station/src/{websocket => }/payload/example/logger_enable.json (100%) rename backend/crates/station/src/{websocket => }/payload/example/logger_response.json (100%) rename backend/crates/station/src/{websocket => }/payload/example/logger_variables.json (100%) rename backend/crates/station/src/{websocket => }/payload/example/message.json (100%) rename backend/crates/station/src/{websocket => }/payload/example/order.json (100%) rename backend/crates/station/src/{websocket => }/payload/example/protection.json (100%) rename backend/crates/station/src/{websocket => }/payload/example/state_orders.json (100%) rename backend/crates/station/src/{websocket => }/payload/message.rs (100%) rename backend/crates/station/src/{websocket => }/payload/order.rs (100%) rename backend/crates/station/src/{websocket => }/payload/protection.rs (100%) rename backend/crates/station/src/{websocket => }/payload/serialize.rs (100%) diff --git a/backend/crates/station/src/http/server.rs b/backend/crates/station/src/http/server.rs index 7feb0abb8..df73c4e86 100644 --- a/backend/crates/station/src/http/server.rs +++ b/backend/crates/station/src/http/server.rs @@ -69,8 +69,9 @@ mod tests { use tower::ServiceExt; use super::setup_router; - use crate::websocket::{ - self, Commands, OrderForwarder, broker::Broker, payload::ProtectionUpdate, + use crate::{ + payload::ProtectionUpdate, + websocket::{self, Commands, OrderForwarder, broker::Broker}, }; pub(in crate::http) const PATHS: [&str; 3] = [ @@ -327,7 +328,7 @@ mod tests { }) .await?; let expected: serde_json::Value = serde_json::from_str(include_str!( - "../websocket/payload/example/protection.json" + "../payload/example/protection.json" ))?; assert_eq!(read_json(&mut socket).await?, expected); diff --git a/backend/crates/station/src/lib.rs b/backend/crates/station/src/lib.rs index bcc30f85f..b7e482da0 100644 --- a/backend/crates/station/src/lib.rs +++ b/backend/crates/station/src/lib.rs @@ -1,3 +1,4 @@ pub mod http; mod vehicle; pub mod websocket; +pub mod payload; \ No newline at end of file diff --git a/backend/crates/station/src/websocket/payload.rs b/backend/crates/station/src/payload.rs similarity index 100% rename from backend/crates/station/src/websocket/payload.rs rename to backend/crates/station/src/payload.rs diff --git a/backend/crates/station/src/websocket/payload/README.md b/backend/crates/station/src/payload/README.md similarity index 100% rename from backend/crates/station/src/websocket/payload/README.md rename to backend/crates/station/src/payload/README.md diff --git a/backend/crates/station/src/websocket/payload/connection.rs b/backend/crates/station/src/payload/connection.rs similarity index 100% rename from backend/crates/station/src/websocket/payload/connection.rs rename to backend/crates/station/src/payload/connection.rs diff --git a/backend/crates/station/src/websocket/payload/data.rs b/backend/crates/station/src/payload/data.rs similarity index 100% rename from backend/crates/station/src/websocket/payload/data.rs rename to backend/crates/station/src/payload/data.rs diff --git a/backend/crates/station/src/websocket/payload/example/connection.json b/backend/crates/station/src/payload/example/connection.json similarity index 100% rename from backend/crates/station/src/websocket/payload/example/connection.json rename to backend/crates/station/src/payload/example/connection.json diff --git a/backend/crates/station/src/websocket/payload/example/data.json b/backend/crates/station/src/payload/example/data.json similarity index 100% rename from backend/crates/station/src/websocket/payload/example/data.json rename to backend/crates/station/src/payload/example/data.json diff --git a/backend/crates/station/src/websocket/payload/example/logger_enable.json b/backend/crates/station/src/payload/example/logger_enable.json similarity index 100% rename from backend/crates/station/src/websocket/payload/example/logger_enable.json rename to backend/crates/station/src/payload/example/logger_enable.json diff --git a/backend/crates/station/src/websocket/payload/example/logger_response.json b/backend/crates/station/src/payload/example/logger_response.json similarity index 100% rename from backend/crates/station/src/websocket/payload/example/logger_response.json rename to backend/crates/station/src/payload/example/logger_response.json diff --git a/backend/crates/station/src/websocket/payload/example/logger_variables.json b/backend/crates/station/src/payload/example/logger_variables.json similarity index 100% rename from backend/crates/station/src/websocket/payload/example/logger_variables.json rename to backend/crates/station/src/payload/example/logger_variables.json diff --git a/backend/crates/station/src/websocket/payload/example/message.json b/backend/crates/station/src/payload/example/message.json similarity index 100% rename from backend/crates/station/src/websocket/payload/example/message.json rename to backend/crates/station/src/payload/example/message.json diff --git a/backend/crates/station/src/websocket/payload/example/order.json b/backend/crates/station/src/payload/example/order.json similarity index 100% rename from backend/crates/station/src/websocket/payload/example/order.json rename to backend/crates/station/src/payload/example/order.json diff --git a/backend/crates/station/src/websocket/payload/example/protection.json b/backend/crates/station/src/payload/example/protection.json similarity index 100% rename from backend/crates/station/src/websocket/payload/example/protection.json rename to backend/crates/station/src/payload/example/protection.json diff --git a/backend/crates/station/src/websocket/payload/example/state_orders.json b/backend/crates/station/src/payload/example/state_orders.json similarity index 100% rename from backend/crates/station/src/websocket/payload/example/state_orders.json rename to backend/crates/station/src/payload/example/state_orders.json diff --git a/backend/crates/station/src/websocket/payload/message.rs b/backend/crates/station/src/payload/message.rs similarity index 100% rename from backend/crates/station/src/websocket/payload/message.rs rename to backend/crates/station/src/payload/message.rs diff --git a/backend/crates/station/src/websocket/payload/order.rs b/backend/crates/station/src/payload/order.rs similarity index 100% rename from backend/crates/station/src/websocket/payload/order.rs rename to backend/crates/station/src/payload/order.rs diff --git a/backend/crates/station/src/websocket/payload/protection.rs b/backend/crates/station/src/payload/protection.rs similarity index 100% rename from backend/crates/station/src/websocket/payload/protection.rs rename to backend/crates/station/src/payload/protection.rs diff --git a/backend/crates/station/src/websocket/payload/serialize.rs b/backend/crates/station/src/payload/serialize.rs similarity index 100% rename from backend/crates/station/src/websocket/payload/serialize.rs rename to backend/crates/station/src/payload/serialize.rs diff --git a/backend/crates/station/src/websocket.rs b/backend/crates/station/src/websocket.rs index 3c002f914..0b71c4a29 100644 --- a/backend/crates/station/src/websocket.rs +++ b/backend/crates/station/src/websocket.rs @@ -11,17 +11,16 @@ use tokio::{ sync::mpsc, time::{Instant, sleep_until}, }; +use super::payload::{LoggerEnable, LoggerVariables}; use self::broker::BrokerClient; use self::handler::SessionEnd; pub(crate) use self::order::OrderForwarder; -use self::payload::{LoggerEnable, LoggerVariables}; pub mod broker; mod error; mod handler; mod order; -pub(super) mod payload; mod receiver; mod sender; diff --git a/backend/crates/station/src/websocket/broker.rs b/backend/crates/station/src/websocket/broker.rs index ba7ce289d..6e3614d42 100644 --- a/backend/crates/station/src/websocket/broker.rs +++ b/backend/crates/station/src/websocket/broker.rs @@ -5,7 +5,7 @@ use std::time::Duration; -use super::payload::{ +use crate::payload::{ Connection, ConnectionUpdate, DataPacketUpdate, DataUpdate, LoggerResponse, MessageUpdate, ProtectionUpdate, StateOrdersUpdate, }; diff --git a/backend/crates/station/src/websocket/order.rs b/backend/crates/station/src/websocket/order.rs index c01f2c613..c13c30e6e 100644 --- a/backend/crates/station/src/websocket/order.rs +++ b/backend/crates/station/src/websocket/order.rs @@ -7,7 +7,7 @@ use software_core::{ use std::sync::Arc; use tokio::sync::mpsc; -use super::payload::{OrderField, OrderSend}; +use crate::payload::{OrderField, OrderSend}; /// Validates frontend requests against the ADJ and forwards them to the vehicle. #[derive(Debug, Clone)] diff --git a/backend/crates/station/src/websocket/receiver.rs b/backend/crates/station/src/websocket/receiver.rs index 23bc28965..49cf64c9e 100644 --- a/backend/crates/station/src/websocket/receiver.rs +++ b/backend/crates/station/src/websocket/receiver.rs @@ -7,15 +7,16 @@ use tokio::{ time::{Instant, timeout_at}, }; +use crate::payload::{ + ConnectionUpdate, DataUpdate, LoggerResponse, MessageUpdate, ProtectionUpdate, + StateOrdersUpdate, +}; + use super::{ Commands, HEARTBEAT, LOGGER_ENABLE, LOGGER_VARIABLES, LoggerCommand, ORDER_SEND, Topic, WsMessage, broker::BrokerClient, error::{Error, LoggerError, OrderError}, - payload::{ - ConnectionUpdate, DataUpdate, LoggerResponse, MessageUpdate, ProtectionUpdate, - StateOrdersUpdate, - }, }; #[derive(Deserialize)] From 7b9f1bf973fe6a4a7a3ece2b59b5a8603d4943cf Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Thu, 26 Nov 2026 00:13:40 +0100 Subject: [PATCH 160/225] docs(payload): update after movement --- backend/crates/station/src/payload/README.md | 44 +++++++++++++------ .../crates/station/src/websocket/README.md | 6 +-- 2 files changed, 34 insertions(+), 16 deletions(-) diff --git a/backend/crates/station/src/payload/README.md b/backend/crates/station/src/payload/README.md index f5f2b2a48..6f1de496c 100644 --- a/backend/crates/station/src/payload/README.md +++ b/backend/crates/station/src/payload/README.md @@ -1,16 +1,28 @@ -# WebSocket Message Models (`websocket::payload`) +# WebSocket Message Models (`payload`) JSON models for telemetry, connections, orders, messages, protection events -and logger control. The types live in station's `websocket/payload.rs` and -`websocket/payload/`, alongside the WebSocket implementation. +and logger control. The public module is `station::payload`, declared in +[`../payload.rs`](../payload.rs), with its implementation in `src/payload/`. The Rust types describe the payload of each topic. Messages sent over the WebSocket wrap that payload in `{topic, payload}`, as shown in the templates and example files below. Connections, subscriptions, channels and the broker -are handled by the surrounding [WebSocket module](../README.md). Shared +are handled by the [WebSocket module](../websocket/README.md). Shared serialization helpers live in [serialize.rs](serialize.rs), and domain types such as `AdjId`, `Value` and `ProtectionPacket` come from `software_core::model`. +## Files + +| File | Models and responsibility | +| --- | --- | +| [`../payload.rs`](../payload.rs) | Public re-exports and logger payload aliases. | +| [`data.rs`](data.rs) | `DataUpdate`, `DataPacketUpdate` and measurement values. | +| [`connection.rs`](connection.rs) | `ConnectionUpdate` and `Connection`. | +| [`order.rs`](order.rs) | `OrderSend`, `OrderField` and `StateOrdersUpdate`. | +| [`message.rs`](message.rs) | `MessageUpdate`, its severity, content and calendar timestamp. | +| [`protection.rs`](protection.rs) | `ProtectionUpdate`, conversion from `ProtectionPacket` and legacy `ProtectionPayload`. | +| [`serialize.rs`](serialize.rs) | Internal Serde adapters for `AdjId` and `Value`. | + ## Topics | Topic | Payload type | Direction | JSON example | @@ -32,10 +44,10 @@ independent of the bundled ADJ fixture and HTTP catalog examples. ## Usage The payload module is compiled as part of station, without a separate feature. -Within station, with a decoded `packet: software_core::model::ProtectionPacket`: +With a decoded `packet: software_core::model::ProtectionPacket`: ```rust -use crate::websocket::payload::{OrderSend, ProtectionUpdate}; +use station::payload::{OrderSend, ProtectionUpdate}; let request: OrderSend = serde_json::from_str(r#"{"id":1002,"fields":{}}"#)?; let protection = ProtectionUpdate::from(packet); @@ -44,11 +56,15 @@ let payload_json = serde_json::to_string(&protection)?; Published structures implement `serde::Serialize`; `OrderSend` and `OrderField` implement `serde::Deserialize`. The logger aliases use the primitive types' -Serde implementations. The payload module is internal to the station library. +Serde implementations. Within station itself, import these types through +`crate::payload`. The implementation submodules are private; use the types +re-exported by `payload`. -Deserializing an order checks its JSON structure. Parameter types, ranges and -their correspondence with the ADJ must be validated by the application before -converting it to an `OrderPacket`. +Deserializing an order checks its JSON structure and the unsigned 16-bit ID. +The [WebSocket order handler](../websocket/order.rs) then validates the order +ID, parameter aliases, types and wire ranges against the ADJ, arranges the +values in ADJ order and queues an `OrderPacket` for the vehicle. Callers that +deserialize `OrderSend` directly must perform that validation themselves. ## JSON Structure Templates @@ -88,8 +104,9 @@ it as a string. ``` The outer key matches the packet's `id`. `count` is the received packet count; -`cycleTime` is the averaged interval between packet receptions. The publisher -supplies these statistics and the hexadecimal packet representation. +`cycleTime` is the averaged interval between packet receptions, in the legacy +timestamp's units. This module does not convert it. The publisher supplies +these statistics and the hexadecimal packet representation. `MeasurementUpdate` has three JSON forms: `{last, average}` for a number, a boolean, or an enum variant string. There is no additional discriminator @@ -110,7 +127,8 @@ around a measurement value. ``` The map key matches `name`. The state describes the connection between the -backend and the board. +backend and the board. Disconnected boards remain in the broker's snapshot +with `isConnected: false`. ### Send Order (`OrderSend`) diff --git a/backend/crates/station/src/websocket/README.md b/backend/crates/station/src/websocket/README.md index 7c77a2463..20fdf3a91 100644 --- a/backend/crates/station/src/websocket/README.md +++ b/backend/crates/station/src/websocket/README.md @@ -1,10 +1,10 @@ # WebSocket `broker.rs` provides `Broker` and the clonable `BrokerClient` for state and event topics, -using the types from `crate::websocket::payload`. -See the [payload models README](payload/README.md) for all topic payloads, +using the types from `crate::payload`, exposed publicly as `station::payload`. +See the [payload models README](../payload/README.md) for all topic payloads, JSON templates, and complete message examples. Their serialization helpers -live in [`payload/serialize.rs`](payload/serialize.rs). +live in [`../payload/serialize.rs`](../payload/serialize.rs). | Topic | Publish through `BrokerClient` | Subscribe through `BrokerClient` | Initial state | | --- | --- | --- | --- | From 152ad49d73e50bf45d94985040c0d2682f86827a Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Thu, 26 Nov 2026 00:21:09 +0100 Subject: [PATCH 161/225] feat(backend, payload): return of isEnabled to websocket payloads for order/send --- backend/crates/station/src/http/server.rs | 2 +- backend/crates/station/src/payload/README.md | 4 ++ .../station/src/payload/example/order.json | 1 + backend/crates/station/src/payload/order.rs | 45 +++++++++++++++++++ backend/crates/station/src/websocket/order.rs | 2 + 5 files changed, 53 insertions(+), 1 deletion(-) diff --git a/backend/crates/station/src/http/server.rs b/backend/crates/station/src/http/server.rs index df73c4e86..f69f2e434 100644 --- a/backend/crates/station/src/http/server.rs +++ b/backend/crates/station/src/http/server.rs @@ -334,7 +334,7 @@ mod tests { send_text( &mut socket, - r#"{"topic":"order/send","payload":{"id":809,"fields":{"desired_current":{"value":12.5,"type":"float32"},"lpu_id":{"value":2,"type":"uint32"}}}}"#, + r#"{"topic":"order/send","payload":{"id":809,"fields":{"desired_current":{"value":12.5,"isEnabled":false,"type":"float32"},"lpu_id":{"value":2,"isEnabled":true,"type":"uint32"}}}}"#, ) .await?; assert_eq!( diff --git a/backend/crates/station/src/payload/README.md b/backend/crates/station/src/payload/README.md index 6f1de496c..85ce46480 100644 --- a/backend/crates/station/src/payload/README.md +++ b/backend/crates/station/src/payload/README.md @@ -140,6 +140,7 @@ with `isConnected: false`. "fields": { "": { "value": number, // A boolean or enum string is also possible. + "isEnabled": boolean, "type": string } } @@ -148,6 +149,9 @@ with `isConnected: false`. ``` An order without parameters has `fields: {}`. Parameter names are aliases. +`isEnabled` preserves the legacy frontend flag and defaults to `false` when +omitted. As in the Go backend, it does not skip validation or encoding: +all parameters declared by the ADJ must be supplied, even with `isEnabled: false`. The application uses the ADJ to place their values in wire order. The `value` field remains raw JSON until validation. Integer fields must contain whole numbers that fit both the wire type and the packet's `f64` representation. diff --git a/backend/crates/station/src/payload/example/order.json b/backend/crates/station/src/payload/example/order.json index 0aa349cb0..853111e21 100644 --- a/backend/crates/station/src/payload/example/order.json +++ b/backend/crates/station/src/payload/example/order.json @@ -5,6 +5,7 @@ "fields": { "target_speed": { "value": 12.5, + "isEnabled": true, "type": "float32" } } diff --git a/backend/crates/station/src/payload/order.rs b/backend/crates/station/src/payload/order.rs index c40dbd6ea..615b1a0ca 100644 --- a/backend/crates/station/src/payload/order.rs +++ b/backend/crates/station/src/payload/order.rs @@ -18,6 +18,10 @@ pub struct OrderSend { pub struct OrderField { /// Raw JSON value retained so integer precision can be checked before conversion to `f64`. pub value: serde_json::Value, + /// Legacy frontend flag, defaulting to false when omitted. + /// As in Go, it does not exclude the parameter from validation or wire encoding. + #[serde(default, rename = "isEnabled")] + pub is_enabled: bool, /// Frontend type name, such as `uint16` or `bool`. The converter checks it against the ADJ. #[serde(rename = "type")] pub field_type: String, @@ -25,3 +29,44 @@ pub struct OrderField { /// Payload of `order/stateOrders`: board names mapped to enabled order ids. pub type StateOrdersUpdate = HashMap>; + +#[cfg(test)] +mod tests { + use serde_json::json; + + use super::OrderSend; + + #[test] + fn order_fields_read_is_enabled_with_the_legacy_default() -> Result<(), serde_json::Error> { + for enabled in [Some(true), Some(false), None] { + let mut field = json!({"value": 12.5, "type": "float32"}); + if let Some(enabled) = enabled { + field["isEnabled"] = json!(enabled); + } + let request: OrderSend = serde_json::from_value(json!({ + "id": 1001, + "fields": {"target_speed": field} + }))?; + assert_eq!( + request.fields["target_speed"].is_enabled, + enabled.unwrap_or(false) + ); + } + Ok(()) + } + + #[test] + fn order_fields_reject_non_boolean_is_enabled() { + for enabled in [json!("true"), json!(1), json!(null)] { + assert!( + serde_json::from_value::(json!({ + "id": 1001, + "fields": { + "target_speed": {"value": 12.5, "type": "float32", "isEnabled": enabled} + } + })) + .is_err() + ); + } + } +} diff --git a/backend/crates/station/src/websocket/order.rs b/backend/crates/station/src/websocket/order.rs index c13c30e6e..c1805ec4d 100644 --- a/backend/crates/station/src/websocket/order.rs +++ b/backend/crates/station/src/websocket/order.rs @@ -46,6 +46,7 @@ fn to_packet(mut request: OrderSend, index: &Index) -> Result Date: Tue, 1 Dec 2026 10:45:07 +0100 Subject: [PATCH 162/225] feat(backend, model): relaction functions --- backend/crates/core/src/model/board.rs | 55 ++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) diff --git a/backend/crates/core/src/model/board.rs b/backend/crates/core/src/model/board.rs index 2dc56b6b7..204ebf7e2 100644 --- a/backend/crates/core/src/model/board.rs +++ b/backend/crates/core/src/model/board.rs @@ -97,6 +97,27 @@ pub struct PodData { pub boards: HashMap, } +impl PodData { + /// The board's name as the ADJ declares it (`"HVSCU"`), or `None` if no + /// board has that id. + pub fn board_name(&self, id: BoardId) -> Option<&str> { + self.boards.get(&id).map(|board| board.name.as_str()) + } + + /// Which board each IP address belongs to: every board's + /// [`Board::ip`], pointing at its id. + /// + /// For whoever only knows where something came from, such as a + /// datagram's sender. Two boards declaring the same IP would leave only + /// one of them in the map; the ADJ gives every board its own. + pub fn boards_by_ip(&self) -> HashMap { + self.boards + .values() + .map(|board| (board.ip, board.id)) + .collect() + } +} + #[cfg(test)] mod tests { use super::*; @@ -147,4 +168,38 @@ mod tests { assert_eq!(measurements.len(), 1); assert_eq!(board.mac.to_string(), "00:11:22:33:44:55"); } + + fn two_boards() -> PodData { + let board = |id: u16, name: &str, last_octet: u8| Board { + id: BoardId(id), + name: name.to_string(), + ip: IpAddr::from([192, 168, 0, last_octet]), + mac: MacAddress([0; 6]), + packets: HashMap::new(), + }; + PodData { + boards: HashMap::from([ + (BoardId(1), board(1, "BCU", 10)), + (BoardId(2), board(2, "VCU", 11)), + ]), + } + } + + #[test] + fn a_board_is_named_as_the_adj_declares_it() { + let pod_data = two_boards(); + assert_eq!(pod_data.board_name(BoardId(2)), Some("VCU")); + assert_eq!(pod_data.board_name(BoardId(9)), None); + } + + #[test] + fn every_board_ip_points_at_its_board() { + let by_ip = two_boards().boards_by_ip(); + assert_eq!(by_ip.len(), 2); + assert_eq!( + by_ip.get(&IpAddr::from([192, 168, 0, 11])), + Some(&BoardId(2)) + ); + assert_eq!(by_ip.get(&IpAddr::from([192, 168, 0, 99])), None); + } } From bba52df2198f773f972da6bc2170db821dfe3129 Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Tue, 1 Dec 2026 10:48:24 +0100 Subject: [PATCH 163/225] feat(backend, udp): obtain board on errors --- backend/crates/core/src/net/README.md | 11 +- backend/crates/core/src/net/report.rs | 14 ++- backend/crates/core/src/net/udp.rs | 104 ++++++++++++---- .../crates/core/src/net/udp/manual_tests.rs | 8 +- .../crates/core/src/net/udp/test_support.rs | 29 ++++- backend/crates/core/src/net/udp/tests.rs | 112 +++++++++++++++--- 6 files changed, 221 insertions(+), 57 deletions(-) diff --git a/backend/crates/core/src/net/README.md b/backend/crates/core/src/net/README.md index dde1b5bd3..50b0f78dd 100644 --- a/backend/crates/core/src/net/README.md +++ b/backend/crates/core/src/net/README.md @@ -85,9 +85,10 @@ that it can afford to queue behind telemetry. `ErrorReport` carries **no board**, unlike a notification: the identity of what failed lives inside the `Error` variant, which is the only place that always has -it. A datagram that fails to decode resolves to no board at all — its id is not in -the ADJ, so there is no `PacketDef` to ask — and all that can be said about it is -the address it came from, which is what `udp::UdpError::Decode` holds. +it. A datagram that fails to decode has no id to resolve a board from — it is not +in the ADJ, so there is no `PacketDef` to ask — so `udp::UdpError::Decode` holds the +address it came from and the board that address belongs to, if it belongs to one +(`UdpConfig::boards`). `UdpError::Fault` carries the same two. ### `Error` — aggregation only @@ -104,7 +105,7 @@ submodule's own error: nobody outside knows which of its variants are fatal. | | `tcp` | `udp` | |---|---|---| | Entry point | `spawn(Config, Arc, Reporter) -> Handles` | `spawn_udp(UdpConfig, Arc, Reporter) -> Result, UdpError>` (binds first) | -| Inputs | its `Config` (boards, timeouts, backoff, keep-alive) | its `Config` (bind address, `SO_RCVBUF`) | +| Inputs | its `Config` (boards, timeouts, backoff, keep-alive) | its `UdpConfig` (bind address, `SO_RCVBUF`, IP → board) | | Role | client only; one connection per board, one task each | one shared socket, receive-only, one task | | Framing | buffer + `&mut Cursor` + advance by `cursor.position()`; bail out past 374 bytes | none — `recv_from` delivers a whole datagram into a reused 64 KiB buffer | | Writing | yes (orders, keep-alive); a single writer task per connection | no | @@ -123,7 +124,7 @@ reads `is_fatal()` and calls `Handles::propagate_fault()`, which puts the order with id 0 into every board's writer channel (the Go backend's `SendFault`). A *received* packet with id 0 is the same action requested by a board, and `station` answers it the same way. In `udp` it arrives on the error channel as -`UdpError::Fault { from }`: recognised by its id alone, before decoding, without +`UdpError::Fault { from, board }`: recognised by its id alone, before decoding, without looking at the ADJ. Three rules both follow: diff --git a/backend/crates/core/src/net/report.rs b/backend/crates/core/src/net/report.rs index 7ff356f1f..4ad86342f 100644 --- a/backend/crates/core/src/net/report.rs +++ b/backend/crates/core/src/net/report.rs @@ -53,11 +53,11 @@ pub struct Notification { /// /// Carries no identity of its own: whose failure it was travels inside /// the [`Error`]'s own variant, which is the only place that always has -/// it. A datagram that fails to decode, for instance, resolves to no -/// board at all — its id is not in the ADJ, so there is no -/// [`crate::model::PacketDef`] to ask — and all that can be said about -/// it is the address it came from, which is exactly what -/// [`super::udp::UdpError::Decode`] holds. +/// it. A datagram that fails to decode, for instance, has no id to resolve +/// a board from — it is not in the ADJ, so there is no +/// [`crate::model::PacketDef`] to ask — so +/// [`super::udp::UdpError::Decode`] holds the address it came from, and +/// the board that address belongs to only if it belongs to one. #[derive(Debug)] pub struct ErrorReport { /// The instant the failure was reported, on the same clock as @@ -345,15 +345,17 @@ mod tests { let addr = SocketAddr::new(IpAddr::from([192, 168, 1, 3]), 50400); let error = udp::UdpError::Decode { from: addr, + board: None, source: crate::protocol::DecodeError::UnknownId(AdjId(9999)), }; // The whole reason an error report carries no board: this one has // an address, and no board to attribute it to. - let Error::Udp(udp::UdpError::Decode { from, .. }) = Error::from(error) else { + let Error::Udp(udp::UdpError::Decode { from, board, .. }) = Error::from(error) else { unreachable!("a decode error should convert into Error::Udp"); }; assert_eq!(from, addr); + assert_eq!(board, None); } #[tokio::test] diff --git a/backend/crates/core/src/net/udp.rs b/backend/crates/core/src/net/udp.rs index e1be8f6cb..a4c719387 100644 --- a/backend/crates/core/src/net/udp.rs +++ b/backend/crates/core/src/net/udp.rs @@ -37,6 +37,13 @@ //! notification looks the same whichever transport brought it. That is //! one `HashMap` lookup per datagram, done here once rather than //! repeated by every consumer downstream. +//! - **An error names its board too, when it can.** A fault or a datagram +//! that will not decode has no id to resolve, so its board comes from +//! the address it was sent from, through [`UdpConfig::boards`]. Both +//! variants carry the address and that board (`None` if the address +//! belongs to no board), so the consumer gets the identity ready, as it +//! does from [`super::tcp`]. The lookup only happens on those two paths, +//! never for a datagram that decodes. //! - **A decode failure is reported as fatal** (see [`UdpError::is_fatal`]), //! but acting on it is not this module's call. Nothing corrupts a //! datagram in flight — UDP checksums it and the pod's network does not @@ -91,9 +98,10 @@ //! ``` use super::Reporter; -use crate::model::Packet; +use crate::model::{BoardId, Packet}; use crate::protocol::{DecodeError, Index}; -use std::net::SocketAddr; +use std::collections::HashMap; +use std::net::{IpAddr, SocketAddr}; use std::sync::Arc; use std::time::{Duration, Instant}; use tokio::task::JoinHandle; @@ -103,7 +111,7 @@ use tracing::{error, info, warn}; /// /// Everything here is resolved by `station` before `net` is reached: this /// module reads no config file and no ADJ of its own. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq, Eq)] pub struct UdpConfig { /// Where to bind: the backend's own address, `addresses["backend"]` /// and `ports["UDP"]` in the ADJ's `general_info.json`. @@ -134,6 +142,13 @@ pub struct UdpConfig { /// it at `net.core.rmem_max` — so [`spawn_udp`] reads the granted size back /// and warns when it is smaller than requested. pub recv_buffer: usize, + /// Which board each address belongs to, so that an error can name the + /// board it came from: [`UdpError::Decode`] and [`UdpError::Fault`]. + /// + /// Built from the ADJ with [`crate::model::PodData::boards_by_ip`]. An + /// address missing from it is not refused: its errors just carry no + /// board. + pub boards: HashMap, } /// Binds the shared socket and spawns the receive loop. @@ -160,13 +175,13 @@ pub fn spawn_udp( adj: Arc, reporter: Reporter, ) -> Result, UdpError> { - let socket = bind_telemetry_socket(config)?; - let handle = tokio::spawn(receive_telemetry(socket, adj, reporter)); + let socket = bind_telemetry_socket(&config)?; + let handle = tokio::spawn(receive_telemetry(socket, adj, config.boards, reporter)); Ok(handle) } /// Binds a UDP socket and configures its OS-level receive buffer size (`SO_RCVBUF`). -fn bind_telemetry_socket(config: UdpConfig) -> Result { +fn bind_telemetry_socket(config: &UdpConfig) -> Result { // Bind using the standard library socket first so we can configure non-blocking mode. let std_socket = std::net::UdpSocket::bind(config.addr).map_err(|source| UdpError::Bind { addr: config.addr, @@ -236,7 +251,12 @@ fn bind_telemetry_socket(config: UdpConfig) -> Result, reporter: Reporter) { +async fn receive_telemetry( + socket: tokio::net::UdpSocket, + adj: Arc, + boards: HashMap, + reporter: Reporter, +) { // Reusable 64 KiB buffer — a datagram can never be silently truncated. let mut buf = vec![0u8; 64 * 1024]; let mut traces = ReceiveTraces::default(); @@ -244,7 +264,11 @@ async fn receive_telemetry(socket: tokio::net::UdpSocket, adj: Arc, repor loop { match socket.recv_from(&mut buf).await { Ok((len, from)) => { - if !decode_and_report(&buf[..len], from, &adj, &reporter, &mut traces).await { + let lookups = Lookups { + adj: &adj, + boards: &boards, + }; + if !decode_and_report(&buf[..len], from, lookups, &reporter, &mut traces).await { // Downstream channels closed; exit cleanly. break; } @@ -268,33 +292,58 @@ async fn receive_telemetry(socket: tokio::net::UdpSocket, adj: Arc, repor /// raises a fault itself (`SendFault`). const FAULT_ID: [u8; 2] = 0u16.to_le_bytes(); -/// Decodes a single datagram slice against `adj` and forwards the result or error to `reporter`. +/// What the receive loop looks things up in, both read-only. +#[derive(Debug, Clone, Copy)] +struct Lookups<'a> { + /// A decoded id to its definition, and through it to its board. + adj: &'a Index, + /// A sender's address to its board, for errors: see [`UdpConfig::boards`]. + boards: &'a HashMap, +} + +impl Lookups<'_> { + /// The board `from` belongs to, if any. + fn board_at(&self, from: SocketAddr) -> Option { + self.boards.get(&from.ip()).copied() + } +} + +/// Decodes a single datagram slice against the ADJ and forwards the result or error to `reporter`. /// /// A fault (packet id 0, see [`FAULT_ID`]) is reported before any of that, -/// without looking at `adj`. +/// without looking at the ADJ. /// /// Returns `false` if the downstream `reporter` channels have closed and the loop should stop. async fn decode_and_report( bytes: &[u8], from: SocketAddr, - adj: &Index, + lookups: Lookups<'_>, reporter: &Reporter, traces: &mut ReceiveTraces, ) -> bool { if bytes.starts_with(&FAULT_ID) { + let board = lookups.board_at(from); if let Some(suppressed) = traces.fault.should_trace(Instant::now()) { - error!(%from, suppressed, "a board signalled a fault (packet id 0)"); + error!(%from, ?board, suppressed, "a board signalled a fault (packet id 0)"); } - return reporter.report(UdpError::Fault { from }).await.is_ok(); + return reporter + .report(UdpError::Fault { from, board }) + .await + .is_ok(); } - let packet = match crate::protocol::udp::decode_datagram(bytes, adj) { + let packet = match crate::protocol::udp::decode_datagram(bytes, lookups.adj) { Ok(p) => p, Err(source) => { + let board = lookups.board_at(from); if let Some(suppressed) = traces.decode.should_trace(Instant::now()) { - error!(%from, %source, suppressed, "UDP datagram could not be decoded"); + error!(%from, ?board, %source, suppressed, "UDP datagram could not be decoded"); } - let error = UdpError::Decode { from, source }; + let error = UdpError::Decode { + from, + board, + source, + }; return reporter.report(error).await.is_ok(); } }; @@ -305,7 +354,7 @@ async fn decode_and_report( // run; it is handled rather than unwrapped because the decode lives // in another module. One extra `HashMap` lookup per datagram is not // worth changing `protocol`'s API to avoid. - let Some(packet_def) = adj.packet(packet.id) else { + let Some(packet_def) = lookups.adj.packet(packet.id) else { warn!(id = ?packet.id, "decoded packet id not in index"); return true; }; @@ -370,11 +419,11 @@ impl TraceRateLimit { /// Something that went wrong on the shared UDP socket, or that a board /// says went wrong ([`UdpError::Fault`]). /// -/// No [`crate::model::BoardId`] in any variant, on purpose: the socket -/// belongs to no board, and a datagram that fails to decode may not -/// resolve to one at all — [`UdpError::Decode`] and [`UdpError::Fault`] -/// carry the address the datagram came from, which is the only identity -/// that always exists. +/// [`UdpError::Decode`] and [`UdpError::Fault`] concern one datagram, so +/// they carry the address it came from, the only identity that always +/// exists, and the board that address belongs to, when it belongs to one +/// (see [`UdpConfig::boards`]). [`UdpError::Bind`] and [`UdpError::Recv`] +/// concern the socket, which belongs to no board. #[derive(Debug, thiserror::Error)] pub enum UdpError { /// The socket could not be bound, so no telemetry will arrive at all. @@ -400,9 +449,10 @@ pub enum UdpError { /// [`UdpError::is_fatal`]. #[error("could not decode a datagram from {from}")] Decode { - /// Where the datagram came from — there may be no board to - /// attribute it to. + /// Where the datagram came from. from: SocketAddr, + /// The board `from` belongs to; `None` if it belongs to none. + board: Option, /// What [`crate::protocol`] said about it. #[source] source: DecodeError, @@ -413,9 +463,11 @@ pub enum UdpError { /// arrived fine — but the pod telling the backend it is in trouble. #[error("the board at {from} signalled a fault (packet id 0)")] Fault { - /// Where the fault came from: the board's address, since a fault - /// carries nothing else that says which board sent it. + /// Where the fault came from. A fault carries nothing else that + /// says which board sent it. from: SocketAddr, + /// The board `from` belongs to; `None` if it belongs to none. + board: Option, }, } diff --git a/backend/crates/core/src/net/udp/manual_tests.rs b/backend/crates/core/src/net/udp/manual_tests.rs index eb890291d..a992487bd 100644 --- a/backend/crates/core/src/net/udp/manual_tests.rs +++ b/backend/crates/core/src/net/udp/manual_tests.rs @@ -155,7 +155,13 @@ async fn manual_udp_load() { let (socket, addr) = bind_on_loopback(recv_buffer); let granted = socket2::SockRef::from(&socket).recv_buffer_size().ok(); let (reporter, mut sinks) = Reporter::channels(8192, 16); - let receiver = tokio::spawn(receive_telemetry(socket, Arc::new(index), reporter)); + // No boards by address: the probe sends nothing that fails. + let receiver = tokio::spawn(receive_telemetry( + socket, + Arc::new(index), + HashMap::new(), + reporter, + )); // Counts until told the sender is done, then drains what is left. No // timer per message, so that the consumer costs as little as possible diff --git a/backend/crates/core/src/net/udp/test_support.rs b/backend/crates/core/src/net/udp/test_support.rs index aa8425133..11cfa9ff9 100644 --- a/backend/crates/core/src/net/udp/test_support.rs +++ b/backend/crates/core/src/net/udp/test_support.rs @@ -23,11 +23,25 @@ pub(super) const UNKNOWN_ID_DATAGRAM: [u8; 2] = [0xFF, 0xFF]; /// declare either — a fault is recognised without the ADJ. pub(super) const FAULT_DATAGRAM: [u8; 2] = [0x00, 0x00]; +/// The board every fixture here declares. +pub(super) const TEST_BOARD: BoardId = BoardId(1); + /// A board's address on the pod's network, for errors that carry one. pub(super) fn example_board_addr() -> SocketAddr { SocketAddr::new(IpAddr::from([192, 168, 1, 3]), 50400) } +/// An address that belongs to no board. +pub(super) fn stranger_addr() -> SocketAddr { + SocketAddr::new(IpAddr::from([192, 168, 1, 99]), 50400) +} + +/// [`UdpConfig::boards`] with a single entry: `ip` belongs to +/// [`TEST_BOARD`]. +pub(super) fn boards_at(ip: IpAddr) -> HashMap { + HashMap::from([(ip, TEST_BOARD)]) +} + /// `127.0.0.1` with port 0, so that the OS picks a free one. pub(super) fn any_loopback_port() -> SocketAddr { SocketAddr::new(IpAddr::from([127, 0, 0, 1]), 0) @@ -41,12 +55,12 @@ pub(super) fn any_loopback_port() -> SocketAddr { pub(super) fn index_with_empty_data_packet() -> Index { let packet = PacketDef { id: AdjId(1000), - board: BoardId(1), + board: TEST_BOARD, name: "test_data".to_string(), packet_type: PacketType::Data(vec![]), }; let board = Board { - id: BoardId(1), + id: TEST_BOARD, name: "TEST".to_string(), ip: IpAddr::from([192, 168, 0, 10]), mac: MacAddress([0; 6]), @@ -78,7 +92,7 @@ pub(super) async fn receive_error_report(sinks: &mut Sinks) -> ErrorReport { /// Asserts that `notification` is what [`EMPTY_DATA_DATAGRAM`] decodes to. pub(super) fn assert_is_empty_data_packet(notification: Notification) { - assert_eq!(notification.board, BoardId(1)); + assert_eq!(notification.board, TEST_BOARD); let Event::Received(Packet::Data(packet)) = notification.event else { unreachable!("a datagram should arrive as Event::Received(Packet::Data)"); }; @@ -92,8 +106,9 @@ pub(super) fn bind_on_loopback(recv_buffer: usize) -> (tokio::net::UdpSocket, So let config = UdpConfig { addr: any_loopback_port(), recv_buffer, + boards: HashMap::new(), }; - let Ok(socket) = bind_telemetry_socket(config) else { + let Ok(socket) = bind_telemetry_socket(&config) else { unreachable!("binding to a free loopback port should succeed"); }; let Ok(addr) = socket.local_addr() else { @@ -105,10 +120,14 @@ pub(super) fn bind_on_loopback(recv_buffer: usize) -> (tokio::net::UdpSocket, So /// Starts receiving on a free loopback port with /// [`index_with_empty_data_packet`], as [`spawn_udp`] does, and returns the /// address to send to along with the task's handle. +/// +/// `127.0.0.1`, where [`bind_fake_board`] sends from, belongs to +/// [`TEST_BOARD`]. pub(super) fn start_receiving_on_loopback(reporter: Reporter) -> (SocketAddr, JoinHandle<()>) { let (socket, addr) = bind_on_loopback(256 * 1024); let index = Arc::new(index_with_empty_data_packet()); - let handle = tokio::spawn(receive_telemetry(socket, index, reporter)); + let boards = boards_at(any_loopback_port().ip()); + let handle = tokio::spawn(receive_telemetry(socket, index, boards, reporter)); (addr, handle) } diff --git a/backend/crates/core/src/net/udp/tests.rs b/backend/crates/core/src/net/udp/tests.rs index b71efb004..01bcfe99c 100644 --- a/backend/crates/core/src/net/udp/tests.rs +++ b/backend/crates/core/src/net/udp/tests.rs @@ -13,6 +13,7 @@ use crate::model::AdjId; fn a_datagram_that_will_not_decode_faults_the_pod() { let error = UdpError::Decode { from: example_board_addr(), + board: Some(TEST_BOARD), source: DecodeError::UnknownId(AdjId(9999)), }; @@ -32,6 +33,7 @@ fn losing_the_socket_faults_the_pod_too() { fn a_decode_failure_says_where_it_came_from() { let error = UdpError::Decode { from: example_board_addr(), + board: Some(TEST_BOARD), source: DecodeError::UnknownId(AdjId(9999)), }; @@ -42,6 +44,7 @@ fn a_decode_failure_says_where_it_came_from() { fn a_board_signalling_a_fault_faults_the_pod() { let error = UdpError::Fault { from: example_board_addr(), + board: Some(TEST_BOARD), }; assert!(error.is_fatal()); @@ -51,6 +54,7 @@ fn a_board_signalling_a_fault_faults_the_pod() { fn a_fault_says_where_it_came_from() { let error = UdpError::Fault { from: example_board_addr(), + board: Some(TEST_BOARD), }; assert!(error.to_string().contains("192.168.1.3:50400")); @@ -64,12 +68,17 @@ fn a_fault_says_where_it_came_from() { async fn decode_and_report_notifies_a_valid_datagram() { let (reporter, mut sinks) = Reporter::channels(16, 16); let index = index_with_empty_data_packet(); + let boards = boards_at(example_board_addr().ip()); + let lookups = Lookups { + adj: &index, + boards: &boards, + }; let mut traces = ReceiveTraces::default(); let keep_going = decode_and_report( &EMPTY_DATA_DATAGRAM, example_board_addr(), - &index, + lookups, &reporter, &mut traces, ) @@ -84,15 +93,20 @@ async fn decode_and_report_notifies_a_valid_datagram() { } #[tokio::test] -async fn decode_and_report_reports_an_unknown_id() { +async fn decode_and_report_reports_an_unknown_id_with_its_board() { let (reporter, mut sinks) = Reporter::channels(16, 16); let index = index_with_empty_data_packet(); + let boards = boards_at(example_board_addr().ip()); + let lookups = Lookups { + adj: &index, + boards: &boards, + }; let mut traces = ReceiveTraces::default(); let keep_going = decode_and_report( &UNKNOWN_ID_DATAGRAM, example_board_addr(), - &index, + lookups, &reporter, &mut traces, ) @@ -100,10 +114,16 @@ async fn decode_and_report_reports_an_unknown_id() { assert!(keep_going); let report = receive_error_report(&mut sinks).await; - let crate::net::Error::Udp(UdpError::Decode { from, source }) = report.error else { + let crate::net::Error::Udp(UdpError::Decode { + from, + board, + source, + }) = report.error + else { unreachable!("an undecodable datagram should be reported as udp::UdpError::Decode"); }; assert_eq!(from, example_board_addr()); + assert_eq!(board, Some(TEST_BOARD), "resolved from the address"); assert!(matches!(source, DecodeError::UnknownId(AdjId(0xFFFF)))); assert!( sinks.notifications.try_recv().is_err(), @@ -116,12 +136,17 @@ async fn decode_and_report_reports_a_fault_without_looking_at_the_adj() { let (reporter, mut sinks) = Reporter::channels(16, 16); // Declares id 1000 only: id 0 is unknown to it, and yet it is a fault. let index = index_with_empty_data_packet(); + let boards = boards_at(example_board_addr().ip()); + let lookups = Lookups { + adj: &index, + boards: &boards, + }; let mut traces = ReceiveTraces::default(); let keep_going = decode_and_report( &FAULT_DATAGRAM, example_board_addr(), - &index, + lookups, &reporter, &mut traces, ) @@ -129,26 +154,72 @@ async fn decode_and_report_reports_a_fault_without_looking_at_the_adj() { assert!(keep_going); let report = receive_error_report(&mut sinks).await; - let crate::net::Error::Udp(UdpError::Fault { from }) = report.error else { + let crate::net::Error::Udp(UdpError::Fault { from, board }) = report.error else { unreachable!("a datagram with packet id 0 should be reported as udp::UdpError::Fault"); }; assert_eq!(from, example_board_addr()); + assert_eq!(board, Some(TEST_BOARD), "resolved from the address"); assert!( sinks.notifications.try_recv().is_err(), "should not have notified a packet" ); } +#[tokio::test] +async fn an_address_that_belongs_to_no_board_is_reported_without_one() { + let (reporter, mut sinks) = Reporter::channels(16, 16); + let index = index_with_empty_data_packet(); + let boards = boards_at(example_board_addr().ip()); + let lookups = Lookups { + adj: &index, + boards: &boards, + }; + let mut traces = ReceiveTraces::default(); + + decode_and_report( + &FAULT_DATAGRAM, + stranger_addr(), + lookups, + &reporter, + &mut traces, + ) + .await; + decode_and_report( + &UNKNOWN_ID_DATAGRAM, + stranger_addr(), + lookups, + &reporter, + &mut traces, + ) + .await; + + // Still reported, with the address: only the board is missing. + let fault = receive_error_report(&mut sinks).await; + let crate::net::Error::Udp(UdpError::Fault { from, board: None }) = fault.error else { + unreachable!("a fault from an unknown address should carry no board"); + }; + assert_eq!(from, stranger_addr()); + let decode = receive_error_report(&mut sinks).await; + let crate::net::Error::Udp(UdpError::Decode { board: None, .. }) = decode.error else { + unreachable!("a decode failure from an unknown address should carry no board"); + }; +} + #[tokio::test] async fn whatever_follows_the_fault_id_is_not_read() { let (reporter, mut sinks) = Reporter::channels(16, 16); let index = index_with_empty_data_packet(); + let boards = HashMap::new(); + let lookups = Lookups { + adj: &index, + boards: &boards, + }; let mut traces = ReceiveTraces::default(); decode_and_report( &[0x00, 0x00, 0xAB, 0xCD], example_board_addr(), - &index, + lookups, &reporter, &mut traces, ) @@ -165,13 +236,18 @@ async fn whatever_follows_the_fault_id_is_not_read() { async fn a_single_zero_byte_is_not_a_fault() { let (reporter, mut sinks) = Reporter::channels(16, 16); let index = index_with_empty_data_packet(); + let boards = HashMap::new(); + let lookups = Lookups { + adj: &index, + boards: &boards, + }; let mut traces = ReceiveTraces::default(); // An id takes two bytes: one zero byte is a truncated datagram. decode_and_report( &[0x00], example_board_addr(), - &index, + lookups, &reporter, &mut traces, ) @@ -188,6 +264,11 @@ async fn a_single_zero_byte_is_not_a_fault() { async fn decode_and_report_stops_once_nobody_listens() { let (reporter, sinks) = Reporter::channels(16, 16); let index = index_with_empty_data_packet(); + let boards = HashMap::new(); + let lookups = Lookups { + adj: &index, + boards: &boards, + }; let mut traces = ReceiveTraces::default(); drop(sinks); @@ -195,7 +276,7 @@ async fn decode_and_report_stops_once_nobody_listens() { let keep_going = decode_and_report( &UNKNOWN_ID_DATAGRAM, example_board_addr(), - &index, + lookups, &reporter, &mut traces, ) @@ -258,7 +339,7 @@ async fn a_datagram_sent_to_the_socket_arrives_as_a_notification() { } #[tokio::test] -async fn an_undecodable_datagram_is_reported_with_its_sender() { +async fn an_undecodable_datagram_is_reported_with_its_sender_and_board() { let (reporter, mut sinks) = Reporter::channels(16, 16); let (addr, handle) = start_receiving_on_loopback(reporter); let board = bind_fake_board().await; @@ -269,15 +350,16 @@ async fn an_undecodable_datagram_is_reported_with_its_sender() { send_datagram(&board, &UNKNOWN_ID_DATAGRAM, addr).await; let report = receive_error_report(&mut sinks).await; - let crate::net::Error::Udp(UdpError::Decode { from, .. }) = report.error else { + let crate::net::Error::Udp(UdpError::Decode { from, board, .. }) = report.error else { unreachable!("an undecodable datagram should be reported as udp::UdpError::Decode"); }; assert_eq!(from, board_addr); + assert_eq!(board, Some(TEST_BOARD)); handle.abort(); } #[tokio::test] -async fn a_fault_sent_to_the_socket_is_reported_with_its_sender() { +async fn a_fault_sent_to_the_socket_is_reported_with_its_sender_and_board() { let (reporter, mut sinks) = Reporter::channels(16, 16); let (addr, handle) = start_receiving_on_loopback(reporter); let board = bind_fake_board().await; @@ -288,10 +370,11 @@ async fn a_fault_sent_to_the_socket_is_reported_with_its_sender() { send_datagram(&board, &FAULT_DATAGRAM, addr).await; let report = receive_error_report(&mut sinks).await; - let crate::net::Error::Udp(UdpError::Fault { from }) = report.error else { + let crate::net::Error::Udp(UdpError::Fault { from, board }) = report.error else { unreachable!("a datagram with packet id 0 should be reported as udp::UdpError::Fault"); }; assert_eq!(from, board_addr); + assert_eq!(board, Some(TEST_BOARD)); handle.abort(); } @@ -315,9 +398,10 @@ async fn the_loop_stops_on_the_next_datagram_once_nobody_listens() { async fn binding_an_address_already_in_use_is_a_bind_error() { let (_first, taken) = bind_on_loopback(256 * 1024); - let second = bind_telemetry_socket(UdpConfig { + let second = bind_telemetry_socket(&UdpConfig { addr: taken, recv_buffer: 256 * 1024, + boards: HashMap::new(), }); let Err(UdpError::Bind { addr, .. }) = second else { From 7689c9157c9f897053538c2548546e2c0ffca990 Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Tue, 1 Dec 2026 12:52:09 +0100 Subject: [PATCH 164/225] refactor(backend, event): incoporate fault --- backend/crates/station/src/event.rs | 547 +++--------------- backend/crates/station/src/event/README.md | 231 ++++---- backend/crates/station/src/event/fault.rs | 153 +++-- .../crates/station/src/event/manual_tests.rs | 10 +- backend/crates/station/src/event/orders.rs | 24 +- backend/crates/station/src/event/policy.rs | 206 ++++++- backend/crates/station/src/event/router.rs | 453 +++++++++++++++ backend/crates/station/src/event/tests.rs | 298 +++++++--- 8 files changed, 1225 insertions(+), 697 deletions(-) create mode 100644 backend/crates/station/src/event/router.rs diff --git a/backend/crates/station/src/event.rs b/backend/crates/station/src/event.rs index e28a64d55..5749e36b3 100644 --- a/backend/crates/station/src/event.rs +++ b/backend/crates/station/src/event.rs @@ -17,6 +17,7 @@ mod fault; mod orders; mod policy; +mod router; #[cfg(test)] mod manual_tests; @@ -25,25 +26,19 @@ mod tests; pub use policy::full_message; -use std::collections::{HashMap, HashSet}; use std::future::Future; -use std::net::IpAddr; use std::pin::Pin; use std::sync::Arc; use std::time::{Duration, SystemTime}; use software_core::model::{BoardId, OrderPacket, PodData}; -use software_core::net::{ErrorReport, Notification, Reporter, Sinks}; -use tokio::sync::{mpsc, oneshot}; +use software_core::net::{Notification, Reporter}; +use software_core::protocol::Index; +use tokio::sync::mpsc; use tokio::task::{JoinHandle, JoinSet}; -use tracing::{debug, error, warn}; -use self::fault::{FAULT_QUEUE, FaultRequest}; -use self::policy::Action; - -/// A batch of notifications, shared by `logging` and `pipeline` without -/// copying it: one allocation per batch, freed when both have let go of it. -pub type Batch = Arc<[Notification]>; +use self::fault::FAULT_QUEUE; +use self::router::{Router, RouterEnds}; /// A future that can be sent to another task, boxed so that [`TcpLink`] can /// be used as a trait object. @@ -73,8 +68,6 @@ pub trait TcpLink: Send + Sync { /// Every size is clamped to at least 1. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct EventConfig { - /// Most notifications taken out of ③ or ④ at once. - pub batch: usize, /// Slots in each of `net`'s error queues (①, one per transport). pub errors_queue: usize, /// Slots in ② (problems from station modules). @@ -84,14 +77,14 @@ pub struct EventConfig { /// Slots in ④ (UDP notifications). The only stretch of queue between the /// UDP socket and the routing loop, so the widest. pub udp_queue: usize, - /// Slots in ⑤, counted in **batches**, not notifications. + /// Slots in ⑤ (to `logging`). pub logging_queue: usize, - /// Slots in ⑥, counted in **batches**, not notifications. + /// Slots in ⑥ (to `pipeline`). pub pipeline_queue: usize, /// Slots in ⑦ (orders from the front). pub orders_queue: usize, - /// Forward a board's fault to the other boards. - pub forward_board_faults: bool, + /// Send the fault a board sends to every other board as well. + pub propagate_fault: bool, /// How long a fatal stop waits for the fault to be sent. pub fault_timeout: Duration, } @@ -100,15 +93,14 @@ impl Default for EventConfig { // Default config fn default() -> Self { Self { - batch: 512, errors_queue: 16, problems_queue: 16, tcp_queue: 1024, udp_queue: 8192, - logging_queue: 64, - pipeline_queue: 64, + logging_queue: 8192, + pipeline_queue: 8192, orders_queue: 32, - forward_board_faults: true, + propagate_fault: true, fault_timeout: Duration::from_secs(2), } } @@ -145,7 +137,7 @@ impl Problem { pub enum ProblemKind { /// Shown on the front; the backend keeps running. Shown, - /// Shown on the front; the fault is sent and the backend stops. + /// The fault is sent, it is shown on the front and the backend stops. Fatal, /// Only written to the trace: not shown, the backend keeps running. Silent, @@ -154,14 +146,16 @@ pub enum ProblemKind { /// What `logging` receives (⑤). #[derive(Debug)] pub enum ToLogging { - /// A batch of notifications, TCP or UDP. - Received(Batch), + /// A notification, TCP or UDP, as soon as it arrives. `pipeline` gets the + /// same copy. + Received(Arc), /// An order TCP confirmed it wrote. OrderSent { /// When the write was confirmed. at: SystemTime, - /// The board it was written to. - board: BoardId, + /// The board it was written to; `None` for the fault, which goes to + /// every board. + board: Option, /// The order. order: OrderPacket, }, @@ -170,11 +164,24 @@ pub enum ToLogging { /// What `pipeline` receives (⑥). #[derive(Debug)] pub enum ToPipeline { - /// A batch of notifications, TCP or UDP. - Received(Batch), + /// A notification, TCP or UDP, as soon as it arrives. `logging` gets the + /// same copy. + Received(Arc), /// Something the operator has to see. Problem(Problem), - /// An order that did not go out. + /// An order the front sent that went out: shown on the front as a message + /// from the backend. + OrderSent { + /// When the write was confirmed. + at: SystemTime, + /// The board it was written to; `None` for the fault, which goes to + /// every board. + board: Option, + /// The order. + order: OrderPacket, + }, + /// An order the front sent that did not go out: shown on the front as a + /// message from the backend, with the reason. OrderFailed { /// When it failed. at: SystemTime, @@ -194,42 +201,12 @@ pub enum Stop { NetGone, } -/// The boards as `event` needs them: who an IP belongs to, and what each -/// board is called. Built once from the ADJ. -#[derive(Debug, Clone, Default)] -pub struct Boards { - by_ip: HashMap, - names: HashMap, -} - -impl Boards { - /// Reads every board's IP and name. - pub fn from_pod_data(pod_data: &PodData) -> Self { - let by_ip = pod_data - .boards - .values() - .map(|board| (board.ip, board.id)) - .collect(); - let names = pod_data - .boards - .values() - .map(|board| (board.id, board.name.clone())) - .collect(); - Self { by_ip, names } - } - - /// The board at `ip`, if any. - pub fn by_ip(&self, ip: IpAddr) -> Option { - self.by_ip.get(&ip).copied() - } - - /// The board's name, or its id if the ADJ does not declare it. - pub fn name(&self, board: BoardId) -> String { - self.names - .get(&board) - .cloned() - .unwrap_or_else(|| format!("{board:?}")) - } +/// The board's name for the operator, as the ADJ declares it, or its id if +/// the ADJ does not declare it. +fn board_name(pod_data: &PodData, board: BoardId) -> String { + pod_data + .board_name(board) + .map_or_else(|| format!("{board:?}"), str::to_owned) } /// Every queue between modules, as [`channels`] hands them out. @@ -255,15 +232,10 @@ pub struct Channels { /// writing side of ⑤ ⑥. Only [`spawn`] opens it. #[derive(Debug)] pub struct EventEnds { - udp: Sinks, - tcp: Sinks, - problems: mpsc::Receiver, + /// ① ② ③ ④ ⑤ ⑥: for the routing loop. + router: RouterEnds, + /// ⑦: for the orders worker. orders: mpsc::Receiver, - logging: mpsc::Sender, - pipeline: mpsc::Sender, - /// Capacities of ③ and ④: how much a fatal stop drains at most. - tcp_capacity: usize, - udp_capacity: usize, } /// Creates every queue between modules. `main` calls it once, before @@ -273,10 +245,11 @@ pub struct EventEnds { /// transport: TCP and UDP each get their own notification queue, so that TCP /// can be read first, and their own error queue. pub fn channels(config: &EventConfig) -> Channels { - let errors = config.errors_queue.max(1); + let errors = config.errors_queue.max(1); //max(1) to avoid 0-capacity channels let tcp_capacity = config.tcp_queue.max(1); let udp_capacity = config.udp_queue.max(1); + // Channel creation let (udp, udp_sinks) = Reporter::channels(udp_capacity, errors); let (tcp, tcp_sinks) = Reporter::channels(tcp_capacity, errors); let (problems_tx, problems_rx) = mpsc::channel(config.problems_queue.max(1)); @@ -288,14 +261,16 @@ pub fn channels(config: &EventConfig) -> Channels { udp, tcp, event: EventEnds { - udp: udp_sinks, - tcp: tcp_sinks, - problems: problems_rx, + router: RouterEnds { + udp: udp_sinks, + tcp: tcp_sinks, + problems: problems_rx, + logging: logging_tx, + pipeline: pipeline_tx, + tcp_capacity, + udp_capacity, + }, orders: orders_rx, - logging: logging_tx, - pipeline: pipeline_tx, - tcp_capacity, - udp_capacity, }, orders: orders_tx, problems: problems_tx, @@ -306,6 +281,10 @@ pub fn channels(config: &EventConfig) -> Channels { /// Starts the routing loop and the two workers. /// +/// `pod_data` is only read for the boards' names, which the texts shown on +/// the front and written to the trace use; `index` for which protections and +/// messages a board sends mean that it is in fault. +/// /// Without a TCP client (`tcp: None`), every order fails with "TCP not /// available" and the fault is only traced. /// @@ -315,401 +294,65 @@ pub fn channels(config: &EventConfig) -> Channels { pub fn spawn( config: EventConfig, ends: EventEnds, - boards: Boards, + pod_data: Arc, + index: Arc, tcp: Option>, ) -> JoinHandle { - tokio::spawn(run(config, ends, boards, tcp)) + tokio::spawn(run(config, ends, pod_data, index, tcp)) } +/// The body of the task [`spawn`] starts: the routing loop (towards the +/// front) and the orders and fault workers (towards the boards). +/// +/// Three tasks rather than one loop because writing to a socket can wait, and +/// the routing loop never must: while it waits, nobody reads `net`'s queues. +/// Returns why event stopped, once the workers have stopped too. async fn run( config: EventConfig, ends: EventEnds, - boards: Boards, + pod_data: Arc, + index: Arc, tcp: Option>, ) -> Stop { - let boards = Arc::new(boards); + // ⑦ goes straight to the orders worker, so an order never queues behind + // telemetry in the routing loop; everything else goes to the loop. + let EventEnds { + router: ends, + orders: orders_rx, + } = ends; + + // ⑧ never leaves event: its senders and its reader are all created here, + // so it needs no place in `channels`, and no other module can ask for a + // fault behind event's back. let (fault_tx, fault_rx) = mpsc::channel(FAULT_QUEUE); + // One set, so that both workers can be stopped together at the end. let mut workers = JoinSet::new(); workers.spawn(fault::run( fault_rx, - tcp.clone(), + tcp.clone(), // the same client (an `Arc`), not a second connection + ends.logging.clone(), ends.pipeline.clone(), - boards.clone(), + pod_data.clone(), // for the boards' names in its messages )); workers.spawn(orders::run( - ends.orders, + orders_rx, tcp, - fault_tx.clone(), + fault_tx.clone(), // order id 0 is the fault: passed on to the fault worker ends.logging.clone(), ends.pipeline.clone(), )); - let batch = config.batch.max(1); - let router = Router { - config, - batch, - boards, - udp: ends.udp, - tcp: ends.tcp, - problems: ends.problems, - logging: ends.logging, - pipeline: ends.pipeline, - fault: fault_tx, - open: Open::default(), - tcp_batch: Vec::with_capacity(batch), - udp_batch: Vec::with_capacity(batch), - tcp_capacity: ends.tcp_capacity, - udp_capacity: ends.udp_capacity, - faults_shown: HashSet::new(), - }; + // The loop keeps the original ⑧ sender, for the faults event decides on. + let router = Router::new(config, pod_data, index, ends, fault_tx); - // The router's senders are dropped when `route` returns; the workers' - // when they are stopped here. + // Runs until it has to stop. It takes the router by value, so its ends of + // ⑤ ⑥ ⑧ are dropped when it returns. let stop = router.route().await; + + // The workers would never end on their own (⑦ and ⑧ stay open), and their + // clones of ⑤ ⑥ would keep `logging` and `pipeline` waiting forever. + // Stopping them closes ⑤ ⑥, so those two finish what is queued and end. workers.shutdown().await; stop } - -/// Which transport a notification queue belongs to. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -enum Transport { - Tcp, - Udp, -} - -/// A consumer of the routing loop that has stopped. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -enum Consumer { - Logging, - Pipeline, -} - -/// Why the routing loop has to stop, before it does it. -#[derive(Debug)] -enum Halt { - Fatal(Problem), - Gone(Consumer), -} - -/// What one round of the `select!` got. -enum Step { - NetError(Transport, Option), - Problem(Option), - Notifications(Transport, usize), -} - -/// Which input queues are still open. A closed queue answers "closed" -/// instantly, every time, so it is no longer watched: in fixed order it would -/// win every round and hide the queues below it. -#[derive(Debug, Clone, Copy)] -struct Open { - udp_errors: bool, - tcp_errors: bool, - problems: bool, - tcp_notifications: bool, - udp_notifications: bool, -} - -impl Default for Open { - fn default() -> Self { - Self { - udp_errors: true, - tcp_errors: true, - problems: true, - tcp_notifications: true, - udp_notifications: true, - } - } -} - -impl Open { - /// Whether any of `net`'s four queues is still open. The loop only ends - /// once all four are closed, so an error queued just before its - /// transport stopped is never lost. - fn net(&self) -> bool { - self.udp_errors || self.tcp_errors || self.tcp_notifications || self.udp_notifications - } -} - -/// The routing loop's state: everything towards the front. -struct Router { - config: EventConfig, - batch: usize, - boards: Arc, - udp: Sinks, - tcp: Sinks, - problems: mpsc::Receiver, - logging: mpsc::Sender, - pipeline: mpsc::Sender, - fault: mpsc::Sender, - open: Open, - /// One reused buffer per notification queue (the two are read in the - /// same `select!`, so they cannot share one). - tcp_batch: Vec, - udp_batch: Vec, - tcp_capacity: usize, - udp_capacity: usize, - /// The addresses whose fault has already been shown. - faults_shown: HashSet, -} - -impl Router { - async fn route(mut self) -> Stop { - loop { - if !self.open.net() { - return Stop::NetGone; - } - - let limit = self.batch; - let open = self.open; - // Fixed order: errors, then TCP, then UDP. - let step = tokio::select! { - biased; - report = self.udp.errors.recv(), if open.udp_errors => { - Step::NetError(Transport::Udp, report) - } - report = self.tcp.errors.recv(), if open.tcp_errors => { - Step::NetError(Transport::Tcp, report) - } - problem = self.problems.recv(), if open.problems => Step::Problem(problem), - n = self.tcp.notifications.recv_many(&mut self.tcp_batch, limit), - if open.tcp_notifications => Step::Notifications(Transport::Tcp, n), - n = self.udp.notifications.recv_many(&mut self.udp_batch, limit), - if open.udp_notifications => Step::Notifications(Transport::Udp, n), - else => return Stop::NetGone, - }; - - let handled = match step { - Step::NetError(Transport::Udp, None) => { - self.open.udp_errors = false; - Ok(()) - } - Step::NetError(Transport::Tcp, None) => { - self.open.tcp_errors = false; - Ok(()) - } - Step::NetError(_, Some(report)) => self.on_net_error(report).await, - Step::Problem(None) => { - self.open.problems = false; - Ok(()) - } - Step::Problem(Some(problem)) => self.on_problem(problem).await, - // 0 only once the queue is closed and empty. - Step::Notifications(Transport::Tcp, 0) => { - self.open.tcp_notifications = false; - Ok(()) - } - Step::Notifications(Transport::Udp, 0) => { - self.open.udp_notifications = false; - Ok(()) - } - Step::Notifications(transport, _) => { - self.forward(transport).await.map_err(Halt::Gone) - } - }; - - match handled { - Ok(()) => {} - Err(Halt::Fatal(problem)) => return self.stop_fatal(problem).await, - Err(Halt::Gone(consumer)) => return self.stop_consumer_gone(consumer).await, - } - } - } - - /// Sends the batch just taken from `transport`'s queue to both consumers, - /// as one shared copy. - async fn forward(&mut self, transport: Transport) -> Result<(), Consumer> { - let batch = match transport { - Transport::Tcp => &mut self.tcp_batch, - Transport::Udp => &mut self.udp_batch, - }; - // One allocation; the buffer keeps its capacity for the next batch. - let shared: Batch = batch.drain(..).collect(); - - self.logging - .send(ToLogging::Received(shared.clone())) - .await - .map_err(|_| Consumer::Logging)?; - self.pipeline - .send(ToPipeline::Received(shared)) - .await - .map_err(|_| Consumer::Pipeline) - } - - async fn on_net_error(&mut self, report: ErrorReport) -> Result<(), Halt> { - let action = policy::classify(&report.error); - let source = policy::source(&report.error); - let board = source - .board - .or_else(|| source.ip.and_then(|ip| self.boards.by_ip(ip))); - - // UDP errors only carry an address: put the board's name in front. - let mut text = full_message(&report.error); - if let (Some(board), Some(_)) = (board, source.ip) { - text = format!("{}: {text}", self.boards.name(board)); - } - - let kind = match action { - Action::Fatal => ProblemKind::Fatal, - Action::Silent => ProblemKind::Silent, - Action::Show | Action::BoardFault => ProblemKind::Shown, - }; - let problem = Problem { - at: report.at, - board, - kind, - text, - }; - - match action { - Action::Fatal => Err(Halt::Fatal(problem)), - Action::BoardFault => self.on_board_fault(problem, source.ip).await, - Action::Show => self.show(problem).await.map_err(Halt::Gone), - Action::Silent => { - self.trace_silent(&problem); - Ok(()) - } - } - } - - async fn on_problem(&mut self, problem: Problem) -> Result<(), Halt> { - match policy::for_problem(problem.kind) { - Action::Fatal => Err(Halt::Fatal(problem)), - Action::Silent => { - self.trace_silent(&problem); - Ok(()) - } - Action::Show | Action::BoardFault => self.show(problem).await.map_err(Halt::Gone), - } - } - - /// Procedure 1: written to the trace, and nothing else. - fn trace_silent(&self, problem: &Problem) { - let board = problem.board.map(|board| self.boards.name(board)); - warn!(board = ?board, problem = %problem.text, "problem not shown on the front"); - } - - /// The first fault from each address is shown and forwarded; repeats are - /// not (`net` already traces them, rate-limited). - async fn on_board_fault(&mut self, problem: Problem, ip: Option) -> Result<(), Halt> { - let first = ip.is_none_or(|ip| self.faults_shown.insert(ip)); - if !first { - return Ok(()); - } - - warn!(fault = %problem.text, "first fault from this board"); - self.show(problem).await.map_err(Halt::Gone)?; - - if self.config.forward_board_faults { - // Never waits: if the queue is full a request is already pending, - // and the fault goes out only once anyway. - if let Err(error) = self.fault.try_send(FaultRequest { done: None }) { - debug!(%error, "fault request not queued"); - } - } - Ok(()) - } - - async fn show(&self, problem: Problem) -> Result<(), Consumer> { - self.pipeline - .send(ToPipeline::Problem(problem)) - .await - .map_err(|_| Consumer::Pipeline) - } - - /// Procedure 3: show it, pass on what was already queued, send the fault, - /// stop. - async fn stop_fatal(mut self, problem: Problem) -> Stop { - error!(problem = %problem.text, "fatal error, stopping"); - - let pipeline_alive = self - .pipeline - .send(ToPipeline::Problem(problem.clone())) - .await - .is_ok(); - if pipeline_alive { - // Errors are read first, so this one has overtaken the data that - // arrived just before it: pass that on before stopping. If a - // consumer stops meanwhile, there is nothing left to do with it. - let _ = self.drain().await; - } - - self.send_fault_and_wait().await; - Stop::Fatal(problem) - } - - /// `logging` or `pipeline` stopped: nothing is recorded, or nothing is - /// shown. Fatal, without draining. - async fn stop_consumer_gone(self, consumer: Consumer) -> Stop { - let text = match consumer { - Consumer::Logging => "logging stopped: nothing is being recorded", - Consumer::Pipeline => "pipeline stopped: nothing reaches the front", - }; - let problem = Problem::now(ProblemKind::Fatal, None, text); - error!(problem = %problem.text, "fatal error, stopping"); - - if consumer == Consumer::Logging { - let _ = self - .pipeline - .send(ToPipeline::Problem(problem.clone())) - .await; - } - - self.send_fault_and_wait().await; - Stop::Fatal(problem) - } - - /// Passes on what is already in ③ and ④, at most their capacity each, so - /// that it cannot chase a queue that keeps filling up. - async fn drain(&mut self) -> Result<(), Consumer> { - for transport in [Transport::Tcp, Transport::Udp] { - let mut left = match transport { - Transport::Tcp => self.tcp_capacity, - Transport::Udp => self.udp_capacity, - }; - while left > 0 { - let (queue, batch) = match transport { - Transport::Tcp => (&mut self.tcp.notifications, &mut self.tcp_batch), - Transport::Udp => (&mut self.udp.notifications, &mut self.udp_batch), - }; - let limit = self.batch.min(left); - while batch.len() < limit { - match queue.try_recv() { - Ok(notification) => batch.push(notification), - Err(_) => break, - } - } - if batch.is_empty() { - break; - } - left -= batch.len(); - self.forward(transport).await?; - } - } - Ok(()) - } - - /// Asks the fault worker for the fault and waits until it has gone out - /// (or had gone out already), within [`Config::fault_timeout`]. - async fn send_fault_and_wait(&self) { - let (done_tx, done_rx) = oneshot::channel(); - let request = FaultRequest { - done: Some(done_tx), - }; - let wait = async { - if self.fault.send(request).await.is_ok() { - let _ = done_rx.await; - } - }; - if tokio::time::timeout(self.config.fault_timeout, wait) - .await - .is_err() - { - warn!( - timeout = ?self.config.fault_timeout, - "the fault was not confirmed in time; stopping anyway" - ); - } - } -} diff --git a/backend/crates/station/src/event/README.md b/backend/crates/station/src/event/README.md index 1ce4af010..2963c706a 100644 --- a/backend/crates/station/src/event/README.md +++ b/backend/crates/station/src/event/README.md @@ -53,13 +53,14 @@ the boards. ```text front → websocket ─⑦ orders─► ┌─ task ──────────┐ ──► TCP: write to that board │ orders worker │ ─⑤─► logging (sent) - │ one at a time │ ─⑥─► pipeline (failed) + │ one at a time │ ─⑥─► pipeline (sent or failed) └───────┬─────────┘ │ ⑧ (order id 0 = fault) ▼ routing loop ─⑧─────────────► ┌─ task ──────────┐ ──► TCP: fault to every board - │ fault worker │ ─⑥─► pipeline (boards not reached) - │ "only once" │ + │ fault worker │ ─⑤─► logging (front's fault sent) + │ every request │ ─⑥─► pipeline (front's fault sent or failed, + │ │ boards not reached) └─────────────────┘ main: calls event::channels(), spawns every task with its ends, @@ -97,8 +98,6 @@ Why it is built like this: [`net/report.rs`](../../../core/src/net/report.rs). - **Worker**: a task owned by `event` that does one slow thing (writing an order to TCP, sending the fault), so that the routing loop never waits on a socket. -- **Batch**: several notifications taken out at once (`recv_many`) instead of - one at a time. - **Wait, don't drop**: when a queue is full, whoever is putting into it waits until there is a free slot. That wait travels back up to the socket, so the only thing that can be lost is what the operating system has not handed over @@ -112,8 +111,9 @@ Why it is built like this: ## Files ``` -event.rs # module root: channels, spawn, the routing loop, Stop +event.rs # module root: the public types, channels, spawn event/ +├── router.rs # the routing loop: everything towards the front ├── policy.rs # what to do with each error ├── orders.rs # the orders worker ├── fault.rs # the fault worker @@ -130,7 +130,7 @@ event/ | ② | problems | any station module → routing loop | `Problem` | | ③ | TCP notifications | `net::tcp` → routing loop | `Notification` (protections, messages, connected/disconnected) | | ④ | UDP notifications | `net::udp` → routing loop | `Notification` (data) | -| ⑤ | to logging | routing loop, orders worker → `logging` | `ToLogging` | +| ⑤ | to logging | routing loop, both workers → `logging` | `ToLogging` | | ⑥ | to pipeline | routing loop, both workers → `pipeline` | `ToPipeline` | | ⑦ | orders | `websocket` → orders worker | `OrderPacket` (id 0 = fault) | | ⑧ | fault requests | routing loop, orders worker → fault worker | `FaultRequest` | @@ -158,8 +158,7 @@ let channels = event::channels(&config); spawn_udp(udp_config, index.clone(), channels.udp)?; // ① ④ // the TCP client takes channels.tcp ① ③ -let boards = Boards::from_pod_data(&adj.pod_data); -let event = event::spawn(config, channels.event, boards, tcp); // tcp: Option> +let event = event::spawn(config, channels.event, pod_data, index, tcp); // Arc, Arc, Option> logging::spawn(channels.logging, ...); // ⑤ pipeline::spawn(channels.pipeline, broker_client, ...); // ⑥ OrderForwarder::new(index, channels.orders); // ⑦ (websocket) @@ -188,14 +187,15 @@ Why one place, instead of each module creating its own input queue: | What arrives | `logging` | `pipeline` | fault worker | |---|---|---|---| -| Batch of TCP notifications (③) | yes | yes | — | -| Batch of UDP notifications (④) | yes | yes | — | +| TCP notification (③) | yes | yes | — | +| UDP notification (④) | yes | yes | — | | Problem to show (②, or a non-fatal error from ①) | no (trace only) | yes | — | | Fatal error | no (trace only) | yes, before stopping | yes | -| Fault from a board (packet id 0, ①) | no (trace only) | yes, the first one from each board | yes, if forwarding is on | +| Fault from a board (packet id 0, ①) | no (trace only) | yes, the first one from each board | yes, every time, if `propagate_fault` is on | +| Protection with severity `Fault`, or message `Fault`/`Panic` (③) | yes | yes, as the notification it is | yes, every time, if `propagate_fault` is on | -**How notifications travel.** The routing loop takes up to 512 at once from a -queue, puts them in **one shared copy** (`Arc<[Notification]>`) and sends that +**How notifications travel.** One at a time, as soon as they arrive: the routing +loop puts each one in **one shared copy** (`Arc`) and sends that same copy to both `logging` and `pipeline`. Nothing is duplicated in memory, and each consumer takes what it needs (`logging` its selected measurements, `pipeline` its counts and averages). `event` never looks inside. Each @@ -213,21 +213,34 @@ is expected to keep up with the incoming rate (about 15–25 Mbit/s). - **Orders.** `websocket` validates each order against the ADJ and puts it on ⑦. The orders worker takes them **one at a time**: it writes the order and waits for TCP to say it went out (or why not) before taking the next one. - - **"Sent" means written, not queued.** A sent order goes to `logging` (⑤) - only once TCP confirms the write. - - **A failed order goes to `pipeline`** (⑥), with the reason. An order for a - board that is not connected fails right away instead of waiting in a queue. -- **The fault.** The fault worker sends the fault (order id 0) to every board. - It gets requests on ⑧ from three places: the routing loop on a fatal error, - the routing loop on the first fault from each board (if forwarding is on), and the - orders worker when the front asks for one (an order with id 0). - - **Only once per session.** The fault worker sends it on the first request - and only acknowledges the later ones. It is the one place that keeps that - flag, whoever asks. - - **Boards it did not reach** go to `pipeline` (⑥): a fault that only half - landed is exactly what the operator has to know. + - **"Sent" means written, not queued.** A sent order (`OrderSent`) goes to + `logging` (⑤) and to `pipeline` (⑥) only once TCP confirms the write. + - **A failed order** (`OrderFailed`) goes to `pipeline` (⑥), with the reason. + An order for a board that is not connected fails right away instead of + waiting in a queue. + - **The front sees both**: `pipeline` turns them into a message from the + backend (`message/update`), so the operator always knows whether an order + went out. +- **The fault.** The fault worker sends the fault (order id 0) to every board, + **once per request, every time it is asked**. It gets requests on ⑧ from + three places: + - **A fatal error**, from the routing loop, as the first step of stopping. + - **A board in fault**, from the routing loop, if `propagate_fault` is on + (the default): every fault a board sends is sent on to every board, each + time it arrives. A board is in fault when it sends the fault itself (packet + id 0), a protection the ADJ declares with severity `Fault`, or a message of + level `Fault` or `Panic`. The protection's severity comes from its + measurement's declaration and the message's level from `message_ids`, both + read through the `Index`. + - **The front**, from the orders worker (an order with id 0). It follows the + flow of any other order: sent to every board, and the front is told how it + went: `OrderSent` to `logging` and `pipeline` (with no board: it goes to + every board), or `OrderFailed` with the reason. Nothing else. + - **Boards it did not reach**: a fault that only half landed is exactly what + the operator has to know. For an automatic fault they go to `pipeline` as a + `Problem`; for the front's, they are the reason in `OrderFailed`. - **Without TCP** (no TCP client running), every order fails with "TCP not - available", shown on the front, and the fault is only traced. + available", shown on the front, and an automatic fault is only traced. Neither worker is ever waited on by the routing loop, except when stopping on a fatal error (see [Stopping](#stopping)): writing to a socket can take time (a @@ -254,7 +267,7 @@ There are three procedures, and every one of them ends up in the trace: |---|---|---| | `UdpError::Decode` (any variant) | a datagram that cannot be decoded: the loaded ADJ does not match what the boards send | **3, fatal** | | `UdpError::Recv` | the socket can no longer be read: telemetry from every board is gone | **3, fatal** | -| `UdpError::Fault { from }` | a board detected an error and says so (packet id 0) | **board fault**: shown, forwarded to the other boards; the backend **keeps running** | +| `UdpError::Fault { from, board }` | a board detected an error and says so (packet id 0) | **board fault**: shown (the first one from each board), sent to every board each time if `propagate_fault` is on; the backend **keeps running** | | `UdpError::Bind` | the port could not be opened | never arrives: a startup failure, returned by `spawn_udp` | | TCP frame that cannot be decoded | same as UDP | **3, fatal** | | TCP fault (packet id 0 over TCP) | same as UDP | **board fault** | @@ -269,16 +282,23 @@ enum value out of range also say the ADJ does not match the firmware, and nothing corrupts a packet in flight. A dead `logging` means the run is not recorded; a dead `pipeline` means the operator sees nothing. -**Which board.** UDP errors carry the address the datagram came from (`from`), -not the board. At startup `event` gets an IP → `BoardId` map built from the ADJ -(every `Board` has its `ip`, see [`model/board.rs`](../../../core/src/model/board.rs)), -so the front says "HVSCU" rather than "127.0.0.7". An IP that belongs to no -board stays without a board, and the text carries the address. - -**Board faults on the front.** The first fault from each board is shown, as a -`Shown` problem whose text names the board; repeats are not, since `net` already traces them (at most one line a second, -with how many were skipped). Forwarding a board's fault to the others is -configurable and on by default. +**Which board.** Every error from `net` names its board when there is one: +TCP errors always do, and `UdpError::Decode` and `UdpError::Fault` carry, next +to the address the datagram came from (`from`), the board that address belongs +to, which `net::udp` resolves itself from `UdpConfig::boards`. `event` only +puts the board's name in front of the text, read from the ADJ's `PodData` +(`PodData::board_name`), so the front says "HVSCU" rather than "127.0.0.7". An +address that belongs to no board arrives without a board, and the text carries +the address. + +**Board faults on the front.** A fault packet (id 0) arrives as an error, not +as a notification, so the front only sees it through `event`: the first one +from each board is shown, as a `Shown` problem whose text names the board; +repeats are not, since `net` already traces them (at most one line a second, +with how many were skipped). A `Fault` protection or a `Fault`/`Panic` message +reaches the front as the notification it is, so nothing extra is shown for it. +Either way, whether it is also sent to every board is set by `propagate_fault`, +on by default, and it is sent each time one arrives. **Traces.** Every error ends up in the trace (`tracing`), but never twice: the module where it happens traces it, and `event` only traces what it decides @@ -289,16 +309,18 @@ HVSCU") and the `Silent` problems it is sent. **On a fatal error**, the routing loop: -1. Sends the `Problem` to `pipeline`, so the operator sees it. -2. Empties whatever was already in ③ and ④ (at most their capacity) and passes +1. Asks the fault worker for the fault, without waiting for it to go out: the + fault comes first, and the next steps happen while it is being written. +2. Sends the `Problem` to `pipeline`, so the operator sees it. +3. Empties whatever was already in ③ and ④ (at most their capacity) and passes it on. Errors are read first, so the fatal error has overtaken the data that arrived just before it, and that data is exactly what you want to understand what happened. -3. Asks the fault worker to send the fault and waits for it to finish, with a - time limit (if it was already sent, the answer is immediate). -4. Ends by returning `Stop::Fatal(problem)`. +4. Waits for the fault to have gone out, within `fault_timeout` from step 1 + (if it already has, the answer is immediate). +5. Ends by returning `Stop::Fatal(problem)`. -If what stopped is `logging` or `pipeline`, step 2 is skipped. If it is +If what stopped is `logging` or `pipeline`, step 3 is skipped. If it is `logging`, `event` still tells `pipeline`. **On Ctrl+C:** `main` handles it, not `event`. `main` stops the UDP task @@ -320,12 +342,9 @@ queues close, and the routing loop passes on whatever was left and ends with ## Types ```rust -/// A batch of notifications, shared by logging and pipeline without copying. -pub type Batch = Arc<[Notification]>; - /// Creates every queue between modules. `main` calls it once, before spawning /// anything, and hands each end to whoever uses it. -pub fn channels(config: &Config) -> Channels; +pub fn channels(config: &EventConfig) -> Channels; pub struct Channels { /// For net::udp: reports on ① and ④. @@ -350,9 +369,10 @@ pub struct Channels { /// The task ends with the reason it stopped, once the workers have stopped /// too, so that ⑤ and ⑥ close behind it. pub fn spawn( - config: Config, + config: EventConfig, ends: EventEnds, - boards: Boards, + pod_data: Arc, // only read for the boards' names + index: Arc, // which protections and messages mean fault tcp: Option>, ) -> JoinHandle; @@ -365,24 +385,21 @@ pub trait TcpLink: Send + Sync { fn send_fault(&self) -> BoxFuture<'_, Result<(), Vec>>; } -/// Who an IP belongs to and what each board is called, built from the ADJ. -pub struct Boards { /* ... */ } -impl Boards { - pub fn from_pod_data(pod_data: &PodData) -> Self; - pub fn by_ip(&self, ip: IpAddr) -> Option; - pub fn name(&self, board: BoardId) -> String; -} - pub enum ToLogging { - Received(Batch), - /// An order TCP confirmed it wrote. - OrderSent { at: SystemTime, board: BoardId, order: OrderPacket }, + /// A notification, the same copy pipeline gets. + Received(Arc), + /// An order TCP confirmed it wrote. `board` is `None` for the fault, which + /// goes to every board. + OrderSent { at: SystemTime, board: Option, order: OrderPacket }, } pub enum ToPipeline { - Received(Batch), + /// A notification, the same copy logging gets. + Received(Arc), Problem(Problem), - /// An order that did not go out, and why. + /// An order the front sent that went out, as in `ToLogging`. + OrderSent { at: SystemTime, board: Option, order: OrderPacket }, + /// An order the front sent that did not go out, and why. OrderFailed { at: SystemTime, order: OrderPacket, reason: String }, } @@ -401,7 +418,7 @@ pub struct Problem { pub enum ProblemKind { /// Procedure 2: shown, the backend keeps running. Shown, - /// Procedure 3: shown, the fault is sent and the backend stops. + /// Procedure 3: the fault is sent, it is shown and the backend stops. Fatal, /// Procedure 1: only traced, not shown; the backend keeps running. Silent, @@ -414,18 +431,17 @@ pub enum Stop { NetGone, } -/// `Config::default()` gives the sizes in brackets. Every size is clamped to -/// at least 1. -pub struct Config { - pub batch: usize, // most notifications per batch (512) +/// `EventConfig::default()` gives the values in brackets. Every size is +/// clamped to at least 1. +pub struct EventConfig { pub errors_queue: usize, // each of net's two error queues, ① (16) pub problems_queue: usize, // ② (16) pub tcp_queue: usize, // ③ (1,024) pub udp_queue: usize, // ④ (8,192) - pub logging_queue: usize, // ⑤, in batches (64) - pub pipeline_queue: usize, // ⑥, in batches (64) + pub logging_queue: usize, // ⑤ (8,192) + pub pipeline_queue: usize, // ⑥ (8,192) pub orders_queue: usize, // ⑦ (32) - pub forward_board_faults: bool, // (true) + pub propagate_fault: bool, // send a board's fault to the other boards (true) pub fault_timeout: Duration, // how long a fatal stop waits for the fault (2 s) } ``` @@ -440,23 +456,22 @@ these two calls only. `FaultRequest` (⑧) is private to `event`. loop, select! in fixed order (closed queues are no longer watched): 1. ① UDP errors, ① TCP errors, then ② problems -> policy: fatal -> stop (see "Stopping") - board fault -> first from that board? Problem to ⑥ - forwarding on? request to ⑧ + board fault -> propagate_fault? request to ⑧ (every time) + first from that board? Problem to ⑥ shown -> Problem to ⑥ silent -> trace only - 2. ③ TCP notifications.recv_many(batch, config.batch) -> forward - 3. ④ UDP notifications.recv_many(batch, config.batch) -> forward + 2. ③ TCP notifications.recv() -> fault protection or message? + propagate_fault? request to ⑧ + forward + 3. ④ UDP notifications.recv() -> forward (same check: telemetry never matches) all four of net's queues (① ① ③ ④) closed -> return Stop::NetGone -forward: - shared = batch.drain(..).collect::>() +forward(notification): + shared = Arc::new(notification) ⑤.send(Received(shared.clone())).await // on failure: fatal ⑥.send(Received(shared)).await // on failure: fatal ``` -`batch.drain(..).collect()` allocates once per batch, and the `batch` `Vec` -keeps its capacity for the next one. - ## Performance The requirement is **25 Mbit/s in 76-byte packets, about 41,000 a second**: @@ -464,8 +479,8 @@ under 24 µs per notification, everything included. On loopback, UDP alone loses nothing, but a reader with one timer per message already loses 0.7 %. **The bottleneck is whoever reads `net`'s queues, that is, the routing loop.** Hence: -- notifications in batches, one memory allocation per batch, not per - notification; +- one shared copy per notification for both consumers: a small allocation, and + the packet itself is never copied; - no timer per notification; - the routing loop does not look inside notifications: the expensive work (picking measurements, computing averages, building JSON) is done by @@ -473,6 +488,9 @@ bottleneck is whoever reads `net`'s queues, that is, the routing loop.** Hence: - anything that can wait on a socket is done by a worker, never by the routing loop. +Measured with `manual_event_throughput` (see [Tests](#tests)): about 950,000 +notifications a second through `event`, over 20 times the requirement. + ## Contract with the other modules - **`net`** needs no change: each transport reports through the `Reporter` it @@ -489,15 +507,20 @@ bottleneck is whoever reads `net`'s queues, that is, the routing loop.** Hence: - has an explicit stop, for the safe shutdown; - is handed to `event` as a `TcpLink`, directly or through a thin adapter. - **`websocket`** validates each order against the ADJ and puts it on ⑦ - (`OrderForwarder` takes `channels.orders`). The front's logger requests + (`OrderForwarder` takes `channels.orders`). The fault is one more order + there: the ADJ declares order id 0, so it passes that validation. The front's + logger requests (`logger/enable`, variable selection) go straight to `logging`, not through `event`. - **`logging`** reads ⑤, picks which measurements to store following its own - selection, and reports its own failures (e.g. the disk) on ②. -- **`pipeline`** reads ⑥ and turns it into what the front shows: a batch into - per-packet updates (counts, cycle time, averages) or protection and message - updates, a `Problem` or a failed order into a message. It waits instead of - dropping and does not decide anything about errors. + selection, records the orders that went out, and reports its own failures + (e.g. the disk) on ②. +- **`pipeline`** reads ⑥ and turns it into what the front shows: a notification + into per-packet updates (counts, cycle time, averages) or protection and + message updates; a `Problem`, and an order that went out or failed + (`OrderSent`, `OrderFailed`), into a message from the backend + (`message/update`). It waits instead of dropping and does not decide anything + about errors. ## Implementation notes @@ -507,33 +530,27 @@ bottleneck is whoever reads `net`'s queues, that is, the routing loop.** Hence: - **A closed queue is no longer watched** in the `select!`. A closed queue answers "closed" instantly, every time, so in fixed order it would win every round and the queues below it would never be reached. Each branch has a - condition (`if open.udp_errors`, and so on). This does happen: at shutdown ① closes once both - `Reporter`s are gone while ④ may still have items in it, and without TCP ③ - is closed from the start. + condition (`if open.udp_errors`, and so on). This does happen: at shutdown + UDP's ① closes while ④ may still have items in it, and without TCP ③ is + closed from the start. ## Tests - `policy.rs`: the decision table, one test per row. - `tests.rs`: the routing loop and the workers, with real queues and a fake - `TcpLink`, no sockets. Covers the order of priority, the shared batch, the + `TcpLink`, no sockets. Covers the order of priority, the shared copy, the fatal stop (and that what was queued before the error still gets through), - board faults shown once per board and the fault sent once, orders with and - without TCP, order id 0, a consumer that stops, `net` closing, and a fault - that never finishes sending. Every wait is bounded, so a broken expectation - fails instead of hanging. + board faults (packet id 0 shown once per board, and every fault, protection + or message sent to every board each time; warnings only forwarded), orders + with and without TCP and the front told either way, the fault from the front + (sent every time, the front told how it went), a consumer that stops, `net` + closing, and a fault that never finishes sending. Every wait is bounded, so a + broken expectation fails instead of hanging. - `manual_tests.rs`: `manual_event_throughput`, ignored by default. It pushes a million notifications through a `Reporter` into `event` and two readers - that only count. On a development machine, in release: about 4.9 million a - second, over 100 times the requirement. + that only count. On a development machine, in release: about 950,000 a + second, over 20 times the requirement. ```sh cargo test -p station --release manual_event -- --ignored --nocapture ``` - -## Open questions - -- **Fault from the front.** `websocket` validates orders against the ADJ, and id - 0 is not in it, so today a fault asked for from the front is rejected before - reaching ⑦. -- **Order echo.** Whether a sent order is also shown on the front, not only - logged. diff --git a/backend/crates/station/src/event/fault.rs b/backend/crates/station/src/event/fault.rs index e3a143cd8..8bd2ccc51 100644 --- a/backend/crates/station/src/event/fault.rs +++ b/backend/crates/station/src/event/fault.rs @@ -1,77 +1,138 @@ //! The fault worker: sends the fault (order id 0) to every board, once per -//! session, whoever asks for it. +//! request, every time it is asked. When the operator asked for it, the front +//! is told how it went, as for any order. use std::sync::Arc; +use std::time::SystemTime; -use software_core::model::AdjId; +use software_core::model::{AdjId, OrderPacket, PodData}; use tokio::sync::{mpsc, oneshot}; use tracing::{error, info, warn}; -use super::{Boards, Problem, ProblemKind, TcpLink, ToPipeline}; +use super::orders::TCP_NOT_AVAILABLE; +use super::{Problem, ProblemKind, TcpLink, ToLogging, ToPipeline, board_name}; /// The fault's id on the wire: what a board sends when it detects an error, /// and what the backend sends to every board to put the pod in fault. pub(super) const FAULT_ID: AdjId = AdjId(0); -/// Slots in the fault requests queue (⑧). Requests are rare, and once the -/// fault has been sent every later one is a no-op, so a full queue only -/// means a request is already pending. +/// Slots in the fault requests queue (⑧). Requests are rare; a full queue +/// means faults are already waiting to go out, so the routing loop drops a +/// board's request rather than wait (see `Router::propagate_fault`). pub(super) const FAULT_QUEUE: usize = 8; /// A request to send the fault. #[derive(Debug)] -pub(super) struct FaultRequest { - /// Told once the fault has been sent, or was already sent before: the - /// routing loop waits on it before stopping on a fatal error. - pub(super) done: Option>, +pub(super) enum FaultRequest { + /// The backend's own decision: a fatal error, or a board's fault when + /// `propagate_fault` is on. + Automatic { + /// Told once the fault has gone out (or failed to): the routing loop + /// waits on it before stopping on a fatal error. + done: Option>, + }, + /// The operator asked for it from the front (order id 0). + FromFront { + /// The order as it came from the front. + order: OrderPacket, + }, +} + +/// Why the fault did not reach every board. +enum Undelivered { + /// There is no TCP client. + NoTcp, + /// Some boards did not get it: the text names them. + Missed(String), +} + +impl Undelivered { + fn reason(self) -> String { + match self { + Undelivered::NoTcp => TCP_NOT_AVAILABLE.to_string(), + Undelivered::Missed(text) => text, + } + } } /// Runs the worker until its queue closes (or `event` stops it). /// -/// The "only once" flag lives here and nowhere else: a fatal error, a board's -/// fault and the front all end up in this queue. A request that arrives while -/// the fault is being sent waits behind it, so it is only acknowledged once -/// the fault has really gone out. +/// Requests are sent one at a time, in the order they arrive: one that +/// arrives while the fault is being sent waits behind it. +/// +/// It never stops on its own when `logging` or `pipeline` are gone: that is +/// exactly when a fatal stop still needs it to send the fault. pub(super) async fn run( mut requests: mpsc::Receiver, tcp: Option>, + logging: mpsc::Sender, pipeline: mpsc::Sender, - boards: Arc, + pod_data: Arc, ) { - let mut sent = false; + let tcp = tcp.as_deref(); while let Some(request) = requests.recv().await { - if !sent { - sent = true; - send_fault(tcp.as_deref(), &pipeline, &boards).await; - } - if let Some(done) = request.done { - // The one waiting may have given up already (its time limit). - let _ = done.send(()); + match request { + FaultRequest::Automatic { done } => { + match send_fault(tcp, &pod_data).await { + Ok(()) => info!("fault sent to every board"), + Err(Undelivered::NoTcp) => { + warn!("the fault was not sent to the boards: {TCP_NOT_AVAILABLE}"); + } + Err(Undelivered::Missed(text)) => { + error!(%text); + // A fault that only half landed is exactly what the + // operator has to know. + let problem = Problem::now(ProblemKind::Shown, None, text); + let _ = pipeline.send(ToPipeline::Problem(problem)).await; + } + } + if let Some(done) = done { + // The one waiting may have given up already (its time limit). + let _ = done.send(()); + } + } + FaultRequest::FromFront { order } => { + let outcome = send_fault(tcp, &pod_data).await; + let at = SystemTime::now(); + match outcome { + Ok(()) => { + info!("fault sent to every board, as the front asked"); + let logged = ToLogging::OrderSent { + at, + board: None, + order: order.clone(), + }; + let _ = logging.send(logged).await; + let shown = ToPipeline::OrderSent { + at, + board: None, + order, + }; + let _ = pipeline.send(shown).await; + } + Err(undelivered) => { + let reason = undelivered.reason(); + warn!(%reason, "the fault the front asked for did not go out"); + let failed = ToPipeline::OrderFailed { at, order, reason }; + let _ = pipeline.send(failed).await; + } + } + } } } } -/// Sends the fault and tells the front about the boards it did not reach. -async fn send_fault( - tcp: Option<&dyn TcpLink>, - pipeline: &mpsc::Sender, - boards: &Boards, -) { - let Some(tcp) = tcp else { - warn!("the fault was not sent to the boards: TCP not available"); - return; - }; - - match tcp.send_fault().await { - Ok(()) => info!("fault sent to every board"), - Err(unreached) => { - let names: Vec = unreached.iter().map(|&board| boards.name(board)).collect(); - let text = format!("the fault did not reach these boards: {}", names.join(", ")); - error!(%text); - // A fault that only half landed is exactly what the operator has - // to know. If pipeline is gone, event is stopping anyway. - let problem = Problem::now(ProblemKind::Shown, None, text); - let _ = pipeline.send(ToPipeline::Problem(problem)).await; - } - } +/// Sends the fault to every board. +async fn send_fault(tcp: Option<&dyn TcpLink>, pod_data: &PodData) -> Result<(), Undelivered> { + let tcp = tcp.ok_or(Undelivered::NoTcp)?; + tcp.send_fault().await.map_err(|unreached| { + let names: Vec = unreached + .iter() + .map(|&board| board_name(pod_data, board)) + .collect(); + Undelivered::Missed(format!( + "the fault did not reach these boards: {}", + names.join(", ") + )) + }) } diff --git a/backend/crates/station/src/event/manual_tests.rs b/backend/crates/station/src/event/manual_tests.rs index 3c3da9895..3ca606239 100644 --- a/backend/crates/station/src/event/manual_tests.rs +++ b/backend/crates/station/src/event/manual_tests.rs @@ -33,13 +33,13 @@ async fn manual_event_throughput() -> Result<(), Box> { mut pipeline, } = channels(&config); drop((tcp, orders, problems)); - let event = spawn(config, event, Boards::default(), None); + let event = spawn(config, event, Arc::default(), Arc::default(), None); let logged = tokio::spawn(async move { let mut count = 0; while let Some(message) = logging.recv().await { - if let ToLogging::Received(batch) = message { - count += batch.len(); + if let ToLogging::Received(_) = message { + count += 1; } } count @@ -47,8 +47,8 @@ async fn manual_event_throughput() -> Result<(), Box> { let shown = tokio::spawn(async move { let mut count = 0; while let Some(message) = pipeline.recv().await { - if let ToPipeline::Received(batch) = message { - count += batch.len(); + if let ToPipeline::Received(_) = message { + count += 1; } } count diff --git a/backend/crates/station/src/event/orders.rs b/backend/crates/station/src/event/orders.rs index f3b2a6303..1caecd546 100644 --- a/backend/crates/station/src/event/orders.rs +++ b/backend/crates/station/src/event/orders.rs @@ -16,10 +16,12 @@ pub(super) const TCP_NOT_AVAILABLE: &str = "TCP not available"; /// Runs the worker until its queue closes (or `event` stops it). /// -/// - An order with id 0 is the fault: it goes to the fault worker (⑧). +/// - An order with id 0 is the fault: it goes to the fault worker (⑧), which +/// tells the front how it went. /// - Any other order is written and waited for before the next one is -/// taken. Written: it goes to `logging` (⑤). Not written: it goes to -/// `pipeline` (⑥) with the reason, and to the trace. +/// taken. Written: it goes to `logging` (⑤) and to `pipeline` (⑥), which +/// shows it on the front. Not written: it goes to `pipeline` with the +/// reason, and to the trace. pub(super) async fn run( mut orders: mpsc::Receiver, tcp: Option>, @@ -30,7 +32,7 @@ pub(super) async fn run( while let Some(order) = orders.recv().await { if order.id == FAULT_ID { info!("the front asked for the fault"); - if fault.send(FaultRequest { done: None }).await.is_err() { + if fault.send(FaultRequest::FromFront { order }).await.is_err() { break; } continue; @@ -44,10 +46,16 @@ pub(super) async fn run( // Stamped once the outcome is known: "sent" means written. let at = SystemTime::now(); let delivered = match outcome { - Ok(board) => logging - .send(ToLogging::OrderSent { at, board, order }) - .await - .is_ok(), + Ok(board) => { + let board = Some(board); + let logged = ToLogging::OrderSent { + at, + board, + order: order.clone(), + }; + let shown = ToPipeline::OrderSent { at, board, order }; + logging.send(logged).await.is_ok() && pipeline.send(shown).await.is_ok() + } Err(reason) => { warn!(id = ?order.id, %reason, "order not sent"); pipeline diff --git a/backend/crates/station/src/event/policy.rs b/backend/crates/station/src/event/policy.rs index 4fb8d2b86..074dd551d 100644 --- a/backend/crates/station/src/event/policy.rs +++ b/backend/crates/station/src/event/policy.rs @@ -4,8 +4,9 @@ use std::error::Error; use std::net::IpAddr; -use software_core::model::BoardId; -use software_core::net::{self, tcp, udp::UdpError}; +use software_core::model::{AdjId, BoardId, MessageLevel, Packet, PacketType, Severity}; +use software_core::net::{self, Event, tcp, udp::UdpError}; +use software_core::protocol::Index; use super::ProblemKind; @@ -59,12 +60,50 @@ pub(super) fn for_problem(kind: ProblemKind) -> Action { } } +/// Whether a notification is a board saying it is in fault: a protection the +/// ADJ declares with severity `Fault`, or a message of level `Fault` or +/// `Panic`. Either one is sent to every board when `propagate_fault` is on. +/// +/// Only protections and messages are looked up, so the telemetry that makes +/// up nearly all the traffic costs one `match` and nothing else. +pub(super) fn is_board_fault(event: &Event, index: &Index) -> bool { + match event { + Event::Received(Packet::Protection(protection)) => { + protection_is_fault(protection.id, index) + } + Event::Received(Packet::Message(message)) => matches!( + index.packet(message.id).map(|def| &def.packet_type), + Some(PacketType::Message( + MessageLevel::Fault | MessageLevel::Panic + )) + ), + _ => false, + } +} + +/// Whether the protection a board reported under `id` is declared with +/// severity `Fault`. The compound id leads to the watched measurement, and +/// its position (the high 3 bits) to which of that measurement's protections +/// triggered. +fn protection_is_fault(id: AdjId, index: &Index) -> bool { + let Some(PacketType::Protection(measurement)) = index.packet(id).map(|def| &def.packet_type) + else { + return false; + }; + let position = AdjId(u16::from(id.protection_position())); + measurement + .protections + .iter() + .any(|protection| protection.id == position && protection.severity == Severity::Fault) +} + /// Where an error comes from, as far as the error itself says. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(super) struct Source { - /// The board, when the error names it (TCP errors do). + /// The board, when the error names it: TCP errors always do, UDP errors + /// when the address belongs to a board. pub(super) board: Option, - /// The address a datagram came from, when that is all there is (UDP). + /// The address a datagram came from (UDP errors about one datagram). pub(super) ip: Option, } @@ -72,8 +111,8 @@ pub(super) struct Source { pub(super) fn source(error: &net::Error) -> Source { match error { net::Error::Udp(error) => match error { - UdpError::Decode { from, .. } | UdpError::Fault { from } => Source { - board: None, + UdpError::Decode { from, board, .. } | UdpError::Fault { from, board } => Source { + board: *board, ip: Some(from.ip()), }, UdpError::Recv { .. } | UdpError::Bind { .. } => Source { @@ -110,13 +149,139 @@ pub fn full_message(error: &dyn Error) -> String { message } +/// An ADJ with what [`is_board_fault`] looks at, for this file's tests and the +/// routing loop's: board 1 watches measurement 3000 with two protections, +/// position 1 a `Fault` and position 2 a `Warning`; message ids 2, 3, 4 and 5 +/// are `Fault`, `Panic`, `Warning` and `Info`. +#[cfg(test)] +pub(super) fn index_with_faults() -> Index { + use software_core::model::{ + Board, MacAddress, Measurement, MeasurementKind, PacketDef, PodData, Protection, + ProtectionKind, + }; + use std::collections::HashMap; + use std::time::Duration; + + let protection = |slot: u16, severity| Protection { + id: AdjId(slot), + kind: ProtectionKind::Above { limit: 1.0 }, + severity, + time: Duration::ZERO, + }; + let measurement = Measurement { + id: AdjId(3000), + alias: "temperature".to_string(), + name: "Temperature".to_string(), + display_units: "ºC".to_string(), + kind: MeasurementKind::Boolean, + protections: vec![ + protection(1, Severity::Fault), + protection(2, Severity::Warning), + ], + }; + let packets = [1, 2].map(|slot| { + let id = protection_id(slot); + let def = PacketDef { + id, + board: BoardId(1), + name: format!("temperature_protection_{slot}"), + packet_type: PacketType::Protection(measurement.clone()), + }; + (id, def) + }); + let board = Board { + id: BoardId(1), + name: "PCU".to_string(), + ip: IpAddr::from([127, 0, 0, 7]), + mac: MacAddress([0; 6]), + packets: HashMap::from(packets), + }; + let pod_data = PodData { + boards: HashMap::from([(board.id, board)]), + }; + let levels = HashMap::from([ + (AdjId(2), MessageLevel::Fault), + (AdjId(3), MessageLevel::Panic), + (AdjId(4), MessageLevel::Warning), + (AdjId(5), MessageLevel::Info), + ]); + Index::new(&pod_data, Some(&levels)) +} + +/// The compound id of measurement 3000's protection at `slot`, as a board +/// sends it. +#[cfg(test)] +fn protection_id(slot: u16) -> AdjId { + AdjId((slot << 13) | 3000) +} + +/// A board reporting that measurement 3000's protection at `slot` triggered. +#[cfg(test)] +pub(super) fn protection_triggered(slot: u16) -> Event { + use software_core::model::{ProtectionPacket, ShortTimestamp, Value}; + Event::Received(Packet::Protection(ProtectionPacket { + id: protection_id(slot), + timestamp: ShortTimestamp { + hour: 12, + minute: 0, + second: 0, + subsecond: 0, + }, + value: Value::Bool(true), + })) +} + +/// A board sending a message under message id `id`. +#[cfg(test)] +pub(super) fn message_sent(id: u16) -> Event { + use software_core::model::{MessagePacket, ShortTimestamp}; + Event::Received(Packet::Message(MessagePacket { + id: AdjId(id), + timestamp: ShortTimestamp { + hour: 12, + minute: 0, + second: 0, + subsecond: 0, + }, + origin: "main.c".to_string(), + message: "something happened".to_string(), + })) +} + #[cfg(test)] mod tests { use super::*; - use software_core::model::AdjId; + use software_core::model::DataPacket; use software_core::protocol::DecodeError; use std::net::SocketAddr; + #[test] + fn a_protection_declared_as_a_fault_is_a_board_fault() { + let index = index_with_faults(); + assert!(is_board_fault(&protection_triggered(1), &index)); + assert!( + !is_board_fault(&protection_triggered(2), &index), + "a warning is not" + ); + } + + #[test] + fn fault_and_panic_messages_are_board_faults() { + let index = index_with_faults(); + assert!(is_board_fault(&message_sent(2), &index), "fault"); + assert!(is_board_fault(&message_sent(3), &index), "panic"); + assert!(!is_board_fault(&message_sent(4), &index), "warning"); + assert!(!is_board_fault(&message_sent(5), &index), "info"); + } + + #[test] + fn telemetry_and_connections_are_never_board_faults() { + let index = index_with_faults(); + let data = Event::Received(Packet::Data(DataPacket::new(AdjId(1000), vec![]))); + assert!(!is_board_fault(&data, &index)); + assert!(!is_board_fault(&Event::Connected, &index)); + } + fn from() -> SocketAddr { SocketAddr::new(IpAddr::from([127, 0, 0, 7]), 50400) } @@ -145,6 +310,7 @@ mod tests { ] { let error = udp(UdpError::Decode { from: from(), + board: None, source, }); assert_eq!(classify(&error), Action::Fatal, "{error}"); @@ -159,7 +325,10 @@ mod tests { #[test] fn a_fault_from_a_board_does_not_stop_the_backend() { - let error = udp(UdpError::Fault { from: from() }); + let error = udp(UdpError::Fault { + from: from(), + board: Some(BoardId(7)), + }); assert_eq!(classify(&error), Action::BoardFault); } @@ -191,10 +360,26 @@ mod tests { } #[test] - fn udp_errors_carry_an_address_and_tcp_errors_a_board() { - let fault = udp(UdpError::Fault { from: from() }); + fn udp_errors_carry_an_address_and_maybe_a_board_and_tcp_errors_a_board() { + let fault = udp(UdpError::Fault { + from: from(), + board: Some(BoardId(7)), + }); assert_eq!( source(&fault), + Source { + board: Some(BoardId(7)), + ip: Some(from().ip()) + } + ); + + // An address that belongs to no board keeps the address only. + let stranger = udp(UdpError::Fault { + from: from(), + board: None, + }); + assert_eq!( + source(&stranger), Source { board: None, ip: Some(from().ip()) @@ -227,6 +412,7 @@ mod tests { fn the_full_message_carries_every_cause_once() { let error = udp(UdpError::Decode { from: from(), + board: None, source: DecodeError::UnknownId(AdjId(9999)), }); diff --git a/backend/crates/station/src/event/router.rs b/backend/crates/station/src/event/router.rs new file mode 100644 index 000000000..8a5e817de --- /dev/null +++ b/backend/crates/station/src/event/router.rs @@ -0,0 +1,453 @@ +//! The routing loop: everything towards the front. +//! +//! Reads ① ② ③ ④ in fixed order (errors, problems, TCP, UDP), hands every +//! notification to `logging` and `pipeline` (⑤ ⑥), decides what each error +//! and each board fault means with [`super::policy`], and asks the fault +//! worker (⑧) for the fault. It never writes to a socket itself, so it never +//! waits on one. + +use std::collections::HashSet; +use std::net::IpAddr; +use std::sync::Arc; + +use software_core::model::PodData; +use software_core::net::{ErrorReport, Notification, Sinks}; +use software_core::protocol::Index; +use tokio::sync::{mpsc, oneshot}; +use tokio::time::Instant; +use tracing::{debug, error, warn}; + +use super::fault::FaultRequest; +use super::policy::{self, Action}; +use super::{ + EventConfig, Problem, ProblemKind, Stop, ToLogging, ToPipeline, board_name, full_message, +}; + +/// The routing loop's ends of the queues: the reading side of ① ② ③ ④ and +/// the writing side of ⑤ ⑥. +#[derive(Debug)] +pub(super) struct RouterEnds { + /// ① and ④: UDP's errors and notifications. + pub(super) udp: Sinks, + /// ① and ③: TCP's errors and notifications. + pub(super) tcp: Sinks, + /// ②: problems from station modules. + pub(super) problems: mpsc::Receiver, + /// ⑤: to `logging`. The workers get clones. + pub(super) logging: mpsc::Sender, + /// ⑥: to `pipeline`. The workers get clones. + pub(super) pipeline: mpsc::Sender, + /// Capacity of ③: how much a fatal stop drains at most. + pub(super) tcp_capacity: usize, + /// Capacity of ④: how much a fatal stop drains at most. + pub(super) udp_capacity: usize, +} + +/// Which transport a notification queue belongs to. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Transport { + Tcp, + Udp, +} + +/// A consumer of the routing loop that has stopped. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Consumer { + Logging, + Pipeline, +} + +/// Why the routing loop has to stop, before it does it. +#[derive(Debug)] +enum Halt { + Fatal(Problem), + Gone(Consumer), +} + +/// What one round of the `select!` got. +enum Step { + NetError(Transport, Option), + Problem(Option), + Notification(Transport, Option), +} + +/// Which input queues are still open. A closed queue answers "closed" +/// instantly, every time, so it is no longer watched: in fixed order it would +/// win every round and hide the queues below it. +#[derive(Debug, Clone, Copy)] +struct Open { + udp_errors: bool, + tcp_errors: bool, + problems: bool, + tcp_notifications: bool, + udp_notifications: bool, +} + +impl Default for Open { + fn default() -> Self { + Self { + udp_errors: true, + tcp_errors: true, + problems: true, + tcp_notifications: true, + udp_notifications: true, + } + } +} + +impl Open { + /// Whether any of `net`'s four queues is still open. The loop only ends + /// once all four are closed, so an error queued just before its + /// transport stopped is never lost. + fn net(&self) -> bool { + self.udp_errors || self.tcp_errors || self.tcp_notifications || self.udp_notifications + } +} + +/// The routing loop's state. +pub(super) struct Router { + config: EventConfig, + pod_data: Arc, + index: Arc, + udp: Sinks, + tcp: Sinks, + problems: mpsc::Receiver, + logging: mpsc::Sender, + pipeline: mpsc::Sender, + fault: mpsc::Sender, + open: Open, + tcp_capacity: usize, + udp_capacity: usize, + /// The addresses whose fault has already been shown. + faults_shown: HashSet, +} + +impl Router { + /// A routing loop over `ends`, that asks for the fault on `fault` (⑧). + /// `pod_data` is only read for the boards' names, `index` for which + /// protections and messages mean fault. + pub(super) fn new( + config: EventConfig, + pod_data: Arc, + index: Arc, + ends: RouterEnds, + fault: mpsc::Sender, + ) -> Self { + Self { + config, + pod_data, + index, + udp: ends.udp, + tcp: ends.tcp, + problems: ends.problems, + logging: ends.logging, + pipeline: ends.pipeline, + fault, + open: Open::default(), + tcp_capacity: ends.tcp_capacity, + udp_capacity: ends.udp_capacity, + faults_shown: HashSet::new(), + } + } + + /// Runs the loop until it has to stop, and says why. + /// + /// Takes the router by value: when it returns, the router's ends of ⑤ ⑥ + /// and ⑧ are dropped with it. + pub(super) async fn route(mut self) -> Stop { + loop { + // If all four of `net`'s queues are closed, the loop ends: it has nothing left to do. + if !self.open.net() { + return Stop::NetGone; + } + + let open = self.open; + // Fixed order: errors, then TCP, then UDP. + let step = tokio::select! { + biased; + // UDP has more priority than TCP, since TCP won't be sent if UDP is down: a UDP error is more urgent. + report = self.udp.errors.recv(), if open.udp_errors => { + Step::NetError(Transport::Udp, report) + } + report = self.tcp.errors.recv(), if open.tcp_errors => { + Step::NetError(Transport::Tcp, report) + } + problem = self.problems.recv(), if open.problems => Step::Problem(problem), + + // Then notifications after errrors + notification = self.tcp.notifications.recv(), if open.tcp_notifications => { + Step::Notification(Transport::Tcp, notification) + } + notification = self.udp.notifications.recv(), if open.udp_notifications => { + Step::Notification(Transport::Udp, notification) + } + else => return Stop::NetGone, + }; + + // handle of the error + let handled = match step { + // Errors + Step::NetError(Transport::Udp, None) => { + self.open.udp_errors = false; + Ok(()) + } + Step::NetError(Transport::Tcp, None) => { + self.open.tcp_errors = false; + Ok(()) + } + Step::NetError(_, Some(report)) => self.on_net_error(report).await, + Step::Problem(None) => { + self.open.problems = false; + Ok(()) + } + Step::Problem(Some(problem)) => self.on_problem(problem).await, + + // Notifications empty + Step::Notification(Transport::Tcp, None) => { + self.open.tcp_notifications = false; + Ok(()) + } + Step::Notification(Transport::Udp, None) => { + self.open.udp_notifications = false; + Ok(()) + } + + // Notifications with content + Step::Notification(_, Some(notification)) => { + // Before forwarding: asking for the fault never waits, + // forwarding may (a full ⑤ or ⑥). + if policy::is_board_fault(¬ification.event, &self.index) { + let board = board_name(&self.pod_data, notification.board); + self.propagate_fault(&board); + } + self.forward(notification).await.map_err(Halt::Gone) + } + }; + + match handled { + Ok(()) => {} + Err(Halt::Fatal(problem)) => return self.stop_fatal(problem).await, + Err(Halt::Gone(consumer)) => return self.stop_consumer_gone(consumer).await, + } + } + } + + /// Sends a notification to both consumers, as one shared copy. + async fn forward(&self, notification: Notification) -> Result<(), Consumer> { + let shared = Arc::new(notification); + + // Sent to logging + self.logging + .send(ToLogging::Received(shared.clone())) + .await + .map_err(|_| Consumer::Logging)?; + + // Send to pipeline, + self.pipeline + .send(ToPipeline::Received(shared)) + .await + .map_err(|_| Consumer::Pipeline) + } + + /// Handles a network error: classifies it, shows it if it has to, and + async fn on_net_error(&mut self, report: ErrorReport) -> Result<(), Halt> { + // + let action = policy::classify(&report.error); + let source = policy::source(&report.error); + let board = source.board; + + // A UDP error's message names the address, not the board: put the + // board's name in front. + let mut text = full_message(&report.error); + if let (Some(board), Some(_)) = (board, source.ip) { + text = format!("{}: {text}", board_name(&self.pod_data, board)); + } + + let kind = match action { + Action::Fatal => ProblemKind::Fatal, + Action::Silent => ProblemKind::Silent, + Action::Show | Action::BoardFault => ProblemKind::Shown, + }; + + // Defines the problem to show, or to send with the fault if it is fatal. + let problem = Problem { + at: report.at, + board, + kind, + text, + }; + + // What to do with it: show it, send the fault, or just trace it. + match action { + Action::Fatal => Err(Halt::Fatal(problem)), + Action::BoardFault => self.on_board_fault(problem, source.ip).await, + Action::Show => self.show(problem).await.map_err(Halt::Gone), + Action::Silent => { + self.trace_silent(&problem); + Ok(()) + } + } + } + + async fn on_problem(&mut self, problem: Problem) -> Result<(), Halt> { + match policy::for_problem(problem.kind) { + Action::Fatal => Err(Halt::Fatal(problem)), + Action::Silent => { + self.trace_silent(&problem); + Ok(()) + } + Action::Show | Action::BoardFault => self.show(problem).await.map_err(Halt::Gone), + } + } + + /// Procedure 1: written to the trace, and nothing else. + fn trace_silent(&self, problem: &Problem) { + let board = problem.board.map(|board| board_name(&self.pod_data, board)); + warn!(board = ?board, problem = %problem.text, "problem not shown on the front"); + } + + /// A fault (packet id 0) a board sent: sent to every board each time. + /// + /// It arrives as an error, not as a notification, so the front only sees + /// it if it is shown here: the first one from each address is, repeats + /// are not (`net` already traces them, rate-limited). + async fn on_board_fault(&mut self, problem: Problem, ip: Option) -> Result<(), Halt> { + let board = problem.board.map_or_else( + || "an unknown board".to_string(), + |board| board_name(&self.pod_data, board), + ); + self.propagate_fault(&board); + + let first = ip.is_none_or(|ip| self.faults_shown.insert(ip)); + if first { + warn!(fault = %problem.text, "first fault from this board"); + self.show(problem).await.map_err(Halt::Gone)?; + } + Ok(()) + } + + /// A board is in fault: sends the fault to every board, if + /// `propagate_fault` is on. Every time, like any fault that arrives. + fn propagate_fault(&self, board: &str) { + if !self.config.propagate_fault { + return; + } + // Never waits: if ⑧ is full, faults are already waiting to go out. + let request = FaultRequest::Automatic { done: None }; + match self.fault.try_send(request) { + Ok(()) => warn!(board, "fault from a board: sending it to every board"), + Err(error) => debug!(board, %error, "fault request not queued"), + } + } + + // sends to pipelne a Problem + async fn show(&self, problem: Problem) -> Result<(), Consumer> { + self.pipeline + .send(ToPipeline::Problem(problem)) + .await + .map_err(|_| Consumer::Pipeline) + } + + /// Procedure 3: send the fault, show the problem, pass on what was + /// already queued, stop. + /// + /// The fault is asked for first, since it has to reach the boards as soon + /// as possible; the rest happens while the fault worker writes it, and the + /// loop only stops once it has gone out. + async fn stop_fatal(mut self, problem: Problem) -> Stop { + error!(problem = %problem.text, "fatal error, stopping"); + let deadline = Instant::now() + self.config.fault_timeout; + let fault_sent = self.ask_for_fault(deadline).await; + + let pipeline_alive = self + .pipeline + .send(ToPipeline::Problem(problem.clone())) + .await + .is_ok(); + if pipeline_alive { + // Errors are read first, so this one has overtaken the data that + // arrived just before it: pass that on before stopping. If a + // consumer stops meanwhile, there is nothing left to do with it. + let _ = self.drain().await; + } + + self.wait_for_fault(fault_sent, deadline).await; + Stop::Fatal(problem) + } + + /// `logging` or `pipeline` stopped: nothing is recorded, or nothing is + /// shown. Fatal, without draining. + async fn stop_consumer_gone(self, consumer: Consumer) -> Stop { + let text = match consumer { + Consumer::Logging => "logging stopped: nothing is being recorded", + Consumer::Pipeline => "pipeline stopped: nothing reaches the front", + }; + let problem = Problem::now(ProblemKind::Fatal, None, text); + error!(problem = %problem.text, "fatal error, stopping"); + let deadline = Instant::now() + self.config.fault_timeout; + let fault_sent = self.ask_for_fault(deadline).await; + + if consumer == Consumer::Logging { + let _ = self + .pipeline + .send(ToPipeline::Problem(problem.clone())) + .await; + } + + self.wait_for_fault(fault_sent, deadline).await; + Stop::Fatal(problem) + } + + /// Passes on what is already in ③ and ④, at most their capacity each, so + /// that it cannot chase a queue that keeps filling up. + async fn drain(&mut self) -> Result<(), Consumer> { + for transport in [Transport::Tcp, Transport::Udp] { + let limit = match transport { + Transport::Tcp => self.tcp_capacity, + Transport::Udp => self.udp_capacity, + }; + for _ in 0..limit { + let queue = match transport { + Transport::Tcp => &mut self.tcp.notifications, + Transport::Udp => &mut self.udp.notifications, + }; + let Ok(notification) = queue.try_recv() else { + break; + }; + self.forward(notification).await?; + } + } + Ok(()) + } + + /// Asks the fault worker for the fault, without waiting for it to go out: + /// only for room in ⑧, and no later than `deadline`. Returns what tells + /// once it has gone out, or `None` if it could not be asked for. + async fn ask_for_fault(&self, deadline: Instant) -> Option> { + let (done_tx, done_rx) = oneshot::channel(); + let request = FaultRequest::Automatic { + done: Some(done_tx), + }; + match tokio::time::timeout_at(deadline, self.fault.send(request)).await { + Ok(Ok(())) => Some(done_rx), + _ => { + warn!("the fault could not be asked for; stopping without it"); + None + } + } + } + + /// Waits until the fault asked for has gone out, no later than `deadline` + /// ([`EventConfig::fault_timeout`] after it was asked for). + async fn wait_for_fault(&self, fault_sent: Option>, deadline: Instant) { + let Some(fault_sent) = fault_sent else { + return; + }; + if tokio::time::timeout_at(deadline, fault_sent).await.is_err() { + warn!( + timeout = ?self.config.fault_timeout, + "the fault was not confirmed in time; stopping anyway" + ); + } + } +} diff --git a/backend/crates/station/src/event/tests.rs b/backend/crates/station/src/event/tests.rs index b32518285..0fbfda463 100644 --- a/backend/crates/station/src/event/tests.rs +++ b/backend/crates/station/src/event/tests.rs @@ -9,8 +9,9 @@ use software_core::model::{AdjId, Board, DataPacket, MacAddress, Packet}; use software_core::net::Event; use software_core::net::udp::UdpError; use software_core::protocol::DecodeError; +use std::collections::HashMap; use std::error::Error; -use std::net::SocketAddr; +use std::net::{IpAddr, SocketAddr}; use std::sync::atomic::{AtomicUsize, Ordering}; use tokio::time::{sleep, timeout}; @@ -38,27 +39,38 @@ fn board(id: BoardId, name: &str, addr: SocketAddr) -> Board { } } -fn boards() -> Boards { - let pod_data = PodData { +/// The ADJ lookups: which protections and messages mean fault (see +/// [`policy::index_with_faults`]). +fn index() -> Arc { + Arc::new(policy::index_with_faults()) +} + +fn pod_data() -> Arc { + Arc::new(PodData { boards: HashMap::from([ (HVSCU, board(HVSCU, "HVSCU", hvscu_addr())), (VCU, board(VCU, "VCU", vcu_addr())), ]), - }; - Boards::from_pod_data(&pod_data) + }) } fn data() -> Event { Event::Received(Packet::Data(DataPacket::new(AdjId(1000), vec![]))) } -fn fault_from(from: SocketAddr) -> UdpError { - UdpError::Fault { from } +/// A fault as `net::udp` reports it: with the address and the board it +/// resolved that address to. +fn fault_from(from: SocketAddr, board: BoardId) -> UdpError { + UdpError::Fault { + from, + board: Some(board), + } } fn decode_error() -> UdpError { UdpError::Decode { from: hvscu_addr(), + board: Some(HVSCU), source: DecodeError::UnknownId(AdjId(9999)), } } @@ -134,23 +146,50 @@ fn as_link(fake: &Arc) -> Option> { Some(link) } +/// The next `n` notifications on `pipeline`, failing on anything else. +async fn shown( + pipeline: &mut mpsc::Receiver, + n: usize, +) -> Result>, Box> { + let mut notifications = Vec::with_capacity(n); + for _ in 0..n { + let ToPipeline::Received(notification) = next(pipeline).await? else { + return Err("expected a notification on pipeline".into()); + }; + notifications.push(notification); + } + Ok(notifications) +} + +/// The next `n` notifications on `logging`, failing on anything else. +async fn logged( + logging: &mut mpsc::Receiver, + n: usize, +) -> Result>, Box> { + let mut notifications = Vec::with_capacity(n); + for _ in 0..n { + let ToLogging::Received(notification) = next(logging).await? else { + return Err("expected a notification on logging".into()); + }; + notifications.push(notification); + } + Ok(notifications) +} + #[tokio::test] -async fn a_batch_reaches_logging_and_pipeline_as_the_same_copy() -> TestResult { +async fn each_notification_reaches_logging_and_pipeline_as_the_same_copy() -> TestResult { let config = EventConfig::default(); let mut channels = channels(&config); for _ in 0..3 { channels.udp.notify(HVSCU, data()).await?; } - let _event = spawn(config, channels.event, boards(), None); + let _event = spawn(config, channels.event, pod_data(), index(), None); - let ToLogging::Received(logged) = next(&mut channels.logging).await? else { - unreachable!("the first thing logging gets is the batch"); - }; - let ToPipeline::Received(shown) = next(&mut channels.pipeline).await? else { - unreachable!("the first thing pipeline gets is the batch"); - }; - assert_eq!(logged.len(), 3); - assert!(Arc::ptr_eq(&logged, &shown), "one copy, shared"); + let logged = logged(&mut channels.logging, 3).await?; + let shown = shown(&mut channels.pipeline, 3).await?; + for (logged, shown) in logged.iter().zip(&shown) { + assert!(Arc::ptr_eq(logged, shown), "one copy, shared"); + } Ok(()) } @@ -161,8 +200,8 @@ async fn errors_come_first_then_tcp_then_udp() -> TestResult { // Queued in the opposite order to the one they must come out in. channels.udp.notify(HVSCU, data()).await?; channels.tcp.notify(VCU, Event::Connected).await?; - channels.udp.report(fault_from(hvscu_addr())).await?; - let _event = spawn(config, channels.event, boards(), None); + channels.udp.report(fault_from(hvscu_addr(), HVSCU)).await?; + let _event = spawn(config, channels.event, pod_data(), index(), None); let ToPipeline::Problem(problem) = next(&mut channels.pipeline).await? else { unreachable!("the error comes first"); @@ -176,12 +215,12 @@ async fn errors_come_first_then_tcp_then_udp() -> TestResult { let ToPipeline::Received(tcp) = next(&mut channels.pipeline).await? else { unreachable!("then the TCP notification"); }; - assert!(matches!(tcp[0].event, Event::Connected)); + assert!(matches!(tcp.event, Event::Connected)); let ToPipeline::Received(udp) = next(&mut channels.pipeline).await? else { unreachable!("then the UDP notification"); }; - assert!(matches!(udp[0].event, Event::Received(Packet::Data(_)))); + assert!(matches!(udp.event, Event::Received(Packet::Data(_)))); Ok(()) } @@ -192,24 +231,18 @@ async fn a_fatal_error_passes_on_what_was_queued_and_stops() -> TestResult { channels.udp.notify(HVSCU, data()).await?; channels.udp.notify(HVSCU, data()).await?; channels.udp.report(decode_error()).await?; - let event = spawn(config, channels.event, boards(), None); + let event = spawn(config, channels.event, pod_data(), index(), None); let ToPipeline::Problem(problem) = next(&mut channels.pipeline).await? else { unreachable!("the fatal error is shown first"); }; assert_eq!(problem.kind, ProblemKind::Fatal); - assert_eq!(problem.board, Some(HVSCU), "resolved from the address"); + assert_eq!(problem.board, Some(HVSCU), "the board the error carries"); assert!(problem.text.starts_with("HVSCU: "), "{}", problem.text); - // The data that arrived before the error still gets through. - let ToPipeline::Received(shown) = next(&mut channels.pipeline).await? else { - unreachable!("then what was queued"); - }; - let ToLogging::Received(logged) = next(&mut channels.logging).await? else { - unreachable!("logging gets what was queued too"); - }; - assert_eq!(shown.len(), 2); - assert_eq!(logged.len(), 2); + // The data that arrived before the error still gets through, to both. + shown(&mut channels.pipeline, 2).await?; + logged(&mut channels.logging, 2).await?; let Stop::Fatal(stopped_by) = stops(event).await? else { unreachable!("a decode error is fatal"); @@ -219,16 +252,16 @@ async fn a_fatal_error_passes_on_what_was_queued_and_stops() -> TestResult { } #[tokio::test] -async fn a_board_fault_is_shown_once_per_board_and_the_fault_sent_once() -> TestResult { +async fn a_board_fault_is_shown_once_per_board_and_sent_to_every_board_each_time() -> TestResult { let config = EventConfig::default(); let mut channels = channels(&config); let fake = Arc::new(FakeTcp::default()); - let event = spawn(config, channels.event, boards(), as_link(&fake)); + let event = spawn(config, channels.event, pod_data(), index(), as_link(&fake)); for _ in 0..3 { - channels.udp.report(fault_from(hvscu_addr())).await?; + channels.udp.report(fault_from(hvscu_addr(), HVSCU)).await?; } - channels.udp.report(fault_from(vcu_addr())).await?; + channels.udp.report(fault_from(vcu_addr(), VCU)).await?; // A marker: whatever comes before it on pipeline is all there is. channels.udp.notify(HVSCU, data()).await?; @@ -245,13 +278,8 @@ async fn a_board_fault_is_shown_once_per_board_and_the_fault_sent_once() -> Test assert_eq!(second.board, Some(VCU)); assert_eq!(first.kind, ProblemKind::Shown); - eventually(|| fake.faults.load(Ordering::SeqCst) == 1).await?; - sleep(Duration::from_millis(50)).await; - assert_eq!( - fake.faults.load(Ordering::SeqCst), - 1, - "the fault goes out once" - ); + // Four faults arrived, so the fault goes out four times. + eventually(|| fake.faults.load(Ordering::SeqCst) == 4).await?; assert!( !event.is_finished(), "a board fault does not stop the backend" @@ -260,19 +288,83 @@ async fn a_board_fault_is_shown_once_per_board_and_the_fault_sent_once() -> Test } #[tokio::test] -async fn forwarding_a_board_fault_can_be_turned_off() -> TestResult { +async fn a_fault_protection_or_message_is_forwarded_and_sent_to_every_board() -> TestResult { + let config = EventConfig::default(); + let mut channels = channels(&config); + let fake = Arc::new(FakeTcp::default()); + let _event = spawn(config, channels.event, pod_data(), index(), as_link(&fake)); + + channels + .tcp + .notify(HVSCU, policy::protection_triggered(1)) + .await?; + channels.tcp.notify(HVSCU, policy::message_sent(2)).await?; + channels.tcp.notify(HVSCU, policy::message_sent(3)).await?; + + // They still reach the front as what they are, not as extra problems. + shown(&mut channels.pipeline, 3).await?; + logged(&mut channels.logging, 3).await?; + eventually(|| fake.faults.load(Ordering::SeqCst) == 3).await?; + Ok(()) +} + +#[tokio::test] +async fn a_warning_protection_or_message_is_only_forwarded() -> TestResult { + let config = EventConfig::default(); + let mut channels = channels(&config); + let fake = Arc::new(FakeTcp::default()); + let _event = spawn(config, channels.event, pod_data(), index(), as_link(&fake)); + + channels + .tcp + .notify(HVSCU, policy::protection_triggered(2)) + .await?; + channels.tcp.notify(HVSCU, policy::message_sent(4)).await?; + channels.tcp.notify(HVSCU, policy::message_sent(5)).await?; + + shown(&mut channels.pipeline, 3).await?; + sleep(Duration::from_millis(50)).await; + assert_eq!(fake.faults.load(Ordering::SeqCst), 0); + Ok(()) +} + +#[tokio::test] +async fn a_fault_from_the_front_does_not_stop_a_board_fault_from_going_out() -> TestResult { + let config = EventConfig::default(); + let channels = channels(&config); + let fake = Arc::new(FakeTcp::default()); + let _event = spawn(config, channels.event, pod_data(), index(), as_link(&fake)); + + channels.orders.send(order(0)).await?; + eventually(|| fake.faults.load(Ordering::SeqCst) == 1).await?; + + channels + .tcp + .notify(HVSCU, policy::protection_triggered(1)) + .await?; + eventually(|| fake.faults.load(Ordering::SeqCst) == 2).await?; + Ok(()) +} + +#[tokio::test] +async fn propagating_a_board_fault_can_be_turned_off() -> TestResult { let config = EventConfig { - forward_board_faults: false, + propagate_fault: false, ..EventConfig::default() }; let mut channels = channels(&config); let fake = Arc::new(FakeTcp::default()); - let _event = spawn(config, channels.event, boards(), as_link(&fake)); + let _event = spawn(config, channels.event, pod_data(), index(), as_link(&fake)); - channels.udp.report(fault_from(hvscu_addr())).await?; + channels.udp.report(fault_from(hvscu_addr(), HVSCU)).await?; let ToPipeline::Problem(_) = next(&mut channels.pipeline).await? else { unreachable!("the fault is still shown"); }; + channels + .tcp + .notify(HVSCU, policy::protection_triggered(1)) + .await?; + shown(&mut channels.pipeline, 1).await?; sleep(Duration::from_millis(50)).await; assert_eq!(fake.faults.load(Ordering::SeqCst), 0); Ok(()) @@ -291,13 +383,13 @@ async fn closed_queues_do_not_hide_the_others() -> TestResult { pipeline: _pipeline, } = channels(&config); drop((tcp, orders, problems)); - let _event = spawn(config, event, boards(), None); + let _event = spawn(config, event, pod_data(), index(), None); udp.notify(HVSCU, data()).await?; - let ToLogging::Received(batch) = next(&mut logging).await? else { + let ToLogging::Received(notification) = next(&mut logging).await? else { unreachable!("the UDP notification gets through"); }; - assert_eq!(batch.len(), 1); + assert!(matches!(notification.event, Event::Received(_))); Ok(()) } @@ -305,7 +397,7 @@ async fn closed_queues_do_not_hide_the_others() -> TestResult { async fn without_tcp_an_order_fails() -> TestResult { let config = EventConfig::default(); let mut channels = channels(&config); - let _event = spawn(config, channels.event, boards(), None); + let _event = spawn(config, channels.event, pod_data(), index(), None); channels.orders.send(order(5)).await?; let ToPipeline::OrderFailed { order, reason, .. } = next(&mut channels.pipeline).await? else { @@ -317,17 +409,23 @@ async fn without_tcp_an_order_fails() -> TestResult { } #[tokio::test] -async fn a_written_order_is_logged() -> TestResult { +async fn a_written_order_is_logged_and_shown() -> TestResult { let config = EventConfig::default(); let mut channels = channels(&config); let fake = Arc::new(FakeTcp::default()); - let _event = spawn(config, channels.event, boards(), as_link(&fake)); + let _event = spawn(config, channels.event, pod_data(), index(), as_link(&fake)); channels.orders.send(order(5)).await?; let ToLogging::OrderSent { board, order, .. } = next(&mut channels.logging).await? else { unreachable!("the order is logged"); }; - assert_eq!(board, HVSCU); + assert_eq!(board, Some(HVSCU)); + assert_eq!(order.id, AdjId(5)); + + let ToPipeline::OrderSent { board, order, .. } = next(&mut channels.pipeline).await? else { + unreachable!("the front is told the order went out"); + }; + assert_eq!(board, Some(HVSCU)); assert_eq!(order.id, AdjId(5)); Ok(()) } @@ -340,7 +438,7 @@ async fn an_order_that_was_not_written_is_shown() -> TestResult { refuse_orders: Some("board not connected"), ..FakeTcp::default() }); - let _event = spawn(config, channels.event, boards(), as_link(&fake)); + let _event = spawn(config, channels.event, pod_data(), index(), as_link(&fake)); channels.orders.send(order(5)).await?; let ToPipeline::OrderFailed { reason, .. } = next(&mut channels.pipeline).await? else { @@ -351,14 +449,23 @@ async fn an_order_that_was_not_written_is_shown() -> TestResult { } #[tokio::test] -async fn order_id_0_is_the_fault() -> TestResult { +async fn order_id_0_is_the_fault_and_the_front_is_told() -> TestResult { let config = EventConfig::default(); - let channels = channels(&config); + let mut channels = channels(&config); let fake = Arc::new(FakeTcp::default()); - let _event = spawn(config, channels.event, boards(), as_link(&fake)); + let _event = spawn(config, channels.event, pod_data(), index(), as_link(&fake)); channels.orders.send(order(0)).await?; - eventually(|| fake.faults.load(Ordering::SeqCst) == 1).await?; + let ToPipeline::OrderSent { board, order, .. } = next(&mut channels.pipeline).await? else { + unreachable!("the front is told the fault went out"); + }; + assert_eq!(board, None, "the fault goes to every board"); + assert_eq!(order.id, AdjId(0)); + let ToLogging::OrderSent { board: None, .. } = next(&mut channels.logging).await? else { + unreachable!("the fault is logged"); + }; + + assert_eq!(fake.faults.load(Ordering::SeqCst), 1); assert_eq!( fake.orders.load(Ordering::SeqCst), 0, @@ -367,6 +474,61 @@ async fn order_id_0_is_the_fault() -> TestResult { Ok(()) } +#[tokio::test] +async fn a_fault_from_the_front_goes_out_even_if_one_was_sent_already() -> TestResult { + let config = EventConfig::default(); + let mut channels = channels(&config); + let fake = Arc::new(FakeTcp::default()); + let _event = spawn(config, channels.event, pod_data(), index(), as_link(&fake)); + + // An automatic fault first: a board's, propagated to the others. + channels.udp.report(fault_from(hvscu_addr(), HVSCU)).await?; + eventually(|| fake.faults.load(Ordering::SeqCst) == 1).await?; + + channels.orders.send(order(0)).await?; + let ToPipeline::Problem(_) = next(&mut channels.pipeline).await? else { + unreachable!("the board's fault is shown first"); + }; + let ToPipeline::OrderSent { .. } = next(&mut channels.pipeline).await? else { + unreachable!("then the front's fault, which went out again"); + }; + assert_eq!(fake.faults.load(Ordering::SeqCst), 2); + Ok(()) +} + +#[tokio::test] +async fn without_tcp_a_fault_from_the_front_fails() -> TestResult { + let config = EventConfig::default(); + let mut channels = channels(&config); + let _event = spawn(config, channels.event, pod_data(), index(), None); + + channels.orders.send(order(0)).await?; + let ToPipeline::OrderFailed { order, reason, .. } = next(&mut channels.pipeline).await? else { + unreachable!("the front is told the fault did not go out"); + }; + assert_eq!(order.id, AdjId(0)); + assert_eq!(reason, orders::TCP_NOT_AVAILABLE); + Ok(()) +} + +#[tokio::test] +async fn a_fault_from_the_front_that_misses_boards_fails() -> TestResult { + let config = EventConfig::default(); + let mut channels = channels(&config); + let fake = Arc::new(FakeTcp { + unreachable: vec![VCU], + ..FakeTcp::default() + }); + let _event = spawn(config, channels.event, pod_data(), index(), as_link(&fake)); + + channels.orders.send(order(0)).await?; + let ToPipeline::OrderFailed { reason, .. } = next(&mut channels.pipeline).await? else { + unreachable!("the front is told which boards it missed"); + }; + assert!(reason.contains("VCU"), "{reason}"); + Ok(()) +} + #[tokio::test] async fn a_fault_that_misses_boards_is_shown() -> TestResult { let config = EventConfig::default(); @@ -375,9 +537,9 @@ async fn a_fault_that_misses_boards_is_shown() -> TestResult { unreachable: vec![VCU], ..FakeTcp::default() }); - let _event = spawn(config, channels.event, boards(), as_link(&fake)); + let _event = spawn(config, channels.event, pod_data(), index(), as_link(&fake)); - channels.udp.report(fault_from(hvscu_addr())).await?; + channels.udp.report(fault_from(hvscu_addr(), HVSCU)).await?; let ToPipeline::Problem(fault) = next(&mut channels.pipeline).await? else { unreachable!("the board's fault is shown"); }; @@ -394,7 +556,7 @@ async fn a_fault_that_misses_boards_is_shown() -> TestResult { async fn a_station_problem_is_traced_shown_or_stops_as_its_module_says() -> TestResult { let config = EventConfig::default(); let mut channels = channels(&config); - let event = spawn(config, channels.event, boards(), None); + let event = spawn(config, channels.event, pod_data(), index(), None); let silent = Problem::now(ProblemKind::Silent, None, "only for the trace"); let shown = Problem::now(ProblemKind::Shown, None, "something to show"); @@ -428,7 +590,7 @@ async fn when_logging_stops_event_stops_and_tells_pipeline() -> TestResult { mut pipeline, } = channels(&config); drop(logging); - let event = spawn(config, event, boards(), None); + let event = spawn(config, event, pod_data(), index(), None); udp.notify(HVSCU, data()).await?; let ToPipeline::Problem(problem) = next(&mut pipeline).await? else { @@ -458,12 +620,10 @@ async fn when_net_closes_what_was_left_is_passed_on_and_event_stops() -> TestRes udp.notify(HVSCU, data()).await?; udp.notify(HVSCU, data()).await?; drop((udp, tcp)); - let event = spawn(config, event, boards(), None); + let event = spawn(config, event, pod_data(), index(), None); - let ToLogging::Received(batch) = next(&mut logging).await? else { - unreachable!("what was queued gets through"); - }; - assert_eq!(batch.len(), 2); + // What was queued gets through. + logged(&mut logging, 2).await?; let Stop::NetGone = stops(event).await? else { unreachable!("both transports are gone"); @@ -484,7 +644,7 @@ async fn a_fault_that_never_goes_out_does_not_block_the_stop() -> TestResult { fault_hangs: true, ..FakeTcp::default() }); - let event = spawn(config, channels.event, boards(), as_link(&fake)); + let event = spawn(config, channels.event, pod_data(), index(), as_link(&fake)); channels.udp.report(decode_error()).await?; let Stop::Fatal(_) = stops(event).await? else { From 6c0ea2b06f4f061183da294e47861dde4d5ad660 Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Tue, 1 Dec 2026 12:57:44 +0100 Subject: [PATCH 165/225] feat(backend, station): run UDP through event in main, with stand-ins for logging and pipeline --- backend/crates/station/README.md | 8 + backend/crates/station/src/main.rs | 360 ++++++++++++++++++++++++++++- backend/readme-demo.md | 70 ++++-- 3 files changed, 410 insertions(+), 28 deletions(-) diff --git a/backend/crates/station/README.md b/backend/crates/station/README.md index 00e8661df..aefa4aca6 100644 --- a/backend/crates/station/README.md +++ b/backend/crates/station/README.md @@ -15,3 +15,11 @@ cargo run -p station -- --config ./dev-config.toml *(Pendiente: crear `dev-config.toml` y `config.toml`, portados de `backend_old/cmd/`.)* +Mientras tanto, `src/main.rs` descarga el ADJ, escucha en el puerto UDP y +pasa lo que llega por `event` a dos sustitutos de `logging` y `pipeline`: +`cargo run -p station --release`. Ver +[`../../readme-demo.md`](../../readme-demo.md). + +`event`, la comunicación entre los módulos de station, está documentado en +[`src/event/README.md`](src/event/README.md). + diff --git a/backend/crates/station/src/main.rs b/backend/crates/station/src/main.rs index d872008d1..911ea49b4 100644 --- a/backend/crates/station/src/main.rs +++ b/backend/crates/station/src/main.rs @@ -1,13 +1,361 @@ -//! Ejecutable mínimo para demostrar la integración con `software-core`. +//! The station backend, as far as it goes today: downloads the ADJ, opens the +//! UDP port the ADJ names and runs `event` (see `src/event/README.md`) +//! between UDP and two stand-ins for `logging` and `pipeline`, which do not +//! exist yet: +//! +//! - the **logging stand-in** counts the packets it would record and writes a +//! summary every second (and every packet, with `RUST_LOG=station=debug`); +//! - the **pipeline stand-in** writes to the log what the front would show: +//! problems and failed orders. +//! +//! There is no TCP and no websocket yet: their queues are closed at start. +//! +//! From `backend/`: +//! +//! ```sh +//! cargo run -p station --release # a summary every second +//! RUST_LOG=info,station=debug cargo run -p station --release # and every packet +//! ``` +//! +//! It stops on Ctrl+C (exit code 0) or on a fatal error (exit code 1), such +//! as a datagram that cannot be decoded. A fault sent by a board is shown and +//! does not stop it. +//! +//! The ADJ goes into `core::git`'s default folder +//! (`~/.cache/hyperloop-control-station/adj` on Linux), the same one the Go +//! backend uses: whatever was there is replaced by the [`ADJ_BRANCH`] branch. +//! Offline, whatever is in that folder is used, whichever branch it is. +mod event; + +use std::collections::HashMap; +use std::net::SocketAddr; +use std::path::PathBuf; +use std::process::ExitCode; +use std::sync::Arc; +use std::time::{Duration, SystemTime}; + +use software_core::adj::{self, Adj, LoadError}; +use software_core::git::{self, GitError}; +use software_core::model::{BoardId, Packet, PodData}; +use software_core::net::udp::{UdpConfig, UdpError, spawn_udp}; +use software_core::net::{Event, Notification}; +use software_core::protocol::Index; +use tokio::sync::mpsc; +use tokio::task::JoinError; +use tokio::time::MissedTickBehavior; +use tracing::{debug, error, info, warn}; use tracing_subscriber::EnvFilter; -fn main() { +use event::{ProblemKind, Stop, ToLogging, ToPipeline}; + +/// Branch of the ADJ repository that is downloaded. +const ADJ_BRANCH: &str = "adjv3-software"; + +/// `SO_RCVBUF` requested from the OS: see `UdpConfig::recv_buffer`. +const RECV_BUFFER: usize = 2 * 1024 * 1024; + +/// How often the logging stand-in writes its summary. +const SUMMARY_EVERY: Duration = Duration::from_secs(1); + +/// How long the stand-ins get to finish what they have queued when stopping. +const SHUTDOWN_GRACE: Duration = Duration::from_secs(5); + +/// Everything that stops the program before `event` has a say. +#[derive(Debug, thiserror::Error)] +enum StartError { + #[error("could not get the ADJ (branch {ADJ_BRANCH})")] + Download(#[source] GitError), + #[error("the downloaded ADJ has no working directory")] + NoWorkdir, + #[error("could not load the ADJ from {path}")] + Load { + path: PathBuf, + #[source] + source: LoadError, + }, + #[error("the ADJ's general_info.json has no `{0}`")] + MissingInAdj(&'static str), + #[error("could not start tokio")] + Runtime(#[source] std::io::Error), + #[error("could not listen for Ctrl+C")] + CtrlC(#[source] std::io::Error), + #[error("could not open the UDP port")] + Bind(#[source] UdpError), + #[error("the event task failed")] + Event(#[source] JoinError), +} + +fn main() -> ExitCode { let filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info")); tracing_subscriber::fmt().with_env_filter(filter).init(); - tracing::info!("iniciando demo de station"); - let name = std::env::args().nth(1).unwrap_or_else(|| "World".into()); - let _greeting = software_core::hello_world::greet(&name); - tracing::info!("demo finalizada"); + match run() { + Ok(code) => code, + Err(error) => { + error!(error = %event::full_message(&error), "stopping"); + ExitCode::FAILURE + } + } +} + +fn run() -> Result { + let adj = download_adj()?; + let addr = udp_addr(&adj)?; + let index = Arc::new(Index::new(&adj.pod_data, Some(&adj.info.message_levels))); + let pod_data = Arc::new(adj.pod_data); + + let runtime = tokio::runtime::Runtime::new().map_err(StartError::Runtime)?; + runtime.block_on(serve(addr, index, pod_data)) +} + +/// Downloads the [`ADJ_BRANCH`] branch and loads it. +/// +/// `update_adj` blocks while downloading (network and disk), so it is called +/// before tokio starts. +fn download_adj() -> Result { + let commit = git::update_adj(None, ADJ_BRANCH).map_err(StartError::Download)?; + + // `update_adj` does not return the folder; it is read from the repository. + let repo = git::open_repo(None).map_err(StartError::Download)?; + let path = repo.workdir().ok_or(StartError::NoWorkdir)?.to_path_buf(); + + let adj = adj::load_from_dir(&path).map_err(|source| StartError::Load { + path: path.clone(), + source, + })?; + info!( + branch = ADJ_BRANCH, + %commit, + path = %path.display(), + boards = adj.pod_data.boards.len(), + "ADJ loaded" + ); + Ok(adj) +} + +/// Where to listen: the backend's IP and the UDP port, as the ADJ gives them. +fn udp_addr(adj: &Adj) -> Result { + let ip = adj + .info + .addresses + .get("backend") + .ok_or(StartError::MissingInAdj("addresses.backend"))?; + let port = adj + .info + .ports + .get("UDP") + .ok_or(StartError::MissingInAdj("ports.UDP"))?; + Ok(SocketAddr::new(*ip, port.0)) +} + +/// Creates every queue, spawns every task, and shuts everything down in order +/// when `event` stops or on Ctrl+C. +async fn serve( + addr: SocketAddr, + index: Arc, + pod_data: Arc, +) -> Result { + let config = event::EventConfig::default(); + let event::Channels { + udp, + tcp, + event: ends, + orders, + problems, + logging, + pipeline, + } = event::channels(&config); + + // Not built yet: TCP, websocket, and modules that report problems. + // Dropping their ends closes those queues, and event stops watching them. + drop((tcp, orders, problems)); + + let udp_task = spawn_udp( + UdpConfig { + addr, + recv_buffer: RECV_BUFFER, + boards: pod_data.boards_by_ip(), + }, + index.clone(), + udp, + ) + .map_err(StartError::Bind)?; + info!(%addr, "listening on UDP (Ctrl+C to stop)"); + + let logging_task = tokio::spawn(stand_in_logging(logging, pod_data.clone())); + let pipeline_task = tokio::spawn(stand_in_pipeline(pipeline, pod_data.clone())); + let mut event_task = event::spawn(config, ends, pod_data, index, None); + + let (stop, by_ctrl_c) = tokio::select! { + stop = &mut event_task => (stop, false), + signal = tokio::signal::ctrl_c() => { + signal.map_err(StartError::CtrlC)?; + info!("Ctrl+C, stopping"); + // Stopping UDP closes its queues: event passes on what is left + // and stops with `Stop::NetGone`. + udp_task.abort(); + (event_task.await, true) + } + }; + udp_task.abort(); + + // event is done, so logging's and pipeline's queues are closed: they + // finish what they have and end on their own. + let finished = tokio::time::timeout(SHUTDOWN_GRACE, async { + let _ = logging_task.await; + let _ = pipeline_task.await; + }) + .await; + if finished.is_err() { + warn!(grace = ?SHUTDOWN_GRACE, "logging and pipeline did not finish in time"); + } + + match stop.map_err(StartError::Event)? { + Stop::Fatal(problem) => { + info!(reason = %problem.text, "stopped after a fatal error"); + Ok(ExitCode::FAILURE) + } + Stop::NetGone if by_ctrl_c => { + info!("stopped"); + Ok(ExitCode::SUCCESS) + } + Stop::NetGone => { + error!("UDP stopped on its own"); + Ok(ExitCode::FAILURE) + } + } +} + +/// Stands in for `logging`: counts what it would record, per board, and +/// writes a summary every second. +async fn stand_in_logging(mut queue: mpsc::Receiver, pod_data: Arc) { + let mut summary = tokio::time::interval(SUMMARY_EVERY); + summary.set_missed_tick_behavior(MissedTickBehavior::Delay); + let mut counts: HashMap = HashMap::new(); + + loop { + tokio::select! { + // The summary first, or under load it would never get its turn. + biased; + _ = summary.tick() => log_summary(&mut counts, &pod_data), + message = queue.recv() => match message { + None => break, + Some(ToLogging::Received(notification)) => { + count_and_trace(¬ification, &mut counts, &pod_data); + } + Some(ToLogging::OrderSent { at, board, order }) => { + let to = order_target(board, &pod_data); + info!(to, id = ?order.id, at = %clock(at), "order sent"); + } + }, + } + } + log_summary(&mut counts, &pod_data); +} + +/// Stands in for `pipeline`: writes to the log what the front would show. +async fn stand_in_pipeline(mut queue: mpsc::Receiver, pod_data: Arc) { + let mut received: u64 = 0; + while let Some(message) = queue.recv().await { + match message { + // The front would get counts, cycle times and averages; here + // packets are only counted, to check that nothing went missing. + ToPipeline::Received(notification) => { + received += 1; + let board = name(&pod_data, notification.board); + match notification.event { + Event::Connected => info!(board, "front: board connected"), + Event::Disconnected => warn!(board, "front: board disconnected"), + Event::Received(_) => {} + } + } + ToPipeline::Problem(problem) => { + let board = problem.board.map(|board| name(&pod_data, board)); + match problem.kind { + ProblemKind::Fatal => { + error!(board = ?board, text = %problem.text, "front: fatal error"); + } + ProblemKind::Shown => { + warn!(board = ?board, text = %problem.text, "front: problem") + } + // event only traces these: they never reach pipeline. + ProblemKind::Silent => {} + } + } + // The front shows both as a message from the backend. + ToPipeline::OrderSent { at, board, order } => { + let to = order_target(board, &pod_data); + info!(to, id = ?order.id, at = %clock(at), "front: order sent"); + } + ToPipeline::OrderFailed { at, order, reason } => { + warn!(id = ?order.id, %reason, at = %clock(at), "front: order not sent"); + } + } + } + info!(notifications = received, "pipeline stand-in finished"); +} + +/// Who an order went to: its board, or every board for the fault. +fn order_target(board: Option, pod_data: &PodData) -> String { + match board { + Some(board) => name(pod_data, board), + None => "every board".to_string(), + } +} + +/// The board's name as the ADJ declares it, or its id if it does not. +fn name(pod_data: &PodData, board: BoardId) -> String { + pod_data + .board_name(board) + .map_or_else(|| format!("{board:?}"), str::to_owned) +} + +/// `at` as seconds since the Unix epoch, with milliseconds, for the log. +fn clock(at: SystemTime) -> String { + match at.duration_since(SystemTime::UNIX_EPOCH) { + Ok(since) => format!("{}.{:03}", since.as_secs(), since.subsec_millis()), + Err(_) => "before 1970".to_string(), + } +} + +/// Counts the notification for the summary and, with `RUST_LOG=debug`, +/// writes it. +fn count_and_trace( + notification: &Notification, + counts: &mut HashMap, + pod_data: &PodData, +) { + *counts.entry(notification.board).or_insert(0) += 1; + + // `debug!`'s fields are only computed when debug is enabled. + match ¬ification.event { + Event::Received(Packet::Data(packet)) => debug!( + board = %name(pod_data, notification.board), + id = ?packet.id, + values = ?packet.values, + "packet" + ), + other => debug!( + board = %name(pod_data, notification.board), + event = ?other, + "notification" + ), + } +} + +/// Writes how many packets arrived from each board since the last summary. +/// Writes nothing if none did. +fn log_summary(counts: &mut HashMap, pod_data: &PodData) { + let total: u64 = counts.values().sum(); + if total == 0 { + return; + } + let mut per_board: Vec = counts + .iter() + .map(|(&board, count)| format!("{}={count}", name(pod_data, board))) + .collect(); + per_board.sort(); + info!(total, boards = %per_board.join(" "), "packets in the last second"); + counts.clear(); } diff --git a/backend/readme-demo.md b/backend/readme-demo.md index 050e911ac..644b186e6 100644 --- a/backend/readme-demo.md +++ b/backend/readme-demo.md @@ -1,22 +1,39 @@ -# Demo: core → station + tracing +# Demo: UDP → event → logging y pipeline + +`crates/station/src/main.rs` junta, por ahora, las piezas que ya existen: + +1. `core::git::update_adj` descarga el ADJ de la rama `adjv3-software`. +2. `core::adj::load_from_dir` lo carga. +3. Con él se construye el `core::protocol::Index`. +4. `core::net::udp::spawn_udp` abre el puerto UDP del ADJ: + `addresses["backend"]` y `ports["UDP"]` de `general_info.json`. +5. `station::event` (ver [`crates/station/src/event/README.md`](crates/station/src/event/README.md)) + crea todas las colas, aplica las reglas de errores y reparte lo que llega + a dos sustitutos de `logging` y `pipeline`, que todavía no existen: el de + logging cuenta los paquetes por placa y escribe un resumen por segundo; el + de pipeline escribe en el log lo que vería el front (problemas, órdenes que + no salieron). Desde `software/backend`, con Rust 1.98.0 y Cargo instalados (la primera ejecución descarga las dependencias): ```sh -# Ejecutar: muestra el saludo y el ciclo de vida a nivel INFO. -cargo run -p station -cargo run -p station -- "Hyperloop UPV" - -# Mostrar también DEBUG del módulo, manteniendo INFO en station. -RUST_LOG=info,software_core::hello_world=debug cargo run -p station -- "Lucía" +# Ejecutar: una línea INFO por segundo con los paquetes recibidos por placa. +cargo run -p station --release -# Filtrar todos los eventos de esta demo (no emite errores). -RUST_LOG=error cargo run -p station +# Además, cada paquete con sus valores decodificados. +# (RUST_LOG=debug a secas también saca el detalle de gix durante la descarga.) +RUST_LOG=info,station=debug cargo run -p station --release -# Tests unitarios y ejemplo de documentación ejecutable (doctest). +# Tests unitarios y doctests (incluye los de UDP, con socket real en loopback). cargo test --workspace +# Prueba de carga de UDP (25 Mbit/s en paquetes de 76 bytes), ignorada por defecto. +cargo test -p software-core --features net --release manual_udp_load -- --ignored --nocapture + +# Prueba de rendimiento de event (un millón de avisos), ignorada por defecto. +cargo test -p station --release manual_event -- --ignored --nocapture + # Generar documentación HTML de la API. cargo doc --workspace --no-deps @@ -25,17 +42,26 @@ cargo fmt --all -- --check cargo clippy --workspace --all-targets -- -D warnings ``` -Abre `target/doc/software_core/hello_world/index.html` para ver la API. +Cómo se comporta: + +- **Un error fatal lo para** y sale con código 1: un datagrama que no se + puede decodificar o perder el socket. El error lleva el nombre de la placa, + sacado de la IP de quien lo mandó. +- **Un fault que mande una placa** (paquete id 0, que UDP reconoce sin mirar + el ADJ) **no lo para**: se muestra el primero de cada placa. Reenviarlo al + resto necesita TCP, que todavía no está, así que solo queda en la traza. +- **Ctrl+C** lo para limpio y sale con código 0. +- Para probarlo en local hace falta algo que mande paquetes a la dirección + del ADJ (`127.0.0.9:50400` en `adjv3-software`), como un simulador de + placas. -- `crates/core/src/hello_world.rs`: `greet(&str) -> String`, con rustdoc, -- `crates/core/src/lib.rs`: exporta el módulo público. -- `crates/station/src/main.rs`: inicializa el subscriber una sola vez y llama a `greet`. -- `#[tracing::instrument]` crea el span `hello_world`; los eventos incluyen - el destinatario y campos estructurados como `greeting` o `used_default`. - `INFO` muestra el saludo; `DEBUG` permite inspeccionar la elección del destinatario. -- Core solo emite eventos: sin subscriber, devuelve igualmente el saludo. - Los tests comprueban ese resultado sin configurar logging global. +Ojo: el ADJ va a la carpeta por defecto de `core::git` +(`~/.cache/hyperloop-control-station/adj` en Linux), la misma que usa el +backend de Go, y cada ejecución con conexión la sustituye por +`adjv3-software`. -Esta demo termina tras saludar; todavía no arranca servidores ni carga TOML. -Usa los comandos Cargo de arriba: los scripts `pnpm dev` están preparados para -la futura configuración del backend, que esta demo no interpreta. +`crates/core/src/hello_world.rs` sigue en core como ejemplo de cómo se +escribe un módulo (docs, trazas, tests, doctest), pero `station` ya no lo +usa. Esta demo todavía no arranca TCP, websocket ni HTTP, ni carga TOML: los scripts +`pnpm dev` están preparados para la futura configuración del backend, que +esta demo no interpreta. From da342fd08fd2893c9a25cd12e263bfe5c06dfa4b Mon Sep 17 00:00:00 2001 From: GaziH Date: Tue, 1 Dec 2026 19:16:34 +0100 Subject: [PATCH 166/225] Feat(backend, pipeline): move pipeline to station and publish WS payloads" -m "- Move pipeline from software-core into station (crates/station/src/pipeline.rs) - Map ToPipeline variants (connections, protections, board messages, problems, order outcomes) to payload types and publish immediately via BrokerClient - Aggregate Packet::Data telemetry per packet ID over 100 ms windows (cumulative count, mean cycle_time, per-measurement last and window average) and flush on shutdown - Re-export MeasurementUpdate, MessageKind, MessagePayload, and MessageTimestamp from station::payload - Expose event and pipeline from station::lib so station modules share crate-level imports - Add unit tests for immediate event forwarding, 100 ms data windowing, and UTC calendar timestamp conversion --- backend/crates/core/src/pipeline/pipeline.rs | 292 ------ .../{core => station}/src/pipeline/mod.rs | 0 .../crates/station/src/pipeline/pipeline.rs | 888 ++++++++++++++++++ 3 files changed, 888 insertions(+), 292 deletions(-) delete mode 100644 backend/crates/core/src/pipeline/pipeline.rs rename backend/crates/{core => station}/src/pipeline/mod.rs (100%) create mode 100644 backend/crates/station/src/pipeline/pipeline.rs diff --git a/backend/crates/core/src/pipeline/pipeline.rs b/backend/crates/core/src/pipeline/pipeline.rs deleted file mode 100644 index 2c68a6a47..000000000 --- a/backend/crates/core/src/pipeline/pipeline.rs +++ /dev/null @@ -1,292 +0,0 @@ -//! Central routing and fan-out stage between `net` and downstream consumers. -//! -//! # What this module is -//! -//! The single consumer of [`crate::net::Sinks`]. Everything that comes off the -//! wire (UDP telemetry, TCP orders/messages, connection transitions, and -//! transport errors) enters here once and is distributed to whoever needs it: -//! live observers (WebSocket/frontend, protection checks), optional disk -//! recording, and the pod fault supervisor. -//! -//! # Entry point -//! -//! [`spawn`], taking [`Config`], [`crate::net::Sinks`], and an optional -//! recorder channel. Returns a [`Pipeline`] handle exposing live telemetry -//! subscriptions, the single-shot fault receiver, and the task's `JoinHandle`. -//! -//! # Contract -//! -//! - **Never backpressure `net`.** Both `sinks.notifications` and -//! `sinks.errors` are drained continuously in a single `tokio::select!` loop. -//! A slow frontend or stalled disk writer must never block UDP/TCP ingestion: -//! live consumers use a [`tokio::sync::broadcast`] channel (lagging receivers -//! skip old frames), and optional disk recording uses non-blocking `try_send`. -//! - **Single "fault once" guard.** Transport modules (`net::udp`, `net::tcp`) -//! report every error and keep running without acting on it. This module -//! checks [`NetError::is_fatal`] and emits **at most one** fault trigger on -//! [`Pipeline::faults`] so `station` sends the pod to fault once—even if a -//! mismatched ADJ produces thousands of decode errors per second. -//! - **Stay alive after fault.** Faulting is about the **pod**, not this -//! process. After emitting a fault trigger, the loop keeps routing packets -//! and draining errors so operators can inspect telemetry and logs. -//! - **Zero-copy fan-out.** Each [`Notification`] is wrapped in an `Arc` once -//! and shared across all subscribers rather than cloned per consumer. -//! - **Clean shutdown.** Disables closed `select!` branches to avoid busy -//! spinning and exits once both upstream `net` channels have closed. - -use crate::net::{Error as NetError, Notification, Sinks}; -use std::sync::Arc; -use tokio::sync::mpsc::error::TrySendError; -use tokio::sync::{broadcast, mpsc}; -use tokio::task::JoinHandle; -use tracing::{error, warn}; - -/// Sizing parameters for the pipeline's internal channels. -/// -/// Resolved by `station` before spawning; this module reads no config files. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct Config { - /// Capacity of the live [`broadcast`] channel shared by subscribers - /// (WebSocket server, state aggregator, protections). - /// - /// A subscriber falling more than this many notifications behind receives - /// `RecvError::Lagged` and jumps to the latest frame instead of stalling - /// the network receive loops. - pub broadcast_capacity: usize, -} - -impl Default for Config { - fn default() -> Self { - Self { - broadcast_capacity: 1024, - } - } -} - -/// Handle to a running pipeline task. -pub struct Pipeline { - telemetry_tx: broadcast::Sender>, - /// Fires at most once when the first fatal transport error arrives. - /// - /// `station` listens here to command the pod into fault state. - pub faults: mpsc::Receiver, - /// Handle to the background routing task. - pub handle: JoinHandle<()>, -} - -impl Pipeline { - /// Subscribes a new live consumer (e.g. WebSocket broadcaster or state - /// cache) to every [`Notification`] flowing through the pipeline. - pub fn subscribe(&self) -> broadcast::Receiver> { - self.telemetry_tx.subscribe() - } -} - -/// Spawns the pipeline routing task. -/// -/// `recorder` is optional: pass `Some(tx)` when disk recording is enabled, or -/// `None` in lightweight demos/tests. Recording uses `try_send` so a full disk -/// buffer drops frames with a warning rather than stalling `net`. -/// -/// TODO(review): Confirm whether protections (ADJv3 range/limit checks) should -/// run inline in `handle_notification` before fan-out, or as a separate task -/// calling `pipeline.subscribe()`. -pub fn spawn( - config: Config, - sinks: Sinks, - recorder: Option>>, -) -> Pipeline { - let (telemetry_tx, _) = broadcast::channel(config.broadcast_capacity); - // Capacity 1 is enough: the fault-once guard sends at most one fatal error. - let (fault_tx, fault_rx) = mpsc::channel(1); - - let handle = tokio::spawn(run_loop(sinks, telemetry_tx.clone(), fault_tx, recorder)); - - Pipeline { - telemetry_tx, - faults: fault_rx, - handle, - } -} - -/// Main routing loop: drains both `net` channels until upstream closes. -async fn run_loop( - mut sinks: Sinks, - telemetry_tx: broadcast::Sender>, - fault_tx: mpsc::Sender, - mut recorder: Option>>, -) { - let mut faulted = false; - let mut notifications_open = true; - let mut errors_open = true; - - while notifications_open || errors_open { - tokio::select! { - res = sinks.notifications.recv(), if notifications_open => { - match res { - Some(notification) => { - handle_notification(notification, &telemetry_tx, &mut recorder); - } - None => notifications_open = false, - } - } - res = sinks.errors.recv(), if errors_open => { - match res { - Some(err) => { - handle_error(err, &mut faulted, &fault_tx); - } - None => errors_open = false, - } - } - } - } -} - -/// Fans a single notification out to live subscribers and the optional recorder. -fn handle_notification( - notification: Notification, - telemetry_tx: &broadcast::Sender>, - recorder: &mut Option>>, -) { - let shared = Arc::new(notification); - - // TODO(review): If state aggregation / rate throttling for the frontend - // belongs inside `pipeline` rather than downstream, hook it in here. - - // Broadcast returns Err only when there are zero active subscribers, which - // is expected during startup or headless runs. - let _ = telemetry_tx.send(Arc::clone(&shared)); - - if let Some(tx) = recorder.as_ref() { - match tx.try_send(shared) { - Ok(()) => {} - Err(TrySendError::Full(_)) => { - // TODO(review): Consider rate-limiting this warning or tracking - // a dropped-frame counter if high-rate telemetry overflows disk. - warn!("recorder channel full, dropping notification to avoid stalling net"); - } - Err(TrySendError::Closed(_)) => { - warn!("recorder channel closed, disabling recording sink"); - *recorder = None; - } - } - } -} - -/// Evaluates a transport error against the fault-once guard. -fn handle_error(err: NetError, faulted: &mut bool, fault_tx: &mpsc::Sender) { - if !err.is_fatal() { - warn!(%err, "non-fatal network error"); - return; - } - - if *faulted { - // Already triggered a pod fault; keep draining silently so `sinks.errors` - // never fills up and deadlocks the transport tasks. - return; - } - - *faulted = true; - error!(%err, "fatal network error — triggering pod fault"); - - if let Err(send_err) = fault_tx.try_send(err) { - error!(%send_err, "could not deliver fault trigger to supervisor"); - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::model::{AdjId, BoardId, DataOrderPacket, Packet}; - use crate::net::{udp, Event, Reporter}; - use crate::protocol::DecodeError; - use std::net::{IpAddr, SocketAddr}; - - fn sample_notification() -> (BoardId, Event) { - let packet = DataOrderPacket::new(AdjId(551), vec![]); - (BoardId(5), Event::Received(Packet::Data(packet))) - } - - fn fatal_udp_error() -> udp::Error { - udp::Error::Decode { - from: SocketAddr::new(IpAddr::from([192, 168, 1, 3]), 50400), - source: DecodeError::UnknownId(AdjId(9999)), - } - } - - #[tokio::test] - async fn fans_out_notifications_to_multiple_subscribers_and_recorder() { - let (reporter, sinks) = Reporter::channels(16, 16); - let (rec_tx, mut rec_rx) = mpsc::channel(16); - - let pipeline = spawn(Config::default(), sinks, Some(rec_tx)); - let mut sub_a = pipeline.subscribe(); - let mut sub_b = pipeline.subscribe(); - - let (board, event) = sample_notification(); - reporter.notify(board, event).await.unwrap(); - - let a = sub_a.recv().await.unwrap(); - let b = sub_b.recv().await.unwrap(); - let rec = rec_rx.recv().await.unwrap(); - - assert_eq!(a.board, BoardId(5)); - assert_eq!(b.board, BoardId(5)); - assert_eq!(rec.board, BoardId(5)); - - drop(reporter); - pipeline.handle.await.unwrap(); - } - - #[tokio::test] - async fn fatal_errors_trigger_fault_only_once_and_keep_draining() { - let (reporter, sinks) = Reporter::channels(16, 4); - let mut pipeline = spawn(Config::default(), sinks, None); - let mut sub = pipeline.subscribe(); - - // Flood more fatal errors than the error channel capacity (4) to verify - // the pipeline keeps draining without deadlocking. - for _ in 0..20 { - reporter.report(fatal_udp_error()).await.unwrap(); - } - - // Exactly one fault trigger should be emitted. - let first_fault = pipeline.faults.recv().await; - assert!(first_fault.is_some()); - - // Telemetry must still flow after faulting. - let (board, event) = sample_notification(); - reporter.notify(board, event).await.unwrap(); - let received = sub.recv().await.unwrap(); - assert_eq!(received.board, BoardId(5)); - - drop(reporter); - pipeline.handle.await.unwrap(); - - // No second fault trigger was queued. - assert!(pipeline.faults.try_recv().is_err()); - } - - #[tokio::test] - async fn full_recorder_does_not_block_live_subscribers() { - let (reporter, sinks) = Reporter::channels(16, 16); - // Recorder with capacity 1 that nobody reads from. - let (rec_tx, _rec_rx) = mpsc::channel(1); - - let pipeline = spawn(Config::default(), sinks, Some(rec_tx)); - let mut sub = pipeline.subscribe(); - - for _ in 0..5 { - let (board, event) = sample_notification(); - reporter.notify(board, event).await.unwrap(); - } - - for _ in 0..5 { - let msg = sub.recv().await.unwrap(); - assert_eq!(msg.board, BoardId(5)); - } - - drop(reporter); - pipeline.handle.await.unwrap(); - } -} \ No newline at end of file diff --git a/backend/crates/core/src/pipeline/mod.rs b/backend/crates/station/src/pipeline/mod.rs similarity index 100% rename from backend/crates/core/src/pipeline/mod.rs rename to backend/crates/station/src/pipeline/mod.rs diff --git a/backend/crates/station/src/pipeline/pipeline.rs b/backend/crates/station/src/pipeline/pipeline.rs new file mode 100644 index 000000000..8270f442e --- /dev/null +++ b/backend/crates/station/src/pipeline/pipeline.rs @@ -0,0 +1,888 @@ +//! Transforms [`crate::event::ToPipeline`] items into frontend WebSocket payloads +//! and publishes them through [`crate::websocket::broker::BrokerClient`]. +//! +//! # Contract +//! +//! - **Immediate events.** Connections, protections, board messages, backend +//! problems, and order outcomes are converted and published immediately. +//! - **100 ms data aggregation.** `Packet::Data` frames are accumulated per +//! packet ID in memory (cumulative `count`, mean `cycle_time` over the +//! window, and per-measurement `last` + window `average`) and flushed to +//! `podData/update` on a fixed interval. Idle packets are not republished. +//! - **Wait, don't drop.** Reads continuously from `channels.pipeline` and +//! awaits broker capacity instead of dropping decoded events. +//! - **Clean shutdown.** When `event` closes the input channel (`None`), any +//! pending telemetry is flushed to the broker before the task exits. +//! - **No error policy.** `event` already decides what is silent, shown, or +//! fatal; `pipeline` only formats and publishes. +//! +//! # Topics not handled here +//! +//! - Frontend-to-backend topics (`order/send`, `logger/enable`, +//! `logger/variables`, `connection/heartbeat`) are consumed by `websocket`. +//! - `logger/response` is published directly by `logging`. +//! - `order/stateOrders` has no corresponding packet variant in +//! `software_core::model::Packet` yet. + +use std::collections::HashMap; +use std::sync::Arc; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +use crate::event::{Problem, ProblemKind, ToPipeline}; +use crate::payload::{ + Connection, DataPacketUpdate, MeasurementUpdate, MessageKind, MessagePayload, + MessageTimestamp, MessageUpdate, ProtectionUpdate, +}; +use crate::websocket::broker::BrokerClient; +use software_core::model::{ + AdjId, BoardId, DataPacket, MessagePacket, OrderPacket, Packet, PacketType, PodData, + ShortTimestamp, Value, +}; +use software_core::net::{Event, Notification}; +use software_core::protocol::Index; +use tokio::sync::mpsc; +use tokio::task::JoinHandle; +use tokio::time::{Instant, MissedTickBehavior, interval_at}; +use tracing::{error, warn}; + +/// Configuration for the pipeline task. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Config { + /// How often accumulated `Data` telemetry is flushed to the broker. + pub data_flush_interval: Duration, +} + +impl Default for Config { + fn default() -> Self { + Self { + data_flush_interval: Duration::from_millis(100), + } + } +} + +/// Spawns the pipeline task consuming `rx` and publishing to `broker`. +/// +/// The task exits cleanly once `rx` closes and pending telemetry is flushed, +/// or immediately if `broker` has already shut down. +pub fn spawn( + config: Config, + rx: mpsc::Receiver, + broker: BrokerClient, + pod_data: Arc, + index: Arc, +) -> JoinHandle<()> { + tokio::spawn(run_loop(config, rx, broker, pod_data, index)) +} + +async fn run_loop( + config: Config, + mut rx: mpsc::Receiver, + broker: BrokerClient, + pod_data: Arc, + index: Arc, +) { + let period = config.data_flush_interval.max(Duration::from_millis(1)); + let mut tick = interval_at(Instant::now() + period, period); + tick.set_missed_tick_behavior(MissedTickBehavior::Skip); + + let mut accumulator = DataAccumulator::default(); + + loop { + // Poll the 100 ms flush tick first so sustained high-rate UDP traffic + // can never starve telemetry publication. + tokio::select! { + biased; + _ = tick.tick() => { + if !flush_data(&broker, &index, &mut accumulator).await { + return; + } + } + item = rx.recv() => { + match item { + Some(msg) => { + if !handle_item(msg, &broker, &pod_data, &index, &mut accumulator).await { + return; + } + } + None => { + let _ = flush_data(&broker, &index, &mut accumulator).await; + return; + } + } + } + } + } +} + +/// Handles a single [`ToPipeline`] item. Returns `false` if the broker closed. +async fn handle_item( + item: ToPipeline, + broker: &BrokerClient, + pod_data: &PodData, + index: &Index, + accumulator: &mut DataAccumulator, +) -> bool { + match item { + ToPipeline::Received(notification) => { + handle_notification(¬ification, broker, pod_data, index, accumulator).await + } + ToPipeline::Problem(problem) => handle_problem(problem, broker, pod_data).await, + ToPipeline::OrderSent { at, board, order } => { + handle_order_sent(at, board, order, broker, pod_data).await + } + ToPipeline::OrderFailed { at, order, reason } => { + handle_order_failed(at, order, reason, broker, pod_data, index).await + } + } +} + +async fn handle_notification( + notification: &Notification, + broker: &BrokerClient, + pod_data: &PodData, + index: &Index, + accumulator: &mut DataAccumulator, +) -> bool { + match ¬ification.event { + Event::Connected => { + let update = Connection { + name: board_name(pod_data, notification.board), + is_connected: true, + }; + publish_or_log(broker.publish_connection(update).await) + } + Event::Disconnected => { + let update = Connection { + name: board_name(pod_data, notification.board), + is_connected: false, + }; + publish_or_log(broker.publish_connection(update).await) + } + Event::Received(Packet::Data(data)) => { + accumulator.record(data, notification.at, index); + true + } + Event::Received(Packet::Protection(protection)) => { + let update = ProtectionUpdate::from(protection.clone()); + publish_or_log(broker.publish_protection(update).await) + } + Event::Received(Packet::Message(message)) => { + let update = build_board_message(notification.board, notification.at, message, pod_data, index); + publish_or_log(broker.publish_message(update).await) + } + Event::Received(Packet::Order(order)) => { + warn!(id = order.id.0, "ignoring unexpected inbound order packet"); + true + } + } +} + +async fn handle_problem(problem: Problem, broker: &BrokerClient, pod_data: &PodData) -> bool { + let kind = match problem.kind { + ProblemKind::Shown => MessageKind::Warning, + ProblemKind::Fatal => MessageKind::Fault, + ProblemKind::Silent => return true, + }; + + let board = problem + .board + .map_or_else(|| "backend".to_string(), |id| board_name(pod_data, id)); + + let update = MessageUpdate { + kind, + payload: MessagePayload::Text(problem.text), + board, + name: "backend".to_string(), + timestamp: timestamp_from_system_time(problem.at), + }; + + publish_or_log(broker.publish_message(update).await) +} + +async fn handle_order_sent( + at: SystemTime, + board: Option, + order: OrderPacket, + broker: &BrokerClient, + pod_data: &PodData, +) -> bool { + let board_label = board.map_or_else(|| "all".to_string(), |id| board_name(pod_data, id)); + + let update = MessageUpdate { + kind: MessageKind::Info, + payload: MessagePayload::Text(format!("Order {} sent", order.id.0)), + board: board_label, + name: order.id.0.to_string(), + timestamp: timestamp_from_system_time(at), + }; + + publish_or_log(broker.publish_message(update).await) +} + +async fn handle_order_failed( + at: SystemTime, + order: OrderPacket, + reason: String, + broker: &BrokerClient, + pod_data: &PodData, + index: &Index, +) -> bool { + let board_label = if order.id == AdjId(0) { + "all".to_string() + } else if let Some(def) = index.packet(order.id) { + board_name(pod_data, def.board) + } else { + "backend".to_string() + }; + + let update = MessageUpdate { + kind: MessageKind::Warning, + payload: MessagePayload::Text(reason), + board: board_label, + name: order.id.0.to_string(), + timestamp: timestamp_from_system_time(at), + }; + + publish_or_log(broker.publish_message(update).await) +} + +fn build_board_message( + board: BoardId, + at: SystemTime, + message: &MessagePacket, + pod_data: &PodData, + index: &Index, +) -> MessageUpdate { + let kind = match index.packet(message.id) { + Some(def) => match def.packet_type { + PacketType::Message(level) => MessageKind::from(level), + _ => { + warn!(id = message.id.0, "message packet id does not map to PacketType::Message"); + MessageKind::Info + } + }, + None => { + warn!(id = message.id.0, "unknown message packet id in index"); + MessageKind::Info + } + }; + + let name = if message.origin.is_empty() { + message.id.0.to_string() + } else { + message.origin.clone() + }; + + MessageUpdate { + kind, + payload: MessagePayload::Text(message.message.clone()), + board: board_name(pod_data, board), + name, + timestamp: timestamp_from_short(at, message.timestamp), + } +} + +async fn flush_data( + broker: &BrokerClient, + index: &Index, + accumulator: &mut DataAccumulator, +) -> bool { + for update in accumulator.drain_updates(index) { + if !publish_or_log(broker.publish_data(update).await) { + return false; + } + } + true +} + +fn publish_or_log(result: Result<(), crate::websocket::broker::Error>) -> bool { + match result { + Ok(()) => true, + Err(err) => { + error!(%err, "websocket broker closed, stopping pipeline"); + false + } + } +} + +fn board_name(pod_data: &PodData, board: BoardId) -> String { + pod_data + .boards + .get(&board) + .map_or_else(|| format!("board-{}", board.0), |b| b.name.clone()) +} + +// --------------------------------------------------------------------------- +// 100 ms Telemetry Accumulator +// --------------------------------------------------------------------------- + +#[derive(Debug, Default)] +struct DataAccumulator { + packets: HashMap, +} + +#[derive(Debug)] +struct PacketWindow { + /// Total packets received for this ID since startup. + count: u64, + /// Arrival timestamp of the previous packet (persists across flush windows). + last_at: Option, + /// Last computed mean cycle time in nanoseconds. + last_cycle_time_ns: u64, + /// Sum of inter-arrival deltas (ns) within the current window. + cycle_sum_ns: u128, + /// Number of inter-arrival deltas recorded within the current window. + cycle_samples: u64, + /// Positional measurement accumulators matching `PacketType::Data`. + measurements: Vec>, + /// Whether at least one packet arrived since the last flush. + dirty: bool, +} + +#[derive(Debug)] +enum MeasurementAccumulator { + Numeric { last: f64, sum: f64, samples: u64 }, + Boolean(bool), + Enum(String), +} + +impl MeasurementAccumulator { + fn from_value(value: &Value) -> Self { + match value { + Value::Number(v) => Self::Numeric { + last: *v, + sum: *v, + samples: 1, + }, + Value::Bool(b) => Self::Boolean(*b), + Value::Enum(s) => Self::Enum(s.clone()), + } + } + + fn update(&mut self, value: &Value) { + match (self, value) { + ( + Self::Numeric { + last, + sum, + samples, + }, + Value::Number(v), + ) => { + *last = *v; + *sum += *v; + *samples += 1; + } + (Self::Boolean(last), Value::Bool(b)) => { + *last = *b; + } + (Self::Enum(last), Value::Enum(s)) => { + if last != s { + last.clone_from(s); + } + } + (slot, other) => { + *slot = Self::from_value(other); + } + } + } + + fn into_update(self) -> MeasurementUpdate { + match self { + Self::Numeric { + last, + sum, + samples, + } => MeasurementUpdate::Numeric { + last, + average: sum / (samples as f64), + }, + Self::Boolean(b) => MeasurementUpdate::Boolean(b), + Self::Enum(s) => MeasurementUpdate::Enum(s), + } + } +} + +impl DataAccumulator { + fn record(&mut self, packet: &DataPacket, at: SystemTime, index: &Index) { + let Some(def) = index.packet(packet.id) else { + warn!(id = packet.id.0, "unknown data packet id in index"); + return; + }; + let PacketType::Data(defs) = &def.packet_type else { + warn!(id = packet.id.0, "packet id in DataPacket does not map to PacketType::Data"); + return; + }; + + if packet.values.len() != defs.len() { + warn!( + id = packet.id.0, + expected = defs.len(), + actual = packet.values.len(), + "data packet value count mismatch" + ); + } + + let window = self.packets.entry(packet.id).or_insert_with(|| PacketWindow { + count: 0, + last_at: None, + last_cycle_time_ns: 0, + cycle_sum_ns: 0, + cycle_samples: 0, + measurements: (0..defs.len()).map(|_| None).collect(), + dirty: false, + }); + + window.count = window.count.saturating_add(1); + if let Some(prev) = window.last_at + && let Ok(delta) = at.duration_since(prev) + { + window.cycle_sum_ns = window.cycle_sum_ns.saturating_add(delta.as_nanos()); + window.cycle_samples = window.cycle_samples.saturating_add(1); + } + window.last_at = Some(at); + + for (slot, value) in window.measurements.iter_mut().zip(packet.values.iter()) { + match slot { + Some(acc) => acc.update(value), + None => *slot = Some(MeasurementAccumulator::from_value(value)), + } + } + + window.dirty = true; + } + + fn drain_updates(&mut self, index: &Index) -> Vec { + let mut updates = Vec::new(); + + for (&id, window) in &mut self.packets { + if !window.dirty { + continue; + } + window.dirty = false; + + if window.cycle_samples > 0 { + let avg_ns = window.cycle_sum_ns / u128::from(window.cycle_samples); + window.last_cycle_time_ns = u64::try_from(avg_ns).unwrap_or(u64::MAX); + window.cycle_sum_ns = 0; + window.cycle_samples = 0; + } + + let Some(def) = index.packet(id) else { + continue; + }; + let PacketType::Data(defs) = &def.packet_type else { + continue; + }; + + let mut measurement_updates = HashMap::with_capacity(defs.len()); + for (measurement_def, slot) in defs.iter().zip(window.measurements.iter_mut()) { + if let Some(acc) = slot.take() { + measurement_updates.insert(measurement_def.alias.clone(), acc.into_update()); + } + } + + updates.push(DataPacketUpdate { + id, + // Raw wire bytes are not carried by `Notification`; left empty. + hex_value: String::new(), + count: window.count, + cycle_time: window.last_cycle_time_ns, + measurement_updates, + }); + } + + updates + } +} + +// --------------------------------------------------------------------------- +// UTC Calendar Timestamp Conversion (zero external dependencies) +// --------------------------------------------------------------------------- + +/// Converts a [`SystemTime`] into a UTC [`MessageTimestamp`]. +fn timestamp_from_system_time(at: SystemTime) -> MessageTimestamp { + let dur = at.duration_since(UNIX_EPOCH).unwrap_or(Duration::ZERO); + let total_secs = dur.as_secs(); + let days = i64::try_from(total_secs / 86_400).unwrap_or(0); + let secs_of_day = total_secs % 86_400; + + let (year, month, day) = civil_from_days(days); + let hour = u8::try_from(secs_of_day / 3_600).unwrap_or(0); + let minute = u8::try_from((secs_of_day % 3_600) / 60).unwrap_or(0); + let second = u8::try_from(secs_of_day % 60).unwrap_or(0); + let counter = u16::try_from(dur.subsec_millis()).unwrap_or(0); + + MessageTimestamp { + counter, + second, + minute, + hour, + day, + month, + year, + } +} + +/// Combines the reception calendar date from `received_at` with the board's +/// [`ShortTimestamp`] time of day and raw subsecond byte. +fn timestamp_from_short(received_at: SystemTime, short: ShortTimestamp) -> MessageTimestamp { + let date = timestamp_from_system_time(received_at); + MessageTimestamp { + counter: u16::from(short.subsecond), + second: short.second, + minute: short.minute, + hour: short.hour, + day: date.day, + month: date.month, + year: date.year, + } +} + +/// Converts days since 1970-01-01 (UTC) to `(year, month, day)` using +/// Howard Hinnant's civil calendar algorithm. +fn civil_from_days(days_since_epoch: i64) -> (u16, u8, u8) { + let z = days_since_epoch + 719_468; + let era = if z >= 0 { z } else { z - 146_096 } / 146_097; + let doe = u64::try_from(z - era * 146_097).unwrap_or(0); + let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365; + let y = i64::try_from(yoe).unwrap_or(0) + era * 400; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + let mp = (5 * doy + 2) / 153; + let d = doy - (153 * mp + 2) / 5 + 1; + let m = if mp < 10 { mp + 3 } else { mp - 9 }; + let year = y + i64::from(m <= 2); + + ( + u16::try_from(year).unwrap_or(0), + u8::try_from(m).unwrap_or(1), + u8::try_from(d).unwrap_or(1), + ) +} + +#[cfg(test)] +mod tests { + use std::net::IpAddr; + + use software_core::model::{ + Board, MacAddress, Measurement, MeasurementKind, MessageLevel, NumericKind, PacketDef, + ProtectionPacket, + }; + use tokio::time::{advance, timeout}; + + use super::*; + use crate::websocket::broker::Broker; + + fn sample_fixture() -> (Arc, Arc) { + let voltage_a = Measurement { + id: AdjId(3001), + alias: "voltage_battery_a".to_string(), + name: "Voltage Battery A".to_string(), + display_units: "V".to_string(), + kind: MeasurementKind::Numeric { + wire_type: NumericKind::F32, + }, + protections: vec![], + }; + let active = Measurement { + id: AdjId(3002), + alias: "is_active".to_string(), + name: "Is Active".to_string(), + display_units: String::new(), + kind: MeasurementKind::Boolean, + protections: vec![], + }; + let state = Measurement { + id: AdjId(3003), + alias: "state".to_string(), + name: "State".to_string(), + display_units: String::new(), + kind: MeasurementKind::Enum { + options: vec!["Idle".to_string(), "Fault".to_string()], + }, + protections: vec![], + }; + + let data_def = PacketDef { + id: AdjId(551), + board: BoardId(5), + name: "Batteries Voltage".to_string(), + packet_type: PacketType::Data(vec![voltage_a, active, state]), + }; + let order_def = PacketDef { + id: AdjId(1001), + board: BoardId(5), + name: "Start".to_string(), + packet_type: PacketType::Order(vec![]), + }; + let msg_def = PacketDef { + id: AdjId(10), + board: BoardId(0), + name: "warning".to_string(), + packet_type: PacketType::Message(MessageLevel::Warning), + }; + + let pcu = Board { + id: BoardId(5), + name: "PCU".to_string(), + ip: IpAddr::from([192, 168, 0, 5]), + mac: MacAddress([0; 6]), + packets: HashMap::from([ + (data_def.id, data_def), + (order_def.id, order_def), + (msg_def.id, msg_def), + ]), + }; + + let pod_data = Arc::new(PodData { + boards: HashMap::from([(pcu.id, pcu)]), + }); + let index = Arc::new(Index::new(&pod_data, None)); + (pod_data, index) + } + + #[tokio::test] + async fn forwards_connections_protections_messages_problems_and_orders_immediately() + -> Result<(), Box> { + let (pod_data, index) = sample_fixture(); + let (broker, client) = Broker::new(); + let mut conn_sub = client.subscribe_connections(); + let mut msg_sub = client.subscribe_messages()?; + let mut prot_sub = client.subscribe_protections()?; + let broker_task = tokio::spawn(broker.run()); + + let (tx, rx) = mpsc::channel(32); + let pipe_task = spawn(Config::default(), rx, client, pod_data, index); + + // 1. Connection update + tx.send(ToPipeline::Received(Arc::new(Notification { + board: BoardId(5), + at: UNIX_EPOCH + Duration::from_secs(1_700_000_000), + event: Event::Connected, + }))) + .await?; + timeout(Duration::from_secs(1), conn_sub.changed()).await??; + assert!(conn_sub.borrow_and_update()["PCU"].is_connected); + + // 2. Protection event + let protection = ProtectionPacket { + id: AdjId((1 << 13) | 3001), + timestamp: ShortTimestamp { + hour: 12, + minute: 34, + second: 56, + subsecond: 7, + }, + value: Value::Number(48.5), + }; + tx.send(ToPipeline::Received(Arc::new(Notification { + board: BoardId(5), + at: UNIX_EPOCH + Duration::from_secs(1_700_000_001), + event: Event::Received(Packet::Protection(protection.clone())), + }))) + .await?; + let got_prot = timeout(Duration::from_secs(1), prot_sub.recv()).await??; + assert_eq!(got_prot, ProtectionUpdate::from(protection)); + + // 3. Board message + tx.send(ToPipeline::Received(Arc::new(Notification { + board: BoardId(5), + at: UNIX_EPOCH + Duration::from_secs(1_700_000_002), + event: Event::Received(Packet::Message(MessagePacket { + id: AdjId(10), + timestamp: ShortTimestamp { + hour: 1, + minute: 2, + second: 3, + subsecond: 4, + }, + origin: "pcu.c".to_string(), + message: "temp high".to_string(), + })), + }))) + .await?; + let got_msg = timeout(Duration::from_secs(1), msg_sub.recv()).await??; + assert_eq!(got_msg.kind, MessageKind::Warning); + assert_eq!(got_msg.board, "PCU"); + assert_eq!(got_msg.name, "pcu.c"); + assert_eq!(got_msg.payload, MessagePayload::Text("temp high".to_string())); + assert_eq!(got_msg.timestamp.hour, 1); + assert_eq!(got_msg.timestamp.counter, 4); + + // 4. Problem (Fatal -> Fault) + tx.send(ToPipeline::Problem(Problem { + at: UNIX_EPOCH + Duration::from_secs(1_700_000_003), + board: Some(BoardId(5)), + kind: ProblemKind::Fatal, + text: "decode failed".to_string(), + })) + .await?; + let got_problem = timeout(Duration::from_secs(1), msg_sub.recv()).await??; + assert_eq!(got_problem.kind, MessageKind::Fault); + assert_eq!(got_problem.board, "PCU"); + assert_eq!( + got_problem.payload, + MessagePayload::Text("decode failed".to_string()) + ); + + // 5. OrderSent & OrderFailed + tx.send(ToPipeline::OrderSent { + at: UNIX_EPOCH + Duration::from_secs(1_700_000_004), + board: Some(BoardId(5)), + order: OrderPacket::new(AdjId(1001), vec![]), + }) + .await?; + let got_sent = timeout(Duration::from_secs(1), msg_sub.recv()).await??; + assert_eq!(got_sent.kind, MessageKind::Info); + assert_eq!(got_sent.name, "1001"); + assert_eq!(got_sent.board, "PCU"); + + tx.send(ToPipeline::OrderFailed { + at: UNIX_EPOCH + Duration::from_secs(1_700_000_005), + order: OrderPacket::new(AdjId(1001), vec![]), + reason: "board disconnected".to_string(), + }) + .await?; + let got_failed = timeout(Duration::from_secs(1), msg_sub.recv()).await??; + assert_eq!(got_failed.kind, MessageKind::Warning); + assert_eq!(got_failed.name, "1001"); + assert_eq!( + got_failed.payload, + MessagePayload::Text("board disconnected".to_string()) + ); + + drop(tx); + timeout(Duration::from_secs(1), pipe_task).await??; + timeout(Duration::from_secs(1), broker_task).await??; + Ok(()) + } + + #[tokio::test(start_paused = true)] + async fn batches_data_every_100ms_with_window_average_last_and_cycle_time() + -> Result<(), Box> { + let (pod_data, index) = sample_fixture(); + let (broker, client) = Broker::new(); + let mut data_sub = client.subscribe_data(); + let broker_task = tokio::spawn(broker.run()); + + let (tx, rx) = mpsc::channel(32); + let pipe_task = spawn(Config::default(), rx, client, pod_data, index); + tokio::task::yield_now().await; + + let t0 = UNIX_EPOCH + Duration::from_secs(1_700_000_000); + let samples = [ + (t0, 10.0, false, "Idle"), + (t0 + Duration::from_millis(20), 20.0, true, "Idle"), + (t0 + Duration::from_millis(50), 30.0, true, "Fault"), + ]; + + for (at, voltage, active, state) in samples { + tx.send(ToPipeline::Received(Arc::new(Notification { + board: BoardId(5), + at, + event: Event::Received(Packet::Data(DataPacket::new( + AdjId(551), + vec![ + Value::Number(voltage), + Value::Bool(active), + Value::Enum(state.to_string()), + ], + ))), + }))) + .await?; + } + tokio::task::yield_now().await; + + // First 100 ms tick flushes pipeline -> broker; next 100 ms tick flushes broker -> watch. + advance(Duration::from_millis(100)).await; + tokio::task::yield_now().await; + advance(Duration::from_millis(100)).await; + timeout(Duration::from_millis(10), data_sub.changed()).await??; + + let first = data_sub.borrow_and_update()[&551].clone(); + assert_eq!(first.count, 3); + // Deltas were 20 ms and 30 ms -> average 25 ms = 25_000_000 ns. + assert_eq!(first.cycle_time, 25_000_000); + assert_eq!( + first.measurement_updates["voltage_battery_a"], + MeasurementUpdate::Numeric { + last: 30.0, + average: 20.0, + } + ); + assert_eq!( + first.measurement_updates["is_active"], + MeasurementUpdate::Boolean(true) + ); + assert_eq!( + first.measurement_updates["state"], + MeasurementUpdate::Enum("Fault".to_string()) + ); + + // Next window resets the measurement average while preserving cumulative count. + tx.send(ToPipeline::Received(Arc::new(Notification { + board: BoardId(5), + at: t0 + Duration::from_millis(150), + event: Event::Received(Packet::Data(DataPacket::new( + AdjId(551), + vec![ + Value::Number(50.0), + Value::Bool(false), + Value::Enum("Idle".to_string()), + ], + ))), + }))) + .await?; + + // Dropping `tx` flushes remaining data immediately and stops both tasks cleanly. + drop(tx); + timeout(Duration::from_secs(1), pipe_task).await??; + timeout(Duration::from_secs(1), broker_task).await??; + + let second = data_sub.borrow_and_update()[&551].clone(); + assert_eq!(second.count, 4); + assert_eq!(second.cycle_time, 100_000_000); + assert_eq!( + second.measurement_updates["voltage_battery_a"], + MeasurementUpdate::Numeric { + last: 50.0, + average: 50.0, + } + ); + Ok(()) + } + + #[test] + fn utc_calendar_conversion_handles_epoch_and_leap_day() { + let epoch = timestamp_from_system_time(UNIX_EPOCH); + assert_eq!( + epoch, + MessageTimestamp { + counter: 0, + second: 0, + minute: 0, + hour: 0, + day: 1, + month: 1, + year: 1970, + } + ); + + // 2024-02-29 13:45:09.250 UTC = 1_709_214_309 s + 250 ms + let leap = timestamp_from_system_time( + UNIX_EPOCH + Duration::from_secs(1_709_214_309) + Duration::from_millis(250), + ); + assert_eq!( + leap, + MessageTimestamp { + counter: 250, + second: 9, + minute: 45, + hour: 13, + day: 29, + month: 2, + year: 2024, + } + ); + } +} \ No newline at end of file From 4b67a0dcc8bbd9fbc1f12caa938085a8b36f76e8 Mon Sep 17 00:00:00 2001 From: GaziH Date: Tue, 1 Dec 2026 19:28:32 +0100 Subject: [PATCH 167/225] Feat(backend, pipeline): Refactored pipeline to be split up in similiar format as rest of station. Created README --- backend/crates/station/src/lib.rs | 6 +- backend/crates/station/src/main.rs | 2 +- backend/crates/station/src/payload.rs | 4 +- backend/crates/station/src/pipeline.rs | 208 ++++ backend/crates/station/src/pipeline/README.md | 134 +++ .../station/src/pipeline/accumulator.rs | 191 ++++ .../crates/station/src/pipeline/message.rs | 115 +++ backend/crates/station/src/pipeline/mod.rs | 1 - .../crates/station/src/pipeline/pipeline.rs | 888 ------------------ backend/crates/station/src/pipeline/tests.rs | 335 +++++++ .../crates/station/src/pipeline/timestamp.rs | 64 ++ 11 files changed, 1055 insertions(+), 893 deletions(-) create mode 100644 backend/crates/station/src/pipeline.rs create mode 100644 backend/crates/station/src/pipeline/README.md create mode 100644 backend/crates/station/src/pipeline/accumulator.rs create mode 100644 backend/crates/station/src/pipeline/message.rs delete mode 100644 backend/crates/station/src/pipeline/mod.rs delete mode 100644 backend/crates/station/src/pipeline/pipeline.rs create mode 100644 backend/crates/station/src/pipeline/tests.rs create mode 100644 backend/crates/station/src/pipeline/timestamp.rs diff --git a/backend/crates/station/src/lib.rs b/backend/crates/station/src/lib.rs index b7e482da0..3c53fc30c 100644 --- a/backend/crates/station/src/lib.rs +++ b/backend/crates/station/src/lib.rs @@ -1,4 +1,8 @@ pub mod http; mod vehicle; pub mod websocket; -pub mod payload; \ No newline at end of file +pub mod payload; + +pub mod pipeline; + +pub mod event; \ No newline at end of file diff --git a/backend/crates/station/src/main.rs b/backend/crates/station/src/main.rs index 911ea49b4..6da759f7f 100644 --- a/backend/crates/station/src/main.rs +++ b/backend/crates/station/src/main.rs @@ -26,7 +26,7 @@ //! backend uses: whatever was there is replaced by the [`ADJ_BRANCH`] branch. //! Offline, whatever is in that folder is used, whichever branch it is. -mod event; +use station::event; use std::collections::HashMap; use std::net::SocketAddr; diff --git a/backend/crates/station/src/payload.rs b/backend/crates/station/src/payload.rs index a2f6d5069..edcb33277 100644 --- a/backend/crates/station/src/payload.rs +++ b/backend/crates/station/src/payload.rs @@ -12,8 +12,8 @@ mod protection; mod serialize; pub use connection::{Connection, ConnectionUpdate}; -pub use data::{DataPacketUpdate, DataUpdate}; -pub use message::{MessageUpdate}; +pub use data::{DataPacketUpdate, DataUpdate, MeasurementUpdate}; +pub use message::{MessageKind, MessagePayload, MessageTimestamp, MessageUpdate}; pub use order::{OrderField, OrderSend, StateOrdersUpdate}; pub use protection::{ProtectionPayload, ProtectionUpdate}; diff --git a/backend/crates/station/src/pipeline.rs b/backend/crates/station/src/pipeline.rs new file mode 100644 index 000000000..29ff104bc --- /dev/null +++ b/backend/crates/station/src/pipeline.rs @@ -0,0 +1,208 @@ +//! Transforms [`crate::event::ToPipeline`] items into frontend WebSocket payloads +//! and publishes them through [`crate::websocket::broker::BrokerClient`]. +//! +//! # Contract +//! +//! - **Immediate events.** Connections, protections, board messages, backend +//! problems, and order outcomes are converted and published immediately. +//! - **100 ms data aggregation.** `Packet::Data` frames are accumulated per +//! packet ID in memory (cumulative `count`, mean `cycle_time` over the +//! window, and per-measurement `last` + window `average`) and flushed to +//! `podData/update` on a fixed interval. Idle packets are not republished. +//! - **Wait, don't drop.** Reads continuously from `channels.pipeline` and +//! awaits broker capacity instead of dropping decoded events. +//! - **Clean shutdown.** When `event` closes the input channel (`None`), any +//! pending telemetry is flushed to the broker before the task exits. +//! - **No error policy.** `event` already decides what is silent, shown, or +//! fatal; `pipeline` only formats and publishes. +//! +//! # Topics not handled here +//! +//! - Frontend-to-backend topics (`order/send`, `logger/enable`, +//! `logger/variables`, `connection/heartbeat`) are consumed by `websocket`. +//! - `logger/response` is published directly by `logging`. +//! - `order/stateOrders` has no corresponding packet variant in +//! `software_core::model::Packet` yet. + +mod accumulator; +mod message; +mod timestamp; + +#[cfg(test)] +mod tests; + +use std::sync::Arc; +use std::time::Duration; + +use accumulator::DataAccumulator; +use crate::event::ToPipeline; +use crate::payload::{Connection, ProtectionUpdate}; +use crate::websocket::broker::BrokerClient; +use software_core::model::{Packet, PodData}; +use software_core::net::{Event, Notification}; +use software_core::protocol::Index; +use tokio::sync::mpsc; +use tokio::task::JoinHandle; +use tokio::time::{Instant, MissedTickBehavior, interval_at}; +use tracing::{error, warn}; + +/// Configuration for the pipeline task. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Config { + /// How often accumulated `Data` telemetry is flushed to the broker. + pub data_flush_interval: Duration, +} + +impl Default for Config { + fn default() -> Self { + Self { + data_flush_interval: Duration::from_millis(100), + } + } +} + +/// Spawns the pipeline task consuming `rx` and publishing to `broker`. +/// +/// The task exits cleanly once `rx` closes and pending telemetry is flushed, +/// or immediately if `broker` has already shut down. +pub fn spawn( + config: Config, + rx: mpsc::Receiver, + broker: BrokerClient, + pod_data: Arc, + index: Arc, +) -> JoinHandle<()> { + tokio::spawn(run_loop(config, rx, broker, pod_data, index)) +} + +async fn run_loop( + config: Config, + mut rx: mpsc::Receiver, + broker: BrokerClient, + pod_data: Arc, + index: Arc, +) { + let period = config.data_flush_interval.max(Duration::from_millis(1)); + let mut tick = interval_at(Instant::now() + period, period); + tick.set_missed_tick_behavior(MissedTickBehavior::Skip); + + let mut accumulator = DataAccumulator::default(); + + loop { + // Poll the 100 ms flush tick first so sustained high-rate UDP traffic + // can never starve telemetry publication. + tokio::select! { + biased; + _ = tick.tick() => { + if !flush_data(&broker, &index, &mut accumulator).await { + return; + } + } + item = rx.recv() => { + match item { + Some(msg) => { + if !handle_item(msg, &broker, &pod_data, &index, &mut accumulator).await { + return; + } + } + None => { + let _ = flush_data(&broker, &index, &mut accumulator).await; + return; + } + } + } + } + } +} + +/// Handles a single [`ToPipeline`] item. Returns `false` if the broker closed. +async fn handle_item( + item: ToPipeline, + broker: &BrokerClient, + pod_data: &PodData, + index: &Index, + accumulator: &mut DataAccumulator, +) -> bool { + match item { + ToPipeline::Received(notification) => { + handle_notification(¬ification, broker, pod_data, index, accumulator).await + } + ToPipeline::Problem(problem) => match message::from_problem(problem, pod_data) { + Some(update) => publish_or_log(broker.publish_message(update).await), + None => true, + }, + ToPipeline::OrderSent { at, board, order } => { + let update = message::from_order_sent(at, board, order, pod_data); + publish_or_log(broker.publish_message(update).await) + } + ToPipeline::OrderFailed { at, order, reason } => { + let update = message::from_order_failed(at, order, reason, pod_data, index); + publish_or_log(broker.publish_message(update).await) + } + } +} + +async fn handle_notification( + notification: &Notification, + broker: &BrokerClient, + pod_data: &PodData, + index: &Index, + accumulator: &mut DataAccumulator, +) -> bool { + match ¬ification.event { + Event::Connected => { + let update = Connection { + name: message::board_name(pod_data, notification.board), + is_connected: true, + }; + publish_or_log(broker.publish_connection(update).await) + } + Event::Disconnected => { + let update = Connection { + name: message::board_name(pod_data, notification.board), + is_connected: false, + }; + publish_or_log(broker.publish_connection(update).await) + } + Event::Received(Packet::Data(data)) => { + accumulator.record(data, notification.at, index); + true + } + Event::Received(Packet::Protection(protection)) => { + let update = ProtectionUpdate::from(protection.clone()); + publish_or_log(broker.publish_protection(update).await) + } + Event::Received(Packet::Message(msg)) => { + let update = + message::from_board_message(notification.board, notification.at, msg, pod_data, index); + publish_or_log(broker.publish_message(update).await) + } + Event::Received(Packet::Order(order)) => { + warn!(id = order.id.0, "ignoring unexpected inbound order packet"); + true + } + } +} + +async fn flush_data( + broker: &BrokerClient, + index: &Index, + accumulator: &mut DataAccumulator, +) -> bool { + for update in accumulator.drain_updates(index) { + if !publish_or_log(broker.publish_data(update).await) { + return false; + } + } + true +} + +fn publish_or_log(result: Result<(), crate::websocket::broker::Error>) -> bool { + match result { + Ok(()) => true, + Err(err) => { + error!(%err, "websocket broker closed, stopping pipeline"); + false + } + } +} \ No newline at end of file diff --git a/backend/crates/station/src/pipeline/README.md b/backend/crates/station/src/pipeline/README.md new file mode 100644 index 000000000..ee1ee5f57 --- /dev/null +++ b/backend/crates/station/src/pipeline/README.md @@ -0,0 +1,134 @@ +# Pipeline (`station::pipeline`) + +Transforms [`crate::event::ToPipeline`] items into frontend WebSocket payloads +(`station::payload`) and publishes them through [`crate::websocket::broker::BrokerClient`]. + +`event` routes decoded packets and backend outcomes without inspecting their +contents. `pipeline` is the stage that turns those domain events into the exact +shapes the frontend expects: publishing discrete events immediately and +aggregating high-rate UDP telemetry into 100 ms windows. + +## Overview + +```text + event ──(channels.pipeline: ToPipeline)──► pipeline + ├── immediate ──► BrokerClient + │ ├── connection/update + │ ├── protection/update + │ └── message/update + └── 100 ms tick ─► BrokerClient + └── podData/update +``` + +## Files + +```text +pipeline.rs # module root: Config, spawn, select! loop, routing +pipeline/ +├── accumulator.rs # 100 ms telemetry windowing (count, cycle_time, last, average) +├── message.rs # MessageUpdate builders (board messages, problems, order outcomes) +├── timestamp.rs # SystemTime / ShortTimestamp -> UTC MessageTimestamp +├── tests.rs # unit tests against a real Broker +└── README.md +``` + +## Input-to-Topic Mapping + +| `ToPipeline` variant | Condition / inner event | Target topic | `BrokerClient` method | Delivery | +| --- | --- | --- | --- | --- | +| `Received(Notification)` | `Event::Connected` / `Event::Disconnected` | `connection/update` | `publish_connection` | Immediate | +| `Received(Notification)` | `Event::Received(Packet::Data(_))` | `podData/update` | `publish_data` | 100 ms window | +| `Received(Notification)` | `Event::Received(Packet::Protection(_))` | `protection/update` | `publish_protection` | Immediate | +| `Received(Notification)` | `Event::Received(Packet::Message(_))` | `message/update` | `publish_message` | Immediate | +| `Received(Notification)` | `Event::Received(Packet::Order(_))` | — | Ignored (logged as warning) | — | +| `Problem(Problem)` | `ProblemKind::Shown` → `warning` | `message/update` | `publish_message` | Immediate | +| `Problem(Problem)` | `ProblemKind::Fatal` → `fault` | `message/update` | `publish_message` | Immediate | +| `Problem(Problem)` | `ProblemKind::Silent` | — | Ignored | — | +| `OrderSent` | Confirmed TCP write → `info` | `message/update` | `publish_message` | Immediate | +| `OrderFailed` | Failed TCP write → `warning` | `message/update` | `publish_message` | Immediate | + +### Topics not handled by `pipeline` + +- **Frontend-to-backend topics** (`order/send`, `logger/enable`, + `logger/variables`, `connection/heartbeat`) are handled directly by `websocket`. +- **`logger/response`** is published directly by `logging`. +- **`order/stateOrders`** is not produced yet because `software_core::model::Packet` + has no state-orders packet variant. + +## 100 ms Data Aggregation (`accumulator.rs`) + +High-frequency telemetry (`Packet::Data`) is accumulated in place per packet ID +and flushed every `Config::data_flush_interval` (default `100 ms`). + +- **Per-packet statistics:** + - `count`: cumulative number of packets received for that `AdjId` since startup. + - `cycleTime`: mean inter-arrival interval in nanoseconds across packets + received in the current window (`last_at` persists across window boundaries). + - `hexValue`: left empty (`""`), as `Notification` carries decoded `Value`s + rather than raw UDP bytes. +- **Per-measurement updates** (keyed by each measurement's ADJ `alias`): + - Numeric measurements emit `{ "last": f64, "average": f64 }`, where `last` is + the most recent sample and `average` is the arithmetic mean over the window. + - Boolean and enum measurements emit their latest value directly. +- **Idle packets** (no frames received during a window) are skipped on flush; the + WebSocket broker retains their previous snapshot. +- **Starvation protection:** the main `tokio::select!` uses `biased;` with the + flush timer polled first so sustained UDP rates cannot delay telemetry flushes. + +## Messages & Timestamps (`message.rs`, `timestamp.rs`) + +- **Board names** are resolved from `PodData::boards` (falling back to + `"board-"`). Backend-wide problems use `"backend"`, and broadcast fault + orders (`board = None` or `AdjId(0)`) use `"all"`. +- **Order notices** use the numeric order ID as `name` (`order.id.0.to_string()`), + matching the legacy frontend convention. +- **UTC calendar conversion** uses a zero-dependency civil-date calculation from + `SystemTime`: + - Backend-generated messages (`Problem`, `OrderSent`, `OrderFailed`) populate + `timestamp` from `at`, with `counter` set to milliseconds (`0–999`). + - Board messages (`Packet::Message`) combine the reception calendar date from + `Notification::at` with the board's `ShortTimestamp` (`hour`, `minute`, + `second`) and store its raw `subsecond` byte in `counter`. + +## Contract & Shutdown + +- **Wait, don't drop.** `pipeline` reads continuously from `channels.pipeline` + and awaits `BrokerClient` capacity rather than dropping decoded events. +- **No error policy.** Error classification and fault propagation belong solely + to `event`. +- **Clean shutdown.** + - When `event` closes `channels.pipeline` (`recv()` returns `None`), `pipeline` + flushes any dirty telemetry in the accumulator to the broker and exits. + - If `BrokerClient` returns `Error::BrokerClosed`, `pipeline` logs the error + and exits immediately. + +## Usage + +```rust +use station::pipeline::{self, Config}; + +let pipeline_handle = pipeline::spawn( + Config::default(), + channels.pipeline, + broker_client, + pod_data, + index, +); +``` + +## Tests + +Unit tests in `pipeline/tests.rs` wire `pipeline::spawn` to a real `Broker` +instance (no sockets required) and verify: + +- Immediate forwarding of connections, protections, board messages, problems, + and order outcomes (`OrderSent` / `OrderFailed`). +- 100 ms windowing for `Packet::Data` (cumulative `count`, mean `cycleTime`, + window `average`, `last`, and flush-on-shutdown). +- UTC calendar conversion on epoch and leap-day timestamps. + +Run them with: + +```sh +cargo test -p station pipeline +``` \ No newline at end of file diff --git a/backend/crates/station/src/pipeline/accumulator.rs b/backend/crates/station/src/pipeline/accumulator.rs new file mode 100644 index 000000000..e6d2a0a72 --- /dev/null +++ b/backend/crates/station/src/pipeline/accumulator.rs @@ -0,0 +1,191 @@ +use std::collections::HashMap; +use std::time::SystemTime; + +use crate::payload::{DataPacketUpdate, MeasurementUpdate}; +use software_core::model::{AdjId, DataPacket, PacketType, Value}; +use software_core::protocol::Index; +use tracing::warn; + +/// Accumulates `Data` packets per packet ID across each flush window. +#[derive(Debug, Default)] +pub(super) struct DataAccumulator { + packets: HashMap, +} + +#[derive(Debug)] +struct PacketWindow { + /// Total packets received for this ID since startup. + count: u64, + /// Arrival timestamp of the previous packet (persists across flush windows). + last_at: Option, + /// Last computed mean cycle time in nanoseconds. + last_cycle_time_ns: u64, + /// Sum of inter-arrival deltas (ns) within the current window. + cycle_sum_ns: u128, + /// Number of inter-arrival deltas recorded within the current window. + cycle_samples: u64, + /// Positional measurement accumulators matching `PacketType::Data`. + measurements: Vec>, + /// Whether at least one packet arrived since the last flush. + dirty: bool, +} + +#[derive(Debug)] +enum MeasurementAccumulator { + Numeric { last: f64, sum: f64, samples: u64 }, + Boolean(bool), + Enum(String), +} + +impl MeasurementAccumulator { + fn from_value(value: &Value) -> Self { + match value { + Value::Number(v) => Self::Numeric { + last: *v, + sum: *v, + samples: 1, + }, + Value::Bool(b) => Self::Boolean(*b), + Value::Enum(s) => Self::Enum(s.clone()), + } + } + + fn update(&mut self, value: &Value) { + match (self, value) { + ( + Self::Numeric { + last, + sum, + samples, + }, + Value::Number(v), + ) => { + *last = *v; + *sum += *v; + *samples += 1; + } + (Self::Boolean(last), Value::Bool(b)) => { + *last = *b; + } + (Self::Enum(last), Value::Enum(s)) => { + if last != s { + last.clone_from(s); + } + } + (slot, other) => { + *slot = Self::from_value(other); + } + } + } + + fn into_update(self) -> MeasurementUpdate { + match self { + Self::Numeric { + last, + sum, + samples, + } => MeasurementUpdate::Numeric { + last, + average: sum / (samples as f64), + }, + Self::Boolean(b) => MeasurementUpdate::Boolean(b), + Self::Enum(s) => MeasurementUpdate::Enum(s), + } + } +} + +impl DataAccumulator { + pub(super) fn record(&mut self, packet: &DataPacket, at: SystemTime, index: &Index) { + let Some(def) = index.packet(packet.id) else { + warn!(id = packet.id.0, "unknown data packet id in index"); + return; + }; + let PacketType::Data(defs) = &def.packet_type else { + warn!( + id = packet.id.0, + "packet id in DataPacket does not map to PacketType::Data" + ); + return; + }; + + if packet.values.len() != defs.len() { + warn!( + id = packet.id.0, + expected = defs.len(), + actual = packet.values.len(), + "data packet value count mismatch" + ); + } + + let window = self.packets.entry(packet.id).or_insert_with(|| PacketWindow { + count: 0, + last_at: None, + last_cycle_time_ns: 0, + cycle_sum_ns: 0, + cycle_samples: 0, + measurements: (0..defs.len()).map(|_| None).collect(), + dirty: false, + }); + + window.count = window.count.saturating_add(1); + if let Some(prev) = window.last_at + && let Ok(delta) = at.duration_since(prev) + { + window.cycle_sum_ns = window.cycle_sum_ns.saturating_add(delta.as_nanos()); + window.cycle_samples = window.cycle_samples.saturating_add(1); + } + window.last_at = Some(at); + + for (slot, value) in window.measurements.iter_mut().zip(packet.values.iter()) { + match slot { + Some(acc) => acc.update(value), + None => *slot = Some(MeasurementAccumulator::from_value(value)), + } + } + + window.dirty = true; + } + + pub(super) fn drain_updates(&mut self, index: &Index) -> Vec { + let mut updates = Vec::new(); + + for (&id, window) in &mut self.packets { + if !window.dirty { + continue; + } + window.dirty = false; + + if window.cycle_samples > 0 { + let avg_ns = window.cycle_sum_ns / u128::from(window.cycle_samples); + window.last_cycle_time_ns = u64::try_from(avg_ns).unwrap_or(u64::MAX); + window.cycle_sum_ns = 0; + window.cycle_samples = 0; + } + + let Some(def) = index.packet(id) else { + continue; + }; + let PacketType::Data(defs) = &def.packet_type else { + continue; + }; + + let mut measurement_updates = HashMap::with_capacity(defs.len()); + for (measurement_def, slot) in defs.iter().zip(window.measurements.iter_mut()) { + if let Some(acc) = slot.take() { + measurement_updates.insert(measurement_def.alias.clone(), acc.into_update()); + } + } + + updates.push(DataPacketUpdate { + id, + // Raw wire bytes are not carried by `Notification`; left empty. + hex_value: String::new(), + count: window.count, + cycle_time: window.last_cycle_time_ns, + measurement_updates, + }); + } + + updates + } +} \ No newline at end of file diff --git a/backend/crates/station/src/pipeline/message.rs b/backend/crates/station/src/pipeline/message.rs new file mode 100644 index 000000000..a5a408ccd --- /dev/null +++ b/backend/crates/station/src/pipeline/message.rs @@ -0,0 +1,115 @@ +use std::time::SystemTime; + +use super::timestamp; +use crate::event::{Problem, ProblemKind}; +use crate::payload::{MessageKind, MessagePayload, MessageUpdate}; +use software_core::model::{AdjId, BoardId, MessagePacket, OrderPacket, PacketType, PodData}; +use software_core::protocol::Index; +use tracing::warn; + +pub(super) fn board_name(pod_data: &PodData, board: BoardId) -> String { + pod_data + .boards + .get(&board) + .map_or_else(|| format!("board-{}", board.0), |b| b.name.clone()) +} + +pub(super) fn from_board_message( + board: BoardId, + at: SystemTime, + message: &MessagePacket, + pod_data: &PodData, + index: &Index, +) -> MessageUpdate { + let kind = match index.packet(message.id) { + Some(def) => match def.packet_type { + PacketType::Message(level) => MessageKind::from(level), + _ => { + warn!( + id = message.id.0, + "message packet id does not map to PacketType::Message" + ); + MessageKind::Info + } + }, + None => { + warn!(id = message.id.0, "unknown message packet id in index"); + MessageKind::Info + } + }; + + let name = if message.origin.is_empty() { + message.id.0.to_string() + } else { + message.origin.clone() + }; + + MessageUpdate { + kind, + payload: MessagePayload::Text(message.message.clone()), + board: board_name(pod_data, board), + name, + timestamp: timestamp::from_short(at, message.timestamp), + } +} + +pub(super) fn from_problem(problem: Problem, pod_data: &PodData) -> Option { + let kind = match problem.kind { + ProblemKind::Shown => MessageKind::Warning, + ProblemKind::Fatal => MessageKind::Fault, + ProblemKind::Silent => return None, + }; + + let board = problem + .board + .map_or_else(|| "backend".to_string(), |id| board_name(pod_data, id)); + + Some(MessageUpdate { + kind, + payload: MessagePayload::Text(problem.text), + board, + name: "backend".to_string(), + timestamp: timestamp::from_system_time(problem.at), + }) +} + +pub(super) fn from_order_sent( + at: SystemTime, + board: Option, + order: OrderPacket, + pod_data: &PodData, +) -> MessageUpdate { + let board_label = board.map_or_else(|| "all".to_string(), |id| board_name(pod_data, id)); + + MessageUpdate { + kind: MessageKind::Info, + payload: MessagePayload::Text(format!("Order {} sent", order.id.0)), + board: board_label, + name: order.id.0.to_string(), + timestamp: timestamp::from_system_time(at), + } +} + +pub(super) fn from_order_failed( + at: SystemTime, + order: OrderPacket, + reason: String, + pod_data: &PodData, + index: &Index, +) -> MessageUpdate { + let board_label = if order.id == AdjId(0) { + "all".to_string() + } else if let Some(def) = index.packet(order.id) { + board_name(pod_data, def.board) + } else { + "backend".to_string() + }; + + MessageUpdate { + kind: MessageKind::Warning, + payload: MessagePayload::Text(reason), + board: board_label, + name: order.id.0.to_string(), + timestamp: timestamp::from_system_time(at), + } +} \ No newline at end of file diff --git a/backend/crates/station/src/pipeline/mod.rs b/backend/crates/station/src/pipeline/mod.rs deleted file mode 100644 index e979cae3b..000000000 --- a/backend/crates/station/src/pipeline/mod.rs +++ /dev/null @@ -1 +0,0 @@ -pub mod pipeline; \ No newline at end of file diff --git a/backend/crates/station/src/pipeline/pipeline.rs b/backend/crates/station/src/pipeline/pipeline.rs deleted file mode 100644 index 8270f442e..000000000 --- a/backend/crates/station/src/pipeline/pipeline.rs +++ /dev/null @@ -1,888 +0,0 @@ -//! Transforms [`crate::event::ToPipeline`] items into frontend WebSocket payloads -//! and publishes them through [`crate::websocket::broker::BrokerClient`]. -//! -//! # Contract -//! -//! - **Immediate events.** Connections, protections, board messages, backend -//! problems, and order outcomes are converted and published immediately. -//! - **100 ms data aggregation.** `Packet::Data` frames are accumulated per -//! packet ID in memory (cumulative `count`, mean `cycle_time` over the -//! window, and per-measurement `last` + window `average`) and flushed to -//! `podData/update` on a fixed interval. Idle packets are not republished. -//! - **Wait, don't drop.** Reads continuously from `channels.pipeline` and -//! awaits broker capacity instead of dropping decoded events. -//! - **Clean shutdown.** When `event` closes the input channel (`None`), any -//! pending telemetry is flushed to the broker before the task exits. -//! - **No error policy.** `event` already decides what is silent, shown, or -//! fatal; `pipeline` only formats and publishes. -//! -//! # Topics not handled here -//! -//! - Frontend-to-backend topics (`order/send`, `logger/enable`, -//! `logger/variables`, `connection/heartbeat`) are consumed by `websocket`. -//! - `logger/response` is published directly by `logging`. -//! - `order/stateOrders` has no corresponding packet variant in -//! `software_core::model::Packet` yet. - -use std::collections::HashMap; -use std::sync::Arc; -use std::time::{Duration, SystemTime, UNIX_EPOCH}; - -use crate::event::{Problem, ProblemKind, ToPipeline}; -use crate::payload::{ - Connection, DataPacketUpdate, MeasurementUpdate, MessageKind, MessagePayload, - MessageTimestamp, MessageUpdate, ProtectionUpdate, -}; -use crate::websocket::broker::BrokerClient; -use software_core::model::{ - AdjId, BoardId, DataPacket, MessagePacket, OrderPacket, Packet, PacketType, PodData, - ShortTimestamp, Value, -}; -use software_core::net::{Event, Notification}; -use software_core::protocol::Index; -use tokio::sync::mpsc; -use tokio::task::JoinHandle; -use tokio::time::{Instant, MissedTickBehavior, interval_at}; -use tracing::{error, warn}; - -/// Configuration for the pipeline task. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct Config { - /// How often accumulated `Data` telemetry is flushed to the broker. - pub data_flush_interval: Duration, -} - -impl Default for Config { - fn default() -> Self { - Self { - data_flush_interval: Duration::from_millis(100), - } - } -} - -/// Spawns the pipeline task consuming `rx` and publishing to `broker`. -/// -/// The task exits cleanly once `rx` closes and pending telemetry is flushed, -/// or immediately if `broker` has already shut down. -pub fn spawn( - config: Config, - rx: mpsc::Receiver, - broker: BrokerClient, - pod_data: Arc, - index: Arc, -) -> JoinHandle<()> { - tokio::spawn(run_loop(config, rx, broker, pod_data, index)) -} - -async fn run_loop( - config: Config, - mut rx: mpsc::Receiver, - broker: BrokerClient, - pod_data: Arc, - index: Arc, -) { - let period = config.data_flush_interval.max(Duration::from_millis(1)); - let mut tick = interval_at(Instant::now() + period, period); - tick.set_missed_tick_behavior(MissedTickBehavior::Skip); - - let mut accumulator = DataAccumulator::default(); - - loop { - // Poll the 100 ms flush tick first so sustained high-rate UDP traffic - // can never starve telemetry publication. - tokio::select! { - biased; - _ = tick.tick() => { - if !flush_data(&broker, &index, &mut accumulator).await { - return; - } - } - item = rx.recv() => { - match item { - Some(msg) => { - if !handle_item(msg, &broker, &pod_data, &index, &mut accumulator).await { - return; - } - } - None => { - let _ = flush_data(&broker, &index, &mut accumulator).await; - return; - } - } - } - } - } -} - -/// Handles a single [`ToPipeline`] item. Returns `false` if the broker closed. -async fn handle_item( - item: ToPipeline, - broker: &BrokerClient, - pod_data: &PodData, - index: &Index, - accumulator: &mut DataAccumulator, -) -> bool { - match item { - ToPipeline::Received(notification) => { - handle_notification(¬ification, broker, pod_data, index, accumulator).await - } - ToPipeline::Problem(problem) => handle_problem(problem, broker, pod_data).await, - ToPipeline::OrderSent { at, board, order } => { - handle_order_sent(at, board, order, broker, pod_data).await - } - ToPipeline::OrderFailed { at, order, reason } => { - handle_order_failed(at, order, reason, broker, pod_data, index).await - } - } -} - -async fn handle_notification( - notification: &Notification, - broker: &BrokerClient, - pod_data: &PodData, - index: &Index, - accumulator: &mut DataAccumulator, -) -> bool { - match ¬ification.event { - Event::Connected => { - let update = Connection { - name: board_name(pod_data, notification.board), - is_connected: true, - }; - publish_or_log(broker.publish_connection(update).await) - } - Event::Disconnected => { - let update = Connection { - name: board_name(pod_data, notification.board), - is_connected: false, - }; - publish_or_log(broker.publish_connection(update).await) - } - Event::Received(Packet::Data(data)) => { - accumulator.record(data, notification.at, index); - true - } - Event::Received(Packet::Protection(protection)) => { - let update = ProtectionUpdate::from(protection.clone()); - publish_or_log(broker.publish_protection(update).await) - } - Event::Received(Packet::Message(message)) => { - let update = build_board_message(notification.board, notification.at, message, pod_data, index); - publish_or_log(broker.publish_message(update).await) - } - Event::Received(Packet::Order(order)) => { - warn!(id = order.id.0, "ignoring unexpected inbound order packet"); - true - } - } -} - -async fn handle_problem(problem: Problem, broker: &BrokerClient, pod_data: &PodData) -> bool { - let kind = match problem.kind { - ProblemKind::Shown => MessageKind::Warning, - ProblemKind::Fatal => MessageKind::Fault, - ProblemKind::Silent => return true, - }; - - let board = problem - .board - .map_or_else(|| "backend".to_string(), |id| board_name(pod_data, id)); - - let update = MessageUpdate { - kind, - payload: MessagePayload::Text(problem.text), - board, - name: "backend".to_string(), - timestamp: timestamp_from_system_time(problem.at), - }; - - publish_or_log(broker.publish_message(update).await) -} - -async fn handle_order_sent( - at: SystemTime, - board: Option, - order: OrderPacket, - broker: &BrokerClient, - pod_data: &PodData, -) -> bool { - let board_label = board.map_or_else(|| "all".to_string(), |id| board_name(pod_data, id)); - - let update = MessageUpdate { - kind: MessageKind::Info, - payload: MessagePayload::Text(format!("Order {} sent", order.id.0)), - board: board_label, - name: order.id.0.to_string(), - timestamp: timestamp_from_system_time(at), - }; - - publish_or_log(broker.publish_message(update).await) -} - -async fn handle_order_failed( - at: SystemTime, - order: OrderPacket, - reason: String, - broker: &BrokerClient, - pod_data: &PodData, - index: &Index, -) -> bool { - let board_label = if order.id == AdjId(0) { - "all".to_string() - } else if let Some(def) = index.packet(order.id) { - board_name(pod_data, def.board) - } else { - "backend".to_string() - }; - - let update = MessageUpdate { - kind: MessageKind::Warning, - payload: MessagePayload::Text(reason), - board: board_label, - name: order.id.0.to_string(), - timestamp: timestamp_from_system_time(at), - }; - - publish_or_log(broker.publish_message(update).await) -} - -fn build_board_message( - board: BoardId, - at: SystemTime, - message: &MessagePacket, - pod_data: &PodData, - index: &Index, -) -> MessageUpdate { - let kind = match index.packet(message.id) { - Some(def) => match def.packet_type { - PacketType::Message(level) => MessageKind::from(level), - _ => { - warn!(id = message.id.0, "message packet id does not map to PacketType::Message"); - MessageKind::Info - } - }, - None => { - warn!(id = message.id.0, "unknown message packet id in index"); - MessageKind::Info - } - }; - - let name = if message.origin.is_empty() { - message.id.0.to_string() - } else { - message.origin.clone() - }; - - MessageUpdate { - kind, - payload: MessagePayload::Text(message.message.clone()), - board: board_name(pod_data, board), - name, - timestamp: timestamp_from_short(at, message.timestamp), - } -} - -async fn flush_data( - broker: &BrokerClient, - index: &Index, - accumulator: &mut DataAccumulator, -) -> bool { - for update in accumulator.drain_updates(index) { - if !publish_or_log(broker.publish_data(update).await) { - return false; - } - } - true -} - -fn publish_or_log(result: Result<(), crate::websocket::broker::Error>) -> bool { - match result { - Ok(()) => true, - Err(err) => { - error!(%err, "websocket broker closed, stopping pipeline"); - false - } - } -} - -fn board_name(pod_data: &PodData, board: BoardId) -> String { - pod_data - .boards - .get(&board) - .map_or_else(|| format!("board-{}", board.0), |b| b.name.clone()) -} - -// --------------------------------------------------------------------------- -// 100 ms Telemetry Accumulator -// --------------------------------------------------------------------------- - -#[derive(Debug, Default)] -struct DataAccumulator { - packets: HashMap, -} - -#[derive(Debug)] -struct PacketWindow { - /// Total packets received for this ID since startup. - count: u64, - /// Arrival timestamp of the previous packet (persists across flush windows). - last_at: Option, - /// Last computed mean cycle time in nanoseconds. - last_cycle_time_ns: u64, - /// Sum of inter-arrival deltas (ns) within the current window. - cycle_sum_ns: u128, - /// Number of inter-arrival deltas recorded within the current window. - cycle_samples: u64, - /// Positional measurement accumulators matching `PacketType::Data`. - measurements: Vec>, - /// Whether at least one packet arrived since the last flush. - dirty: bool, -} - -#[derive(Debug)] -enum MeasurementAccumulator { - Numeric { last: f64, sum: f64, samples: u64 }, - Boolean(bool), - Enum(String), -} - -impl MeasurementAccumulator { - fn from_value(value: &Value) -> Self { - match value { - Value::Number(v) => Self::Numeric { - last: *v, - sum: *v, - samples: 1, - }, - Value::Bool(b) => Self::Boolean(*b), - Value::Enum(s) => Self::Enum(s.clone()), - } - } - - fn update(&mut self, value: &Value) { - match (self, value) { - ( - Self::Numeric { - last, - sum, - samples, - }, - Value::Number(v), - ) => { - *last = *v; - *sum += *v; - *samples += 1; - } - (Self::Boolean(last), Value::Bool(b)) => { - *last = *b; - } - (Self::Enum(last), Value::Enum(s)) => { - if last != s { - last.clone_from(s); - } - } - (slot, other) => { - *slot = Self::from_value(other); - } - } - } - - fn into_update(self) -> MeasurementUpdate { - match self { - Self::Numeric { - last, - sum, - samples, - } => MeasurementUpdate::Numeric { - last, - average: sum / (samples as f64), - }, - Self::Boolean(b) => MeasurementUpdate::Boolean(b), - Self::Enum(s) => MeasurementUpdate::Enum(s), - } - } -} - -impl DataAccumulator { - fn record(&mut self, packet: &DataPacket, at: SystemTime, index: &Index) { - let Some(def) = index.packet(packet.id) else { - warn!(id = packet.id.0, "unknown data packet id in index"); - return; - }; - let PacketType::Data(defs) = &def.packet_type else { - warn!(id = packet.id.0, "packet id in DataPacket does not map to PacketType::Data"); - return; - }; - - if packet.values.len() != defs.len() { - warn!( - id = packet.id.0, - expected = defs.len(), - actual = packet.values.len(), - "data packet value count mismatch" - ); - } - - let window = self.packets.entry(packet.id).or_insert_with(|| PacketWindow { - count: 0, - last_at: None, - last_cycle_time_ns: 0, - cycle_sum_ns: 0, - cycle_samples: 0, - measurements: (0..defs.len()).map(|_| None).collect(), - dirty: false, - }); - - window.count = window.count.saturating_add(1); - if let Some(prev) = window.last_at - && let Ok(delta) = at.duration_since(prev) - { - window.cycle_sum_ns = window.cycle_sum_ns.saturating_add(delta.as_nanos()); - window.cycle_samples = window.cycle_samples.saturating_add(1); - } - window.last_at = Some(at); - - for (slot, value) in window.measurements.iter_mut().zip(packet.values.iter()) { - match slot { - Some(acc) => acc.update(value), - None => *slot = Some(MeasurementAccumulator::from_value(value)), - } - } - - window.dirty = true; - } - - fn drain_updates(&mut self, index: &Index) -> Vec { - let mut updates = Vec::new(); - - for (&id, window) in &mut self.packets { - if !window.dirty { - continue; - } - window.dirty = false; - - if window.cycle_samples > 0 { - let avg_ns = window.cycle_sum_ns / u128::from(window.cycle_samples); - window.last_cycle_time_ns = u64::try_from(avg_ns).unwrap_or(u64::MAX); - window.cycle_sum_ns = 0; - window.cycle_samples = 0; - } - - let Some(def) = index.packet(id) else { - continue; - }; - let PacketType::Data(defs) = &def.packet_type else { - continue; - }; - - let mut measurement_updates = HashMap::with_capacity(defs.len()); - for (measurement_def, slot) in defs.iter().zip(window.measurements.iter_mut()) { - if let Some(acc) = slot.take() { - measurement_updates.insert(measurement_def.alias.clone(), acc.into_update()); - } - } - - updates.push(DataPacketUpdate { - id, - // Raw wire bytes are not carried by `Notification`; left empty. - hex_value: String::new(), - count: window.count, - cycle_time: window.last_cycle_time_ns, - measurement_updates, - }); - } - - updates - } -} - -// --------------------------------------------------------------------------- -// UTC Calendar Timestamp Conversion (zero external dependencies) -// --------------------------------------------------------------------------- - -/// Converts a [`SystemTime`] into a UTC [`MessageTimestamp`]. -fn timestamp_from_system_time(at: SystemTime) -> MessageTimestamp { - let dur = at.duration_since(UNIX_EPOCH).unwrap_or(Duration::ZERO); - let total_secs = dur.as_secs(); - let days = i64::try_from(total_secs / 86_400).unwrap_or(0); - let secs_of_day = total_secs % 86_400; - - let (year, month, day) = civil_from_days(days); - let hour = u8::try_from(secs_of_day / 3_600).unwrap_or(0); - let minute = u8::try_from((secs_of_day % 3_600) / 60).unwrap_or(0); - let second = u8::try_from(secs_of_day % 60).unwrap_or(0); - let counter = u16::try_from(dur.subsec_millis()).unwrap_or(0); - - MessageTimestamp { - counter, - second, - minute, - hour, - day, - month, - year, - } -} - -/// Combines the reception calendar date from `received_at` with the board's -/// [`ShortTimestamp`] time of day and raw subsecond byte. -fn timestamp_from_short(received_at: SystemTime, short: ShortTimestamp) -> MessageTimestamp { - let date = timestamp_from_system_time(received_at); - MessageTimestamp { - counter: u16::from(short.subsecond), - second: short.second, - minute: short.minute, - hour: short.hour, - day: date.day, - month: date.month, - year: date.year, - } -} - -/// Converts days since 1970-01-01 (UTC) to `(year, month, day)` using -/// Howard Hinnant's civil calendar algorithm. -fn civil_from_days(days_since_epoch: i64) -> (u16, u8, u8) { - let z = days_since_epoch + 719_468; - let era = if z >= 0 { z } else { z - 146_096 } / 146_097; - let doe = u64::try_from(z - era * 146_097).unwrap_or(0); - let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365; - let y = i64::try_from(yoe).unwrap_or(0) + era * 400; - let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); - let mp = (5 * doy + 2) / 153; - let d = doy - (153 * mp + 2) / 5 + 1; - let m = if mp < 10 { mp + 3 } else { mp - 9 }; - let year = y + i64::from(m <= 2); - - ( - u16::try_from(year).unwrap_or(0), - u8::try_from(m).unwrap_or(1), - u8::try_from(d).unwrap_or(1), - ) -} - -#[cfg(test)] -mod tests { - use std::net::IpAddr; - - use software_core::model::{ - Board, MacAddress, Measurement, MeasurementKind, MessageLevel, NumericKind, PacketDef, - ProtectionPacket, - }; - use tokio::time::{advance, timeout}; - - use super::*; - use crate::websocket::broker::Broker; - - fn sample_fixture() -> (Arc, Arc) { - let voltage_a = Measurement { - id: AdjId(3001), - alias: "voltage_battery_a".to_string(), - name: "Voltage Battery A".to_string(), - display_units: "V".to_string(), - kind: MeasurementKind::Numeric { - wire_type: NumericKind::F32, - }, - protections: vec![], - }; - let active = Measurement { - id: AdjId(3002), - alias: "is_active".to_string(), - name: "Is Active".to_string(), - display_units: String::new(), - kind: MeasurementKind::Boolean, - protections: vec![], - }; - let state = Measurement { - id: AdjId(3003), - alias: "state".to_string(), - name: "State".to_string(), - display_units: String::new(), - kind: MeasurementKind::Enum { - options: vec!["Idle".to_string(), "Fault".to_string()], - }, - protections: vec![], - }; - - let data_def = PacketDef { - id: AdjId(551), - board: BoardId(5), - name: "Batteries Voltage".to_string(), - packet_type: PacketType::Data(vec![voltage_a, active, state]), - }; - let order_def = PacketDef { - id: AdjId(1001), - board: BoardId(5), - name: "Start".to_string(), - packet_type: PacketType::Order(vec![]), - }; - let msg_def = PacketDef { - id: AdjId(10), - board: BoardId(0), - name: "warning".to_string(), - packet_type: PacketType::Message(MessageLevel::Warning), - }; - - let pcu = Board { - id: BoardId(5), - name: "PCU".to_string(), - ip: IpAddr::from([192, 168, 0, 5]), - mac: MacAddress([0; 6]), - packets: HashMap::from([ - (data_def.id, data_def), - (order_def.id, order_def), - (msg_def.id, msg_def), - ]), - }; - - let pod_data = Arc::new(PodData { - boards: HashMap::from([(pcu.id, pcu)]), - }); - let index = Arc::new(Index::new(&pod_data, None)); - (pod_data, index) - } - - #[tokio::test] - async fn forwards_connections_protections_messages_problems_and_orders_immediately() - -> Result<(), Box> { - let (pod_data, index) = sample_fixture(); - let (broker, client) = Broker::new(); - let mut conn_sub = client.subscribe_connections(); - let mut msg_sub = client.subscribe_messages()?; - let mut prot_sub = client.subscribe_protections()?; - let broker_task = tokio::spawn(broker.run()); - - let (tx, rx) = mpsc::channel(32); - let pipe_task = spawn(Config::default(), rx, client, pod_data, index); - - // 1. Connection update - tx.send(ToPipeline::Received(Arc::new(Notification { - board: BoardId(5), - at: UNIX_EPOCH + Duration::from_secs(1_700_000_000), - event: Event::Connected, - }))) - .await?; - timeout(Duration::from_secs(1), conn_sub.changed()).await??; - assert!(conn_sub.borrow_and_update()["PCU"].is_connected); - - // 2. Protection event - let protection = ProtectionPacket { - id: AdjId((1 << 13) | 3001), - timestamp: ShortTimestamp { - hour: 12, - minute: 34, - second: 56, - subsecond: 7, - }, - value: Value::Number(48.5), - }; - tx.send(ToPipeline::Received(Arc::new(Notification { - board: BoardId(5), - at: UNIX_EPOCH + Duration::from_secs(1_700_000_001), - event: Event::Received(Packet::Protection(protection.clone())), - }))) - .await?; - let got_prot = timeout(Duration::from_secs(1), prot_sub.recv()).await??; - assert_eq!(got_prot, ProtectionUpdate::from(protection)); - - // 3. Board message - tx.send(ToPipeline::Received(Arc::new(Notification { - board: BoardId(5), - at: UNIX_EPOCH + Duration::from_secs(1_700_000_002), - event: Event::Received(Packet::Message(MessagePacket { - id: AdjId(10), - timestamp: ShortTimestamp { - hour: 1, - minute: 2, - second: 3, - subsecond: 4, - }, - origin: "pcu.c".to_string(), - message: "temp high".to_string(), - })), - }))) - .await?; - let got_msg = timeout(Duration::from_secs(1), msg_sub.recv()).await??; - assert_eq!(got_msg.kind, MessageKind::Warning); - assert_eq!(got_msg.board, "PCU"); - assert_eq!(got_msg.name, "pcu.c"); - assert_eq!(got_msg.payload, MessagePayload::Text("temp high".to_string())); - assert_eq!(got_msg.timestamp.hour, 1); - assert_eq!(got_msg.timestamp.counter, 4); - - // 4. Problem (Fatal -> Fault) - tx.send(ToPipeline::Problem(Problem { - at: UNIX_EPOCH + Duration::from_secs(1_700_000_003), - board: Some(BoardId(5)), - kind: ProblemKind::Fatal, - text: "decode failed".to_string(), - })) - .await?; - let got_problem = timeout(Duration::from_secs(1), msg_sub.recv()).await??; - assert_eq!(got_problem.kind, MessageKind::Fault); - assert_eq!(got_problem.board, "PCU"); - assert_eq!( - got_problem.payload, - MessagePayload::Text("decode failed".to_string()) - ); - - // 5. OrderSent & OrderFailed - tx.send(ToPipeline::OrderSent { - at: UNIX_EPOCH + Duration::from_secs(1_700_000_004), - board: Some(BoardId(5)), - order: OrderPacket::new(AdjId(1001), vec![]), - }) - .await?; - let got_sent = timeout(Duration::from_secs(1), msg_sub.recv()).await??; - assert_eq!(got_sent.kind, MessageKind::Info); - assert_eq!(got_sent.name, "1001"); - assert_eq!(got_sent.board, "PCU"); - - tx.send(ToPipeline::OrderFailed { - at: UNIX_EPOCH + Duration::from_secs(1_700_000_005), - order: OrderPacket::new(AdjId(1001), vec![]), - reason: "board disconnected".to_string(), - }) - .await?; - let got_failed = timeout(Duration::from_secs(1), msg_sub.recv()).await??; - assert_eq!(got_failed.kind, MessageKind::Warning); - assert_eq!(got_failed.name, "1001"); - assert_eq!( - got_failed.payload, - MessagePayload::Text("board disconnected".to_string()) - ); - - drop(tx); - timeout(Duration::from_secs(1), pipe_task).await??; - timeout(Duration::from_secs(1), broker_task).await??; - Ok(()) - } - - #[tokio::test(start_paused = true)] - async fn batches_data_every_100ms_with_window_average_last_and_cycle_time() - -> Result<(), Box> { - let (pod_data, index) = sample_fixture(); - let (broker, client) = Broker::new(); - let mut data_sub = client.subscribe_data(); - let broker_task = tokio::spawn(broker.run()); - - let (tx, rx) = mpsc::channel(32); - let pipe_task = spawn(Config::default(), rx, client, pod_data, index); - tokio::task::yield_now().await; - - let t0 = UNIX_EPOCH + Duration::from_secs(1_700_000_000); - let samples = [ - (t0, 10.0, false, "Idle"), - (t0 + Duration::from_millis(20), 20.0, true, "Idle"), - (t0 + Duration::from_millis(50), 30.0, true, "Fault"), - ]; - - for (at, voltage, active, state) in samples { - tx.send(ToPipeline::Received(Arc::new(Notification { - board: BoardId(5), - at, - event: Event::Received(Packet::Data(DataPacket::new( - AdjId(551), - vec![ - Value::Number(voltage), - Value::Bool(active), - Value::Enum(state.to_string()), - ], - ))), - }))) - .await?; - } - tokio::task::yield_now().await; - - // First 100 ms tick flushes pipeline -> broker; next 100 ms tick flushes broker -> watch. - advance(Duration::from_millis(100)).await; - tokio::task::yield_now().await; - advance(Duration::from_millis(100)).await; - timeout(Duration::from_millis(10), data_sub.changed()).await??; - - let first = data_sub.borrow_and_update()[&551].clone(); - assert_eq!(first.count, 3); - // Deltas were 20 ms and 30 ms -> average 25 ms = 25_000_000 ns. - assert_eq!(first.cycle_time, 25_000_000); - assert_eq!( - first.measurement_updates["voltage_battery_a"], - MeasurementUpdate::Numeric { - last: 30.0, - average: 20.0, - } - ); - assert_eq!( - first.measurement_updates["is_active"], - MeasurementUpdate::Boolean(true) - ); - assert_eq!( - first.measurement_updates["state"], - MeasurementUpdate::Enum("Fault".to_string()) - ); - - // Next window resets the measurement average while preserving cumulative count. - tx.send(ToPipeline::Received(Arc::new(Notification { - board: BoardId(5), - at: t0 + Duration::from_millis(150), - event: Event::Received(Packet::Data(DataPacket::new( - AdjId(551), - vec![ - Value::Number(50.0), - Value::Bool(false), - Value::Enum("Idle".to_string()), - ], - ))), - }))) - .await?; - - // Dropping `tx` flushes remaining data immediately and stops both tasks cleanly. - drop(tx); - timeout(Duration::from_secs(1), pipe_task).await??; - timeout(Duration::from_secs(1), broker_task).await??; - - let second = data_sub.borrow_and_update()[&551].clone(); - assert_eq!(second.count, 4); - assert_eq!(second.cycle_time, 100_000_000); - assert_eq!( - second.measurement_updates["voltage_battery_a"], - MeasurementUpdate::Numeric { - last: 50.0, - average: 50.0, - } - ); - Ok(()) - } - - #[test] - fn utc_calendar_conversion_handles_epoch_and_leap_day() { - let epoch = timestamp_from_system_time(UNIX_EPOCH); - assert_eq!( - epoch, - MessageTimestamp { - counter: 0, - second: 0, - minute: 0, - hour: 0, - day: 1, - month: 1, - year: 1970, - } - ); - - // 2024-02-29 13:45:09.250 UTC = 1_709_214_309 s + 250 ms - let leap = timestamp_from_system_time( - UNIX_EPOCH + Duration::from_secs(1_709_214_309) + Duration::from_millis(250), - ); - assert_eq!( - leap, - MessageTimestamp { - counter: 250, - second: 9, - minute: 45, - hour: 13, - day: 29, - month: 2, - year: 2024, - } - ); - } -} \ No newline at end of file diff --git a/backend/crates/station/src/pipeline/tests.rs b/backend/crates/station/src/pipeline/tests.rs new file mode 100644 index 000000000..30c3f074e --- /dev/null +++ b/backend/crates/station/src/pipeline/tests.rs @@ -0,0 +1,335 @@ +use std::collections::HashMap; +use std::net::IpAddr; +use std::sync::Arc; +use std::time::{Duration, UNIX_EPOCH}; + +use software_core::model::{ + AdjId, Board, BoardId, DataPacket, MacAddress, Measurement, MeasurementKind, MessageLevel, + MessagePacket, NumericKind, OrderPacket, Packet, PacketDef, PacketType, PodData, + ProtectionPacket, ShortTimestamp, Value, +}; +use software_core::net::{Event, Notification}; +use software_core::protocol::Index; +use tokio::sync::mpsc; +use tokio::time::{advance, timeout}; + +use super::{Config, spawn, timestamp}; +use crate::event::{Problem, ProblemKind, ToPipeline}; +use crate::payload::{ + MeasurementUpdate, MessageKind, MessagePayload, MessageTimestamp, ProtectionUpdate, +}; +use crate::websocket::broker::Broker; + +fn sample_fixture() -> (Arc, Arc) { + let voltage_a = Measurement { + id: AdjId(3001), + alias: "voltage_battery_a".to_string(), + name: "Voltage Battery A".to_string(), + display_units: "V".to_string(), + kind: MeasurementKind::Numeric { + wire_type: NumericKind::F32, + }, + protections: vec![], + }; + let active = Measurement { + id: AdjId(3002), + alias: "is_active".to_string(), + name: "Is Active".to_string(), + display_units: String::new(), + kind: MeasurementKind::Boolean, + protections: vec![], + }; + let state = Measurement { + id: AdjId(3003), + alias: "state".to_string(), + name: "State".to_string(), + display_units: String::new(), + kind: MeasurementKind::Enum { + options: vec!["Idle".to_string(), "Fault".to_string()], + }, + protections: vec![], + }; + + let data_def = PacketDef { + id: AdjId(551), + board: BoardId(5), + name: "Batteries Voltage".to_string(), + packet_type: PacketType::Data(vec![voltage_a, active, state]), + }; + let order_def = PacketDef { + id: AdjId(1001), + board: BoardId(5), + name: "Start".to_string(), + packet_type: PacketType::Order(vec![]), + }; + let msg_def = PacketDef { + id: AdjId(10), + board: BoardId(0), + name: "warning".to_string(), + packet_type: PacketType::Message(MessageLevel::Warning), + }; + + let pcu = Board { + id: BoardId(5), + name: "PCU".to_string(), + ip: IpAddr::from([192, 168, 0, 5]), + mac: MacAddress([0; 6]), + packets: HashMap::from([ + (data_def.id, data_def), + (order_def.id, order_def), + (msg_def.id, msg_def), + ]), + }; + + let pod_data = Arc::new(PodData { + boards: HashMap::from([(pcu.id, pcu)]), + }); + let index = Arc::new(Index::new(&pod_data, None)); + (pod_data, index) +} + +#[tokio::test] +async fn forwards_connections_protections_messages_problems_and_orders_immediately() + -> Result<(), Box> { + let (pod_data, index) = sample_fixture(); + let (broker, client) = Broker::new(); + let mut conn_sub = client.subscribe_connections(); + let mut msg_sub = client.subscribe_messages()?; + let mut prot_sub = client.subscribe_protections()?; + let broker_task = tokio::spawn(broker.run()); + + let (tx, rx) = mpsc::channel(32); + let pipe_task = spawn(Config::default(), rx, client, pod_data, index); + + // 1. Connection update + tx.send(ToPipeline::Received(Arc::new(Notification { + board: BoardId(5), + at: UNIX_EPOCH + Duration::from_secs(1_700_000_000), + event: Event::Connected, + }))) + .await?; + timeout(Duration::from_secs(1), conn_sub.changed()).await??; + assert!(conn_sub.borrow_and_update()["PCU"].is_connected); + + // 2. Protection event + let protection = ProtectionPacket { + id: AdjId((1 << 13) | 3001), + timestamp: ShortTimestamp { + hour: 12, + minute: 34, + second: 56, + subsecond: 7, + }, + value: Value::Number(48.5), + }; + tx.send(ToPipeline::Received(Arc::new(Notification { + board: BoardId(5), + at: UNIX_EPOCH + Duration::from_secs(1_700_000_001), + event: Event::Received(Packet::Protection(protection.clone())), + }))) + .await?; + let got_prot = timeout(Duration::from_secs(1), prot_sub.recv()).await??; + assert_eq!(got_prot, ProtectionUpdate::from(protection)); + + // 3. Board message + tx.send(ToPipeline::Received(Arc::new(Notification { + board: BoardId(5), + at: UNIX_EPOCH + Duration::from_secs(1_700_000_002), + event: Event::Received(Packet::Message(MessagePacket { + id: AdjId(10), + timestamp: ShortTimestamp { + hour: 1, + minute: 2, + second: 3, + subsecond: 4, + }, + origin: "pcu.c".to_string(), + message: "temp high".to_string(), + })), + }))) + .await?; + let got_msg = timeout(Duration::from_secs(1), msg_sub.recv()).await??; + assert_eq!(got_msg.kind, MessageKind::Warning); + assert_eq!(got_msg.board, "PCU"); + assert_eq!(got_msg.name, "pcu.c"); + assert_eq!(got_msg.payload, MessagePayload::Text("temp high".to_string())); + assert_eq!(got_msg.timestamp.hour, 1); + assert_eq!(got_msg.timestamp.counter, 4); + + // 4. Problem (Fatal -> Fault) + tx.send(ToPipeline::Problem(Problem { + at: UNIX_EPOCH + Duration::from_secs(1_700_000_003), + board: Some(BoardId(5)), + kind: ProblemKind::Fatal, + text: "decode failed".to_string(), + })) + .await?; + let got_problem = timeout(Duration::from_secs(1), msg_sub.recv()).await??; + assert_eq!(got_problem.kind, MessageKind::Fault); + assert_eq!(got_problem.board, "PCU"); + assert_eq!( + got_problem.payload, + MessagePayload::Text("decode failed".to_string()) + ); + + // 5. OrderSent & OrderFailed + tx.send(ToPipeline::OrderSent { + at: UNIX_EPOCH + Duration::from_secs(1_700_000_004), + board: Some(BoardId(5)), + order: OrderPacket::new(AdjId(1001), vec![]), + }) + .await?; + let got_sent = timeout(Duration::from_secs(1), msg_sub.recv()).await??; + assert_eq!(got_sent.kind, MessageKind::Info); + assert_eq!(got_sent.name, "1001"); + assert_eq!(got_sent.board, "PCU"); + + tx.send(ToPipeline::OrderFailed { + at: UNIX_EPOCH + Duration::from_secs(1_700_000_005), + order: OrderPacket::new(AdjId(1001), vec![]), + reason: "board disconnected".to_string(), + }) + .await?; + let got_failed = timeout(Duration::from_secs(1), msg_sub.recv()).await??; + assert_eq!(got_failed.kind, MessageKind::Warning); + assert_eq!(got_failed.name, "1001"); + assert_eq!( + got_failed.payload, + MessagePayload::Text("board disconnected".to_string()) + ); + + drop(tx); + timeout(Duration::from_secs(1), pipe_task).await??; + timeout(Duration::from_secs(1), broker_task).await??; + Ok(()) +} + +#[tokio::test(start_paused = true)] +async fn batches_data_every_100ms_with_window_average_last_and_cycle_time() + -> Result<(), Box> { + let (pod_data, index) = sample_fixture(); + let (broker, client) = Broker::new(); + let mut data_sub = client.subscribe_data(); + let broker_task = tokio::spawn(broker.run()); + + let (tx, rx) = mpsc::channel(32); + let pipe_task = spawn(Config::default(), rx, client, pod_data, index); + tokio::task::yield_now().await; + + let t0 = UNIX_EPOCH + Duration::from_secs(1_700_000_000); + let samples = [ + (t0, 10.0, false, "Idle"), + (t0 + Duration::from_millis(20), 20.0, true, "Idle"), + (t0 + Duration::from_millis(50), 30.0, true, "Fault"), + ]; + + for (at, voltage, active, state) in samples { + tx.send(ToPipeline::Received(Arc::new(Notification { + board: BoardId(5), + at, + event: Event::Received(Packet::Data(DataPacket::new( + AdjId(551), + vec![ + Value::Number(voltage), + Value::Bool(active), + Value::Enum(state.to_string()), + ], + ))), + }))) + .await?; + } + tokio::task::yield_now().await; + + // First 100 ms tick flushes pipeline -> broker; next 100 ms tick flushes broker -> watch. + advance(Duration::from_millis(100)).await; + tokio::task::yield_now().await; + tokio::task::yield_now().await; + advance(Duration::from_millis(100)).await; + timeout(Duration::from_millis(10), data_sub.changed()).await??; + + let first = data_sub.borrow_and_update()[&551].clone(); + assert_eq!(first.count, 3); + // Deltas were 20 ms and 30 ms -> average 25 ms = 25_000_000 ns. + assert_eq!(first.cycle_time, 25_000_000); + assert_eq!( + first.measurement_updates["voltage_battery_a"], + MeasurementUpdate::Numeric { + last: 30.0, + average: 20.0, + } + ); + assert_eq!( + first.measurement_updates["is_active"], + MeasurementUpdate::Boolean(true) + ); + assert_eq!( + first.measurement_updates["state"], + MeasurementUpdate::Enum("Fault".to_string()) + ); + + // Next window resets the measurement average while preserving cumulative count. + tx.send(ToPipeline::Received(Arc::new(Notification { + board: BoardId(5), + at: t0 + Duration::from_millis(150), + event: Event::Received(Packet::Data(DataPacket::new( + AdjId(551), + vec![ + Value::Number(50.0), + Value::Bool(false), + Value::Enum("Idle".to_string()), + ], + ))), + }))) + .await?; + + // Dropping `tx` flushes remaining data immediately and stops both tasks cleanly. + drop(tx); + timeout(Duration::from_secs(1), pipe_task).await??; + timeout(Duration::from_secs(1), broker_task).await??; + + let second = data_sub.borrow_and_update()[&551].clone(); + assert_eq!(second.count, 4); + assert_eq!(second.cycle_time, 100_000_000); + assert_eq!( + second.measurement_updates["voltage_battery_a"], + MeasurementUpdate::Numeric { + last: 50.0, + average: 50.0, + } + ); + Ok(()) +} + +#[test] +fn utc_calendar_conversion_handles_epoch_and_leap_day() { + let epoch = timestamp::from_system_time(UNIX_EPOCH); + assert_eq!( + epoch, + MessageTimestamp { + counter: 0, + second: 0, + minute: 0, + hour: 0, + day: 1, + month: 1, + year: 1970, + } + ); + + // 2024-02-29 13:45:09.250 UTC = 1_709_214_309 s + 250 ms + let leap = timestamp::from_system_time( + UNIX_EPOCH + Duration::from_secs(1_709_214_309) + Duration::from_millis(250), + ); + assert_eq!( + leap, + MessageTimestamp { + counter: 250, + second: 9, + minute: 45, + hour: 13, + day: 29, + month: 2, + year: 2024, + } + ); +} \ No newline at end of file diff --git a/backend/crates/station/src/pipeline/timestamp.rs b/backend/crates/station/src/pipeline/timestamp.rs new file mode 100644 index 000000000..de8dab49c --- /dev/null +++ b/backend/crates/station/src/pipeline/timestamp.rs @@ -0,0 +1,64 @@ +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +use crate::payload::MessageTimestamp; +use software_core::model::ShortTimestamp; + +/// Converts a [`SystemTime`] into a UTC [`MessageTimestamp`]. +pub(super) fn from_system_time(at: SystemTime) -> MessageTimestamp { + let dur = at.duration_since(UNIX_EPOCH).unwrap_or(Duration::ZERO); + let total_secs = dur.as_secs(); + let days = i64::try_from(total_secs / 86_400).unwrap_or(0); + let secs_of_day = total_secs % 86_400; + + let (year, month, day) = civil_from_days(days); + let hour = u8::try_from(secs_of_day / 3_600).unwrap_or(0); + let minute = u8::try_from((secs_of_day % 3_600) / 60).unwrap_or(0); + let second = u8::try_from(secs_of_day % 60).unwrap_or(0); + let counter = u16::try_from(dur.subsec_millis()).unwrap_or(0); + + MessageTimestamp { + counter, + second, + minute, + hour, + day, + month, + year, + } +} + +/// Combines the reception calendar date from `received_at` with the board's +/// [`ShortTimestamp`] time of day and raw subsecond byte. +pub(super) fn from_short(received_at: SystemTime, short: ShortTimestamp) -> MessageTimestamp { + let date = from_system_time(received_at); + MessageTimestamp { + counter: u16::from(short.subsecond), + second: short.second, + minute: short.minute, + hour: short.hour, + day: date.day, + month: date.month, + year: date.year, + } +} + +/// Converts days since 1970-01-01 (UTC) to `(year, month, day)` using +/// Howard Hinnant's civil calendar algorithm. +fn civil_from_days(days_since_epoch: i64) -> (u16, u8, u8) { + let z = days_since_epoch + 719_468; + let era = if z >= 0 { z } else { z - 146_096 } / 146_097; + let doe = u64::try_from(z - era * 146_097).unwrap_or(0); + let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365; + let y = i64::try_from(yoe).unwrap_or(0) + era * 400; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + let mp = (5 * doy + 2) / 153; + let d = doy - (153 * mp + 2) / 5 + 1; + let m = if mp < 10 { mp + 3 } else { mp - 9 }; + let year = y + i64::from(m <= 2); + + ( + u16::try_from(year).unwrap_or(0), + u8::try_from(m).unwrap_or(1), + u8::try_from(d).unwrap_or(1), + ) +} \ No newline at end of file From 33d7fbd188c2a3164eb0f91c655aca90124e7d76 Mon Sep 17 00:00:00 2001 From: GaziH Date: Tue, 1 Dec 2026 20:11:28 +0100 Subject: [PATCH 168/225] Feat(backend, pipeline): Made in line comments where necessary. --- backend/crates/station/src/pipeline.rs | 25 +++++++++++-- .../station/src/pipeline/accumulator.rs | 36 +++++++++++++++++-- .../crates/station/src/pipeline/message.rs | 14 ++++++++ .../crates/station/src/pipeline/timestamp.rs | 4 +++ 4 files changed, 74 insertions(+), 5 deletions(-) diff --git a/backend/crates/station/src/pipeline.rs b/backend/crates/station/src/pipeline.rs index 29ff104bc..c94b2b805 100644 --- a/backend/crates/station/src/pipeline.rs +++ b/backend/crates/station/src/pipeline.rs @@ -75,6 +75,11 @@ pub fn spawn( tokio::spawn(run_loop(config, rx, broker, pod_data, index)) } +/// Runs the main pipeline event loop, interleaving incoming `ToPipeline` +/// events with periodic flushes of accumulated telemetry. +/// +/// Exits cleanly once `rx` closes (after a final telemetry flush) or +/// immediately if the WebSocket broker shuts down. async fn run_loop( config: Config, mut rx: mpsc::Receiver, @@ -82,15 +87,19 @@ async fn run_loop( pod_data: Arc, index: Arc, ) { + // `tokio::time::interval_at` panics on a zero duration; clamp to at least 1 ms. let period = config.data_flush_interval.max(Duration::from_millis(1)); + // Start the first tick after one full period rather than immediately at t = 0. let mut tick = interval_at(Instant::now() + period, period); + // If the runtime stalls, skip missed ticks instead of firing a burst of catch-up flushes. tick.set_missed_tick_behavior(MissedTickBehavior::Skip); let mut accumulator = DataAccumulator::default(); loop { - // Poll the 100 ms flush tick first so sustained high-rate UDP traffic - // can never starve telemetry publication. + // `biased;` polls branches in top-to-bottom order instead of randomly. + // Checking the flush tick first guarantees sustained high-rate UDP traffic + // cannot starve the 100 ms telemetry publication. tokio::select! { biased; _ = tick.tick() => { @@ -106,6 +115,8 @@ async fn run_loop( } } None => { + // Upstream (`event`) closed: perform a best-effort flush of any + // buffered telemetry before exiting. let _ = flush_data(&broker, &index, &mut accumulator).await; return; } @@ -142,6 +153,10 @@ async fn handle_item( } } +/// Maps a wire-level [`Notification`] (connection state change or decoded +/// packet) to its corresponding WebSocket topic or telemetry accumulator. +/// +/// Returns `false` if publishing fails because the broker closed. async fn handle_notification( notification: &Notification, broker: &BrokerClient, @@ -184,6 +199,10 @@ async fn handle_notification( } } +/// Drains all telemetry packets updated during the current window and +/// publishes each [`crate::payload::DataPacketUpdate`] to the broker. +/// +/// Stops early and returns `false` if the broker has closed. async fn flush_data( broker: &BrokerClient, index: &Index, @@ -197,6 +216,8 @@ async fn flush_data( true } +/// Converts a broker publish result into a loop-continuation flag (`true` to +/// keep running, `false` to exit), logging an error when the broker closes. fn publish_or_log(result: Result<(), crate::websocket::broker::Error>) -> bool { match result { Ok(()) => true, diff --git a/backend/crates/station/src/pipeline/accumulator.rs b/backend/crates/station/src/pipeline/accumulator.rs index e6d2a0a72..1e694f60d 100644 --- a/backend/crates/station/src/pipeline/accumulator.rs +++ b/backend/crates/station/src/pipeline/accumulator.rs @@ -38,6 +38,9 @@ enum MeasurementAccumulator { } impl MeasurementAccumulator { + + /// Initializes an accumulator from the first decoded [`Value`] observed in + /// the current flush window. fn from_value(value: &Value) -> Self { match value { Value::Number(v) => Self::Numeric { @@ -50,10 +53,13 @@ impl MeasurementAccumulator { } } + /// Folds a newly received [`Value`] into this measurement's window state, + /// updating the running sum/sample count for numbers or replacing the + /// latest value for booleans and enums. fn update(&mut self, value: &Value) { match (self, value) { ( - Self::Numeric { + Self::Numeric { // If Numeric, update last, add to sum and 1 sample to calculate rolling average last, sum, samples, @@ -64,10 +70,11 @@ impl MeasurementAccumulator { *sum += *v; *samples += 1; } - (Self::Boolean(last), Value::Bool(b)) => { + (Self::Boolean(last), Value::Bool(b)) => //If Bool just change last variable + { *last = *b; } - (Self::Enum(last), Value::Enum(s)) => { + (Self::Enum(last), Value::Enum(s)) => { //If Enum just change value if different if last != s { last.clone_from(s); } @@ -78,6 +85,9 @@ impl MeasurementAccumulator { } } + /// Finalizes the window accumulator into the serialized + /// [`MeasurementUpdate`] payload, computes rolling average + /// for numeric measurements. fn into_update(self) -> MeasurementUpdate { match self { Self::Numeric { @@ -95,6 +105,9 @@ impl MeasurementAccumulator { } impl DataAccumulator { + + /// Records one incoming [`DataPacket`] into its per-ID window, updating + /// cumulative packet count, inter-arrival timing, and per-measurement stats. pub(super) fn record(&mut self, packet: &DataPacket, at: SystemTime, index: &Index) { let Some(def) = index.packet(packet.id) else { warn!(id = packet.id.0, "unknown data packet id in index"); @@ -117,6 +130,9 @@ impl DataAccumulator { ); } + // Lazily initialize the packet's window on first arrival. Using a map + // over `0..defs.len()` avoids requiring `Clone` on `MeasurementAccumulator` + // (which `vec![None; defs.len()]` would need). let window = self.packets.entry(packet.id).or_insert_with(|| PacketWindow { count: 0, last_at: None, @@ -127,7 +143,11 @@ impl DataAccumulator { dirty: false, }); + window.count = window.count.saturating_add(1); + // Rust 2024 let-chain: only accumulate cycle time when a previous + // timestamp exists and the system clock did not step backwards + // (`duration_since` returns `Err` on backwards clock jumps). if let Some(prev) = window.last_at && let Ok(delta) = at.duration_since(prev) { @@ -136,6 +156,8 @@ impl DataAccumulator { } window.last_at = Some(at); + // Match positional wire values to their positional slots; `zip` stops + // safely at the shorter slice if a count mismatch occurred. for (slot, value) in window.measurements.iter_mut().zip(packet.values.iter()) { match slot { Some(acc) => acc.update(value), @@ -146,6 +168,9 @@ impl DataAccumulator { window.dirty = true; } + /// Builds [`DataPacketUpdate`] payloads for every packet ID that received + /// at least one frame since the last flush, resetting per-window accumulators + /// while preserving cumulative `count` and `last_at`. pub(super) fn drain_updates(&mut self, index: &Index) -> Vec { let mut updates = Vec::new(); @@ -155,6 +180,8 @@ impl DataAccumulator { } window.dirty = false; + // Average inter-arrival deltas in u128 (matching `Duration::as_nanos`) + // and clamp to `u64::MAX` on overflow instead of truncating with `as`. if window.cycle_samples > 0 { let avg_ns = window.cycle_sum_ns / u128::from(window.cycle_samples); window.last_cycle_time_ns = u64::try_from(avg_ns).unwrap_or(u64::MAX); @@ -170,6 +197,9 @@ impl DataAccumulator { }; let mut measurement_updates = HashMap::with_capacity(defs.len()); + + // `slot.take()` moves the accumulator out and resets the slot to + // `None` in one step, preparing it cleanly for the next 100 ms window. for (measurement_def, slot) in defs.iter().zip(window.measurements.iter_mut()) { if let Some(acc) = slot.take() { measurement_updates.insert(measurement_def.alias.clone(), acc.into_update()); diff --git a/backend/crates/station/src/pipeline/message.rs b/backend/crates/station/src/pipeline/message.rs index a5a408ccd..aa1e937b2 100644 --- a/backend/crates/station/src/pipeline/message.rs +++ b/backend/crates/station/src/pipeline/message.rs @@ -7,13 +7,20 @@ use software_core::model::{AdjId, BoardId, MessagePacket, OrderPacket, PacketTyp use software_core::protocol::Index; use tracing::warn; +/// Looks up a board's human-readable name from [`PodData`], falling back to +/// `"board-"` if the ID is absent. pub(super) fn board_name(pod_data: &PodData, board: BoardId) -> String { + + // `map_or_else` evaluates the fallback closure lazily so `"board-"` is + // only allocated when the lookup misses. pod_data .boards .get(&board) .map_or_else(|| format!("board-{}", board.0), |b| b.name.clone()) } +/// Converts a board's free-text [`MessagePacket`] into a frontend +/// [`MessageUpdate`], resolving severity from the ADJ [`Index`]. pub(super) fn from_board_message( board: BoardId, at: SystemTime, @@ -53,6 +60,8 @@ pub(super) fn from_board_message( } } +/// Converts a backend [`Problem`] into a [`MessageUpdate`], returning `None` +/// for [`ProblemKind::Silent`] problems that should not be shown on the front. pub(super) fn from_problem(problem: Problem, pod_data: &PodData) -> Option { let kind = match problem.kind { ProblemKind::Shown => MessageKind::Warning, @@ -73,6 +82,8 @@ pub(super) fn from_problem(problem: Problem, pod_data: &PodData) -> Option, @@ -90,6 +101,8 @@ pub(super) fn from_order_sent( } } +/// Builds a warning [`MessageUpdate`] explaining why an order failed to send. +/// Resolves the target board from the ADJ [`Index`], or `"all"` for fault ID 0. pub(super) fn from_order_failed( at: SystemTime, order: OrderPacket, @@ -97,6 +110,7 @@ pub(super) fn from_order_failed( pod_data: &PodData, index: &Index, ) -> MessageUpdate { + // Order ID 0 is the reserved broadcast fault order targeting every board. let board_label = if order.id == AdjId(0) { "all".to_string() } else if let Some(def) = index.packet(order.id) { diff --git a/backend/crates/station/src/pipeline/timestamp.rs b/backend/crates/station/src/pipeline/timestamp.rs index de8dab49c..e4bd2f42a 100644 --- a/backend/crates/station/src/pipeline/timestamp.rs +++ b/backend/crates/station/src/pipeline/timestamp.rs @@ -5,15 +5,19 @@ use software_core::model::ShortTimestamp; /// Converts a [`SystemTime`] into a UTC [`MessageTimestamp`]. pub(super) fn from_system_time(at: SystemTime) -> MessageTimestamp { + // Clamp timestamps before 1970-01-01 to the Unix epoch rather than panicking. let dur = at.duration_since(UNIX_EPOCH).unwrap_or(Duration::ZERO); let total_secs = dur.as_secs(); + // 86_400 seconds per UTC day (POSIX/Unix time ignores leap seconds). let days = i64::try_from(total_secs / 86_400).unwrap_or(0); let secs_of_day = total_secs % 86_400; let (year, month, day) = civil_from_days(days); + // Use fallible `try_from` instead of `as` casts to avoid silent truncation. let hour = u8::try_from(secs_of_day / 3_600).unwrap_or(0); let minute = u8::try_from((secs_of_day % 3_600) / 60).unwrap_or(0); let second = u8::try_from(secs_of_day % 60).unwrap_or(0); + // Backend-originated messages use millisecond subsecond ticks (0–999) as the RTC counter. let counter = u16::try_from(dur.subsec_millis()).unwrap_or(0); MessageTimestamp { From 5b507ddd7f8a0e1132eaa61d1664a4013c849081 Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Tue, 1 Dec 2026 20:32:07 +0100 Subject: [PATCH 169/225] docs(backend): keep the Spanish demo docs out of this PR --- backend/crates/station/README.md | 8 ---- backend/readme-demo.md | 70 ++++++++++---------------------- 2 files changed, 22 insertions(+), 56 deletions(-) diff --git a/backend/crates/station/README.md b/backend/crates/station/README.md index aefa4aca6..00e8661df 100644 --- a/backend/crates/station/README.md +++ b/backend/crates/station/README.md @@ -15,11 +15,3 @@ cargo run -p station -- --config ./dev-config.toml *(Pendiente: crear `dev-config.toml` y `config.toml`, portados de `backend_old/cmd/`.)* -Mientras tanto, `src/main.rs` descarga el ADJ, escucha en el puerto UDP y -pasa lo que llega por `event` a dos sustitutos de `logging` y `pipeline`: -`cargo run -p station --release`. Ver -[`../../readme-demo.md`](../../readme-demo.md). - -`event`, la comunicación entre los módulos de station, está documentado en -[`src/event/README.md`](src/event/README.md). - diff --git a/backend/readme-demo.md b/backend/readme-demo.md index 644b186e6..050e911ac 100644 --- a/backend/readme-demo.md +++ b/backend/readme-demo.md @@ -1,38 +1,21 @@ -# Demo: UDP → event → logging y pipeline - -`crates/station/src/main.rs` junta, por ahora, las piezas que ya existen: - -1. `core::git::update_adj` descarga el ADJ de la rama `adjv3-software`. -2. `core::adj::load_from_dir` lo carga. -3. Con él se construye el `core::protocol::Index`. -4. `core::net::udp::spawn_udp` abre el puerto UDP del ADJ: - `addresses["backend"]` y `ports["UDP"]` de `general_info.json`. -5. `station::event` (ver [`crates/station/src/event/README.md`](crates/station/src/event/README.md)) - crea todas las colas, aplica las reglas de errores y reparte lo que llega - a dos sustitutos de `logging` y `pipeline`, que todavía no existen: el de - logging cuenta los paquetes por placa y escribe un resumen por segundo; el - de pipeline escribe en el log lo que vería el front (problemas, órdenes que - no salieron). +# Demo: core → station + tracing Desde `software/backend`, con Rust 1.98.0 y Cargo instalados (la primera ejecución descarga las dependencias): ```sh -# Ejecutar: una línea INFO por segundo con los paquetes recibidos por placa. -cargo run -p station --release - -# Además, cada paquete con sus valores decodificados. -# (RUST_LOG=debug a secas también saca el detalle de gix durante la descarga.) -RUST_LOG=info,station=debug cargo run -p station --release +# Ejecutar: muestra el saludo y el ciclo de vida a nivel INFO. +cargo run -p station +cargo run -p station -- "Hyperloop UPV" -# Tests unitarios y doctests (incluye los de UDP, con socket real en loopback). -cargo test --workspace +# Mostrar también DEBUG del módulo, manteniendo INFO en station. +RUST_LOG=info,software_core::hello_world=debug cargo run -p station -- "Lucía" -# Prueba de carga de UDP (25 Mbit/s en paquetes de 76 bytes), ignorada por defecto. -cargo test -p software-core --features net --release manual_udp_load -- --ignored --nocapture +# Filtrar todos los eventos de esta demo (no emite errores). +RUST_LOG=error cargo run -p station -# Prueba de rendimiento de event (un millón de avisos), ignorada por defecto. -cargo test -p station --release manual_event -- --ignored --nocapture +# Tests unitarios y ejemplo de documentación ejecutable (doctest). +cargo test --workspace # Generar documentación HTML de la API. cargo doc --workspace --no-deps @@ -42,26 +25,17 @@ cargo fmt --all -- --check cargo clippy --workspace --all-targets -- -D warnings ``` -Cómo se comporta: - -- **Un error fatal lo para** y sale con código 1: un datagrama que no se - puede decodificar o perder el socket. El error lleva el nombre de la placa, - sacado de la IP de quien lo mandó. -- **Un fault que mande una placa** (paquete id 0, que UDP reconoce sin mirar - el ADJ) **no lo para**: se muestra el primero de cada placa. Reenviarlo al - resto necesita TCP, que todavía no está, así que solo queda en la traza. -- **Ctrl+C** lo para limpio y sale con código 0. -- Para probarlo en local hace falta algo que mande paquetes a la dirección - del ADJ (`127.0.0.9:50400` en `adjv3-software`), como un simulador de - placas. +Abre `target/doc/software_core/hello_world/index.html` para ver la API. -Ojo: el ADJ va a la carpeta por defecto de `core::git` -(`~/.cache/hyperloop-control-station/adj` en Linux), la misma que usa el -backend de Go, y cada ejecución con conexión la sustituye por -`adjv3-software`. +- `crates/core/src/hello_world.rs`: `greet(&str) -> String`, con rustdoc, +- `crates/core/src/lib.rs`: exporta el módulo público. +- `crates/station/src/main.rs`: inicializa el subscriber una sola vez y llama a `greet`. +- `#[tracing::instrument]` crea el span `hello_world`; los eventos incluyen + el destinatario y campos estructurados como `greeting` o `used_default`. + `INFO` muestra el saludo; `DEBUG` permite inspeccionar la elección del destinatario. +- Core solo emite eventos: sin subscriber, devuelve igualmente el saludo. + Los tests comprueban ese resultado sin configurar logging global. -`crates/core/src/hello_world.rs` sigue en core como ejemplo de cómo se -escribe un módulo (docs, trazas, tests, doctest), pero `station` ya no lo -usa. Esta demo todavía no arranca TCP, websocket ni HTTP, ni carga TOML: los scripts -`pnpm dev` están preparados para la futura configuración del backend, que -esta demo no interpreta. +Esta demo termina tras saludar; todavía no arranca servidores ni carga TOML. +Usa los comandos Cargo de arriba: los scripts `pnpm dev` están preparados para +la futura configuración del backend, que esta demo no interpreta. From 381ae81bb7c28aaa3ee2a13064ab18f9d9a80d0e Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Tue, 1 Dec 2026 20:38:58 +0100 Subject: [PATCH 170/225] refactor(backend, station): declare station's modules in lib.rs, keep main.rs as the wiring --- backend/crates/station/src/lib.rs | 12 ++++++++++++ backend/crates/station/src/main.rs | 4 +--- 2 files changed, 13 insertions(+), 3 deletions(-) create mode 100644 backend/crates/station/src/lib.rs diff --git a/backend/crates/station/src/lib.rs b/backend/crates/station/src/lib.rs new file mode 100644 index 000000000..9eb696501 --- /dev/null +++ b/backend/crates/station/src/lib.rs @@ -0,0 +1,12 @@ +//! The station backend's modules. +//! +//! Every module lives here, so that each one compiles and is tested on its +//! own while it is being built, whether or not `main` wires it in yet. +//! `main.rs` only starts them and connects them. +//! +//! - [`event`]: the communication between the modules (see +//! `src/event/README.md`). +//! - [`http`]: the HTTP API (ADJ catalogs and the WebSocket upgrade). + +pub mod event; +pub mod http; diff --git a/backend/crates/station/src/main.rs b/backend/crates/station/src/main.rs index 911ea49b4..bf39e02bd 100644 --- a/backend/crates/station/src/main.rs +++ b/backend/crates/station/src/main.rs @@ -26,8 +26,6 @@ //! backend uses: whatever was there is replaced by the [`ADJ_BRANCH`] branch. //! Offline, whatever is in that folder is used, whichever branch it is. -mod event; - use std::collections::HashMap; use std::net::SocketAddr; use std::path::PathBuf; @@ -47,7 +45,7 @@ use tokio::time::MissedTickBehavior; use tracing::{debug, error, info, warn}; use tracing_subscriber::EnvFilter; -use event::{ProblemKind, Stop, ToLogging, ToPipeline}; +use station::event::{self, ProblemKind, Stop, ToLogging, ToPipeline}; /// Branch of the ADJ repository that is downloaded. const ADJ_BRANCH: &str = "adjv3-software"; From d89de542640160e4664102692dadc3a0a4642522 Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Tue, 1 Dec 2026 20:46:04 +0100 Subject: [PATCH 171/225] docs(backend, udp): explain what Lookups resolves and where its IP map comes from --- backend/crates/core/src/net/udp.rs | 27 ++++++++++++++++++++++++--- 1 file changed, 24 insertions(+), 3 deletions(-) diff --git a/backend/crates/core/src/net/udp.rs b/backend/crates/core/src/net/udp.rs index a4c719387..87eabcbb3 100644 --- a/backend/crates/core/src/net/udp.rs +++ b/backend/crates/core/src/net/udp.rs @@ -292,17 +292,38 @@ async fn receive_telemetry( /// raises a fault itself (`SendFault`). const FAULT_ID: [u8; 2] = 0u16.to_le_bytes(); -/// What the receive loop looks things up in, both read-only. +/// The two read-only tables the receive loop resolves a datagram against, +/// bundled so that [`decode_and_report`] takes one argument for both. +/// +/// They answer the same question, "which board is this from?", for two +/// kinds of datagram: +/// +/// - **One that decodes** carries an id, and the [`Index`] leads from the id +/// to its [`crate::model::PacketDef`], which names its board. +/// - **One that never gets an id**, a fault (packet id 0) or a datagram that +/// fails to decode, only has the sender's address. `boards` leads from +/// that address to its board, so that its error can still name the board +/// ([`UdpError::Fault`], [`UdpError::Decode`]). +/// +/// `boards` is the ADJ's own data, not a second definition of it: it is +/// built once from [`crate::model::PodData`] with +/// [`crate::model::PodData::boards_by_ip`], and comes in through +/// [`UdpConfig::boards`]. It is not in the [`Index`] because the index knows +/// nothing about addresses on purpose (see its docs), and it is not looked up +/// in `PodData` directly so that UDP gets only what it uses, not the whole +/// pod. #[derive(Debug, Clone, Copy)] struct Lookups<'a> { /// A decoded id to its definition, and through it to its board. adj: &'a Index, - /// A sender's address to its board, for errors: see [`UdpConfig::boards`]. + /// A sender's IP to its board, for the datagrams that have no id. boards: &'a HashMap, } impl Lookups<'_> { - /// The board `from` belongs to, if any. + /// The board `from` belongs to, or `None` if its IP is no board's. Only + /// the IP counts: a board is identified by its address, not by the port + /// it sends from. fn board_at(&self, from: SocketAddr) -> Option { self.boards.get(&from.ip()).copied() } From ceb77c3add29e2b449575fe93f5b702fcfcd9bec Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Fri, 27 Nov 2026 01:41:57 +0100 Subject: [PATCH 172/225] feat(backend, logging): logging module initial structure --- backend/crates/station/Cargo.toml | 2 +- backend/crates/station/src/logging.rs | 27 +++++++++++++++++++ backend/crates/station/src/logging/data.rs | 9 +++++++ backend/crates/station/src/logging/error.rs | 6 +++++ backend/crates/station/src/logging/event.rs | 8 ++++++ .../crates/station/src/logging/messages.rs | 8 ++++++ backend/crates/station/src/logging/order.rs | 9 +++++++ .../crates/station/src/logging/protections.rs | 11 ++++++++ backend/crates/station/src/logging/session.rs | 14 ++++++++++ .../crates/station/src/logging/settings.rs | 10 +++++++ backend/crates/station/src/logging/writer.rs | 14 ++++++++++ 11 files changed, 117 insertions(+), 1 deletion(-) create mode 100644 backend/crates/station/src/logging.rs create mode 100644 backend/crates/station/src/logging/data.rs create mode 100644 backend/crates/station/src/logging/error.rs create mode 100644 backend/crates/station/src/logging/event.rs create mode 100644 backend/crates/station/src/logging/messages.rs create mode 100644 backend/crates/station/src/logging/order.rs create mode 100644 backend/crates/station/src/logging/protections.rs create mode 100644 backend/crates/station/src/logging/session.rs create mode 100644 backend/crates/station/src/logging/settings.rs create mode 100644 backend/crates/station/src/logging/writer.rs diff --git a/backend/crates/station/Cargo.toml b/backend/crates/station/Cargo.toml index 9eed62cbe..3dc8f145c 100644 --- a/backend/crates/station/Cargo.toml +++ b/backend/crates/station/Cargo.toml @@ -9,7 +9,7 @@ authors.workspace = true repository.workspace = true [dependencies] -software-core = { workspace = true, features = ["net", "git", "http"] } +software-core = { workspace = true, features = ["net", "git", "http", "logger"] } serde.workspace = true thiserror.workspace = true tokio.workspace = true diff --git a/backend/crates/station/src/logging.rs b/backend/crates/station/src/logging.rs new file mode 100644 index 000000000..816819c9d --- /dev/null +++ b/backend/crates/station/src/logging.rs @@ -0,0 +1,27 @@ +//! Backend recording policy, built on `software_core::logger`. +//! +//! This is the module scaffold; recording and frontend integration are not +//! implemented yet. The file writers stay in `software_core::logger`; this +//! module will decide what to record, where it belongs and when to flush it. +//! +//! Planned lifecycle: +//! - At backend startup, create a `YYYY-MM-DDTHH-MM-SS` directory and its +//! `others/` directory for the ADJ validator output, settings and JSONL trace. +//! - `play` prepares a new recording session and enables event admission. +//! - `stop` stops admission, drains accepted events and closes session files. +//! - `emergency_stop` performs the same drain during backend shutdown, then +//! finishes the writer and flushes the backend trace. +//! +//! Session state, event admission and stop ordering must be coordinated so +//! that an accepted event cannot leak into a later session. The frontend +//! receives success only after the requested transition has completed. + +mod data; +mod error; +mod event; +mod messages; +mod order; +mod protections; +mod session; +mod settings; +mod writer; diff --git a/backend/crates/station/src/logging/data.rs b/backend/crates/station/src/logging/data.rs new file mode 100644 index 000000000..d3b3dcfa8 --- /dev/null +++ b/backend/crates/station/src/logging/data.rs @@ -0,0 +1,9 @@ +//! Measurement recording under `data//.csv`. +//! +//! One directory per connected board and one CSV per selected measurement, +//! named with its textual identifier. Files have no header. Columns, in order: +//! `instant,from,to,value`. +//! +//! This component will own the measurement `software_core::logger::CsvFile` +//! handles and translate typed events into rows, reusing the logger's CSV +//! escaping, buffering and explicit flush/close operations. diff --git a/backend/crates/station/src/logging/error.rs b/backend/crates/station/src/logging/error.rs new file mode 100644 index 000000000..adf643342 --- /dev/null +++ b/backend/crates/station/src/logging/error.rs @@ -0,0 +1,6 @@ +//! Errors for recording setup, lifecycle transitions and the writer. +//! +//! Errors will preserve file context from `software_core::logger` and report +//! queue saturation, writer failure and invalid session transitions. Shutdown +//! must attempt to close all files even if closing one of them fails, and +//! return failures to the caller rather than report a successful stop. diff --git a/backend/crates/station/src/logging/event.rs b/backend/crates/station/src/logging/event.rs new file mode 100644 index 000000000..2d00ab80e --- /dev/null +++ b/backend/crates/station/src/logging/event.rs @@ -0,0 +1,8 @@ +//! Typed recording events for measurements, orders, protections and messages. +//! +//! Events will carry their recording session identity and the elapsed time +//! captured at reception or order execution, before entering the writer queue. +//! Queue latency must not become part of the recorded `instant`. +//! +//! Order events also capture wall-clock time for the timestamp column. Event +//! types and the concrete producer API remain to be implemented. diff --git a/backend/crates/station/src/logging/messages.rs b/backend/crates/station/src/logging/messages.rs new file mode 100644 index 000000000..a35de950e --- /dev/null +++ b/backend/crates/station/src/logging/messages.rs @@ -0,0 +1,8 @@ +//! Message recording in the session's single `messages/messages.csv` file. +//! +//! Columns, in order: `instant,from,to,board,source,severity`. +//! `board` identifies the board that emitted the message; `source` combines +//! file and line in one field when applicable to the message type. +//! +//! This component will own a `software_core::logger::CsvFile` and format rows. +//! Header policy and the exact representation of `source` remain to be defined. diff --git a/backend/crates/station/src/logging/order.rs b/backend/crates/station/src/logging/order.rs new file mode 100644 index 000000000..e39a6d8f6 --- /dev/null +++ b/backend/crates/station/src/logging/order.rs @@ -0,0 +1,9 @@ +//! Order recording in the session's single `order/order.csv` file. +//! +//! Columns, in order: `instant,from,to,id,payload,timestamp`. +//! `timestamp` is the order's wall-clock time formatted as +//! `YYYY-MM-DDTHH-MM-SS` followed by the applicable `Europe/Madrid` UTC offset +//! (`+01:00` for CET or `+02:00` for CEST). +//! +//! This component will own a `software_core::logger::CsvFile` and format rows. +//! Header policy and the exact payload representation remain to be defined. diff --git a/backend/crates/station/src/logging/protections.rs b/backend/crates/station/src/logging/protections.rs new file mode 100644 index 000000000..7b476e47e --- /dev/null +++ b/backend/crates/station/src/logging/protections.rs @@ -0,0 +1,11 @@ +//! Protection recording in `protections/.csv`, one per board. +//! +//! Columns, in order: +//! `instant,from,to,protection_id,severity,protection_type,threshold_1,threshold_2,measurement_id,value,time`. +//! The second threshold is empty unless the protection is a range. `value` +//! is the measurement value that triggered the protection. For a +//! `timeacumulation` protection, `time` is a string containing time and units; +//! for other protection types it is `0`. +//! +//! This component will own the `software_core::logger::CsvFile` handles and +//! format rows. Header policy remains to be defined. diff --git a/backend/crates/station/src/logging/session.rs b/backend/crates/station/src/logging/session.rs new file mode 100644 index 000000000..a7bef0f8a --- /dev/null +++ b/backend/crates/station/src/logging/session.rs @@ -0,0 +1,14 @@ +//! Recording session paths, identity, clock and lifecycle state. +//! +//! Every successful `play` starts a separate session directory named +//! `YYYY-MM-DDTHH-MM-SS` below the backend startup directory. Each session has +//! `logger-settings.json` and `data/`, `protections/`, `order/`, `messages/`. +//! +//! A monotonic `std::time::Instant` will establish the session's zero point. +//! Recorded elapsed times use the configured time unit; the first event need +//! not occur at zero. Wall-clock time is used separately for directory names +//! and order timestamps. Directory creation must never overwrite an earlier +//! session when two starts fall in the same second. +//! +//! Planned states: inactive, starting, recording and stopping. A normal stop +//! preserves the backend-wide `others/` files for subsequent sessions. diff --git a/backend/crates/station/src/logging/settings.rs b/backend/crates/station/src/logging/settings.rs new file mode 100644 index 000000000..369e82d32 --- /dev/null +++ b/backend/crates/station/src/logging/settings.rs @@ -0,0 +1,10 @@ +//! Backend and recording-session `logger-settings.json` metadata. +//! +//! Backend settings in `others/` contain `adj_commit_hash`, `time_unit` and +//! `date`, where `date` matches the backend startup directory name. +//! Session settings preserve that metadata, replace `date` with the session +//! directory name and add `selected_variables`. The representation of that +//! selection remains to be defined. +//! +//! Settings will be written through `software_core::logger::write_json` or +//! `software_core::logger::JsonDocument`, allowing the metadata to grow later. diff --git a/backend/crates/station/src/logging/writer.rs b/backend/crates/station/src/logging/writer.rs new file mode 100644 index 000000000..bf9c898e8 --- /dev/null +++ b/backend/crates/station/src/logging/writer.rs @@ -0,0 +1,14 @@ +//! Dedicated synchronous writer and its bounded event queue. +//! +//! One writer thread will own the session's four recording components and +//! perform their blocking `software_core::logger` operations away from the +//! async network tasks. Keep files open for the session and reuse their +//! existing buffers; flush periodically and according to bytes_since_flush. +//! +//! Admission and control commands must establish a session boundary: stop +//! rejects new events for that session, drains every accepted event, attempts +//! to close every session file and acknowledges completion. Queue saturation +//! must be reported explicitly rather than silently dropping events. +//! +//! Backend trace output has a separate lifetime from recording sessions. It +//! remains active between sessions and is flushed at the end of shutdown. From 667b6609eb7168e1b19bf5055c43752779954fbd Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Fri, 27 Nov 2026 14:46:00 +0100 Subject: [PATCH 173/225] docs(backend, logging): create README.md and explanation of module workflow --- backend/crates/station/src/logging/README.md | 396 +++++++++++++++++++ 1 file changed, 396 insertions(+) create mode 100644 backend/crates/station/src/logging/README.md diff --git a/backend/crates/station/src/logging/README.md b/backend/crates/station/src/logging/README.md new file mode 100644 index 000000000..ac3a61966 --- /dev/null +++ b/backend/crates/station/src/logging/README.md @@ -0,0 +1,396 @@ +# Station Logging + +This module manages backend logging sessions: what is recorded, when a session +starts and ends, how its files are organized, and when buffers are flushed. +Write operations use +[software_core::logger](../../../core/src/logger/README.md). + +## Current Status + +The module currently consists of a scaffold with documented responsibilities. +It is declared in `main.rs`, and `station` enables the `logger` feature of +`software-core`. + +The logging service, control functions, writer, event formats, and integration +with the frontend and backend startup are not implemented yet. The following +sections describe the agreed requirements and planned design, rather than +features that are already operational. + +## File Structure for a Backend Run + +Each backend startup creates a directory named after its start date and time, +using the `YYYY-MM-DDTHH-MM-SS` format. It contains `others/` and the directories +for the logging sessions started during that run. + +Each session is created when **Start logger** is pressed in the frontend. Its +directory uses the same format, but with the session's start date and time. + +```text +/ +└── 2026-11-27T15-30-00/ # Backend startup + ├── others/ + │ ├── .txt + │ ├── logger_settings.json + │ └── .jsonl + ├── 2026-11-27T15-31-05/ # First session + │ ├── logger_settings.json + │ ├── data/ + │ │ └── / + │ │ ├── .csv + │ │ └── .csv + │ ├── protections/ + │ │ └── .csv + │ ├── order/ + │ │ └── order.csv + │ └── messages/ + │ └── messages.csv + └── 2026-11-27T15-35-20/ # Another session in the same run + └── ... +``` + +Names inside `<...>` are placeholders, not final filenames. The exact names +of the validator TXT file and the trace JSONL file are still pending. + +If a new session has the same name as an existing one, the agreed behavior is +to overwrite it. Replacement must avoid mixing old files with the new session's +selection. A collision can occur when starting, stopping, and starting again +within the same second. Handling another `play()` while a session is active +remains undecided; ignoring it has been proposed to prevent a double click +from truncating an ongoing session. + +## Metadata: logger_settings.json + +The name uses an **underscore**, both in `others/` and in each session, to +match the file expected by the frontend viewer. + +### Backend Run Settings + +`others/logger_settings.json` initially contains: + +```json +{ + "adj_commit_hash": "", + "time_unit": "us", + "date": "2026-11-27T15-30-00" +} +``` + +| Field | Meaning | +| --- | --- | +| `adj_commit_hash` | Commit hash of the ADJ used by the backend. | +| `time_unit` | Unit used for the instants recorded in the CSV files. | +| `date` | Startup date and time, exactly matching the parent directory name. | + +This structure may be extended in the future. + +### Session Settings + +Each session keeps its own copy of the settings, with these changes: + +- `date` becomes that session's start date and time, matching its directory + name. +- `selected_variables` is added to represent the variables selected for + recording during that session. Its exact JSON schema is still pending. + +The selection may change between sessions. Only selected variables are +recorded, and only files corresponding to that selection are created; +no CSV files are created for unselected measurements. + +Metadata will be written using `logger::write_json` or `logger::JsonDocument`. + +## Record Timing + +### instant + +`instant` is an **integer** representing the elapsed time since the logging +session started. It is neither a Unix timestamp nor the time since backend +startup. + +The counter starts at zero when each session begins. This does not require +the first row to contain zero: if the first measurement arrives 35 ms after +startup, its `instant` will be `35` with `time_unit = "ms"`, or `35000` with +`"us"`. + +A monotonic clock (`std::time::Instant`) is planned as the session's time +origin. The instant must be captured when the event is received, before +queuing it, so that writing delays do not change the recorded time. + +The units verified in the frontend are: + +| time_unit | Unit | +| --- | --- | +| `ns` | Nanoseconds | +| `us` | Microseconds | +| `ms` | Milliseconds | +| `s` | Seconds | + +### Order Timestamp + +In addition to `instant`, orders include a calendar date and time in the +`YYYY-MM-DDTHH-MM-SS` format, followed by the `Europe/Madrid` UTC offset +applicable to that date: + +```text +2026-07-15T15-30-05+02:00 # CEST, summer +2026-11-27T15-30-05+01:00 # CET, winter +``` + +The offset is not always `+02:00`. This additional information has been agreed +for the orders' `timestamp` column; directory names retain the +`YYYY-MM-DDTHH-MM-SS` format. + +## CSV Format + +**No CSV file has a header.** The column lists in this document describe the +field order and must not be written as the first row. + +Text fields, including order JSON and message text, must use the CSV escaping +provided by `logger::Row::text`. This correctly preserves commas, quotation +marks, and line breaks within a field. Rows must not be built by manually +joining fields with commas. + +### Measurements: data/ + +A directory is created for each connected board, using its name. It contains +one CSV per selected measurement, named after its string ID: + +```text +data//.csv +``` + +Columns, in order: + +```text +instant,from,to,value +``` + +| Field | Content | +| --- | --- | +| `instant` | Time since the session started, in `time_unit`. | +| `from` | Name of the source board. | +| `to` | `backend` or the name of another destination board. | +| `value` | Measurement value. | + +### Orders: order/order.csv + +There is a single `order.csv` file inside `order/`. + +Columns, in order: + +```text +instant,from,to,id,payload,timestamp +``` + +| Field | Content | +| --- | --- | +| `instant` | Time since the session started, in `time_unit`. | +| `from` | Order source. | +| `to` | Order destination. | +| `id` | Order ID. | +| `payload` | JSON received from the frontend over WebSocket, preserved as text. | +| `timestamp` | Order date and time, using the format and offset described above. | + +An order is recorded **when it is received from the frontend**. Recording does +not wait for it to be sent to the board or for execution confirmation. Its +times are captured at that point of reception. + +### Protections: protections/ + +One file is created per connected board: + +```text +protections/.csv +``` + +Columns, in order: + +```text +instant,from,to,protection_id,severity,protection_type,threshold_1,threshold_2,measurement_id,value,time +``` + +| Field | Content | +| --- | --- | +| `instant` | Time since the session started, in `time_unit`. | +| `from` | Event source. | +| `to` | Event destination. | +| `protection_id` | ID of the triggered protection. | +| `severity` | Severity level. | +| `protection_type` | Protection type. | +| `threshold_1` | First trigger value or threshold of the protection. | +| `threshold_2` | Second threshold for `range` protections; empty for other types. | +| `measurement_id` | ID of the associated measurement. | +| `value` | Measurement value that triggered the protection. | +| `time` | Timing result sent by the board for `timeacumulation`, as a string containing time and units; `0` for other types. | + +Both threshold fields are always present, even when the second one is empty. +The thresholds and the value that triggered the event are separate fields. + +The `timeacumulation` data comes from the board. It is not calculated from the +session clock or `time_unit`; its extraction remains to be specified when +integrating the received packet with recording. + +### Messages: messages/messages.csv + +There is a single `messages.csv` file inside `messages/`. + +The agreed columns, in order, are: + +```text +instant,from,to,board,source,severity,message +``` + +| Field | Content | +| --- | --- | +| `instant` | Time since the session started, in `time_unit`. | +| `from` | Event source. | +| `to` | Event destination. | +| `board` | Name of the board that emitted the message. | +| `source` | The `origin` field of the message received over TCP. | +| `severity` | Message severity. | +| `message` | Text of the received message. | + +File and line are kept together in `source` when the message contains that +information. The received `origin` is preserved without moving the line to +another column or reconstructing its format. + +## Frontend Control and Shutdown + +The planned functions are `play()`, `stop()`, and `emergency_stop()`. Their +signatures are not implemented yet, and no WebSocket control protocol has +been defined. + +### play() + +Prepares a new session's directory, settings, variable selection, and files. +Establishes the time origin and starts accepting records once the session +is ready. + +The planned states are: + +```text +Inactive -> Starting -> Recording -> Stopping -> Inactive +``` + +### stop() + +Stops the session in this order: + +1. Stops accepting new records for that session. +2. Processes all events already accepted into the queue. +3. Flushes the buffers and closes the session files. +4. Returns the stop result to the frontend. + +Pending events from one session must not be written into another. +The `others/` directory belongs to the backend run and is preserved between +sessions. + +### emergency_stop() + +Used when the backend shuts down and also when the frontend closes or +disconnects. It reuses the session stop logic and waits for its buffers to be +flushed and its files to be closed before completing the controlled shutdown. + +If the backend remains running after the frontend disconnects, starting +another session later must be possible. The trace belongs to the backend and +may remain active; its final flush takes place during backend shutdown. + +When multiple frontends are connected, it remains undecided whether a +session stops when any frontend disconnects or only when the frontend that +started it disconnects. + +## Efficient Writing + +The planned design uses a dedicated thread for synchronous +`software_core::logger` writes, separate from asynchronous network tasks: + +```text +Event reception + | + v +Capture instant and associate with session + | + v +Queue with limited capacity + | + v +Writer thread and format components + | + v +software_core::logger + | + v +Buffered files +``` + +The writer will own the files. It will keep them open throughout the session +and reuse the buffers already provided by `logger`, avoiding opening, writing, +and closing a file for every record. + +Buffers are planned to be flushed periodically and when a byte threshold is +reached, using `bytes_since_flush()`. Exact capacities and intervals will be +chosen during implementation. Stopping must explicitly call +`flush()`/`close()` and report errors, rather than relying solely on `Drop`. + +### Queue Saturation + +If records arrive faster than they can be written for long enough to fill +the queue, the agreed behavior is to **stop logging and notify the frontend**: + +1. Stop accepting new records. +2. Write records that have already been accepted. +3. Flush and close the session files. +4. Indicate that the session ended because of saturation. + +The backend continues running. Records must not keep being silently dropped +while the session is presented as active. + +A write error must be reported and cannot be treated as a successful stop. +The exact policy for disk failures and frontend status messages remains +undecided. + +## Files in others/ + +`others/` contains three files for the entire backend run: + +| File | Content | Design status | +| --- | --- | --- | +| Validator TXT | Output of `adj-validator`. | Name and method of obtaining the output pending. | +| `logger_settings.json` | Backend startup metadata. | Initial fields defined. | +| Trace JSONL | Backend trace, with one JSON object per line. | Name, levels/filters, and integration pending. | + +The old backend was investigated: it runs the Python script included in the +ADJ repository with `--no-color`, captures stdout and stderr together, attempts +to save the output, and then checks the process result. That implementation +serves as a reference, but **running the validator and obtaining its output +were left undecided**. This flow has not been implemented in the new backend. + +## Responsibilities of Module Files + +| File | Planned responsibility | +| --- | --- | +| `../logging.rs` | Logging service, coordination, and control API. | +| `session.rs` | Identity, paths, clock, and state of each session. | +| `settings.rs` | Backend run and session metadata. | +| `event.rs` | Typed events with their instant and target session. | +| `writer.rs` | Bounded queue, writer thread, flushing, and orderly shutdown. | +| `data.rs` | Measurement files by board and variable. | +| `protections.rs` | Protection files by board. | +| `order.rs` | Order recording in a single CSV. | +| `messages.rs` | Message recording in a single CSV. | +| `error.rs` | Configuration, session, queue, and write errors. | + +`station::logging` knows about the ADJ, boards, selections, and sessions. +`software_core::logger` provides CSV, text, and JSON writing, field escaping, +buffers, and explicit flush and close operations. + +## Pending Decisions + +- Names of the validator TXT file and trace JSONL file. +- Running `adj-validator` and obtaining its output. +- Trace levels and filters, and their connection to the JSONL file. +- Exact schema of `selected_variables` in JSON and frontend control. +- Final position of the text column in `messages.csv`. +- Behavior of repeated `play()` calls during an active session. +- Disconnection stop rule when multiple frontends are connected. +- Write error policy and frontend notification format. +- Queue/buffer capacities, flush intervals, and configuration parameters. From db6d981fe7354a2b4e9c44bb6239321ce0c0f6fc Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Fri, 27 Nov 2026 15:15:04 +0100 Subject: [PATCH 174/225] feat(backend, logging): create directories when the backend is started and when a logging session is started --- backend/Cargo.lock | 3 + backend/Cargo.toml | 1 + backend/crates/station/Cargo.toml | 4 + backend/crates/station/src/lib.rs | 2 + backend/crates/station/src/logging.rs | 20 +- backend/crates/station/src/logging/error.rs | 30 +++ backend/crates/station/src/logging/session.rs | 225 +++++++++++++++++- .../crates/station/src/logging/settings.rs | 75 +++++- 8 files changed, 348 insertions(+), 12 deletions(-) diff --git a/backend/Cargo.lock b/backend/Cargo.lock index e09a599b4..ef89cdfbe 100644 --- a/backend/Cargo.lock +++ b/backend/Cargo.lock @@ -1947,6 +1947,7 @@ checksum = "26699905cc795a23e3949585cc7ba3ee8ade090872a27e4316304a777297894a" dependencies = [ "jiff-core", "jiff-static", + "jiff-tzdb", "jiff-tzdb-platform", "log", "portable-atomic", @@ -2959,9 +2960,11 @@ name = "station" version = "0.1.0" dependencies = [ "axum", + "jiff", "serde", "serde_json", "software-core", + "tempfile", "thiserror", "tokio", "toml", diff --git a/backend/Cargo.toml b/backend/Cargo.toml index d14dd7807..24f3baa88 100644 --- a/backend/Cargo.toml +++ b/backend/Cargo.toml @@ -20,6 +20,7 @@ repository = "https://github.com/Hyperloop-UPV/software" software-core = { path = "crates/core" } bytes = "1" +jiff = { version = "0.2", features = ["tzdb-bundle-always"] } serde = { version = "1", features = ["derive"] } serde_json = "1" thiserror = "2" diff --git a/backend/crates/station/Cargo.toml b/backend/crates/station/Cargo.toml index 3dc8f145c..05d29efb8 100644 --- a/backend/crates/station/Cargo.toml +++ b/backend/crates/station/Cargo.toml @@ -10,6 +10,7 @@ repository.workspace = true [dependencies] software-core = { workspace = true, features = ["net", "git", "http", "logger"] } +jiff.workspace = true serde.workspace = true thiserror.workspace = true tokio.workspace = true @@ -21,5 +22,8 @@ tower = "0.5.3" axum = { version = "0.8.9", features = ["ws", "http1", "http2"] } tower-http = { version = "0.6.11", features = ["cors", "set-header"] } +[dev-dependencies] +tempfile = "3.27" + [lints] workspace = true diff --git a/backend/crates/station/src/lib.rs b/backend/crates/station/src/lib.rs index 9eb696501..380d13823 100644 --- a/backend/crates/station/src/lib.rs +++ b/backend/crates/station/src/lib.rs @@ -7,6 +7,8 @@ //! - [`event`]: the communication between the modules (see //! `src/event/README.md`). //! - [`http`]: the HTTP API (ADJ catalogs and the WebSocket upgrade). +//! - [`logging`]: recording configuration, sessions, and event consumption. pub mod event; pub mod http; +pub mod logging; diff --git a/backend/crates/station/src/logging.rs b/backend/crates/station/src/logging.rs index 816819c9d..902d90cb3 100644 --- a/backend/crates/station/src/logging.rs +++ b/backend/crates/station/src/logging.rs @@ -1,16 +1,19 @@ //! Backend recording policy, built on `software_core::logger`. //! -//! This is the module scaffold; recording and frontend integration are not -//! implemented yet. The file writers stay in `software_core::logger`; this -//! module will decide what to record, where it belongs and when to flush it. +//! Configuration, run directories, session metadata and clocks are implemented. +//! Recording, the writer and frontend integration are not implemented yet. +//! File writing stays in `software_core::logger`; this module decides what +//! to record, where it belongs and when to flush it. +//! The full specification and pending decisions are in `logging/README.md`. //! //! Planned lifecycle: //! - At backend startup, create a `YYYY-MM-DDTHH-MM-SS` directory and its //! `others/` directory for the ADJ validator output, settings and JSONL trace. //! - `play` prepares a new recording session and enables event admission. //! - `stop` stops admission, drains accepted events and closes session files. -//! - `emergency_stop` performs the same drain during backend shutdown, then -//! finishes the writer and flushes the backend trace. +//! - `emergency_stop` performs the same drain on frontend disconnection or +//! backend shutdown. Backend shutdown also finishes the writer and flushes +//! the backend trace; frontend disconnection must allow a later session. //! //! Session state, event admission and stop ordering must be coordinated so //! that an accepted event cannot leak into a later session. The frontend @@ -25,3 +28,10 @@ mod protections; mod session; mod settings; mod writer; + +pub use error::Error; +pub use session::{BackendRun, Session}; +pub use settings::{Config, Settings, TimeUnit}; + +#[cfg(test)] +mod tests; diff --git a/backend/crates/station/src/logging/error.rs b/backend/crates/station/src/logging/error.rs index adf643342..52700c64e 100644 --- a/backend/crates/station/src/logging/error.rs +++ b/backend/crates/station/src/logging/error.rs @@ -4,3 +4,33 @@ //! queue saturation, writer failure and invalid session transitions. Shutdown //! must attempt to close all files even if closing one of them fails, and //! return failures to the caller rather than report a successful stop. + +use std::{io, path::PathBuf}; + +/// Errors preparing logging settings, directories and sessions. +#[derive(Debug, thiserror::Error)] +pub enum Error { + /// A filesystem operation failed. The path identifies its destination. + #[error("couldn't {operation} at {path:?}: {source}")] + Io { + /// Operation being attempted. + operation: &'static str, + /// Destination of the operation. + path: PathBuf, + /// Underlying filesystem error. + #[source] + source: io::Error, + }, + /// A session destination is a file or symlink rather than a directory. + #[error("refusing to replace a session path that is not a directory: {0:?}")] + InvalidSessionPath(PathBuf), + /// The session selection could not be represented as JSON. + #[error("couldn't serialize the logging selection: {0}")] + Selection(#[from] serde_json::Error), + /// A date could not be converted to the recording timezone. + #[error("couldn't determine the logging date in Europe/Madrid: {0}")] + Date(#[from] jiff::Error), + /// The shared logger could not write the metadata file. + #[error(transparent)] + Logger(#[from] software_core::logger::Error), +} diff --git a/backend/crates/station/src/logging/session.rs b/backend/crates/station/src/logging/session.rs index a7bef0f8a..060bd068e 100644 --- a/backend/crates/station/src/logging/session.rs +++ b/backend/crates/station/src/logging/session.rs @@ -2,13 +2,230 @@ //! //! Every successful `play` starts a separate session directory named //! `YYYY-MM-DDTHH-MM-SS` below the backend startup directory. Each session has -//! `logger-settings.json` and `data/`, `protections/`, `order/`, `messages/`. +//! `logger_settings.json` and `data/`, `protections/`, `order/`, `messages/`. //! -//! A monotonic `std::time::Instant` will establish the session's zero point. +//! A monotonic `std::time::Instant` establishes the session's zero point. //! Recorded elapsed times use the configured time unit; the first event need //! not occur at zero. Wall-clock time is used separately for directory names -//! and order timestamps. Directory creation must never overwrite an earlier -//! session when two starts fall in the same second. +//! and order timestamps. A new session with an existing directory name +//! overwrites that session, without retaining files from its old selection. //! //! Planned states: inactive, starting, recording and stopping. A normal stop //! preserves the backend-wide `others/` files for subsequent sessions. + +use std::{ + fs, io, + path::{Path, PathBuf}, + time::Instant, +}; + +use jiff::Timestamp; +use serde::Serialize; +use serde_json::Value; +use software_core::logger::write_json; + +use super::{Config, Error, Settings}; + +const SETTINGS_FILE: &str = "logger_settings.json"; + +/// Directory and metadata for one backend execution. +/// +/// This is filesystem preparation, not the recording service: it does not +/// start a writer, open CSVs or implement `play`/`stop`. The future service +/// must close the previous session before preparing a replacement. +#[derive(Debug)] +pub struct BackendRun { + directory: PathBuf, + settings: Settings, +} + +impl BackendRun { + /// Creates a run directory with the current date and backend metadata. + /// + /// Blocking: call during startup or on the future writer thread. + pub fn new(config: Config, adj_commit_hash: impl Into) -> Result { + Self::new_at(config, adj_commit_hash, Timestamp::now()) + } + + /// Uses a startup time captured by the caller, before ADJ acquisition. + /// + /// Dates use `Europe/Madrid`, including its daylight-saving rules. A run + /// directory that already exists is an error rather than a shared run. + pub fn new_at( + config: Config, + adj_commit_hash: impl Into, + started_at: Timestamp, + ) -> Result { + let date = directory_date(started_at)?; + let root = if config.logging_path.is_absolute() { + config.logging_path + } else { + let cwd = std::env::current_dir().map_err(|source| Error::Io { + operation: "resolve the working directory", + path: config.logging_path.clone(), + source, + })?; + cwd.join(config.logging_path) + } + .join("logger"); + + create_directories(&root)?; + let directory = root.join(&date); + fs::create_dir(&directory).map_err(|source| Error::Io { + operation: "create the backend run directory", + path: directory.clone(), + source, + })?; + + let settings = Settings { + adj_commit_hash: adj_commit_hash.into(), + time_unit: config.time_unit, + date, + }; + write_json(directory.join("others").join(SETTINGS_FILE), &settings)?; + Ok(Self { + directory, + settings, + }) + } + + /// Absolute path of `logger//`. + pub fn directory(&self) -> &Path { + &self.directory + } + + /// Metadata written in `others/logger_settings.json`. + pub fn settings(&self) -> &Settings { + &self.settings + } + + /// Prepares session directories and settings using the current time. + /// + /// `selected_variables` is serialized unchanged, leaving its schema to + /// the application layer. No WebSocket event or payload type is required. + /// This performs blocking filesystem work and overwrites a previous + /// session with the same timestamp. The caller must finish that session + /// and close all of its files first. + pub fn prepare_session( + &mut self, + selected_variables: impl Serialize, + ) -> Result { + self.prepare_session_at(selected_variables, Timestamp::now(), Instant::now()) + } + + /// Captures the wall and monotonic clocks at the same session boundary. + fn prepare_session_at( + &mut self, + selected_variables: impl Serialize, + started_at: Timestamp, + clock_origin: Instant, + ) -> Result { + // Validate serialization before removing any existing session. + let selected_variables = serde_json::to_value(selected_variables)?; + let mut settings = self.settings.clone(); + settings.date = directory_date(started_at)?; + let directory = self.directory.join(&settings.date); + + match fs::symlink_metadata(&directory) { + Ok(metadata) if metadata.is_dir() => { + fs::remove_dir_all(&directory).map_err(|source| Error::Io { + operation: "replace the previous session directory", + path: directory.clone(), + source, + })?; + } + Ok(_) => return Err(Error::InvalidSessionPath(directory)), + Err(error) if error.kind() == io::ErrorKind::NotFound => {} + Err(source) => { + return Err(Error::Io { + operation: "inspect the session directory", + path: directory, + source, + }); + } + } + + for name in ["data", "protections", "order", "messages"] { + create_directories(&directory.join(name))?; + } + let metadata = SessionSettings { + settings, + selected_variables, + }; + write_json(directory.join(SETTINGS_FILE), &metadata)?; + + Ok(Session { + directory, + metadata, + clock_origin, + }) + } +} + +/// Prepared session metadata and its monotonic clock; no CSVs are open yet. +#[derive(Debug)] +pub struct Session { + directory: PathBuf, + metadata: SessionSettings, + clock_origin: Instant, +} + +#[derive(Debug, Serialize)] +struct SessionSettings { + #[serde(flatten)] + settings: Settings, + selected_variables: Value, +} + +impl Session { + /// Absolute path of the session directory. + pub fn directory(&self) -> &Path { + &self.directory + } + + /// Common metadata, with the session's start date. + pub fn settings(&self) -> &Settings { + &self.metadata.settings + } + + /// Selection serialized unchanged into this session's metadata. + pub fn selected_variables(&self) -> &Value { + &self.metadata.selected_variables + } + + /// Elapsed time for an event captured before it enters the writer queue. + /// + /// An event predating this session returns `None`, not a fabricated zero. + /// The future service must also check the event's session identity. + pub fn instant_at(&self, received_at: Instant) -> Option { + received_at + .checked_duration_since(self.clock_origin) + .map(|elapsed| self.metadata.settings.time_unit.convert(elapsed)) + } + + /// Current elapsed session time in the configured unit. + pub fn elapsed(&self) -> u128 { + self.metadata + .settings + .time_unit + .convert(self.clock_origin.elapsed()) + } +} + +fn directory_date(timestamp: Timestamp) -> Result { + Ok(timestamp + .in_tz("Europe/Madrid")? + .strftime("%Y-%m-%dT%H-%M-%S") + .to_string()) +} + +fn create_directories(path: &Path) -> Result<(), Error> { + fs::create_dir_all(path).map_err(|source| Error::Io { + operation: "create logging directories", + path: path.to_path_buf(), + source, + }) +} + +#[cfg(test)] +mod tests; diff --git a/backend/crates/station/src/logging/settings.rs b/backend/crates/station/src/logging/settings.rs index 369e82d32..9162897b0 100644 --- a/backend/crates/station/src/logging/settings.rs +++ b/backend/crates/station/src/logging/settings.rs @@ -1,10 +1,79 @@ -//! Backend and recording-session `logger-settings.json` metadata. +//! Backend and recording-session `logger_settings.json` metadata. //! //! Backend settings in `others/` contain `adj_commit_hash`, `time_unit` and //! `date`, where `date` matches the backend startup directory name. +//! Time units match the frontend: `ns`, `us`, `ms`, `s`; its default is `us`. +//! CSV instants are integers in the chosen unit. //! Session settings preserve that metadata, replace `date` with the session //! directory name and add `selected_variables`. The representation of that //! selection remains to be defined. //! -//! Settings will be written through `software_core::logger::write_json` or -//! `software_core::logger::JsonDocument`, allowing the metadata to grow later. +//! Settings are written through `software_core::logger::write_json`. +//! The metadata schema can grow independently of the frontend integration. + +use std::{path::PathBuf, time::Duration}; + +use serde::{Deserialize, Serialize}; + +/// Fields of the application's `[logging]` configuration section. +/// +/// Relative and empty paths are resolved against the backend's working +/// directory, matching the old backend. `logger/` is added to this path. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct Config { + /// Unit of all elapsed instants recorded during a session. + pub time_unit: TimeUnit, + /// Directory that will contain `logger//`. + pub logging_path: PathBuf, +} + +impl Default for Config { + fn default() -> Self { + Self { + time_unit: TimeUnit::default(), + logging_path: PathBuf::from("."), + } + } +} + +/// Time units supported by the frontend. Sub-unit fractions are truncated. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum TimeUnit { + /// Nanoseconds. + #[serde(rename = "ns")] + Nanoseconds, + /// Microseconds, the frontend's default. + #[default] + #[serde(rename = "us")] + Microseconds, + /// Milliseconds. + #[serde(rename = "ms")] + Milliseconds, + /// Seconds. + #[serde(rename = "s")] + Seconds, +} + +impl TimeUnit { + /// Converts elapsed time to an integer without narrowing or floating point. + pub fn convert(self, elapsed: Duration) -> u128 { + match self { + Self::Nanoseconds => elapsed.as_nanos(), + Self::Microseconds => elapsed.as_micros(), + Self::Milliseconds => elapsed.as_millis(), + Self::Seconds => u128::from(elapsed.as_secs()), + } + } +} + +/// Metadata common to backend runs and logging sessions. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct Settings { + /// Commit of the ADJ used by the backend. + pub adj_commit_hash: String, + /// Unit for the CSV `instant` fields. + pub time_unit: TimeUnit, + /// Start date, matching the owning directory's name. + pub date: String, +} From bd934c3b84a1704e3335d673c74ec34eed3bec5d Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Wed, 2 Dec 2026 20:09:47 +0100 Subject: [PATCH 175/225] refactor(backend, logging): adapt event input --- backend/crates/core/src/logger/csv.rs | 6 + backend/crates/station/src/logging.rs | 73 ++- backend/crates/station/src/logging/README.md | 305 +++++++++-- backend/crates/station/src/logging/catalog.rs | 184 +++++++ backend/crates/station/src/logging/control.rs | 25 + backend/crates/station/src/logging/data.rs | 97 +++- backend/crates/station/src/logging/error.rs | 32 +- backend/crates/station/src/logging/event.rs | 8 - .../crates/station/src/logging/messages.rs | 56 +- backend/crates/station/src/logging/order.rs | 56 +- backend/crates/station/src/logging/output.rs | 50 ++ .../crates/station/src/logging/protections.rs | 108 +++- backend/crates/station/src/logging/service.rs | 149 +++++ .../station/src/logging/service/tests.rs | 382 +++++++++++++ backend/crates/station/src/logging/session.rs | 69 ++- .../station/src/logging/session/tests.rs | 172 ++++++ backend/crates/station/src/logging/status.rs | 98 ++++ backend/crates/station/src/logging/writer.rs | 509 +++++++++++++++++- .../station/src/logging/writer/tests.rs | 218 ++++++++ 19 files changed, 2471 insertions(+), 126 deletions(-) create mode 100644 backend/crates/station/src/logging/catalog.rs create mode 100644 backend/crates/station/src/logging/control.rs delete mode 100644 backend/crates/station/src/logging/event.rs create mode 100644 backend/crates/station/src/logging/output.rs create mode 100644 backend/crates/station/src/logging/service.rs create mode 100644 backend/crates/station/src/logging/service/tests.rs create mode 100644 backend/crates/station/src/logging/session/tests.rs create mode 100644 backend/crates/station/src/logging/status.rs create mode 100644 backend/crates/station/src/logging/writer/tests.rs diff --git a/backend/crates/core/src/logger/csv.rs b/backend/crates/core/src/logger/csv.rs index 8c2fbd723..16cdfca1c 100644 --- a/backend/crates/core/src/logger/csv.rs +++ b/backend/crates/core/src/logger/csv.rs @@ -255,6 +255,12 @@ impl Row<'_, W> { self.number(format_args!("{value}")) } + /// Appends the instant field. Cannot use `Self::int()`, + /// because an instant is an u128 + pub fn instant(self, value: u128) -> Self { + self.number(format_args!("{value}")) + } + /// Appends a boolean field, as `true` or `false`. pub fn bool(self, value: bool) -> Self { self.number(format_args!("{value}")) diff --git a/backend/crates/station/src/logging.rs b/backend/crates/station/src/logging.rs index 902d90cb3..4643787c1 100644 --- a/backend/crates/station/src/logging.rs +++ b/backend/crates/station/src/logging.rs @@ -1,37 +1,88 @@ //! Backend recording policy, built on `software_core::logger`. //! -//! Configuration, run directories, session metadata and clocks are implemented. -//! Recording, the writer and frontend integration are not implemented yet. +//! Configuration, session metadata, CSV recording, event consumption and the +//! dedicated writer are implemented. Frontend and startup integration remain +//! the application's responsibility. //! File writing stays in `software_core::logger`; this module decides what //! to record, where it belongs and when to flush it. //! The full specification and pending decisions are in `logging/README.md`. //! -//! Planned lifecycle: +//! Lifecycle: //! - At backend startup, create a `YYYY-MM-DDTHH-MM-SS` directory and its //! `others/` directory for the ADJ validator output, settings and JSONL trace. -//! - `play` prepares a new recording session and enables event admission. -//! - `stop` stops admission, drains accepted events and closes session files. +//! - `play` prepares a new recording session after discarding inactive backlog. +//! - `stop` drains the ready input prefix up to its reception-time cutoff, +//! flushes buffers and closes session files. //! - `emergency_stop` performs the same drain on frontend disconnection or //! backend shutdown. Backend shutdown also finishes the writer and flushes //! the backend trace; frontend disconnection must allow a later session. //! -//! Session state, event admission and stop ordering must be coordinated so -//! that an accepted event cannot leak into a later session. The frontend -//! receives success only after the requested transition has completed. +//! The writer owns session state and consumes event's existing bounded channel +//! directly. Independent lifecycle controls remain usable when data is full. +//! Async controls return after their transition completes; observers receive +//! status snapshots through a watch channel. Input stays open between sessions. +mod catalog; +mod control; +mod output; mod data; mod error; -mod event; mod messages; mod order; mod protections; +mod service; mod session; mod settings; +mod status; mod writer; +pub use crate::event::ToLogging; pub use error::Error; -pub use session::{BackendRun, Session}; +pub use service::Logging; +pub use session::{BackendRun, MeasurementKey, Session, SessionId, SessionSelection}; pub use settings::{Config, Settings, TimeUnit}; +pub use status::{Phase, SessionInfo, Status, StatusReceiver, StopReason, StopReport}; +pub use writer::WriterOptions; #[cfg(test)] -mod tests; +mod tests { + + use super::{Config, TimeUnit}; + use serde_json::json; + use std::time::Duration; + + type TestResult = Result<(), Box>; + + #[test] + fn config_matches_frontend_units_and_rejects_unknown_units() -> TestResult { + let units = [ + ("ns", TimeUnit::Nanoseconds), + ("us", TimeUnit::Microseconds), + ("ms", TimeUnit::Milliseconds), + ("s", TimeUnit::Seconds), + ]; + for (name, unit) in units { + let config: Config = toml::from_str(&format!( + "time_unit = {name:?}\nlogging_path = \"recordings\"" + ))?; + assert_eq!(config.time_unit, unit); + assert_eq!(serde_json::to_value(unit)?, json!(name)); + } + assert!(toml::from_str::("time_unit = \"minutes\"").is_err()); + assert_eq!(toml::from_str::("")?, Config::default()); + Ok(()) + } + + #[test] + fn integer_conversion_truncates_fractions_without_overflow() { + let elapsed = Duration::new(2, 35_123_456); + assert_eq!(TimeUnit::Seconds.convert(elapsed), 2); + assert_eq!(TimeUnit::Milliseconds.convert(elapsed), 2035); + assert_eq!(TimeUnit::Microseconds.convert(elapsed), 2_035_123); + assert_eq!(TimeUnit::Nanoseconds.convert(elapsed), 2_035_123_456); + assert_eq!( + TimeUnit::Nanoseconds.convert(Duration::MAX), + Duration::MAX.as_nanos() + ); + } +} diff --git a/backend/crates/station/src/logging/README.md b/backend/crates/station/src/logging/README.md index ac3a61966..62cefe79d 100644 --- a/backend/crates/station/src/logging/README.md +++ b/backend/crates/station/src/logging/README.md @@ -7,14 +7,141 @@ Write operations use ## Current Status -The module currently consists of a scaffold with documented responsibilities. -It is declared in `main.rs`, and `station` enables the `logger` feature of -`software-core`. +This is a work-in-progress adaptation to `event` on `backend/net`, reviewed +against the local `origin/backend/net` commit `99a31ba6`. -The logging service, control functions, writer, event formats, and integration -with the frontend and backend startup are not implemented yet. The following -sections describe the agreed requirements and planned design, rather than -features that are already operational. +The input contract is `tokio::sync::mpsc::Receiver`. The +application passes a shared `Arc` and `Arc` to `Logging`. +The CSV writers consume decoded `model` packets and borrow their metadata from +these shared definitions; callers no longer assemble `DataRecord`, +`ProtectionRecord`, `MessageRecord` or `OrderRecord` DTOs. + +**This branch does not yet contain `station::event` or `core::net`.** The +references to those modules intentionally target their real types from +`backend/net`. No duplicate contracts or temporary stubs have been added. +Compilation in this branch and migration of the existing tests are deferred +until the incoming changes have been merged. The production library has also +been checked in a temporary combination with that branch, outside this checkout. + +Session preparation and the buffer lifecycle are retained. The writer now +consumes event's existing bounded channel directly, with no second data queue +or forwarding task. The application's channel for `play`, `stop` and +`emergency_stop` is still to be defined. Startup integration, trace setup and +the validator remain pending. + +### Input and Shared ADJ + +`event` creates the inter-module queue and passes its receiver to logging: + +```text +event -> mpsc -> writer thread -> logger -> CSV + ^ + ADJ / Index +``` + +`service.rs` is a small lifecycle facade. The writer owns session state and all +CSV handles. A separate internal channel carries lifecycle requests, so controls +do not need a free slot in the data channel. `status.rs` exposes snapshots and +notifications through a Tokio watch channel. There is no manual `record` or +capture API: the writer uses the reception timestamp carried by each event. +The application's future control-channel contract remains separate from these +internal controls. + +`ToLogging` has these variants in the reviewed branch: + +- `Received(Arc)`: carries `board: BoardId`, `at: SystemTime` + and a connection event or a decoded `Packet`. +- `OrderSent { at, board, order }`: confirms that an order was written to TCP. + +`Catalog` keeps the supplied ADJ and protocol index shared. It builds a small +measurement locator once, using `(BoardId, AdjId)` as keys. It resolves: + +- Board names from `Adj::pod_data`. +- Positional data values through the packet's ADJ measurement definitions. +- Measurement aliases for CSV filenames, while filters and file maps use IDs. +- Protection severity, kind, thresholds and associated measurement from ADJ. +- Message severity through the supplied `protocol::Index`; message origin and + text are borrowed directly from `MessagePacket`. + +The supplied ADJ and Index must describe the same checkout used by networking. +Unknown IDs, board/packet mismatches and invalid data value counts are rejected +before writing CSV rows. Connection notifications are consumed without a CSV +row; they do not define a session-control protocol. + +### Available Internal API + +`Config` represents `[logging]`, defaulting to `time_unit = "us"` and +`logging_path = "."`. Supported units are `ns`, `us`, `ms` and `s`. + +`BackendRun::new(config, adj_commit_hash)` creates the run directory and writes +`others/logger_settings.json`. `new_at` accepts an earlier startup timestamp. +Dates use `Europe/Madrid`, including daylight-saving rules. A colliding backend +run directory is an error; a colliding session directory is replaced. + +`Logging::new(run, adj, index, receiver, options)` starts the writer thread and +moves event's receiver into it. +Share the service through `Arc`. + +The writer keeps consuming events while inactive, so stopping a session does +not close event's receiver. Input channel closure flushes the active session +and ends the worker. `shutdown()` also closes input and joins the worker. + +`SessionSelection` contains `MeasurementKey { board: BoardId, measurement_id: +AdjId }`, connected board IDs, and the original selection JSON. Its control +payload is pending. Selection validation resolves names and aliases through +ADJ before any existing session directory is replaced. + +The existing internal methods remain available: `play`, `stop`, +`emergency_stop`, `shutdown`, `status` and `subscribe`. They have not been +connected to a new frontend control channel. + +### Example of the Data-Channel Wiring + +This example does not start a session: session control will be specified later. +The consumer can already run and drain notifications while inactive. + +```rust +use std::sync::Arc; +use software_core::{adj::Adj, protocol::Index}; +use station::{event::ToLogging, logging::{BackendRun, Error, Logging, WriterOptions}}; +use tokio::sync::mpsc; + +fn start_logging_consumer( + run: BackendRun, + adj: Arc, + index: Arc, + receiver: mpsc::Receiver, +) -> Result, Error> { + Ok(Arc::new(Logging::new( + run, adj, index, receiver, WriterOptions::default(), + )?)) +} +``` + +### Contract Follow-ups + +These are deliberately not filled in with reconstructed or guessed data: + +- **Orders:** `OrderSent` is later than frontend reception and contains no + original JSON text. The consumer reports this pending contract once and + keeps draining. It does not write misleading order rows. The order file + and formatter are retained for the eventual original-payload input. +- **Accumulated protection timing:** the current `ProtectionPacket` has no + separate accumulated-time result. Untimed protections write `0`; timed + protections temporarily leave that cell empty to mean unavailable. The + configured ADJ duration is not presented as a result sent by the board. +- **Reception clock:** upstream supplies `SystemTime`, not a monotonic stamp. + The event path calculates elapsed time from the supplied reception time and + the session's wall-clock origin. Events older than the session are rejected. + This preserves queue delay correctly but inherits wall-clock adjustments; + adding monotonic reception time remains an event-contract follow-up. +- **Saturation:** the writer stops recording when it observes event's data + channel at full capacity. Event currently uses awaited sends with + backpressure: a transient full condition can clear before the writer observes + it. Detecting every producer-side full condition would require a change to + that input contract. +- **Controls:** the session-control channel and multi-frontend disconnect rule + remain pending. ## File Structure for a Backend Run @@ -26,7 +153,7 @@ Each session is created when **Start logger** is pressed in the frontend. Its directory uses the same format, but with the session's start date and time. ```text -/ +/logger/ └── 2026-11-27T15-30-00/ # Backend startup ├── others/ │ ├── .txt @@ -51,12 +178,14 @@ directory uses the same format, but with the session's start date and time. Names inside `<...>` are placeholders, not final filenames. The exact names of the validator TXT file and the trace JSONL file are still pending. +Relative and empty `logging_path` values are resolved against the backend's +working directory, matching the old backend's behavior. + If a new session has the same name as an existing one, the agreed behavior is to overwrite it. Replacement must avoid mixing old files with the new session's selection. A collision can occur when starting, stopping, and starting again -within the same second. Handling another `play()` while a session is active -remains undecided; ignoring it has been proposed to prevent a double click -from truncating an ongoing session. +within the same second. Another `play()` while a session is active returns +the existing session unchanged, preventing a double click from truncating it. ## Metadata: logger_settings.json @@ -96,7 +225,7 @@ The selection may change between sessions. Only selected variables are recorded, and only files corresponding to that selection are created; no CSV files are created for unselected measurements. -Metadata will be written using `logger::write_json` or `logger::JsonDocument`. +Metadata is written using `logger::write_json`. ## Record Timing @@ -111,9 +240,11 @@ the first row to contain zero: if the first measurement arrives 35 ms after startup, its `instant` will be `35` with `time_unit = "ms"`, or `35000` with `"us"`. -A monotonic clock (`std::time::Instant`) is planned as the session's time -origin. The instant must be captured when the event is received, before -queuing it, so that writing delays do not change the recorded time. +The low-level session retains its monotonic clock for elapsed-time helpers. The +`ToLogging` path uses the upstream `Notification::at` (`SystemTime`) against +the session's wall-clock origin, so queue delays are not added to `instant`. +A monotonic timestamp at original reception is not available in the current +event contract; immunity to wall-clock changes therefore remains pending. The units verified in the frontend are: @@ -190,9 +321,10 @@ instant,from,to,id,payload,timestamp | `payload` | JSON received from the frontend over WebSocket, preserved as text. | | `timestamp` | Order date and time, using the format and offset described above. | -An order is recorded **when it is received from the frontend**. Recording does -not wait for it to be sent to the board or for execution confirmation. Its -times are captured at that point of reception. +The required behavior is to record an order **when received from the frontend**, +with the original JSON. The current `ToLogging::OrderSent` cannot satisfy that +contract, so writing order rows is deferred rather than substituting a later +timestamp or reconstructed payload. ### Protections: protections/ @@ -225,9 +357,10 @@ instant,from,to,protection_id,severity,protection_type,threshold_1,threshold_2,m Both threshold fields are always present, even when the second one is empty. The thresholds and the value that triggered the event are separate fields. -The `timeacumulation` data comes from the board. It is not calculated from the -session clock or `time_unit`; its extraction remains to be specified when -integrating the received packet with recording. +The required `timeacumulation` result must come from the board, not the session +clock, `time_unit`, or the configured ADJ duration. The current model lacks +that result: for now a timed protection's cell is empty (unavailable), while +an untimed protection still writes `0`. Completing this field remains pending. ### Messages: messages/messages.csv @@ -255,17 +388,19 @@ another column or reconstructing its format. ## Frontend Control and Shutdown -The planned functions are `play()`, `stop()`, and `emergency_stop()`. Their -signatures are not implemented yet, and no WebSocket control protocol has -been defined. +The internal functions are `play()`, `stop()`, and `emergency_stop()`. +The `websocket`, `event`, and `payload` +modules in the PR under review will connect this internal API to the frontend; +this module does not define a separate WebSocket control protocol. ### play() Prepares a new session's directory, settings, variable selection, and files. -Establishes the time origin and starts accepting records once the session -is ready. +Discards the finite inactive backlog, establishes the time origin and starts +writing records once the session is ready. Events with older reception times +are ignored even if they arrive later. -The planned states are: +The states are: ```text Inactive -> Starting -> Recording -> Stopping -> Inactive @@ -275,8 +410,9 @@ Inactive -> Starting -> Recording -> Stopping -> Inactive Stops the session in this order: -1. Stops accepting new records for that session. -2. Processes all events already accepted into the queue. +1. Captures the stop request's reception-time cutoff. +2. Processes the finite number of ready events observed when handling the + control, excluding events timestamped after that cutoff. 3. Flushes the buffers and closes the session files. 4. Returns the stop result to the frontend. @@ -284,6 +420,14 @@ Pending events from one session must not be written into another. The `others/` directory belongs to the backend run and is preserved between sessions. +The writer serializes control calls and gives them priority over data. +Cancelling a control future does not cancel a queued transition or its drain. +Controls use their own channel and remain usable when data capacity is +exhausted. The stop drain has a fixed size, so producers cannot extend it +indefinitely. The input receiver stays open and resumes consuming without +recording. Sends that have not yet queued a ready event at the stop boundary +are outside that drain. + ### emergency_stop() Used when the backend shuts down and also when the frontend closes or @@ -294,23 +438,28 @@ If the backend remains running after the frontend disconnects, starting another session later must be possible. The trace belongs to the backend and may remain active; its final flush takes place during backend shutdown. +Backend shutdown should finish with `shutdown().await` to join the writer. +The application must separately flush its trace when that integration exists. +`Drop` provides a synchronous fallback drain and join, while explicit controls +are required to receive write errors. + When multiple frontends are connected, it remains undecided whether a session stops when any frontend disconnects or only when the frontend that started it disconnects. ## Efficient Writing -The planned design uses a dedicated thread for synchronous +The service uses a dedicated thread for synchronous `software_core::logger` writes, separate from asynchronous network tasks: ```text Event reception | v -Capture instant and associate with session +Attach reception timestamp | v -Queue with limited capacity +Event's existing bounded mpsc channel | v Writer thread and format components @@ -322,31 +471,51 @@ software_core::logger Buffered files ``` -The writer will own the files. It will keep them open throughout the session -and reuse the buffers already provided by `logger`, avoiding opening, writing, +The writer owns the files. It keeps them open throughout the session +and reuses the buffers already provided by `logger`, avoiding opening, writing, and closing a file for every record. -Buffers are planned to be flushed periodically and when a byte threshold is -reached, using `bytes_since_flush()`. Exact capacities and intervals will be -chosen during implementation. Stopping must explicitly call -`flush()`/`close()` and report errors, rather than relying solely on `Drop`. +Buffers are flushed periodically and when a per-file byte threshold is reached, +using `bytes_since_flush()`. After each row, only the affected file is checked; +periodic flushing visits dirty files. A private Tokio runtime on the writer +thread waits for events, controls and flush deadlines. When inactive, it drains +events without writing them. Stopping explicitly closes every file and reports +errors. + +`WriterOptions` configures these initial defaults: + +| Option | Default | +| --- | --- | +| `flush_interval` | 250 ms | +| `flush_bytes` | 64 KiB per file | + +Both limits must be positive. Data capacity belongs to event's +`EventConfig::logging_queue`; logging does not configure another queue. +Control commands do not consume data capacity. CSV row buffers are reused. +Unsigned integer fields preserve the +session clock's `u128` values without narrowing or converting to floating point. ### Queue Saturation If records arrive faster than they can be written for long enough to fill -the queue, the agreed behavior is to **stop logging and notify the frontend**: +the channel, the writer stops logging when it observes that full condition: -1. Stop accepting new records. -2. Write records that have already been accepted. +1. Begin stopping the session. +2. Write the ready input prefix at the stop boundary. 3. Flush and close the session files. 4. Indicate that the session ended because of saturation. -The backend continues running. Records must not keep being silently dropped -while the session is presented as active. +The backend continues running and the receiver remains open. `status` and +`subscribe` expose `StopReason::Saturation` for the application to notify the +frontend. As noted above, transient producer-side full conditions can escape +observation with the current input contract. -A write error must be reported and cannot be treated as a successful stop. -The exact policy for disk failures and frontend status messages remains -undecided. +A write or flush error also stops recording. The writer attempts the ready +input prefix and closes every file, including healthy files after another +file fails. The stop report contains the errors and uses `StopReason::WriteError`; +`stop`, `emergency_stop` and `shutdown` return an error instead of reporting a +successful drain. Failed files cannot be assumed to contain all accepted data. +The frontend notification format remains the application adapter's concern. ## Files in others/ @@ -366,18 +535,22 @@ were left undecided**. This flow has not been implemented in the new backend. ## Responsibilities of Module Files -| File | Planned responsibility | +| File | Responsibility | | --- | --- | -| `../logging.rs` | Logging service, coordination, and control API. | -| `session.rs` | Identity, paths, clock, and state of each session. | +| `../logging.rs` | Public API exports. | +| `catalog.rs` | Shared ADJ/Index lookups and measurement locators. | +| `service.rs` | Small public facade for construction, lifecycle controls and status access. | +| `control.rs` | Private writer lifecycle requests and acknowledgements. | +| `status.rs` | Public lifecycle snapshots, stop reports and notifications. | +| `session.rs` | Selection, identity, paths and clocks of each session; writer stamps are private. | | `settings.rs` | Backend run and session metadata. | -| `event.rs` | Typed events with their instant and target session. | -| `writer.rs` | Bounded queue, writer thread, flushing, and orderly shutdown. | +| `writer.rs` | Event consumer, session state, CSV ownership, flushing, and shutdown. | +| `csv.rs` | Shared value formatting and flush/close error handling. | | `data.rs` | Measurement files by board and variable. | | `protections.rs` | Protection files by board. | | `order.rs` | Order recording in a single CSV. | | `messages.rs` | Message recording in a single CSV. | -| `error.rs` | Configuration, session, queue, and write errors. | +| `error.rs` | Configuration, session, control, and write errors. | `station::logging` knows about the ADJ, boards, selections, and sessions. `software_core::logger` provides CSV, text, and JSON writing, field escaping, @@ -388,9 +561,27 @@ buffers, and explicit flush and close operations. - Names of the validator TXT file and trace JSONL file. - Running `adj-validator` and obtaining its output. - Trace levels and filters, and their connection to the JSONL file. -- Exact schema of `selected_variables` in JSON and frontend control. -- Final position of the text column in `messages.csv`. -- Behavior of repeated `play()` calls during an active session. +- Exact schema of `selected_variables` in JSON and the session-control channel. +- Original order JSON and frontend reception time in the input contract. +- Board-supplied accumulated timing and monotonic reception timestamps. - Disconnection stop rule when multiple frontends are connected. -- Write error policy and frontend notification format. -- Queue/buffer capacities, flush intervals, and configuration parameters. +- Frontend notification format and integration through the application modules. +- Wiring `WriterOptions` into application configuration if these defaults need UI controls. + +## Verification During This Adaptation + +`rustfmt` and `git diff --check` validate syntax formatting and whitespace. +The production library is also checked in a temporary workspace combining +these changes with the reviewed `backend/net` source, without merging it into +this checkout. + +The old logging tests still use the former DTO-based API. Their migration and +full test execution are intentionally deferred until the branches are joined. +Do not treat this WIP commit as a passing standalone build before `event` and +`core::net` are brought in. + +`cargo test -p station --test logging_service --offline` checks the native event +API in a workspace that includes those dependencies. It covers session restart, +old reception timestamps, invalid selections, pending-record drains and +controls awaited from spawned Tokio tasks. It also checks stopping while the +producer keeps sending, a one-slot data channel, and input-closure flushing. diff --git a/backend/crates/station/src/logging/catalog.rs b/backend/crates/station/src/logging/catalog.rs new file mode 100644 index 000000000..09ab9cc26 --- /dev/null +++ b/backend/crates/station/src/logging/catalog.rs @@ -0,0 +1,184 @@ +//! Read-only ADJ lookups for input validation and CSV writing. +//! +//! Notifications carry board/packet IDs and decoded values. This catalog +//! resolves the labels and definitions needed to validate those notifications +//! and write CSV rows. The supplied ADJ and protocol Index must describe the +//! same checkout that networking used to decode the packets. + +use std::{collections::HashMap, sync::Arc}; + +use software_core::{ + adj::Adj, + model::{AdjId, Board, BoardId, Measurement, MessageLevel, Packet, PacketType, Protection}, + net::Event, + protocol::Index, +}; + +use crate::event::ToLogging; + +use super::Error; + +/// Keep ADJ labels to a single filename component on supported platforms. +pub(super) fn validate_name(name: &str) -> Result<(), Error> { + if name.is_empty() + || matches!(name, "." | "..") + || name.ends_with(['.', ' ']) + || name + .chars() + .any(|c| c.is_control() || "/\\:*?\"<>|".contains(c)) + { + return Err(Error::InvalidName(name.to_owned())); + } + Ok(()) +} + +/// Keeps the writer's definitions shared with the rest of the application. +/// Returned references borrow existing ADJ/Index entries; no packet metadata +/// needs to be copied into a separate logging record for every event. +#[derive(Debug)] +pub(super) struct Catalog { + /// Vehicle boards and their display/filesystem names. + adj: Arc, + /// Packet definitions, including the synthesized shared message severities. + index: Arc, + /// (Board ID, measurement ID) -> (data packet ID, position in that packet). + /// Store locators instead of self-references into the shared Index. + measurements: HashMap<(BoardId, AdjId), (AdjId, usize)>, +} + +impl Catalog { + /// Build measurement locators once when the logging service is constructed. + /// Only data measurements are eligible for the selected telemetry files; + /// order parameters and protection definitions are resolved through Index. + pub fn new(adj: Arc, index: Arc) -> Self { + let mut measurements = HashMap::new(); + for board in adj.pod_data.boards.values() { + for packet in board.packets.values() { + if let PacketType::Data(fields) = &packet.packet_type { + for (position, measurement) in fields.iter().enumerate() { + // Decoded data values use the same positional ordering + // as this ADJ measurement list. + measurements.insert((board.id, measurement.id), (packet.id, position)); + } + } + } + } + Self { + adj, + index, + measurements, + } + } + + /// Resolve a notification's numeric board ID to its ADJ board definition. + pub fn board(&self, id: BoardId) -> Result<&Board, Error> { + self.adj + .pod_data + .boards + .get(&id) + .ok_or(Error::UnknownBoard(id)) + } + + /// Find a selectable measurement without scanning all boards and packets. + /// The definition includes the textual alias used to name its CSV file. + pub fn measurement(&self, board: BoardId, id: AdjId) -> Result<&Measurement, Error> { + let &(packet, position) = self + .measurements + .get(&(board, id)) + .ok_or(Error::UnknownMeasurement { board, id })?; + // Resolve through the same Index used for incoming data. A missing or + // inconsistent locator is an error before session files are created. + self.data(board, packet)? + .get(position) + .ok_or(Error::UnknownMeasurement { board, id }) + } + + /// Centralize packet existence and ownership checks for all typed lookups. + fn definition(&self, board: BoardId, id: AdjId) -> Result<&PacketType, Error> { + self.board(board)?; + let packet = self.index.packet(id).ok_or(Error::UnknownPacket(id))?; + // Message severities are shared by all boards (reserved BoardId(0)), + // so their synthetic owner must not be compared with the sender board. + // Every other packet must belong to the board named by its notification. + if !matches!(packet.packet_type, PacketType::Message(_)) && packet.board != board { + return Err(Error::PacketBoardMismatch { board, id }); + } + Ok(&packet.packet_type) + } + + /// Return the ordered definitions to zip with a decoded DataPacket's values. + /// A known ID of another packet kind must not be interpreted as telemetry. + pub fn data(&self, board: BoardId, id: AdjId) -> Result<&[Measurement], Error> { + match self.definition(board, id)? { + PacketType::Data(measurements) => Ok(measurements), + _ => Err(Error::UnexpectedPacketType(id)), + } + } + + /// Resolve the watched measurement and the particular protection that fired. + /// The CSV writer uses their static metadata alongside the packet's actual + /// triggered value; the catalog does not recompute the board's decision. + pub fn protection( + &self, + board: BoardId, + id: AdjId, + ) -> Result<(&Measurement, &Protection), Error> { + let PacketType::Protection(measurement) = self.definition(board, id)? else { + return Err(Error::UnexpectedPacketType(id)); + }; + // The wire ID combines the measurement ID with a protection position + // in its high bits. Protection::id stores that position, not the full + // compound ID, so compare against the extracted position. + let protection = measurement + .protections + .iter() + .find(|protection| protection.id.0 == u16::from(id.protection_position())) + .ok_or(Error::UnknownPacket(id))?; + Ok((measurement, protection)) + } + + /// Interpret a message's wire ID through its synthesized Index definition. + /// The notification supplies the real sender board; the ID supplies severity. + pub fn message_level(&self, board: BoardId, id: AdjId) -> Result { + match self.definition(board, id)? { + PacketType::Message(level) => Ok(*level), + _ => Err(Error::UnexpectedPacketType(id)), + } + } + + /// Validate a received packet before writing any of its CSV rows. + /// Connection notifications have no CSV row. + /// `true` means the packet is structurally eligible for writing; measurement + /// selection is applied separately by the CSV writer. + pub fn validate(&self, incoming: &ToLogging) -> Result { + let ToLogging::Received(notification) = incoming else { + // OrderSent has neither the original JSON nor frontend reception time. + return Err(Error::OrderContractPending); + }; + // Board labels become directories or filenames, so validate the label + // from the ADJ before it can reach a file writer. + validate_name(&self.board(notification.board)?.name)?; + match ¬ification.event { + Event::Connected | Event::Disconnected => return Ok(false), + Event::Received(Packet::Data(packet)) => { + // Positional values must match the complete schema, even when + // only some measurements are selected. Reject mismatches before + // any rows from this packet can be written. + if self.data(notification.board, packet.id)?.len() != packet.values.len() { + return Err(Error::MeasurementCount(packet.id)); + } + } + Event::Received(Packet::Protection(packet)) => { + // Confirm both the measurement definition and protection slot. + self.protection(notification.board, packet.id)?; + } + Event::Received(Packet::Message(packet)) => { + self.message_level(notification.board, packet.id)?; + } + // Receiving a decoded order does not restore the missing original + // frontend JSON or establish its frontend reception timestamp. + Event::Received(Packet::Order(_)) => return Err(Error::OrderContractPending), + } + Ok(true) + } +} diff --git a/backend/crates/station/src/logging/control.rs b/backend/crates/station/src/logging/control.rs new file mode 100644 index 000000000..f1f59992e --- /dev/null +++ b/backend/crates/station/src/logging/control.rs @@ -0,0 +1,25 @@ +//! Private lifecycle requests, independent of the event data channel. +//! The frontend control-channel contract remains the application's concern. + +use std::time::SystemTime; + +use tokio::sync::oneshot; + +use super::{Error, SessionInfo, SessionSelection, StopReason, StopReport}; + +#[derive(Debug)] +pub(super) enum Control { + Play { + selection: SessionSelection, + reply: oneshot::Sender>, + }, + Stop { + reason: StopReason, + at: SystemTime, + reply: oneshot::Sender, Error>>, + }, + Shutdown { + at: SystemTime, + reply: Option>, + }, +} diff --git a/backend/crates/station/src/logging/data.rs b/backend/crates/station/src/logging/data.rs index d3b3dcfa8..a42f1b083 100644 --- a/backend/crates/station/src/logging/data.rs +++ b/backend/crates/station/src/logging/data.rs @@ -1,9 +1,88 @@ -//! Measurement recording under `data//.csv`. -//! -//! One directory per connected board and one CSV per selected measurement, -//! named with its textual identifier. Files have no header. Columns, in order: -//! `instant,from,to,value`. -//! -//! This component will own the measurement `software_core::logger::CsvFile` -//! handles and translate typed events into rows, reusing the logger's CSV -//! escaping, buffering and explicit flush/close operations. +//! Selected measurement CSVs. IDs stay numeric internally; filenames use ADJ aliases. + +use std::{collections::HashMap, path::Path}; + +use software_core::{ + logger::CsvFile, + model::{AdjId, Board, BoardId, DataPacket, Measurement}, +}; + +use super::{ + Error, + catalog::Catalog, + output::{flush_if_due, value_field}, + session::MeasurementKey, +}; + +#[derive(Debug)] +pub(super) struct DataLogger { + files: HashMap>, +} + +impl DataLogger { + /// Open only the selected measurement files, resolving labels once from ADJ. + pub fn open( + directory: &Path, + selected: &[MeasurementKey], + catalog: &Catalog, + ) -> Result { + let mut files = HashMap::>::new(); + for variable in selected { + let measurements = files.entry(variable.board).or_default(); + if let std::collections::hash_map::Entry::Vacant(entry) = + measurements.entry(variable.measurement_id) + { + let board = catalog.board(variable.board)?; + let measurement = catalog.measurement(variable.board, variable.measurement_id)?; + let path = directory + .join("data") + .join(&board.name) + .join(format!("{}.csv", measurement.alias)); + entry.insert(CsvFile::create(path, &[])?); + } + } + Ok(Self { files }) + } + + /// Positional packet values are matched with their ADJ measurement definitions. + pub fn write( + &mut self, + instant: u128, + board: &Board, + packet: &DataPacket, + measurements: &[Measurement], + threshold: u64, + ) -> Result<(), Error> { + if measurements.len() != packet.values.len() { + return Err(Error::MeasurementCount(packet.id)); + } + if let Some(files) = self.files.get_mut(&board.id) { + for (measurement, value) in measurements.iter().zip(&packet.values) { + if let Some(file) = files.get_mut(&measurement.id) { + value_field( + file.row() + .instant(instant) + .text(&board.name) + .text("backend"), + value, + ) + .end()?; + flush_if_due(file, threshold)?; + } + } + } + Ok(()) + } + + pub fn files_mut(&mut self) -> impl Iterator { + self.files + .values_mut() + .flat_map(|measurements| measurements.values_mut()) + } + + pub fn into_files(self) -> impl Iterator { + self.files + .into_values() + .flat_map(|measurements| measurements.into_values()) + } +} diff --git a/backend/crates/station/src/logging/error.rs b/backend/crates/station/src/logging/error.rs index 52700c64e..2083a9524 100644 --- a/backend/crates/station/src/logging/error.rs +++ b/backend/crates/station/src/logging/error.rs @@ -1,15 +1,39 @@ //! Errors for recording setup, lifecycle transitions and the writer. //! -//! Errors will preserve file context from `software_core::logger` and report -//! queue saturation, writer failure and invalid session transitions. Shutdown -//! must attempt to close all files even if closing one of them fails, and -//! return failures to the caller rather than report a successful stop. +//! Errors preserve file context from `software_core::logger` and report setup +//! or writer failures. Saturation is exposed through `StopReason` instead. +//! Shutdown attempts every file close and returns write failures to the caller. +use software_core::model::{AdjId, BoardId}; use std::{io, path::PathBuf}; /// Errors preparing logging settings, directories and sessions. #[derive(Debug, thiserror::Error)] pub enum Error { + #[error("board {0:?} is not declared in the logging ADJ")] + UnknownBoard(BoardId), + #[error("measurement {id:?} is not declared as data for board {board:?}")] + UnknownMeasurement { board: BoardId, id: AdjId }, + #[error("packet {0:?} is not declared in the logging ADJ")] + UnknownPacket(AdjId), + #[error("packet {id:?} does not belong to board {board:?}")] + PacketBoardMismatch { board: BoardId, id: AdjId }, + #[error("packet {0:?} has an unexpected ADJ type")] + UnexpectedPacketType(AdjId), + #[error("packet {0:?} value count differs from its ADJ measurement count")] + MeasurementCount(AdjId), + #[error("order logging awaits original frontend JSON and reception time in the event contract")] + OrderContractPending, + #[error("invalid logging file component: {0:?}")] + InvalidName(String), + #[error("flush interval and flush byte threshold must be positive")] + InvalidWriterOptions, + #[error("the logging writer is closed or exited unexpectedly")] + WorkerClosed, + #[error("logging session ID space exhausted")] + SessionIdExhausted, + #[error("the logging session stopped with errors: {0:?}")] + RecordingFailed(Vec), /// A filesystem operation failed. The path identifies its destination. #[error("couldn't {operation} at {path:?}: {source}")] Io { diff --git a/backend/crates/station/src/logging/event.rs b/backend/crates/station/src/logging/event.rs deleted file mode 100644 index 2d00ab80e..000000000 --- a/backend/crates/station/src/logging/event.rs +++ /dev/null @@ -1,8 +0,0 @@ -//! Typed recording events for measurements, orders, protections and messages. -//! -//! Events will carry their recording session identity and the elapsed time -//! captured at reception or order execution, before entering the writer queue. -//! Queue latency must not become part of the recorded `instant`. -//! -//! Order events also capture wall-clock time for the timestamp column. Event -//! types and the concrete producer API remain to be implemented. diff --git a/backend/crates/station/src/logging/messages.rs b/backend/crates/station/src/logging/messages.rs index a35de950e..1f3e7fcbe 100644 --- a/backend/crates/station/src/logging/messages.rs +++ b/backend/crates/station/src/logging/messages.rs @@ -1,8 +1,54 @@ //! Message recording in the session's single `messages/messages.csv` file. //! -//! Columns, in order: `instant,from,to,board,source,severity`. -//! `board` identifies the board that emitted the message; `source` combines -//! file and line in one field when applicable to the message type. +//! Columns, in order: `instant,from,to,board,source,severity,message`. +//! There is no header. +//! `board` identifies the board that emitted the message; `source` preserves +//! the received TCP message's `origin`, including file and line when present. //! -//! This component will own a `software_core::logger::CsvFile` and format rows. -//! Header policy and the exact representation of `source` remain to be defined. +//! This component owns a `software_core::logger::CsvFile` and formats rows. + +use std::path::Path; + +use software_core::{ + logger::CsvFile, + model::{Board, MessageLevel, MessagePacket}, +}; + +use super::{Error, output::flush_if_due}; + +#[derive(Debug)] +pub(super) struct MessagesLogger { + pub file: CsvFile, +} + +impl MessagesLogger { + /// Creates and/or opens messages.csv without a header. + pub fn open(directory: &Path) -> Result { + Ok(Self { + file: CsvFile::create(directory.join("messages/messages.csv"), &[])?, + }) + } + + /// `origin` and text are borrowed directly from the received model packet. + pub fn write( + &mut self, + instant: u128, + board: &Board, + packet: &MessagePacket, + severity: MessageLevel, + threshold: u64, + ) -> Result<(), Error> { + self.file + .row() + .instant(instant) + .text(&board.name) + .text("backend") + .text(&board.name) + .text(&packet.origin) + .text(severity.name()) + .text(&packet.message) + .end()?; + flush_if_due(&mut self.file, threshold)?; + Ok(()) + } +} diff --git a/backend/crates/station/src/logging/order.rs b/backend/crates/station/src/logging/order.rs index e39a6d8f6..078b06b59 100644 --- a/backend/crates/station/src/logging/order.rs +++ b/backend/crates/station/src/logging/order.rs @@ -1,9 +1,59 @@ //! Order recording in the session's single `order/order.csv` file. //! -//! Columns, in order: `instant,from,to,id,payload,timestamp`. +//! Columns, in order: `instant,from,to,order_id,payload,timestamp`. //! `timestamp` is the order's wall-clock time formatted as //! `YYYY-MM-DDTHH-MM-SS` followed by the applicable `Europe/Madrid` UTC offset //! (`+01:00` for CET or `+02:00` for CEST). +//! Orders are recorded when received from the frontend over WebSocket; +//! `payload` preserves the received JSON as text. There is no header. //! -//! This component will own a `software_core::logger::CsvFile` and format rows. -//! Header policy and the exact payload representation remain to be defined. +//! This component owns a `software_core::logger::CsvFile` and formats rows. + +use std::path::Path; + +use software_core::{logger::CsvFile, model::AdjId}; + +use super::{Error, output::flush_if_due, session::RecordTime}; + +#[derive(Debug)] +pub(super) struct OrderLogger { + pub file: CsvFile, +} + +impl OrderLogger { + /// Creates and/or opens the order.csv file + pub fn open(directory: &Path) -> Result { + Ok(Self { + file: CsvFile::create(directory.join("order/order.csv"), &[])?, + }) + } + + /// Pending input contract: only call with the original frontend JSON. + /// Writes a complete row in the order.csv file, following this order per columns + /// instant,from,to,order_id,payload,timestamp + pub fn write( + &mut self, + time: RecordTime, + id: AdjId, + to: &str, + payload: &str, + threshold: u64, + ) -> Result<(), Error> { + let timestamp = time + .wall_time + .in_tz("Europe/Madrid")? + .strftime("%Y-%m-%dT%H-%M-%S%:z") + .to_string(); + self.file + .row() // new row + .instant(time.instant) + .text("backend") // orders will always come from the backend and never from the boards + .text(to) + .int(i64::from(id.0)) + .text(payload) + .text(×tamp) + .end()?; // validates row and ends it + flush_if_due(&mut self.file, threshold)?; + Ok(()) + } +} diff --git a/backend/crates/station/src/logging/output.rs b/backend/crates/station/src/logging/output.rs new file mode 100644 index 000000000..bd47df893 --- /dev/null +++ b/backend/crates/station/src/logging/output.rs @@ -0,0 +1,50 @@ +//! Shared CSV field formatting and explicit close/flush discipline. + +use std::io::Write; + +use software_core::{ + logger::{CsvFile, Row}, + model::Value, +}; + +use super::Error; + +pub(super) fn flush_if_due(file: &mut CsvFile, threshold: u64) -> Result<(), Error> { + if file.bytes_since_flush() >= threshold { + file.flush()?; + } + Ok(()) +} + +pub(super) fn value_field<'a, W: Write>(row: Row<'a, W>, value: &Value) -> Row<'a, W> { + match value { + Value::Number(value) => row.num(*value), + Value::Bool(value) => row.bool(*value), + Value::Enum(value) => row.text(value), + } +} + +pub(super) fn flush_files<'a, W: Write + 'a>( + files: impl Iterator>, + threshold: u64, +) -> Vec { + let mut errors = Vec::new(); + for file in files { + if file.bytes_since_flush() >= threshold + && let Err(error) = file.flush() + { + errors.push(error.into()); + } + } + errors +} + +pub(super) fn close_files(files: impl Iterator>) -> Vec { + let mut errors = Vec::new(); + for file in files { + if let Err(error) = file.close() { + errors.push(error.into()); + } + } + errors +} diff --git a/backend/crates/station/src/logging/protections.rs b/backend/crates/station/src/logging/protections.rs index 7b476e47e..22136e351 100644 --- a/backend/crates/station/src/logging/protections.rs +++ b/backend/crates/station/src/logging/protections.rs @@ -1,11 +1,97 @@ -//! Protection recording in `protections/.csv`, one per board. -//! -//! Columns, in order: -//! `instant,from,to,protection_id,severity,protection_type,threshold_1,threshold_2,measurement_id,value,time`. -//! The second threshold is empty unless the protection is a range. `value` -//! is the measurement value that triggered the protection. For a -//! `timeacumulation` protection, `time` is a string containing time and units; -//! for other protection types it is `0`. -//! -//! This component will own the `software_core::logger::CsvFile` handles and -//! format rows. Header policy remains to be defined. +//! Protection rows resolved from a received packet and the ADJ definition. +//! Board-supplied accumulated timing is not present in the current packet model. + +use std::{ + collections::HashMap, + path::{Path, PathBuf}, +}; + +use software_core::{ + logger::CsvFile, + model::{Board, BoardId, Measurement, Protection, ProtectionKind, ProtectionPacket, Severity}, +}; + +use super::{ + Error, + catalog::Catalog, + output::{flush_if_due, value_field}, +}; + +#[derive(Debug)] +pub(super) struct ProtectionsLogger { + directory: PathBuf, + files: HashMap, +} + +impl ProtectionsLogger { + pub fn open(directory: &Path, boards: &[BoardId], catalog: &Catalog) -> Result { + let mut logger = Self { + directory: directory.join("protections"), + files: HashMap::new(), + }; + for &board in boards { + logger.file(catalog.board(board)?)?; + } + Ok(logger) + } + + fn file(&mut self, board: &Board) -> Result<&mut CsvFile, Error> { + if let std::collections::hash_map::Entry::Vacant(entry) = self.files.entry(board.id) { + entry.insert(CsvFile::create( + self.directory.join(format!("{}.csv", board.name)), + &[], + )?); + } + self.files.get_mut(&board.id).ok_or(Error::WorkerClosed) + } + + pub fn write( + &mut self, + instant: u128, + board: &Board, + packet: &ProtectionPacket, + measurement: &Measurement, + protection: &Protection, + threshold: u64, + ) -> Result<(), Error> { + let (kind, first, second) = match protection.kind { + ProtectionKind::Above { limit } => ("above", limit, None), + ProtectionKind::Below { limit } => ("below", limit, None), + ProtectionKind::Equal { target } => ("equal", target, None), + ProtectionKind::NotEqual { target } => ("not_equal", target, None), + ProtectionKind::Range { min, max } => ("range", min, Some(max)), + }; + let severity = match protection.severity { + Severity::Fault => "fault", + Severity::Warning => "warning", + }; + let file = self.file(board)?; + let row = file + .row() + .instant(instant) + .text(&board.name) + .text("backend") + .int(i64::from(packet.id.0)) + .text(severity) + .text(kind) + .num(first); + let row = match second { + Some(value) => row.num(value), + None => row.text(""), + }; + let row = value_field(row.int(i64::from(measurement.id.0)), &packet.value); + // Never substitute the ADJ's configured duration for a board result. + // An empty timed-protection cell explicitly means unavailable for now. + row.text(if protection.time.is_zero() { "0" } else { "" }) + .end()?; + flush_if_due(file, threshold)?; + Ok(()) + } + + pub fn files_mut(&mut self) -> impl Iterator { + self.files.values_mut() + } + pub fn into_files(self) -> impl Iterator { + self.files.into_values() + } +} diff --git a/backend/crates/station/src/logging/service.rs b/backend/crates/station/src/logging/service.rs new file mode 100644 index 000000000..02275e411 --- /dev/null +++ b/backend/crates/station/src/logging/service.rs @@ -0,0 +1,149 @@ +//! Lifecycle handle for the writer that owns event's data receiver. + +use std::{ + sync::{Arc, Mutex}, + thread::JoinHandle, + time::SystemTime, +}; + +use software_core::{adj::Adj, protocol::Index}; +use tokio::sync::{mpsc, oneshot, watch}; + +use super::{ + BackendRun, Error, Phase, SessionInfo, SessionSelection, Status, StatusReceiver, StopReason, + StopReport, ToLogging, WriterOptions, catalog::Catalog, control::Control, + status::checked_report, writer, +}; + +/// The writer serializes controls and owns all session state. The independent +/// control channel remains usable even when event's data channel is full. +#[derive(Debug)] +pub struct Logging { + controls: mpsc::UnboundedSender, + status: watch::Receiver, + worker: Mutex>>, +} + +impl Logging { + /// Move event's existing receiver directly into the dedicated writer. + /// No additional data channel or forwarding task is created. + pub fn new( + run: BackendRun, + adj: Arc, + index: Arc, + input: mpsc::Receiver, + options: WriterOptions, + ) -> Result { + options.validate()?; + let directory = run.directory().to_path_buf(); + let catalog = Catalog::new(adj, index); + let (controls, control_rx) = mpsc::unbounded_channel(); + let (status_tx, status) = watch::channel(Status::default()); + let worker = std::thread::Builder::new() + .name("logging-writer".into()) + .spawn(move || writer::run(run, input, control_rx, status_tx, catalog, options)) + .map_err(|source| Error::Io { + operation: "spawn the logging writer", + path: directory, + source, + })?; + Ok(Self { + controls, + status, + worker: Mutex::new(Some(worker)), + }) + } + + pub fn status(&self) -> Status { + self.status.borrow().clone() + } + pub fn subscribe(&self) -> StatusReceiver { + StatusReceiver::new(self.status.clone()) + } + + /// Wait until files are ready; repeated play returns the existing session. + /// Cancelling a caller's wait does not retract its already sent request. + pub async fn play(&self, selection: SessionSelection) -> Result { + let (reply, response) = oneshot::channel(); + self.controls + .send(Control::Play { selection, reply }) + .map_err(|_| Error::WorkerClosed)?; + response.await.map_err(|_| Error::WorkerClosed)? + } + + pub async fn stop(&self) -> Result, Error> { + self.stop_with_reason(StopReason::Requested).await + } + + /// Stop the session while retaining event's receiver for a later restart. + pub async fn emergency_stop(&self) -> Result, Error> { + self.stop_with_reason(StopReason::Emergency).await + } + + async fn stop_with_reason(&self, reason: StopReason) -> Result, Error> { + let (reply, response) = oneshot::channel(); + self.controls + .send(Control::Stop { + reason, + at: SystemTime::now(), + reply, + }) + .map_err(|_| Error::WorkerClosed)?; + response.await.map_err(|_| Error::WorkerClosed)? + } + + /// Close event input, drain accepted records, close files and join the writer. + pub async fn shutdown(&self) -> Result<(), Error> { + if self.status().phase != Phase::Closed { + let (reply, response) = oneshot::channel(); + if self + .controls + .send(Control::Shutdown { + at: SystemTime::now(), + reply: Some(reply), + }) + .is_ok() + { + // Input may have closed independently; still join and inspect + // final status even if that race drops the acknowledgement. + let _ = response.await; + } + } + let worker = self.worker.lock().unwrap_or_else(|e| e.into_inner()).take(); + if let Some(worker) = worker { + tokio::task::spawn_blocking(move || worker.join()) + .await + .map_err(|_| Error::WorkerClosed)? + .map_err(|_| Error::WorkerClosed)?; + } + let status = self.status(); + checked_report(status.last_stop)?; + if let Some(error) = status.last_error { + return Err(Error::RecordingFailed(vec![error])); + } + Ok(()) + } +} + +impl Drop for Logging { + fn drop(&mut self) { + // Bounded draining makes this fallback independent of producers that + // would otherwise keep filling the data channel indefinitely. + let _ = self.controls.send(Control::Shutdown { + at: SystemTime::now(), + reply: None, + }); + if let Some(worker) = self + .worker + .get_mut() + .unwrap_or_else(|e| e.into_inner()) + .take() + && worker.join().is_err() + { + tracing::error!("logging writer exited unexpectedly during close"); + } + } +} + +#[cfg(test)] +mod tests; diff --git a/backend/crates/station/src/logging/service/tests.rs b/backend/crates/station/src/logging/service/tests.rs new file mode 100644 index 000000000..36d3fa4d1 --- /dev/null +++ b/backend/crates/station/src/logging/service/tests.rs @@ -0,0 +1,382 @@ +use std::{fs, path::Path}; + +use serde_json::json; +use software_core::model::Value; +use tokio::time::{sleep, timeout}; + +use super::*; +use crate::logging::{Config, DataRecord, MeasurementKey, ProtectionRecord, Thresholds}; + +type TestResult = Result<(), Box>; + +fn selection() -> SessionSelection { + SessionSelection { + measurements: vec![MeasurementKey { + board: "LCU".into(), + measurement_id: "speed".into(), + }], + connected_boards: Vec::new(), + selected_variables: json!({"LCU": ["speed"]}), + } +} + +fn data(value: f64) -> Record { + Record::Data(DataRecord { + from: "LCU".into(), + to: "backend".into(), + measurement_id: "speed".into(), + value: Value::Number(value), + }) +} + +fn logging( + options: WriterOptions, +) -> Result<(tempfile::TempDir, Logging), Box> { + let temp = tempfile::tempdir()?; + let run = BackendRun::new_at( + Config { + logging_path: temp.path().to_path_buf(), + time_unit: TimeUnit::Microseconds, + }, + "adj", + "2026-11-27T14:30:00Z".parse()?, + )?; + let logger = Logging::new(run, options)?; + Ok((temp, logger)) +} + +async fn visible(path: &Path) -> TestResult { + timeout(Duration::from_secs(3), async { + loop { + if !fs::read_to_string(path)?.is_empty() { + return Ok::<(), std::io::Error>(()); + } + sleep(Duration::from_millis(5)).await; + } + }) + .await??; + Ok(()) +} + +#[tokio::test] +async fn stop_drains_records_filters_selection_and_is_idempotent() -> TestResult { + let (_temp, logger) = logging(WriterOptions::default())?; + let session = logger.play(selection()).await?; + let stamp = logger.capture()?; + for n in 0..200 { + assert_eq!( + logger.record_at(stamp, data(f64::from(n)))?, + RecordOutcome::Accepted + ); + } + assert_eq!( + logger.record_at( + stamp, + Record::Data(DataRecord { + from: "LCU".into(), + to: "backend".into(), + measurement_id: "unselected".into(), + value: Value::Bool(true), + }) + )?, + RecordOutcome::Filtered + ); + let first_stop = timeout(Duration::from_secs(3), logger.stop()).await??; + assert_eq!( + first_stop.as_ref().map(|r| r.reason), + Some(StopReason::Requested) + ); + assert_eq!(first_stop, logger.stop().await?); + let text = fs::read_to_string(session.directory.join("data/LCU/speed.csv"))?; + assert_eq!(text.lines().count(), 200); + assert!(text.ends_with(",LCU,backend,199\n")); + assert!(!session.directory.join("data/LCU/unselected.csv").exists()); + assert!(matches!(logger.record(data(1.0)), Err(Error::NotRecording))); + logger.shutdown().await?; + Ok(()) +} + +#[tokio::test] +async fn double_play_preserves_session_and_old_tokens_cannot_enter_a_new_one() -> TestResult { + let (_temp, logger) = logging(WriterOptions::default())?; + let first = logger.play(selection()).await?; + let stamp = logger.capture()?; + logger.record_at(stamp, data(1.0))?; + assert_eq!( + first, + logger + .play(SessionSelection { + measurements: Vec::new(), + connected_boards: Vec::new(), + selected_variables: json!([]), + }) + .await? + ); + logger.emergency_stop().await?; + assert_eq!( + logger.status().last_stop.map(|r| r.reason), + Some(StopReason::Emergency) + ); + let second = logger.play(selection()).await?; + assert_ne!(first.id, second.id); + assert!(matches!( + logger.record_at(stamp, data(99.0)), + Err(Error::SessionChanged) + )); + logger.record(data(2.0))?; + logger.stop().await?; + let text = fs::read_to_string(second.directory.join("data/LCU/speed.csv"))?; + assert_eq!(text.lines().count(), 1); + assert!(text.ends_with(",LCU,backend,2\n")); + logger.shutdown().await?; + Ok(()) +} + +#[tokio::test] +async fn full_queue_reserves_stop_admission_and_drains_every_accepted_record() -> TestResult { + let (_temp, logger) = logging(WriterOptions { + queue_capacity: 2, + ..WriterOptions::default() + })?; + let session = logger.play(selection()).await?; + let stamp = logger.capture()?; + let mut notifications = logger.subscribe(); + { + // Hold the admission lock so the writer cannot consume the test queue. + let mut state = logger.shared.lock(); + assert_eq!( + logger.shared.admit(&mut state, stamp, data(1.0))?, + RecordOutcome::Accepted + ); + assert_eq!( + logger.shared.admit(&mut state, stamp, data(2.0))?, + RecordOutcome::Accepted + ); + assert!(matches!( + logger.shared.admit(&mut state, stamp, data(3.0)), + Err(Error::QueueFull) + )); + assert_eq!(state.phase, Phase::Stopping); + assert_eq!(state.queued_records, 2); + assert!(matches!(state.queue.back(), Some(Command::Stop))); + } + let report = timeout(Duration::from_secs(3), logger.stop()).await??; + assert_eq!( + report.as_ref().map(|r| r.reason), + Some(StopReason::Saturation) + ); + let status = timeout(Duration::from_secs(3), notifications.changed()).await??; + assert_eq!( + status.last_stop.map(|r| r.reason), + Some(StopReason::Saturation) + ); + assert_eq!( + fs::read_to_string(session.directory.join("data/LCU/speed.csv"))? + .lines() + .count(), + 2 + ); + logger.play(selection()).await?; + assert_eq!( + logger.status().last_stop.map(|r| r.reason), + Some(StopReason::Saturation) + ); + logger.shutdown().await?; + Ok(()) +} + +#[tokio::test] +async fn periodic_flush_persists_a_buffered_tail_without_stopping() -> TestResult { + let (_temp, logger) = logging(WriterOptions { + flush_interval: Duration::from_millis(20), + flush_bytes: u64::MAX, + ..WriterOptions::default() + })?; + let session = logger.play(selection()).await?; + logger.record(data(1.0))?; + visible(&session.directory.join("data/LCU/speed.csv")).await?; + assert_eq!(logger.status().phase, Phase::Recording); + logger.shutdown().await?; + Ok(()) +} + +#[tokio::test] +async fn byte_threshold_flushes_without_waiting_for_the_timer() -> TestResult { + let (_temp, logger) = logging(WriterOptions { + flush_interval: Duration::from_secs(60), + flush_bytes: 1, + ..WriterOptions::default() + })?; + let session = logger.play(selection()).await?; + logger.record(data(1.0))?; + visible(&session.directory.join("data/LCU/speed.csv")).await?; + logger.shutdown().await?; + Ok(()) +} + +#[tokio::test] +async fn concurrent_producers_are_drained_before_shutdown() -> TestResult { + let (_temp, logger) = logging(WriterOptions { + queue_capacity: 1024, + ..WriterOptions::default() + })?; + let session = logger.play(selection()).await?; + std::thread::scope(|scope| -> TestResult { + let workers: Vec<_> = (0..8) + .map(|producer| { + let logger = &logger; + scope.spawn(move || -> Result<(), Error> { + for n in 0..100 { + logger.record(data(f64::from(producer * 100 + n)))?; + } + Ok(()) + }) + }) + .collect(); + for worker in workers { + worker.join().map_err(|_| "producer panicked")??; + } + Ok(()) + })?; + timeout(Duration::from_secs(3), logger.shutdown()).await??; + assert_eq!(logger.status().phase, Phase::Closed); + let text = fs::read_to_string(session.directory.join("data/LCU/speed.csv"))?; + assert_eq!(text.lines().count(), 800); + let unique: std::collections::HashSet<_> = text + .lines() + .filter_map(|line| line.rsplit(',').next()) + .collect(); + assert_eq!(unique.len(), 800); + assert!(matches!( + logger.play(selection()).await, + Err(Error::WorkerClosed) + )); + Ok(()) +} + +#[tokio::test] +async fn write_failure_stops_with_an_error_and_closes_the_other_files() -> TestResult { + let (_temp, logger) = logging(WriterOptions::default())?; + let session = logger.play(selection()).await?; + let protections = session.directory.join("protections"); + fs::remove_dir(&protections)?; + fs::write(&protections, "not a directory")?; + let stamp = logger.capture()?; + { + let mut state = logger.shared.lock(); + logger.shared.admit( + &mut state, + stamp, + Record::Protection(ProtectionRecord { + board: "PCU".into(), + from: "PCU".into(), + to: "backend".into(), + protection_id: "1".into(), + severity: "fault".into(), + protection_type: "above".into(), + thresholds: Thresholds::Single(Value::Number(1.0)), + measurement_id: "temperature".into(), + value: Value::Number(2.0), + accumulated_time: None, + }), + )?; + logger.shared.admit(&mut state, stamp, data(7.0))?; + } + assert!(matches!( + timeout(Duration::from_secs(3), logger.stop()).await?, + Err(Error::RecordingFailed(_)) + )); + assert_eq!( + logger.status().last_stop.map(|r| r.reason), + Some(StopReason::WriteError) + ); + assert!( + fs::read_to_string(session.directory.join("data/LCU/speed.csv"))? + .ends_with(",LCU,backend,7\n") + ); + // A later session can recover; its replacement removes the blocking file. + logger.play(selection()).await?; + logger.record(data(8.0))?; + logger.shutdown().await?; + Ok(()) +} + +#[tokio::test] +async fn invalid_selection_is_rejected_before_replacing_existing_files() -> TestResult { + let (_temp, logger) = logging(WriterOptions::default())?; + let session = logger.play(selection()).await?; + logger.record(data(1.0))?; + logger.stop().await?; + let before = fs::read(session.directory.join("data/LCU/speed.csv"))?; + let mut invalid = selection(); + invalid.measurements[0].measurement_id = "../escape".into(); + assert!(matches!( + logger.play(invalid).await, + Err(Error::InvalidName(_)) + )); + assert_eq!( + fs::read(session.directory.join("data/LCU/speed.csv"))?, + before + ); + logger.shutdown().await?; + Ok(()) +} + +#[tokio::test] +async fn an_abandoned_start_reply_does_not_prevent_emergency_stop_or_restart() -> TestResult { + let (_temp, logger) = logging(WriterOptions::default())?; + let (reply, response) = oneshot::channel(); + drop(response); + { + let mut state = logger.shared.lock(); + state.phase = Phase::Starting; + state.next_id = 1; + state.queue.push_back(Command::Start { + id: SessionId(1), + selection: selection(), + reply, + }); + logger.shared.publish(); + logger.shared.ready.notify_one(); + } + let report = timeout(Duration::from_secs(3), logger.emergency_stop()).await??; + assert_eq!(report.map(|r| r.reason), Some(StopReason::Emergency)); + assert_eq!(logger.play(selection()).await?.id, SessionId(2)); + logger.shutdown().await?; + Ok(()) +} + +#[tokio::test] +async fn drop_is_a_fallback_drain_when_explicit_shutdown_was_missed() -> TestResult { + let (_temp, logger) = logging(WriterOptions::default())?; + let session = logger.play(selection()).await?; + for n in 0..100 { + logger.record(data(f64::from(n)))?; + } + drop(logger); + assert_eq!( + fs::read_to_string(session.directory.join("data/LCU/speed.csv"))? + .lines() + .count(), + 100 + ); + Ok(()) +} + +#[tokio::test] +async fn controls_can_run_in_spawned_application_tasks() -> TestResult { + let (_temp, logger) = logging(WriterOptions::default())?; + let logger = Arc::new(logger); + let controller = logger.clone(); + let session = tokio::spawn(async move { controller.play(selection()).await }).await??; + logger.record(data(1.0))?; + let controller = logger.clone(); + tokio::spawn(async move { controller.emergency_stop().await }).await??; + assert!( + fs::read_to_string(session.directory.join("data/LCU/speed.csv"))? + .ends_with(",LCU,backend,1\n") + ); + let controller = logger.clone(); + tokio::spawn(async move { controller.shutdown().await }).await??; + Ok(()) +} diff --git a/backend/crates/station/src/logging/session.rs b/backend/crates/station/src/logging/session.rs index 060bd068e..3c7826b6e 100644 --- a/backend/crates/station/src/logging/session.rs +++ b/backend/crates/station/src/logging/session.rs @@ -16,22 +16,74 @@ use std::{ fs, io, path::{Path, PathBuf}, - time::Instant, + time::{Instant, SystemTime}, }; use jiff::Timestamp; use serde::Serialize; use serde_json::Value; use software_core::logger::write_json; +use software_core::model::{AdjId, BoardId}; -use super::{Config, Error, Settings}; +use super::{ + Config, Error, Settings, + catalog::{Catalog, validate_name}, +}; + +/// Selected measurements use native ADJ IDs; file labels are resolved separately. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub struct MeasurementKey { + pub board: BoardId, + pub measurement_id: AdjId, +} + +/// Resolved session selection, independent of the pending control-channel schema. +#[derive(Debug, Clone)] +pub struct SessionSelection { + pub measurements: Vec, + pub connected_boards: Vec, + pub selected_variables: Value, +} + +impl SessionSelection { + pub(super) fn validate(&self, catalog: &Catalog) -> Result<(), Error> { + for variable in &self.measurements { + validate_name(&catalog.board(variable.board)?.name)?; + validate_name( + &catalog + .measurement(variable.board, variable.measurement_id)? + .alias, + )?; + } + for &board in &self.connected_boards { + validate_name(&catalog.board(board)?.name)?; + } + Ok(()) + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub struct SessionId(pub(super) u64); + +impl SessionId { + pub fn get(self) -> u64 { + self.0 + } +} + +/// Writer-private stamp, always derived from the incoming event's reception time. +#[derive(Debug, Clone, Copy)] +pub(super) struct RecordTime { + pub instant: u128, + pub wall_time: Timestamp, +} const SETTINGS_FILE: &str = "logger_settings.json"; /// Directory and metadata for one backend execution. /// /// This is filesystem preparation, not the recording service: it does not -/// start a writer, open CSVs or implement `play`/`stop`. The future service +/// start a writer, open CSVs or implement `play`/`stop`. The recording service /// must close the previous session before preparing a replacement. #[derive(Debug)] pub struct BackendRun { @@ -42,7 +94,7 @@ pub struct BackendRun { impl BackendRun { /// Creates a run directory with the current date and backend metadata. /// - /// Blocking: call during startup or on the future writer thread. + /// Blocking: call during startup or on the writer thread. pub fn new(config: Config, adj_commit_hash: impl Into) -> Result { Self::new_at(config, adj_commit_hash, Timestamp::now()) } @@ -158,6 +210,7 @@ impl BackendRun { directory, metadata, clock_origin, + wall_origin: started_at.into(), }) } } @@ -168,6 +221,7 @@ pub struct Session { directory: PathBuf, metadata: SessionSettings, clock_origin: Instant, + wall_origin: SystemTime, } #[derive(Debug, Serialize)] @@ -178,6 +232,9 @@ struct SessionSettings { } impl Session { + pub(super) fn wall_origin(&self) -> SystemTime { + self.wall_origin + } /// Absolute path of the session directory. pub fn directory(&self) -> &Path { &self.directory @@ -193,10 +250,10 @@ impl Session { &self.metadata.selected_variables } - /// Elapsed time for an event captured before it enters the writer queue. + /// Elapsed time for an externally supplied monotonic reception timestamp. /// /// An event predating this session returns `None`, not a fabricated zero. - /// The future service must also check the event's session identity. + /// The current ToLogging input supplies SystemTime instead of Instant. pub fn instant_at(&self, received_at: Instant) -> Option { received_at .checked_duration_since(self.clock_origin) diff --git a/backend/crates/station/src/logging/session/tests.rs b/backend/crates/station/src/logging/session/tests.rs new file mode 100644 index 000000000..d63345c62 --- /dev/null +++ b/backend/crates/station/src/logging/session/tests.rs @@ -0,0 +1,172 @@ +use std::{fs, time::Duration}; + +use serde_json::json; +use software_core::logger::read_json; + +use super::*; +use crate::logging::TimeUnit; + +type TestResult = Result<(), Box>; + +fn config(directory: &Path) -> Config { + Config { + logging_path: directory.to_path_buf(), + time_unit: TimeUnit::Microseconds, + } +} + +#[test] +fn backend_and_session_settings_have_their_own_dates_and_selection() -> TestResult { + let temp = tempfile::tempdir()?; + let mut run = BackendRun::new_at( + config(temp.path()), + "adj-commit", + "2026-11-27T14:30:00Z".parse()?, + )?; + let backend_directory = temp.path().join("logger/2026-11-27T15-30-00"); + assert_eq!(run.directory(), backend_directory); + assert!(backend_directory.join("others").is_dir()); + + let selected = json!({"LCU": ["speed", "temperature"]}); + let clock_origin = Instant::now(); + let session = + run.prepare_session_at(&selected, "2026-11-27T14:31:05Z".parse()?, clock_origin)?; + let backend_settings: Value = read_json(backend_directory.join("others").join(SETTINGS_FILE))?; + let session_settings: Value = read_json(session.directory().join(SETTINGS_FILE))?; + assert_eq!( + backend_settings, + json!({ + "adj_commit_hash": "adj-commit", "time_unit": "us", "date": "2026-11-27T15-30-00" + }) + ); + assert_eq!( + session_settings, + json!({ + "adj_commit_hash": "adj-commit", "time_unit": "us", "date": "2026-11-27T15-31-05", + "selected_variables": selected + }) + ); + assert_eq!(session.selected_variables(), &selected); + assert_eq!(session.settings().date, "2026-11-27T15-31-05"); + for name in ["data", "protections", "order", "messages"] { + assert!(session.directory().join(name).is_dir()); + assert_eq!(fs::read_dir(session.directory().join(name))?.count(), 0); + } + assert_eq!(session.instant_at(clock_origin), Some(0)); + assert_eq!( + session.instant_at(clock_origin + Duration::from_millis(35)), + Some(35000) + ); + if let Some(earlier) = clock_origin.checked_sub(Duration::from_millis(1)) { + assert_eq!(session.instant_at(earlier), None); + } + Ok(()) +} + +#[test] +fn session_replacement_removes_stale_files_and_keeps_backend_files() -> TestResult { + let temp = tempfile::tempdir()?; + let mut run = BackendRun::new_at(config(temp.path()), "adj", "2026-07-15T13:30:00Z".parse()?)?; + // Both calls fall in the same named second, despite different subsecond times. + let first = run.prepare_session_at( + json!(["LCU/old"]), + "2026-07-15T13:31:00.100Z".parse()?, + Instant::now(), + )?; + assert_eq!(first.settings().date, "2026-07-15T15-31-00"); + fs::create_dir(first.directory().join("data/LCU"))?; + fs::write(first.directory().join("data/LCU/old.csv"), "old data")?; + let previous_directory = first.directory().to_path_buf(); + drop(first); + let trace = run.directory().join("others/existing-trace.jsonl"); + fs::write(&trace, "preserve this")?; + + let replacement = run.prepare_session_at( + json!(["PCU/new"]), + "2026-07-15T13:31:00.900Z".parse()?, + Instant::now(), + )?; + assert_eq!(replacement.directory(), previous_directory); + assert!(!replacement.directory().join("data/LCU").exists()); + let settings: Value = read_json(replacement.directory().join(SETTINGS_FILE))?; + assert_eq!(settings["selected_variables"], json!(["PCU/new"])); + assert_eq!(fs::read_to_string(trace)?, "preserve this"); + Ok(()) +} + +#[test] +fn colliding_backend_startups_do_not_share_or_overwrite_a_run() -> TestResult { + let temp = tempfile::tempdir()?; + let timestamp: Timestamp = "2026-11-27T14:30:00Z".parse()?; + let first = BackendRun::new_at(config(temp.path()), "first", timestamp)?; + let result = BackendRun::new_at(config(temp.path()), "second", timestamp); + assert!( + matches!(result, Err(Error::Io { source, .. }) if source.kind() == io::ErrorKind::AlreadyExists) + ); + let settings: Settings = read_json(first.directory().join("others").join(SETTINGS_FILE))?; + assert_eq!(settings.adj_commit_hash, "first"); + Ok(()) +} + +#[test] +fn relative_logging_paths_are_resolved_against_the_working_directory() -> TestResult { + let cwd = std::env::current_dir()?; + let temp = tempfile::tempdir_in(&cwd)?; + let relative = temp.path().strip_prefix(&cwd)?; + let run = BackendRun::new_at(config(relative), "adj", "2026-11-27T14:30:00Z".parse()?)?; + assert_eq!( + run.directory(), + temp.path().join("logger/2026-11-27T15-30-00") + ); + Ok(()) +} + +#[test] +fn invalid_selection_does_not_delete_an_existing_session() -> TestResult { + let temp = tempfile::tempdir()?; + let mut run = BackendRun::new_at(config(temp.path()), "adj", "2026-11-27T14:30:00Z".parse()?)?; + let timestamp: Timestamp = "2026-11-27T14:31:00Z".parse()?; + let session = run.prepare_session_at(json!(["speed"]), timestamp, Instant::now())?; + let settings_file = session.directory().join(SETTINGS_FILE); + let before = fs::read(&settings_file)?; + drop(session); + // A JSON object cannot have an array as a key. + let invalid = std::collections::BTreeMap::from([(vec![1, 2], "invalid")]); + assert!(matches!( + run.prepare_session_at(invalid, timestamp, Instant::now()), + Err(Error::Selection(_)) + )); + assert_eq!(fs::read(settings_file)?, before); + Ok(()) +} + +#[cfg(unix)] +#[test] +fn session_replacement_does_not_follow_symlinks() -> TestResult { + let temp = tempfile::tempdir()?; + let mut run = BackendRun::new_at(config(temp.path()), "adj", "2026-11-27T14:30:00Z".parse()?)?; + let outside = temp.path().join("outside"); + fs::create_dir(&outside)?; + fs::write(outside.join("keep.txt"), "keep")?; + std::os::unix::fs::symlink(&outside, run.directory().join("2026-11-27T15-31-00"))?; + assert!(matches!( + run.prepare_session_at(json!([]), "2026-11-27T14:31:00Z".parse()?, Instant::now()), + Err(Error::InvalidSessionPath(_)) + )); + assert_eq!(fs::read_to_string(outside.join("keep.txt"))?, "keep"); + Ok(()) +} + +#[test] +fn directory_errors_include_the_destination() -> TestResult { + let temp = tempfile::tempdir()?; + fs::write( + temp.path().join("logger"), + "a file cannot contain run directories", + )?; + assert!(matches!( + BackendRun::new_at(config(temp.path()), "adj", "2026-11-27T14:30:00Z".parse()?), + Err(Error::Io { path, .. }) if path == temp.path().join("logger") + )); + Ok(()) +} diff --git a/backend/crates/station/src/logging/status.rs b/backend/crates/station/src/logging/status.rs new file mode 100644 index 000000000..f193414d5 --- /dev/null +++ b/backend/crates/station/src/logging/status.rs @@ -0,0 +1,98 @@ +//! Public lifecycle snapshots; observers never borrow the writer's file handles. + +use std::path::PathBuf; + +use tokio::sync::watch; + +use super::{Error, SessionId, TimeUnit}; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Phase { + Inactive, + Starting, + Recording, + Stopping, + Closed, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SessionInfo { + /// Unique even if a later session replaces the same directory. + pub id: SessionId, + pub directory: PathBuf, + pub date: String, + pub time_unit: TimeUnit, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum StopReason { + Requested, + Emergency, + Saturation, + WriteError, + Shutdown, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct StopReport { + pub session: SessionInfo, + pub reason: StopReason, + /// Every file close was attempted; nonempty means the drain failed. + pub errors: Vec, +} + +#[derive(Debug, Clone)] +pub struct Status { + pub phase: Phase, + pub session: Option, + /// Retained across starts and replaced by the next completed stop. + pub last_stop: Option, + pub last_error: Option, +} + +impl Default for Status { + fn default() -> Self { + Self { + phase: Phase::Inactive, + session: None, + last_stop: None, + last_error: None, + } + } +} + +/// Notifications may coalesce; use `current` for the latest complete snapshot. +#[derive(Debug)] +pub struct StatusReceiver { + changes: watch::Receiver, +} + +impl StatusReceiver { + pub(super) fn new(changes: watch::Receiver) -> Self { + Self { changes } + } + + pub fn current(&self) -> Status { + self.changes.borrow().clone() + } + + pub async fn changed(&mut self) -> Result { + if self.current().phase == Phase::Closed { + return Err(Error::WorkerClosed); + } + self.changes + .changed() + .await + .map_err(|_| Error::WorkerClosed)?; + Ok(self.current()) + } +} + +pub(super) fn checked_report(report: Option) -> Result, Error> { + if let Some(report) = &report + && !report.errors.is_empty() + { + return Err(Error::RecordingFailed(report.errors.clone())); + } + Ok(report) +} diff --git a/backend/crates/station/src/logging/writer.rs b/backend/crates/station/src/logging/writer.rs index bf9c898e8..0ecb9ef0a 100644 --- a/backend/crates/station/src/logging/writer.rs +++ b/backend/crates/station/src/logging/writer.rs @@ -1,14 +1,499 @@ -//! Dedicated synchronous writer and its bounded event queue. +//! Single data-channel consumer and owner of all session files. //! -//! One writer thread will own the session's four recording components and -//! perform their blocking `software_core::logger` operations away from the -//! async network tasks. Keep files open for the session and reuse their -//! existing buffers; flush periodically and according to bytes_since_flush. +//! This runs on a dedicated OS thread with a private Tokio timer runtime. Disk +//! operations never run on the application's async workers. Lifecycle controls +//! have their own channel and do not need a free slot in event's data channel. //! -//! Admission and control commands must establish a session boundary: stop -//! rejects new events for that session, drains every accepted event, attempts -//! to close every session file and acknowledges completion. Queue saturation -//! must be reported explicitly rather than silently dropping events. -//! -//! Backend trace output has a separate lifetime from recording sessions. It -//! remains active between sessions and is flushed at the end of shutdown. +//! A stop snapshots the number of queued events and drains that finite prefix, +//! excluding reception timestamps after its cutoff. Producers can keep running; +//! new traffic is consumed without recording once the session is inactive. + +use std::{ + path::Path, + time::{Duration, SystemTime}, +}; + +use software_core::{logger::CsvFile, model::Packet, net::Event}; +use tokio::sync::{mpsc, watch}; + +use super::{ + BackendRun, Error, Phase, Session, SessionId, SessionInfo, SessionSelection, Status, + StopReason, StopReport, ToLogging, + catalog::Catalog, + control::Control, + output::{close_files, flush_files}, + data::DataLogger, + messages::MessagesLogger, + order::OrderLogger, + protections::ProtectionsLogger, + session::RecordTime, + status::checked_report, +}; + +/// Flush limits. Event owns the sole data channel and configures its capacity. +#[derive(Debug, Clone)] +pub struct WriterOptions { + /// Maximum interval between flush attempts while a session is active. + /// A slow filesystem operation can delay the next attempt. + pub flush_interval: Duration, + /// Per-file threshold. Only the file touched by a row is checked. + pub flush_bytes: u64, +} + +impl Default for WriterOptions { + fn default() -> Self { + Self { + flush_interval: Duration::from_millis(250), + flush_bytes: 64 * 1024, + } + } +} + +impl WriterOptions { + /// A zero timer would spin; a zero byte threshold would flush every row. + pub(super) fn validate(&self) -> Result<(), Error> { + if self.flush_interval.is_zero() || self.flush_bytes == 0 { + return Err(Error::InvalidWriterOptions); + } + Ok(()) + } +} + +/// Owns every CSV handle for one session, grouped by the row format it writes. +/// Sharing these handles with producers would require locking around disk I/O. +#[derive(Debug)] +pub(super) struct SessionFiles { + data: DataLogger, + protections: ProtectionsLogger, + orders: OrderLogger, + messages: MessagesLogger, +} + +impl SessionFiles { + /// Opens selected measurement files, connected boards' protection files, + /// and the two shared order/message files. Metadata is already prepared. + /// A session is not published as recording until all of these opens succeed. + pub fn open( + directory: &Path, + selection: &SessionSelection, + catalog: &Catalog, + ) -> Result { + Ok(Self { + data: DataLogger::open(directory, &selection.measurements, catalog)?, + protections: ProtectionsLogger::open(directory, &selection.connected_boards, catalog)?, + orders: OrderLogger::open(directory)?, + messages: MessagesLogger::open(directory)?, + }) + } + + /// Dispatches a decoded event without copying its packet values. + /// The catalog supplies board labels and packet definitions from the ADJ; + /// each format writer also checks the touched file's byte flush threshold. + pub fn write( + &mut self, + time: RecordTime, + record: &ToLogging, + threshold: u64, + catalog: &Catalog, + ) -> Result<(), Error> { + let ToLogging::Received(notification) = record else { + // OrderSent lacks the original frontend JSON and reception time. + // Keep that contract pending instead of inventing an order row. + return Err(Error::OrderContractPending); + }; + let board = catalog.board(notification.board)?; + match ¬ification.event { + // Connection events have no row in the agreed CSV layouts. + Event::Connected | Event::Disconnected => Ok(()), + Event::Received(Packet::Data(packet)) => self.data.write( + time.instant, + board, + packet, + catalog.data(notification.board, packet.id)?, + threshold, + ), + Event::Received(Packet::Protection(packet)) => { + // The packet carries the triggered value and compound ID; + // its severity, limits and measurement come from the ADJ. + let (measurement, protection) = + catalog.protection(notification.board, packet.id)?; + self.protections.write( + time.instant, + board, + packet, + measurement, + protection, + threshold, + ) + } + Event::Received(Packet::Message(packet)) => self.messages.write( + time.instant, + board, + packet, + catalog.message_level(notification.board, packet.id)?, + threshold, + ), + Event::Received(Packet::Order(_)) => Err(Error::OrderContractPending), + } + } + + fn files_mut(&mut self) -> impl Iterator { + // Flatten the different registries so flushing has one error policy. + self.data + .files_mut() + .chain(self.protections.files_mut()) + .chain(std::iter::once(&mut self.orders.file)) + .chain(std::iter::once(&mut self.messages.file)) + } + + fn flush(&mut self) -> Vec { + // A threshold of one skips clean files while flushing every dirty one. + flush_files(self.files_mut(), 1) + } + + fn close(self) -> Vec { + // Consuming ownership prevents later writes. The helper attempts every + // close even when one fails, returning all errors rather than stopping + // at the first poisoned or unwritable file. + close_files( + self.data + .into_files() + .chain(self.protections.into_files()) + .chain(std::iter::once(self.orders.file)) + .chain(std::iter::once(self.messages.file)), + ) + } +} + +/// All recording state is local to this writer; observers receive snapshots. +struct Recording { + session: Session, + info: SessionInfo, + files: SessionFiles, + errors: Vec, +} + +impl Recording { + fn remember(&mut self, errors: impl IntoIterator) { + for error in errors { + let text = error_chain(&error); + if !self.errors.contains(&text) { + self.errors.push(text); + } + } + } +} + +struct Writer { + run: BackendRun, + input: mpsc::Receiver, + controls: mpsc::UnboundedReceiver, + updates: watch::Sender, + status: Status, + catalog: Catalog, + options: WriterOptions, + active: Option, + next_id: u64, + order_contract_reported: bool, +} + +enum Step { + Control(Option), + Input(Option), + Flush, + Saturated, +} + +/// The runtime is created and dropped on this OS thread. Its timer and channel +/// waits stay asynchronous, while synchronous file operations stay off the +/// application's Tokio worker threads. +pub(super) fn run( + run: BackendRun, + input: mpsc::Receiver, + controls: mpsc::UnboundedReceiver, + updates: watch::Sender, + catalog: Catalog, + options: WriterOptions, +) { + let _exit = ExitGuard(updates.clone()); + match tokio::runtime::Builder::new_current_thread() + .enable_time() + .build() + { + Ok(runtime) => runtime.block_on( + Writer { + run, + input, + controls, + updates, + catalog, + options, + status: Status::default(), + active: None, + next_id: 0, + order_contract_reported: false, + } + .run(), + ), + Err(error) => { + updates.send_replace(Status { + phase: Phase::Closed, + last_error: Some(format!("couldn't start the logging timer runtime: {error}")), + ..Status::default() + }); + } + } +} + +impl Writer { + async fn run(mut self) { + let mut timer = tokio::time::interval(self.options.flush_interval); + timer.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); + timer.tick().await; // Consume the interval's immediate first tick. + loop { + let saturated = self.active.is_some() && self.input.len() == self.input.max_capacity(); + // Controls win over data, including when input is full. recv is + // cancellation-safe: an unselected branch does not steal a record. + let step = tokio::select! { + biased; + command = self.controls.recv() => Step::Control(command), + _ = std::future::ready(()), if saturated => Step::Saturated, + _ = timer.tick(), if self.active.is_some() => Step::Flush, + incoming = self.input.recv() => Step::Input(incoming), + }; + match step { + Step::Control(Some(Control::Play { selection, reply })) => { + let result = self.start(selection).await; + // Invalid selections never enter Starting and must not + // turn a rejected request into a recording failure. + if let Err(error) = &result + && self.status.phase == Phase::Starting + { + self.status.phase = Phase::Inactive; + self.status.last_error = Some(error_chain(error)); + self.publish(); + } + let _ = reply.send(result); + } + Step::Control(Some(Control::Stop { reason, at, reply })) => { + let report = self.stop(reason, at).await; + let _ = reply.send(checked_report(report)); + } + Step::Control(Some(Control::Shutdown { at, reply })) => { + self.shutdown(at).await; + if let Some(reply) = reply { + let _ = reply.send(()); + } + break; + } + Step::Control(None) | Step::Input(None) => { + self.shutdown(SystemTime::now()).await; + break; + } + Step::Saturated => { + self.stop(StopReason::Saturation, SystemTime::now()).await; + } + Step::Flush => { + if let Some(recording) = &mut self.active { + let errors = recording.files.flush(); + if !errors.is_empty() { + recording.remember(errors); + self.stop(StopReason::WriteError, SystemTime::now()).await; + } + } + } + Step::Input(Some(incoming)) => { + if self.write(&incoming, None) { + self.stop(StopReason::WriteError, SystemTime::now()).await; + } + } + } + } + } + + async fn start(&mut self, selection: SessionSelection) -> Result { + if let Some(recording) = &self.active { + return Ok(recording.info.clone()); + } + selection.validate(&self.catalog)?; + let id = SessionId( + self.next_id + .checked_add(1) + .ok_or(Error::SessionIdExhausted)?, + ); + self.next_id = id.0; + // Clear only the finite inactive backlog. New arrivals are not allowed + // to keep a start waiting forever, and older timestamps are also filtered. + let pending = self.input.len(); + for _ in 0..pending { + if self.input.recv().await.is_none() { + break; + } + } + self.status.phase = Phase::Starting; + self.status.last_error = None; + self.publish(); + let session = self.run.prepare_session(&selection.selected_variables)?; + let files = SessionFiles::open(session.directory(), &selection, &self.catalog)?; + let info = SessionInfo { + id, + directory: session.directory().to_path_buf(), + date: session.settings().date.clone(), + time_unit: session.settings().time_unit, + }; + self.active = Some(Recording { + session, + info: info.clone(), + files, + errors: Vec::new(), + }); + self.status.phase = Phase::Recording; + self.status.session = Some(info.clone()); + self.publish(); + Ok(info) + } + + /// Returns true only for a write failure that requires an ordered stop. + fn write(&mut self, incoming: &ToLogging, cutoff: Option) -> bool { + let Some(recording) = &mut self.active else { + return false; + }; + let at = match incoming { + ToLogging::Received(notification) => notification.at, + ToLogging::OrderSent { at, .. } => *at, + }; + if cutoff.is_some_and(|cutoff| at > cutoff) { + return false; + } + let Ok(elapsed) = at.duration_since(recording.session.wall_origin()) else { + return false; + }; + match self.catalog.validate(incoming) { + Ok(false) => return false, + Err(Error::OrderContractPending) => { + if !self.order_contract_reported { + tracing::warn!( + "OrderSent logging pending: original frontend JSON and reception time are unavailable" + ); + self.order_contract_reported = true; + } + return false; + } + Err(error) => { + tracing::warn!(%error, "logging input could not be recorded"); + return false; + } + Ok(true) => {} + } + let result = jiff::Timestamp::try_from(at) + .map_err(Error::from) + .and_then(|wall_time| { + recording.files.write( + RecordTime { + instant: recording.info.time_unit.convert(elapsed), + wall_time, + }, + incoming, + self.options.flush_bytes, + &self.catalog, + ) + }); + if let Err(error) = result { + recording.remember([error]); + return true; + } + false + } + + /// Drain the ready prefix observed at the stop boundary, never the + /// continuously growing tail. Reception timestamps after the caller's + /// cutoff are excluded from this session even if already queued. + async fn stop(&mut self, reason: StopReason, cutoff: SystemTime) -> Option { + if self.active.is_none() { + return self.status.last_stop.clone(); + } + self.status.phase = Phase::Stopping; + self.publish(); + let pending = self.input.len(); + for _ in 0..pending { + let Some(incoming) = self.input.recv().await else { + break; + }; + self.write(&incoming, Some(cutoff)); + } + if let Some(Recording { + info, + files, + mut errors, + .. + }) = self.active.take() + { + for error in files.close() { + let text = error_chain(&error); + if !errors.contains(&text) { + errors.push(text); + } + } + let reason = if errors.is_empty() { + reason + } else { + StopReason::WriteError + }; + if let Some(error) = errors.first() { + self.status.last_error = Some(error.clone()); + } + self.status.last_stop = Some(StopReport { + session: info, + reason, + errors, + }); + self.status.phase = Phase::Inactive; + self.status.session = None; + self.publish(); + } + self.status.last_stop.clone() + } + + async fn shutdown(&mut self, cutoff: SystemTime) { + // Closing prevents new sends. Existing ready records are still drained; + // a normal session stop never closes this receiver. + self.input.close(); + self.controls.close(); + self.stop(StopReason::Shutdown, cutoff).await; + self.status.phase = Phase::Closed; + self.publish(); + } + + fn publish(&self) { + self.updates.send_replace(self.status.clone()); + } +} + +fn error_chain(error: &dyn std::error::Error) -> String { + let mut text = error.to_string(); + let mut source = error.source(); + while let Some(error) = source { + text.push_str(": "); + text.push_str(&error.to_string()); + source = error.source(); + } + text +} + +/// Dropping pending control replies releases their callers on an unexpected +/// exit. The status signal records failure rather than claiming a clean drain. +struct ExitGuard(watch::Sender); + +impl Drop for ExitGuard { + fn drop(&mut self) { + let mut status = self.0.borrow().clone(); + if status.phase != Phase::Closed { + status.phase = Phase::Closed; + status.last_error = Some("logging writer exited unexpectedly".into()); + self.0.send_replace(status); + } + } +} + +#[cfg(test)] +mod tests; diff --git a/backend/crates/station/src/logging/writer/tests.rs b/backend/crates/station/src/logging/writer/tests.rs new file mode 100644 index 000000000..bc856b203 --- /dev/null +++ b/backend/crates/station/src/logging/writer/tests.rs @@ -0,0 +1,218 @@ +use std::{ + fs, + io::{self, Write}, + sync::{ + Arc, + atomic::{AtomicBool, Ordering}, + }, +}; + +use serde_json::json; +use software_core::{logger::CsvFile, model::Value}; + +use super::*; +use crate::logging::{ + DataRecord, MeasurementKey, MessageRecord, OrderRecord, ProtectionRecord, Thresholds, +}; + +type TestResult = Result<(), Box>; + +fn selection() -> SessionSelection { + SessionSelection { + measurements: vec![MeasurementKey { + board: "LCU".into(), + measurement_id: "speed".into(), + }], + connected_boards: vec!["LCU".into()], + selected_variables: json!({"LCU": ["speed"]}), + } +} + +fn time(wall_time: &str) -> Result { + Ok(RecordTime { + session_id: SessionId(1), + instant: u128::MAX, + wall_time: wall_time.parse()?, + }) +} + +#[test] +fn all_csv_formats_preserve_fields_without_headers() -> TestResult { + let temp = tempfile::tempdir()?; + let mut files = SessionFiles::open(temp.path(), &selection())?; + let mut stamp = time("2026-07-15T13:30:05Z")?; + stamp.instant = 35000; + files.write( + stamp, + &Record::Data(DataRecord { + from: "LCU".into(), + to: "backend".into(), + measurement_id: "speed".into(), + value: Value::Number(12.5), + }), + u64::MAX, + )?; + files.write( + stamp, + &Record::Data(DataRecord { + from: "LCU".into(), + to: "backend".into(), + measurement_id: "unselected".into(), + value: Value::Bool(true), + }), + u64::MAX, + )?; + files.write( + stamp, + &Record::Order(OrderRecord { + from: "backend".into(), + to: "LCU".into(), + id: "start".into(), + payload: "{ \"mode\": \"run\" }".into(), + }), + u64::MAX, + )?; + let mut protection = ProtectionRecord { + board: "LCU".into(), + from: "LCU".into(), + to: "backend".into(), + protection_id: "42".into(), + severity: "fault".into(), + protection_type: "above".into(), + thresholds: Thresholds::Single(Value::Number(50.0)), + measurement_id: "temperature".into(), + value: Value::Number(55.0), + accumulated_time: Some("500ms".into()), + }; + files.write(stamp, &Record::Protection(protection.clone()), u64::MAX)?; + protection.protection_type = "range".into(); + protection.thresholds = Thresholds::Range { + min: Value::Number(0.0), + max: Value::Number(100.0), + }; + protection.accumulated_time = None; + files.write(stamp, &Record::Protection(protection), u64::MAX)?; + files.write( + stamp, + &Record::Message(MessageRecord { + from: "LCU".into(), + to: "backend".into(), + board: "LCU".into(), + source: "control.cpp:123".into(), + severity: "fault".into(), + message: "failed, \"overload\"\nagain".into(), + }), + u64::MAX, + )?; + assert!(files.close().is_empty()); + assert_eq!( + fs::read_to_string(temp.path().join("data/LCU/speed.csv"))?, + "35000,LCU,backend,12.5\n" + ); + assert!(!temp.path().join("data/LCU/unselected.csv").exists()); + assert_eq!( + fs::read_to_string(temp.path().join("order/order.csv"))?, + "35000,backend,LCU,start,\"{ \"\"mode\"\": \"\"run\"\" }\",2026-07-15T15-30-05+02:00\n" + ); + assert_eq!( + fs::read_to_string(temp.path().join("protections/LCU.csv"))?, + "35000,LCU,backend,42,fault,above,50,,temperature,55,500ms\n35000,LCU,backend,42,fault,range,0,100,temperature,55,0\n" + ); + assert_eq!( + fs::read_to_string(temp.path().join("messages/messages.csv"))?, + "35000,LCU,backend,LCU,control.cpp:123,fault,\"failed, \"\"overload\"\"\nagain\"\n" + ); + Ok(()) +} + +#[test] +fn winter_order_offset_and_large_integer_instants_are_preserved() -> TestResult { + let temp = tempfile::tempdir()?; + let mut files = SessionFiles::open(temp.path(), &selection())?; + files.write( + time("2026-11-27T14:30:05Z")?, + &Record::Order(OrderRecord { + from: "backend".into(), + to: "LCU".into(), + id: "off".into(), + payload: "{}".into(), + }), + u64::MAX, + )?; + assert!(files.close().is_empty()); + assert_eq!( + fs::read_to_string(temp.path().join("order/order.csv"))?, + format!( + "{},backend,LCU,off,{{}},2026-11-27T15-30-05+01:00\n", + u128::MAX + ) + ); + Ok(()) +} + +#[test] +fn close_attempts_every_file_even_when_one_flush_fails() -> TestResult { + struct Destination { + flushed: Arc, + fail: bool, + } + impl Write for Destination { + fn write(&mut self, bytes: &[u8]) -> io::Result { + Ok(bytes.len()) + } + fn flush(&mut self) -> io::Result<()> { + self.flushed.store(true, Ordering::SeqCst); + if self.fail { + Err(io::Error::other("disk full")) + } else { + Ok(()) + } + } + } + let first = Arc::new(AtomicBool::new(false)); + let second = Arc::new(AtomicBool::new(false)); + let files = [ + CsvFile::new( + Destination { + flushed: first.clone(), + fail: true, + }, + "first", + &[], + )?, + CsvFile::new( + Destination { + flushed: second.clone(), + fail: false, + }, + "second", + &[], + )?, + ]; + let errors = close_files(files.into_iter()); + assert_eq!(errors.len(), 1); + assert!(first.load(Ordering::SeqCst)); + assert!(second.load(Ordering::SeqCst)); + Ok(()) +} + +#[test] +fn unexpected_exit_releases_queued_start_replies() { + let shared = Arc::new(Shared::new(2)); + let (reply, mut response) = tokio::sync::oneshot::channel(); + { + let mut state = shared.lock(); + state.phase = Phase::Starting; + state.queue.push_back(Command::Start { + id: SessionId(1), + selection: selection(), + reply, + }); + } + drop(ExitGuard(shared.clone())); + assert_eq!(shared.lock().phase, Phase::Closed); + assert!(matches!( + response.try_recv(), + Err(tokio::sync::oneshot::error::TryRecvError::Closed) + )); +} From 7b6608cfc324cd8d5e01911e5e0e692043a350c1 Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Thu, 3 Dec 2026 11:53:00 +0100 Subject: [PATCH 176/225] fix(frontend-kit): ws keep alvie --- frontend/frontend-kit/kit/src/core/types.ts | 5 ++++- frontend/frontend-kit/kit/src/core/websocket.ts | 14 ++++++++------ 2 files changed, 12 insertions(+), 7 deletions(-) diff --git a/frontend/frontend-kit/kit/src/core/types.ts b/frontend/frontend-kit/kit/src/core/types.ts index e8b600a69..342d7f7f4 100644 --- a/frontend/frontend-kit/kit/src/core/types.ts +++ b/frontend/frontend-kit/kit/src/core/types.ts @@ -76,6 +76,9 @@ export interface SocketConfig { /** Use wss:// instead of ws://. Defaults to false. */ secure?: boolean; - /** Heartbeat period in milliseconds. 0 disables it. Defaults to 1000. */ + /** + * Heartbeat period in milliseconds. 0 disables it. Defaults to 25, so several + * heartbeats arrive within the backend's 100 ms timeout. + */ heartbeatIntervalMs?: number; } diff --git a/frontend/frontend-kit/kit/src/core/websocket.ts b/frontend/frontend-kit/kit/src/core/websocket.ts index d9a619810..29767fd11 100644 --- a/frontend/frontend-kit/kit/src/core/websocket.ts +++ b/frontend/frontend-kit/kit/src/core/websocket.ts @@ -28,7 +28,7 @@ const DEFAULT_CONFIG = { port: 4000, path: "/backend/ws", secure: false, - heartbeatIntervalMs: 1000, + heartbeatIntervalMs: 25, } as const; /** @@ -194,9 +194,10 @@ class SocketService { } /** - * Starts the periodic heartbeat that lets the backend detect a dead or - * frozen GUI. The backend expects one at least every 3 seconds and treats - * a missing heartbeat as a disconnection. + * Starts the heartbeat that lets the backend detect a dead or frozen GUI. + * The backend faults the pod when 100 ms pass without a message from any + * frontend, so one is sent as soon as the socket opens and then every + * `heartbeatIntervalMs`. * * A `heartbeatIntervalMs` of 0 disables it. */ @@ -207,9 +208,10 @@ class SocketService { this.config.heartbeatIntervalMs ?? DEFAULT_CONFIG.heartbeatIntervalMs; if (interval <= 0) return; - this.heartbeatInterval = setInterval(() => { + const beat = () => this.ws?.next({ topic: "connection/heartbeat", payload: {} }); - }, interval); + beat(); + this.heartbeatInterval = setInterval(beat, interval); } private stopHeartbeat() { From dcd781a6e329957ed24c1d4131e04ccbcb677f25 Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Thu, 3 Dec 2026 11:56:26 +0100 Subject: [PATCH 177/225] fix(backend, ws): add keep alive properly --- backend/crates/station/src/http/server.rs | 12 ++- backend/crates/station/src/websocket.rs | 94 ++++++++++--------- .../crates/station/src/websocket/README.md | 20 ++-- .../crates/station/src/websocket/handler.rs | 23 ++--- .../crates/station/src/websocket/receiver.rs | 18 +++- 5 files changed, 96 insertions(+), 71 deletions(-) diff --git a/backend/crates/station/src/http/server.rs b/backend/crates/station/src/http/server.rs index f69f2e434..a2f94877a 100644 --- a/backend/crates/station/src/http/server.rs +++ b/backend/crates/station/src/http/server.rs @@ -64,7 +64,7 @@ mod tests { io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader}, net::{TcpListener, TcpStream}, sync::{mpsc, oneshot}, - time::{Instant, timeout}, + time::{Instant, sleep, timeout}, }; use tower::ServiceExt; @@ -296,7 +296,8 @@ mod tests { let (broker, client) = Broker::new(); let broker_task = tokio::spawn(broker.run()); let (sockets, receiver) = mpsc::channel(1); - let heartbeat_timeout = Duration::from_secs(3); + // Longer than the default so a loaded machine cannot time out between steps. + let heartbeat_timeout = Duration::from_millis(500); let socket_task = tokio::spawn(websocket::run( receiver, client.clone(), @@ -332,6 +333,7 @@ mod tests { ))?; assert_eq!(read_json(&mut socket).await?, expected); + let last_sent = Instant::now(); send_text( &mut socket, r#"{"topic":"order/send","payload":{"id":809,"fields":{"desired_current":{"value":12.5,"isEnabled":false,"type":"float32"},"lpu_id":{"value":2,"isEnabled":true,"type":"uint32"}}}}"#, @@ -345,10 +347,14 @@ mod tests { )) ); + // The frontend stays silent for half the timeout before disconnecting: + // the deadline counts from its last message, not from the disconnection. + sleep(heartbeat_timeout / 2).await; let disconnected_at = Instant::now(); drop(socket); assert_eq!(socket_task.await?, Err(websocket::FrontendDisconnected)); - assert!(disconnected_at.elapsed() >= heartbeat_timeout); + assert!(last_sent.elapsed() >= heartbeat_timeout); + assert!(disconnected_at.elapsed() < heartbeat_timeout); drop(sockets); drop(client); broker_task.await?; diff --git a/backend/crates/station/src/websocket.rs b/backend/crates/station/src/websocket.rs index 0b71c4a29..15ac5bcd7 100644 --- a/backend/crates/station/src/websocket.rs +++ b/backend/crates/station/src/websocket.rs @@ -5,13 +5,13 @@ use std::time::Duration; +use super::payload::{LoggerEnable, LoggerVariables}; use axum::extract::ws::WebSocket; use serde::{Deserialize, Serialize}; use tokio::{ sync::mpsc, time::{Instant, sleep_until}, }; -use super::payload::{LoggerEnable, LoggerVariables}; use self::broker::BrokerClient; use self::handler::SessionEnd; @@ -24,6 +24,10 @@ mod order; mod receiver; mod sender; +/// Longest time without a valid application message from any frontend before +/// `run` returns `FrontendDisconnected`. +pub const DEFAULT_HEARTBEAT_TIMEOUT: Duration = Duration::from_millis(100); + const CONNECTION_UPDATE: &str = "connection/update"; const STATE_ORDERS: &str = "order/stateOrders"; const LOGGER_ENABLE: &str = "logger/enable"; @@ -96,16 +100,18 @@ pub struct WsMessage { pub payload: serde_json::Value, } -/// The last frontend's heartbeat or reconnect deadline expired. +/// No frontend sent a valid application message within the heartbeat timeout. #[derive(Debug, PartialEq, Eq, thiserror::Error)] #[error("lost connection to the last frontend")] pub struct FrontendDisconnected; /// Runs one task per upgraded socket so a slow client stays isolated. /// -/// Returns `FrontendDisconnected` after the last session times out or the -/// reconnect window expires. Closing the HTTP handoff channel ends socket -/// intake. Existing sessions end independently. +/// Returns `FrontendDisconnected` once every session has ended and +/// `heartbeat_timeout` has passed since the last valid application message +/// of any of them. A frontend that reconnects within that period cancels it. +/// There is no deadline before the first frontend connects. Closing the HTTP +/// handoff channel ends socket intake. Existing sessions end independently. /// /// The caller should report `FrontendDisconnected` to `event` when station /// wires the two modules together. @@ -122,10 +128,10 @@ pub async fn run( tokio::select! { biased; _ = async { - if let Some(deadline) = sessions.reconnect_deadline { + if let Some(deadline) = sessions.deadline { sleep_until(deadline).await; } - }, if sessions.reconnect_deadline.is_some() => return Err(FrontendDisconnected), + }, if sessions.deadline.is_some() => return Err(FrontendDisconnected), socket = connections.recv() => { let Some(socket) = socket else { return Ok(()); }; sessions.connected(); @@ -136,43 +142,35 @@ pub async fn run( handler::handle(socket, broker, &commands, heartbeat_timeout, session_ends).await; }); } - Some(end) = ended.recv() => { - sessions.ended(end, heartbeat_timeout)?; - } + Some(end) = ended.recv() => sessions.ended(end, heartbeat_timeout), } } } -/// Tracks the active frontend sessions and the reconnect window after the last one ends. +/// Tracks the active frontend sessions and the deadline after the last one ends. #[derive(Default)] struct FrontendSessions { /// Sessions accepted by the supervisor whose handlers have yet to report an end. active: usize, - /// Set after the last session reports `SessionEnd::Closed` and cleared on reconnect. - reconnect_deadline: Option, + /// Latest application message reported by any ended session. + last_message: Option, + /// Set after the last session ends and cleared on reconnect. A session that + /// timed out leaves a deadline that has already passed. + deadline: Option, } impl FrontendSessions { fn connected(&mut self) { self.active += 1; - self.reconnect_deadline = None; + self.deadline = None; } - fn ended( - &mut self, - end: SessionEnd, - reconnect_window: Duration, - ) -> Result<(), FrontendDisconnected> { + fn ended(&mut self, end: SessionEnd, heartbeat_timeout: Duration) { self.active -= 1; - if self.active > 0 { - return Ok(()); - } - match end { - SessionEnd::HeartbeatTimeout => Err(FrontendDisconnected), - SessionEnd::Closed(at) => { - self.reconnect_deadline = Some(at + reconnect_window); - Ok(()) - } + // A session that ended earlier may have heard from its frontend more recently. + self.last_message = self.last_message.max(Some(end.last_message)); + if self.active == 0 { + self.deadline = self.last_message.map(|at| at + heartbeat_timeout); } } } @@ -181,38 +179,44 @@ impl FrontendSessions { mod tests { use super::*; - const HEARTBEAT_TIMEOUT: Duration = Duration::from_secs(3); - #[test] - fn reconnect_cancels_the_deadline_after_the_last_socket_closes() - -> Result<(), FrontendDisconnected> { + fn reconnect_cancels_the_deadline_after_the_last_session_ends() { let mut sessions = FrontendSessions::default(); let at = Instant::now(); - assert_eq!(sessions.reconnect_deadline, None); + assert_eq!(sessions.deadline, None); sessions.connected(); sessions.connected(); - sessions.ended(SessionEnd::Closed(at), HEARTBEAT_TIMEOUT)?; - assert_eq!(sessions.reconnect_deadline, None); - sessions.ended(SessionEnd::Closed(at), HEARTBEAT_TIMEOUT)?; - assert_eq!(sessions.reconnect_deadline, Some(at + HEARTBEAT_TIMEOUT)); + sessions.ended(SessionEnd { last_message: at }, DEFAULT_HEARTBEAT_TIMEOUT); + assert_eq!(sessions.deadline, None); + sessions.ended(SessionEnd { last_message: at }, DEFAULT_HEARTBEAT_TIMEOUT); + assert_eq!(sessions.deadline, Some(at + DEFAULT_HEARTBEAT_TIMEOUT)); sessions.connected(); - assert_eq!(sessions.reconnect_deadline, None); - Ok(()) + assert_eq!(sessions.deadline, None); } #[test] - fn the_last_heartbeat_timeout_is_fatal_immediately() -> Result<(), FrontendDisconnected> { + fn the_deadline_counts_from_the_latest_message_of_any_session() { let mut sessions = FrontendSessions::default(); + let quiet = Instant::now(); + let recent = quiet + Duration::from_millis(50); sessions.connected(); sessions.connected(); - sessions.ended(SessionEnd::HeartbeatTimeout, HEARTBEAT_TIMEOUT)?; - assert_eq!( - sessions.ended(SessionEnd::HeartbeatTimeout, HEARTBEAT_TIMEOUT), - Err(FrontendDisconnected) + // The session that ends first heard from its frontend more recently. + sessions.ended( + SessionEnd { + last_message: recent, + }, + DEFAULT_HEARTBEAT_TIMEOUT, + ); + sessions.ended( + SessionEnd { + last_message: quiet, + }, + DEFAULT_HEARTBEAT_TIMEOUT, ); - Ok(()) + assert_eq!(sessions.deadline, Some(recent + DEFAULT_HEARTBEAT_TIMEOUT)); } } diff --git a/backend/crates/station/src/websocket/README.md b/backend/crates/station/src/websocket/README.md index 20fdf3a91..4b7f3aff7 100644 --- a/backend/crates/station/src/websocket/README.md +++ b/backend/crates/station/src/websocket/README.md @@ -50,17 +50,23 @@ from a caller, bind a listener and pass it and the sender of a bounded socket channel to `station::http::serve`. Create the broker and client with `station::websocket::broker::Broker::new()` and start `broker.run()` as a Tokio task. Pass the socket receiver, the `BrokerClient`, the command destinations, and a -heartbeat timeout to `station::websocket::run`. +heartbeat timeout, normally `station::websocket::DEFAULT_HEARTBEAT_TIMEOUT`, +to `station::websocket::run`. `Commands::default()` leaves the order and logger destinations unset. Each socket has independent reading and writing futures, coordinated by `handler.rs`. Either future finishing closes the session. -With a heartbeat timeout of three seconds, the loss of the last frontend makes -`websocket::run` return `FrontendDisconnected`. A heartbeat timeout already -satisfies that period. Other socket closures allow three seconds to reconnect. -The station startup task can report this error as a `ProblemKind::Fatal` on -`channels.problems` so `event` requests the fault and stops the backend. +`websocket::run` returns `FrontendDisconnected` when every session has ended +and no frontend has sent a valid application message for the heartbeat timeout, +100 ms with `DEFAULT_HEARTBEAT_TIMEOUT`. The period counts from the last message +of any session, not from the moment a socket closes: a frontend that disconnects +has only the rest of that period to reconnect, and a session that timed out +leaves none. Sessions the backend closes, such as one that lags behind an event +topic, count like any other closure. There is no deadline before the first +frontend connects. The station startup task can report this error as a +`ProblemKind::Fatal` on `channels.problems` so `event` requests the fault and +stops the backend. Connect to `/backend/ws` on the listener's address and port and send this message to subscribe to `connection/update`. @@ -80,6 +86,8 @@ socket writer through a bounded `mpsc` queue. A full queue closes that session. `receiver.rs` consumes `connection/heartbeat` without publishing a response. It uses `timeout_at` with the caller's heartbeat timeout. Each valid JSON application message renews the deadline. WebSocket ping/pong frames do not renew it. +The frontend kit sends a heartbeat as soon as the socket opens and then every +25 ms, several within each 100 ms period. Unknown topics are logged and ignored while their handlers are implemented. `sender.rs` releases each watch borrow before awaiting socket I/O. diff --git a/backend/crates/station/src/websocket/handler.rs b/backend/crates/station/src/websocket/handler.rs index b8b80d00e..57b5a2b10 100644 --- a/backend/crates/station/src/websocket/handler.rs +++ b/backend/crates/station/src/websocket/handler.rs @@ -7,14 +7,13 @@ use tokio::{ time::{Instant, timeout}, }; -use super::{Commands, broker::BrokerClient, error::Error, receiver, sender}; +use super::{Commands, broker::BrokerClient, receiver, sender}; -/// Reports why a session ended before the handler closes the socket. -pub(super) enum SessionEnd { - /// The full heartbeat timeout elapsed while waiting for an application message. - HeartbeatTimeout, - /// The session ended at this instant. For the last session, this starts the reconnect window. - Closed(Instant), +/// Reported once per session so the supervisor can apply the heartbeat timeout across sessions. +pub(super) struct SessionEnd { + /// When the session last received a valid application message, or when it + /// started if none arrived. + pub(super) last_message: Instant, } /// Runs reading and writing concurrently. The first side to finish ends the session. @@ -27,16 +26,14 @@ pub(super) async fn handle( ) { let (mut write, read) = socket.split(); let (changes, subscriptions) = mpsc::channel(16); + // The connection itself is the first news from the frontend. + let mut last_message = Instant::now(); let result = tokio::select! { - result = receiver::run(read, &broker, commands, changes, heartbeat_timeout) => result, + result = receiver::run(read, &broker, commands, changes, heartbeat_timeout, &mut last_message) => result, result = sender::run(&mut write, subscriptions) => result, }; - let end = match result { - Err(Error::HeartbeatTimeout) => SessionEnd::HeartbeatTimeout, - _ => SessionEnd::Closed(Instant::now()), - }; // Report the end of the session before waiting on socket I/O. - let _ = session_ends.send(end).await; + let _ = session_ends.send(SessionEnd { last_message }).await; if let Err(error) = result { tracing::warn!(%error, "WebSocket connection ended with an error"); } diff --git a/backend/crates/station/src/websocket/receiver.rs b/backend/crates/station/src/websocket/receiver.rs index 49cf64c9e..f6c8370c8 100644 --- a/backend/crates/station/src/websocket/receiver.rs +++ b/backend/crates/station/src/websocket/receiver.rs @@ -60,17 +60,22 @@ impl SubscriptionChange { } /// Routes frontend requests and tracks application-level liveness. +/// +/// `last_message` holds the instant of the last decoded application message, +/// starting with the caller's value. The deadline is that instant plus +/// `heartbeat_timeout`. pub(super) async fn run( mut read: impl Stream> + Unpin, broker: &BrokerClient, commands: &Commands, changes: mpsc::Sender, heartbeat_timeout: Duration, + last_message: &mut Instant, ) -> Result<(), Error> { let mut subscriptions = HashSet::new(); - // Keep one deadline across frames. Only decoded application messages renew it. - let mut deadline = Instant::now() + heartbeat_timeout; loop { + // Only decoded application messages renew the deadline. + let deadline = *last_message + heartbeat_timeout; let frame = timeout_at(deadline, read.next()) .await .map_err(|_| Error::HeartbeatTimeout)?; @@ -119,7 +124,7 @@ pub(super) async fn run( } else if message.topic != HEARTBEAT { tracing::warn!(topic = %message.topic, "unsupported WebSocket topic"); } - deadline = Instant::now() + heartbeat_timeout; + *last_message = Instant::now(); } Frame::Close(_) => return Ok(()), _ => {} @@ -166,7 +171,8 @@ mod tests { &client, &Commands::default(), changes, - HEARTBEAT_TIMEOUT + HEARTBEAT_TIMEOUT, + &mut Instant::now(), ) .await, Err(Error::HeartbeatTimeout) @@ -187,6 +193,7 @@ mod tests { &Commands::default(), changes, HEARTBEAT_TIMEOUT, + &mut Instant::now(), ) .await }); @@ -225,6 +232,7 @@ mod tests { &Commands::default(), changes, HEARTBEAT_TIMEOUT, + &mut Instant::now(), ) .await?; assert!(subscriptions.recv().await.is_none()); @@ -250,6 +258,7 @@ mod tests { &Commands::default(), changes, HEARTBEAT_TIMEOUT, + &mut Instant::now(), ) .await?; assert!(matches!( @@ -292,6 +301,7 @@ mod tests { &Commands::default(), changes, HEARTBEAT_TIMEOUT, + &mut Instant::now(), ) .await?; assert!(matches!( From 822606a5128dc72a772e6d74f57dea4a98303f82 Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Thu, 3 Dec 2026 12:51:27 +0100 Subject: [PATCH 178/225] test(backend, logging): correct tests --- backend/crates/station/src/logging.rs | 3 + backend/crates/station/src/logging/README.md | 46 +- .../station/src/logging/service/tests.rs | 505 +++++++++++------- .../station/src/logging/test_support.rs | 163 ++++++ .../station/src/logging/writer/tests.rs | 295 ++++++---- 5 files changed, 693 insertions(+), 319 deletions(-) create mode 100644 backend/crates/station/src/logging/test_support.rs diff --git a/backend/crates/station/src/logging.rs b/backend/crates/station/src/logging.rs index 4643787c1..3c1650a59 100644 --- a/backend/crates/station/src/logging.rs +++ b/backend/crates/station/src/logging.rs @@ -36,6 +36,9 @@ mod settings; mod status; mod writer; +#[cfg(test)] +mod test_support; + pub use crate::event::ToLogging; pub use error::Error; pub use service::Logging; diff --git a/backend/crates/station/src/logging/README.md b/backend/crates/station/src/logging/README.md index 62cefe79d..4748a9c69 100644 --- a/backend/crates/station/src/logging/README.md +++ b/backend/crates/station/src/logging/README.md @@ -7,8 +7,8 @@ Write operations use ## Current Status -This is a work-in-progress adaptation to `event` on `backend/net`, reviewed -against the local `origin/backend/net` commit `99a31ba6`. +The module uses the native `event` and `core::net` types now present in this +checkout. Application startup and frontend integration remain pending. The input contract is `tokio::sync::mpsc::Receiver`. The application passes a shared `Arc` and `Arc` to `Logging`. @@ -16,12 +16,9 @@ The CSV writers consume decoded `model` packets and borrow their metadata from these shared definitions; callers no longer assemble `DataRecord`, `ProtectionRecord`, `MessageRecord` or `OrderRecord` DTOs. -**This branch does not yet contain `station::event` or `core::net`.** The -references to those modules intentionally target their real types from -`backend/net`. No duplicate contracts or temporary stubs have been added. -Compilation in this branch and migration of the existing tests are deferred -until the incoming changes have been merged. The production library has also -been checked in a temporary combination with that branch, outside this checkout. +Production code and logging tests compile against those modules directly. +Tests build native ADJ definitions and send decoded packets through the real +`ToLogging` channel; no duplicate event contracts or temporary stubs are used. Session preparation and the buffer lifecycle are retained. The writer now consumes event's existing bounded channel directly, with no second data queue @@ -545,7 +542,7 @@ were left undecided**. This flow has not been implemented in the new backend. | `session.rs` | Selection, identity, paths and clocks of each session; writer stamps are private. | | `settings.rs` | Backend run and session metadata. | | `writer.rs` | Event consumer, session state, CSV ownership, flushing, and shutdown. | -| `csv.rs` | Shared value formatting and flush/close error handling. | +| `output.rs` | Shared value formatting and flush/close error handling. | | `data.rs` | Measurement files by board and variable. | | `protections.rs` | Protection files by board. | | `order.rs` | Order recording in a single CSV. | @@ -568,20 +565,23 @@ buffers, and explicit flush and close operations. - Frontend notification format and integration through the application modules. - Wiring `WriterOptions` into application configuration if these defaults need UI controls. -## Verification During This Adaptation +## Verification -`rustfmt` and `git diff --check` validate syntax formatting and whitespace. -The production library is also checked in a temporary workspace combining -these changes with the reviewed `backend/net` source, without merging it into -this checkout. +Run the logging tests with `cargo test -p station --lib logging --offline`, or +the whole station suite with `cargo test -p station --offline`. The HTTP +WebSocket tests in the full suite need permission to open local sockets. -The old logging tests still use the former DTO-based API. Their migration and -full test execution are intentionally deferred until the branches are joined. -Do not treat this WIP commit as a passing standalone build before `event` and -`core::net` are brought in. +`test_support.rs` supplies shared native ADJ, Index and packet fixtures. +Service tests cover variable selection, restarts, old reception timestamps, +buffer flushing, concurrent producers, write failures, cancelled control +replies, fallback drop and input closure. An integration scenario connects +`event::channels` and the real event router to `Logging`, stops and restarts +sessions, then checks the persisted CSVs and orderly shutdown. -`cargo test -p station --test logging_service --offline` checks the native event -API in a workspace that includes those dependencies. It covers session restart, -old reception timestamps, invalid selections, pending-record drains and -controls awaited from spawned Tokio tasks. It also checks stopping while the -producer keeps sending, a one-slot data channel, and input-closure flushing. +Writer tests check headerless CSVs, escaping, protection metadata, missing +board timing, the order formatter's original JSON and timezone offsets, +large integer instants, deterministic full-channel handling and failed closes. +Pending `OrderSent` input is explicitly checked to leave the order CSV empty; +testing the formatter directly does not imply that order reception is wired. + +`rustfmt` and `git diff --check` validate formatting and whitespace. diff --git a/backend/crates/station/src/logging/service/tests.rs b/backend/crates/station/src/logging/service/tests.rs index 36d3fa4d1..ad7bbd6b5 100644 --- a/backend/crates/station/src/logging/service/tests.rs +++ b/backend/crates/station/src/logging/service/tests.rs @@ -1,52 +1,46 @@ -use std::{fs, path::Path}; +//! Lifecycle tests using the real ToLogging channel, ADJ and protocol index. -use serde_json::json; -use software_core::model::Value; +use std::{ + fs, + path::Path, + time::{Duration, SystemTime}, +}; use tokio::time::{sleep, timeout}; use super::*; -use crate::logging::{Config, DataRecord, MeasurementKey, ProtectionRecord, Thresholds}; +use crate::logging::{Config, MeasurementKey, TimeUnit, test_support::*}; +use software_core::{ + model::{AdjId, DataPacket, OrderPacket, Packet}, + net::Event, +}; -type TestResult = Result<(), Box>; +type Fixture = (tempfile::TempDir, Logging, mpsc::Sender); -fn selection() -> SessionSelection { - SessionSelection { - measurements: vec![MeasurementKey { - board: "LCU".into(), - measurement_id: "speed".into(), - }], - connected_boards: Vec::new(), - selected_variables: json!({"LCU": ["speed"]}), - } -} - -fn data(value: f64) -> Record { - Record::Data(DataRecord { - from: "LCU".into(), - to: "backend".into(), - measurement_id: "speed".into(), - value: Value::Number(value), - }) +fn logging(options: WriterOptions) -> Result> { + logging_with_capacity(options, 1024) } -fn logging( +fn logging_with_capacity( options: WriterOptions, -) -> Result<(tempfile::TempDir, Logging), Box> { + capacity: usize, +) -> Result> { let temp = tempfile::tempdir()?; + let (adj, index) = definitions(); let run = BackendRun::new_at( Config { - logging_path: temp.path().to_path_buf(), + logging_path: temp.path().into(), time_unit: TimeUnit::Microseconds, }, "adj", "2026-11-27T14:30:00Z".parse()?, )?; - let logger = Logging::new(run, options)?; - Ok((temp, logger)) + let (sender, receiver) = mpsc::channel(capacity); + let logger = Logging::new(run, adj, index, receiver, options)?; + Ok((temp, logger, sender)) } async fn visible(path: &Path) -> TestResult { - timeout(Duration::from_secs(3), async { + timeout(WAIT, async { loop { if !fs::read_to_string(path)?.is_empty() { return Ok::<(), std::io::Error>(()); @@ -60,28 +54,12 @@ async fn visible(path: &Path) -> TestResult { #[tokio::test] async fn stop_drains_records_filters_selection_and_is_idempotent() -> TestResult { - let (_temp, logger) = logging(WriterOptions::default())?; + let (_temp, logger, sender) = logging(WriterOptions::default())?; let session = logger.play(selection()).await?; - let stamp = logger.capture()?; for n in 0..200 { - assert_eq!( - logger.record_at(stamp, data(f64::from(n)))?, - RecordOutcome::Accepted - ); + sender.send(data(SystemTime::now(), f64::from(n))).await?; } - assert_eq!( - logger.record_at( - stamp, - Record::Data(DataRecord { - from: "LCU".into(), - to: "backend".into(), - measurement_id: "unselected".into(), - value: Value::Bool(true), - }) - )?, - RecordOutcome::Filtered - ); - let first_stop = timeout(Duration::from_secs(3), logger.stop()).await??; + let first_stop = timeout(WAIT, logger.stop()).await??; assert_eq!( first_stop.as_ref().map(|r| r.reason), Some(StopReason::Requested) @@ -91,39 +69,40 @@ async fn stop_drains_records_filters_selection_and_is_idempotent() -> TestResult assert_eq!(text.lines().count(), 200); assert!(text.ends_with(",LCU,backend,199\n")); assert!(!session.directory.join("data/LCU/unselected.csv").exists()); - assert!(matches!(logger.record(data(1.0)), Err(Error::NotRecording))); + // Inactive logging must keep event's receiver alive. + sender.send(data(SystemTime::now(), 999.0)).await?; logger.shutdown().await?; + assert_eq!( + fs::read_to_string(session.directory.join("data/LCU/speed.csv"))?, + text + ); Ok(()) } #[tokio::test] -async fn double_play_preserves_session_and_old_tokens_cannot_enter_a_new_one() -> TestResult { - let (_temp, logger) = logging(WriterOptions::default())?; +async fn double_play_preserves_session_and_old_receptions_cannot_enter_a_new_one() -> TestResult { + let (_temp, logger, sender) = logging(WriterOptions::default())?; let first = logger.play(selection()).await?; - let stamp = logger.capture()?; - logger.record_at(stamp, data(1.0))?; + let old_reception = SystemTime::now(); + sender.send(data(old_reception, 1.0)).await?; assert_eq!( first, logger .play(SessionSelection { - measurements: Vec::new(), - connected_boards: Vec::new(), - selected_variables: json!([]), + measurements: vec![], + connected_boards: vec![], + selected_variables: serde_json::json!([]) }) .await? ); - logger.emergency_stop().await?; assert_eq!( - logger.status().last_stop.map(|r| r.reason), + logger.emergency_stop().await?.map(|r| r.reason), Some(StopReason::Emergency) ); let second = logger.play(selection()).await?; assert_ne!(first.id, second.id); - assert!(matches!( - logger.record_at(stamp, data(99.0)), - Err(Error::SessionChanged) - )); - logger.record(data(2.0))?; + sender.send(data(old_reception, 99.0)).await?; + sender.send(data(SystemTime::now(), 2.0)).await?; logger.stop().await?; let text = fs::read_to_string(second.directory.join("data/LCU/speed.csv"))?; assert_eq!(text.lines().count(), 1); @@ -133,67 +112,68 @@ async fn double_play_preserves_session_and_old_tokens_cannot_enter_a_new_one() - } #[tokio::test] -async fn full_queue_reserves_stop_admission_and_drains_every_accepted_record() -> TestResult { - let (_temp, logger) = logging(WriterOptions { - queue_capacity: 2, - ..WriterOptions::default() - })?; - let session = logger.play(selection()).await?; - let stamp = logger.capture()?; - let mut notifications = logger.subscribe(); - { - // Hold the admission lock so the writer cannot consume the test queue. - let mut state = logger.shared.lock(); - assert_eq!( - logger.shared.admit(&mut state, stamp, data(1.0))?, - RecordOutcome::Accepted - ); - assert_eq!( - logger.shared.admit(&mut state, stamp, data(2.0))?, - RecordOutcome::Accepted - ); - assert!(matches!( - logger.shared.admit(&mut state, stamp, data(3.0)), - Err(Error::QueueFull) - )); - assert_eq!(state.phase, Phase::Stopping); - assert_eq!(state.queued_records, 2); - assert!(matches!(state.queue.back(), Some(Command::Stop))); - } - let report = timeout(Duration::from_secs(3), logger.stop()).await??; +async fn selection_can_change_between_sessions() -> TestResult { + let (_temp, logger, sender) = logging(WriterOptions::default())?; + logger.play(selection()).await?; + sender.send(data(SystemTime::now(), 1.0)).await?; + logger.stop().await?; + let mut next = selection(); + next.measurements = vec![MeasurementKey { + board: LCU, + measurement_id: UNSELECTED, + }]; + next.selected_variables = serde_json::json!({"LCU": ["unselected"]}); + let session = logger.play(next).await?; + sender.send(data(SystemTime::now(), 2.0)).await?; + logger.stop().await?; + let data_dir = session.directory.join("data/LCU"); assert_eq!( - report.as_ref().map(|r| r.reason), - Some(StopReason::Saturation) + fs::read_to_string(data_dir.join("unselected.csv"))? + .lines() + .count(), + 1 ); - let status = timeout(Duration::from_secs(3), notifications.changed()).await??; + let metadata: serde_json::Value = + software_core::logger::read_json(session.directory.join("logger_settings.json"))?; assert_eq!( - status.last_stop.map(|r| r.reason), - Some(StopReason::Saturation) + metadata["selected_variables"], + serde_json::json!({"LCU": ["unselected"]}) ); + assert_eq!(metadata["date"], session.date); + logger.shutdown().await?; + Ok(()) +} + +#[tokio::test] +async fn stopping_a_one_slot_data_channel_never_needs_an_extra_data_slot() -> TestResult { + let (_temp, logger, sender) = logging_with_capacity(WriterOptions::default(), 1)?; + let session = logger.play(selection()).await?; + sender.try_send(data(SystemTime::now(), 1.0))?; + let report = timeout(WAIT, logger.stop()).await??; + // Either the control or the full-channel observation may win this race. + assert!(matches!( + report.map(|r| r.reason), + Some(StopReason::Requested | StopReason::Saturation) + )); assert_eq!( fs::read_to_string(session.directory.join("data/LCU/speed.csv"))? .lines() .count(), - 2 - ); - logger.play(selection()).await?; - assert_eq!( - logger.status().last_stop.map(|r| r.reason), - Some(StopReason::Saturation) + 1 ); + assert!(!sender.is_closed()); logger.shutdown().await?; Ok(()) } #[tokio::test] async fn periodic_flush_persists_a_buffered_tail_without_stopping() -> TestResult { - let (_temp, logger) = logging(WriterOptions { + let (_temp, logger, sender) = logging(WriterOptions { flush_interval: Duration::from_millis(20), flush_bytes: u64::MAX, - ..WriterOptions::default() })?; let session = logger.play(selection()).await?; - logger.record(data(1.0))?; + sender.send(data(SystemTime::now(), 1.0)).await?; visible(&session.directory.join("data/LCU/speed.csv")).await?; assert_eq!(logger.status().phase, Phase::Recording); logger.shutdown().await?; @@ -202,43 +182,38 @@ async fn periodic_flush_persists_a_buffered_tail_without_stopping() -> TestResul #[tokio::test] async fn byte_threshold_flushes_without_waiting_for_the_timer() -> TestResult { - let (_temp, logger) = logging(WriterOptions { + let (_temp, logger, sender) = logging(WriterOptions { flush_interval: Duration::from_secs(60), flush_bytes: 1, - ..WriterOptions::default() })?; let session = logger.play(selection()).await?; - logger.record(data(1.0))?; + sender.send(data(SystemTime::now(), 1.0)).await?; visible(&session.directory.join("data/LCU/speed.csv")).await?; + assert_eq!(logger.status().phase, Phase::Recording); logger.shutdown().await?; Ok(()) } #[tokio::test] async fn concurrent_producers_are_drained_before_shutdown() -> TestResult { - let (_temp, logger) = logging(WriterOptions { - queue_capacity: 1024, - ..WriterOptions::default() - })?; + let (_temp, logger, sender) = logging(WriterOptions::default())?; let session = logger.play(selection()).await?; - std::thread::scope(|scope| -> TestResult { - let workers: Vec<_> = (0..8) - .map(|producer| { - let logger = &logger; - scope.spawn(move || -> Result<(), Error> { - for n in 0..100 { - logger.record(data(f64::from(producer * 100 + n)))?; - } - Ok(()) - }) - }) - .collect(); - for worker in workers { - worker.join().map_err(|_| "producer panicked")??; - } - Ok(()) - })?; - timeout(Duration::from_secs(3), logger.shutdown()).await??; + let mut producers = tokio::task::JoinSet::new(); + for producer in 0..8 { + let sender = sender.clone(); + producers.spawn(async move { + for n in 0..100 { + sender + .send(data(SystemTime::now(), f64::from(producer * 100 + n))) + .await?; + } + Ok::<(), mpsc::error::SendError>(()) + }); + } + while let Some(result) = producers.join_next().await { + result??; + } + timeout(WAIT, logger.shutdown()).await??; assert_eq!(logger.status().phase, Phase::Closed); let text = fs::read_to_string(session.directory.join("data/LCU/speed.csv"))?; assert_eq!(text.lines().count(), 800); @@ -256,34 +231,19 @@ async fn concurrent_producers_are_drained_before_shutdown() -> TestResult { #[tokio::test] async fn write_failure_stops_with_an_error_and_closes_the_other_files() -> TestResult { - let (_temp, logger) = logging(WriterOptions::default())?; - let session = logger.play(selection()).await?; + let (_temp, logger, sender) = logging(WriterOptions::default())?; + let mut selected = selection(); + selected.connected_boards.clear(); // Keep protection files unopened until the event. + let session = logger.play(selected).await?; let protections = session.directory.join("protections"); fs::remove_dir(&protections)?; fs::write(&protections, "not a directory")?; - let stamp = logger.capture()?; - { - let mut state = logger.shared.lock(); - logger.shared.admit( - &mut state, - stamp, - Record::Protection(ProtectionRecord { - board: "PCU".into(), - from: "PCU".into(), - to: "backend".into(), - protection_id: "1".into(), - severity: "fault".into(), - protection_type: "above".into(), - thresholds: Thresholds::Single(Value::Number(1.0)), - measurement_id: "temperature".into(), - value: Value::Number(2.0), - accumulated_time: None, - }), - )?; - logger.shared.admit(&mut state, stamp, data(7.0))?; - } + sender.send(data(SystemTime::now(), 7.0)).await?; + sender + .send(protection(PCU, AdjId((1 << 13) | 3003), 55.0)) + .await?; assert!(matches!( - timeout(Duration::from_secs(3), logger.stop()).await?, + timeout(WAIT, logger.stop()).await?, Err(Error::RecordingFailed(_)) )); assert_eq!( @@ -294,64 +254,57 @@ async fn write_failure_stops_with_an_error_and_closes_the_other_files() -> TestR fs::read_to_string(session.directory.join("data/LCU/speed.csv"))? .ends_with(",LCU,backend,7\n") ); - // A later session can recover; its replacement removes the blocking file. + // Remove the obstruction even if the next session has a different second. + fs::remove_file(protections)?; logger.play(selection()).await?; - logger.record(data(8.0))?; + sender.send(data(SystemTime::now(), 8.0)).await?; logger.shutdown().await?; Ok(()) } #[tokio::test] async fn invalid_selection_is_rejected_before_replacing_existing_files() -> TestResult { - let (_temp, logger) = logging(WriterOptions::default())?; + let (_temp, logger, sender) = logging(WriterOptions::default())?; let session = logger.play(selection()).await?; - logger.record(data(1.0))?; + sender.send(data(SystemTime::now(), 1.0)).await?; logger.stop().await?; - let before = fs::read(session.directory.join("data/LCU/speed.csv"))?; + let file = session.directory.join("data/LCU/speed.csv"); + let before = fs::read(&file)?; let mut invalid = selection(); - invalid.measurements[0].measurement_id = "../escape".into(); + invalid.measurements[0].measurement_id = AdjId(7000); assert!(matches!( logger.play(invalid).await, - Err(Error::InvalidName(_)) + Err(Error::UnknownMeasurement { .. }) )); - assert_eq!( - fs::read(session.directory.join("data/LCU/speed.csv"))?, - before - ); + assert_eq!(fs::read(file)?, before); + assert_eq!(logger.status().phase, Phase::Inactive); logger.shutdown().await?; Ok(()) } #[tokio::test] async fn an_abandoned_start_reply_does_not_prevent_emergency_stop_or_restart() -> TestResult { - let (_temp, logger) = logging(WriterOptions::default())?; + let (_temp, logger, _sender) = logging(WriterOptions::default())?; let (reply, response) = oneshot::channel(); drop(response); - { - let mut state = logger.shared.lock(); - state.phase = Phase::Starting; - state.next_id = 1; - state.queue.push_back(Command::Start { - id: SessionId(1), - selection: selection(), - reply, - }); - logger.shared.publish(); - logger.shared.ready.notify_one(); - } - let report = timeout(Duration::from_secs(3), logger.emergency_stop()).await??; + logger.controls.send(Control::Play { + selection: selection(), + reply, + })?; + let report = timeout(WAIT, logger.emergency_stop()).await??; + let first_id = report.as_ref().ok_or("start was not processed")?.session.id; assert_eq!(report.map(|r| r.reason), Some(StopReason::Emergency)); - assert_eq!(logger.play(selection()).await?.id, SessionId(2)); + assert!(logger.play(selection()).await?.id.get() > first_id.get()); logger.shutdown().await?; Ok(()) } #[tokio::test] async fn drop_is_a_fallback_drain_when_explicit_shutdown_was_missed() -> TestResult { - let (_temp, logger) = logging(WriterOptions::default())?; + let (_temp, logger, sender) = logging(WriterOptions::default())?; let session = logger.play(selection()).await?; for n in 0..100 { - logger.record(data(f64::from(n)))?; + sender.send(data(SystemTime::now(), f64::from(n))).await?; } drop(logger); assert_eq!( @@ -360,16 +313,17 @@ async fn drop_is_a_fallback_drain_when_explicit_shutdown_was_missed() -> TestRes .count(), 100 ); + assert!(sender.is_closed()); Ok(()) } #[tokio::test] async fn controls_can_run_in_spawned_application_tasks() -> TestResult { - let (_temp, logger) = logging(WriterOptions::default())?; + let (_temp, logger, sender) = logging(WriterOptions::default())?; let logger = Arc::new(logger); let controller = logger.clone(); let session = tokio::spawn(async move { controller.play(selection()).await }).await??; - logger.record(data(1.0))?; + sender.send(data(SystemTime::now(), 1.0)).await?; let controller = logger.clone(); tokio::spawn(async move { controller.emergency_stop().await }).await??; assert!( @@ -380,3 +334,186 @@ async fn controls_can_run_in_spawned_application_tasks() -> TestResult { tokio::spawn(async move { controller.shutdown().await }).await??; Ok(()) } + +#[tokio::test] +async fn stop_drains_a_finite_prefix_while_the_producer_keeps_sending() -> TestResult { + use std::{ + future::{Future, poll_fn}, + task::Poll, + }; + let (_temp, logger, sender) = logging(WriterOptions::default())?; + let session = logger.play(selection()).await?; + for n in 0..128 { + sender.send(data(SystemTime::now(), f64::from(n))).await?; + } + let mut stopping = Box::pin(logger.stop()); + let completed = poll_fn(|cx| { + Poll::Ready(match stopping.as_mut().poll(cx) { + Poll::Ready(result) => Some(result), + Poll::Pending => None, + }) + }) + .await; + for _ in 0..1024 { + sender.send(data(SystemTime::now(), 999.0)).await?; + } + let report = match completed { + Some(result) => result?, + None => timeout(WAIT, stopping).await??, + }; + assert_eq!(report.map(|r| r.reason), Some(StopReason::Requested)); + assert_eq!( + fs::read_to_string(session.directory.join("data/LCU/speed.csv"))? + .lines() + .count(), + 128 + ); + assert!(!sender.is_closed()); + logger.shutdown().await?; + Ok(()) +} + +#[tokio::test] +async fn input_closure_flushes_the_session_and_releases_the_worker() -> TestResult { + let (_temp, logger, sender) = logging(WriterOptions::default())?; + let session = logger.play(selection()).await?; + let mut updates = logger.subscribe(); + for n in 0..128 { + sender.send(data(SystemTime::now(), f64::from(n))).await?; + } + drop(sender); + timeout(WAIT, async { + while logger.status().phase != Phase::Closed { + if updates.changed().await.is_err() { + break; + } + } + Ok::<(), Error>(()) + }) + .await??; + logger.shutdown().await?; + assert_eq!( + fs::read_to_string(session.directory.join("data/LCU/speed.csv"))? + .lines() + .count(), + 128 + ); + Ok(()) +} + +#[tokio::test] +async fn invalid_packets_and_pending_orders_do_not_write_partial_or_fabricated_rows() -> TestResult +{ + let (_temp, logger, sender) = logging(WriterOptions::default())?; + let session = logger.play(selection()).await?; + sender + .send(received( + LCU, + SystemTime::now(), + Event::Received(Packet::Data(DataPacket::new(TELEMETRY, vec![]))), + )) + .await?; + sender + .send(received( + PCU, + SystemTime::now(), + Event::Received(Packet::Data(DataPacket::new(TELEMETRY, vec![]))), + )) + .await?; + sender + .send(received(LCU, SystemTime::now(), Event::Connected)) + .await?; + sender + .send(ToLogging::OrderSent { + at: SystemTime::now(), + board: Some(LCU), + order: OrderPacket::new(AdjId(2000), vec![]), + }) + .await?; + sender.send(data(SystemTime::now(), 42.0)).await?; + logger.stop().await?; + assert_eq!( + fs::read_to_string(session.directory.join("data/LCU/speed.csv"))? + .lines() + .count(), + 1 + ); + assert!(fs::read(session.directory.join("order/order.csv"))?.is_empty()); + logger.shutdown().await?; + Ok(()) +} + +#[tokio::test] +async fn event_routes_to_the_real_logger_across_session_stop_and_restart() -> TestResult { + use crate::event::{self, ToPipeline}; + + let temp = tempfile::tempdir()?; + let (adj, index) = definitions(); + let pod_data = Arc::new(adj.pod_data.clone()); + let config = event::EventConfig::default(); + let event::Channels { + udp, + tcp, + event: ends, + orders, + problems, + logging: input, + mut pipeline, + } = event::channels(&config); + let run = BackendRun::new( + Config { + logging_path: temp.path().into(), + ..Config::default() + }, + "adj", + )?; + let logger = Logging::new(run, adj, index.clone(), input, WriterOptions::default())?; + let event_task = event::spawn(config, ends, pod_data, index, None); + + for recording in [true, false, true] { + let session = if recording { + Some(logger.play(selection()).await?) + } else { + None + }; + for n in 0..4 { + udp.notify( + LCU, + Event::Received(Packet::Data(DataPacket::new( + TELEMETRY, + vec![ + software_core::model::Value::Number(f64::from(n)), + software_core::model::Value::Number(999.0), + ], + ))), + ) + .await?; + } + // Router sends to logging before pipeline. Receiving these four proves + // that all four passed through event's real logging sender. + for _ in 0..4 { + assert!(matches!( + timeout(WAIT, pipeline.recv()).await?, + Some(ToPipeline::Received(_)) + )); + } + if let Some(session) = session { + logger.stop().await?; + assert_eq!( + fs::read_to_string(session.directory.join("data/LCU/speed.csv"))? + .lines() + .count(), + 4 + ); + } + assert!(!event_task.is_finished()); + } + drop((udp, tcp, orders, problems)); + assert!(matches!( + timeout(WAIT, event_task).await??, + event::Stop::NetGone + )); + timeout(WAIT, logger.shutdown()).await??; + assert_eq!(logger.status().phase, Phase::Closed); + Ok(()) +} diff --git a/backend/crates/station/src/logging/test_support.rs b/backend/crates/station/src/logging/test_support.rs new file mode 100644 index 000000000..47d4d6cbe --- /dev/null +++ b/backend/crates/station/src/logging/test_support.rs @@ -0,0 +1,163 @@ +//! Native ADJ and event fixtures shared by the logging tests. + +use std::{ + collections::HashMap, + sync::Arc, + time::{Duration, SystemTime}, +}; + +use serde_json::json; +use software_core::{ + adj::Adj, + model::{ + AdjId, Board, BoardId, DataPacket, MacAddress, Measurement, MeasurementKind, MessageLevel, + NumericKind, Packet, PacketDef, PacketType, PodData, Protection, ProtectionKind, + ProtectionPacket, Severity, ShortTimestamp, Value, + }, + net::{Event, Notification}, + protocol::Index, +}; + +use super::{MeasurementKey, SessionSelection, ToLogging}; + +pub(super) type TestResult = Result<(), Box>; +pub(super) const LCU: BoardId = BoardId(1); +pub(super) const PCU: BoardId = BoardId(2); +pub(super) const TELEMETRY: AdjId = AdjId(1000); +pub(super) const SPEED: AdjId = AdjId(3000); +pub(super) const UNSELECTED: AdjId = AdjId(3001); +pub(super) const TEMPERATURE: AdjId = AdjId(3002); +pub(super) const ABOVE: AdjId = AdjId((1 << 13) | TEMPERATURE.0); +pub(super) const RANGE: AdjId = AdjId((2 << 13) | TEMPERATURE.0); +pub(super) const FAULT_MESSAGE: AdjId = AdjId(2); +pub(super) const WAIT: Duration = Duration::from_secs(3); + +pub(super) fn definitions() -> (Arc, Arc) { + let measurement = |id, alias: &str| Measurement { + id, + alias: alias.into(), + name: alias.into(), + display_units: String::new(), + kind: MeasurementKind::Numeric { + wire_type: NumericKind::F64, + }, + protections: vec![], + }; + let mut temperature = measurement(TEMPERATURE, "temperature"); + temperature.protections = vec![ + Protection { + id: AdjId(1), + kind: ProtectionKind::Above { limit: 50.0 }, + severity: Severity::Fault, + time: Duration::from_millis(500), + }, + Protection { + id: AdjId(2), + kind: ProtectionKind::Range { + min: 0.0, + max: 100.0, + }, + severity: Severity::Warning, + time: Duration::ZERO, + }, + ]; + let telemetry = PacketDef { + id: TELEMETRY, + board: LCU, + name: "telemetry".into(), + packet_type: PacketType::Data(vec![ + measurement(SPEED, "speed"), + measurement(UNSELECTED, "unselected"), + ]), + }; + let protection = |board, id| PacketDef { + id, + board, + name: "temperature protection".into(), + packet_type: PacketType::Protection(temperature.clone()), + }; + let board = |id, name: &str, packets: Vec| Board { + id, + name: name.into(), + ip: std::net::IpAddr::from([127, 0, 0, id.0 as u8]), + mac: MacAddress([0; 6]), + packets: packets + .into_iter() + .map(|packet| (packet.id, packet)) + .collect(), + }; + // PCU has its own compound ID, so Index ownership checks remain meaningful. + let pcu_protection = PacketDef { + id: AdjId((1 << 13) | 3003), + board: PCU, + name: "PCU protection".into(), + packet_type: PacketType::Protection(Measurement { + id: AdjId(3003), + ..temperature.clone() + }), + }; + let boards = [ + board( + LCU, + "LCU", + vec![telemetry, protection(LCU, ABOVE), protection(LCU, RANGE)], + ), + board(PCU, "PCU", vec![pcu_protection]), + ]; + let mut adj = Adj { + pod_data: PodData { + boards: boards.into_iter().map(|board| (board.id, board)).collect(), + }, + info: Default::default(), + }; + adj.info.message_levels = HashMap::from([(FAULT_MESSAGE, MessageLevel::Fault)]); + let index = Arc::new(Index::new(&adj.pod_data, Some(&adj.info.message_levels))); + (Arc::new(adj), index) +} + +pub(super) fn selection() -> SessionSelection { + SessionSelection { + measurements: vec![MeasurementKey { + board: LCU, + measurement_id: SPEED, + }], + connected_boards: vec![LCU], + selected_variables: json!({"LCU": ["speed"]}), + } +} + +pub(super) fn received(board: BoardId, at: SystemTime, event: Event) -> ToLogging { + ToLogging::Received(Arc::new(Notification { board, at, event })) +} + +pub(super) fn data(at: SystemTime, value: f64) -> ToLogging { + received( + LCU, + at, + Event::Received(Packet::Data(DataPacket::new( + TELEMETRY, + vec![Value::Number(value), Value::Number(999.0)], + ))), + ) +} + +pub(super) fn short_timestamp() -> ShortTimestamp { + ShortTimestamp { + hour: 12, + minute: 30, + second: 0, + subsecond: 0, + } +} + +pub(super) fn protection(board: BoardId, id: AdjId, value: f64) -> ToLogging { + received( + board, + SystemTime::now(), + Event::Received(Packet::Protection(ProtectionPacket { + id, + timestamp: short_timestamp(), + value: Value::Number(value), + })), + ) +} diff --git a/backend/crates/station/src/logging/writer/tests.rs b/backend/crates/station/src/logging/writer/tests.rs index bc856b203..0cb5b50cb 100644 --- a/backend/crates/station/src/logging/writer/tests.rs +++ b/backend/crates/station/src/logging/writer/tests.rs @@ -7,102 +7,49 @@ use std::{ }, }; -use serde_json::json; -use software_core::{logger::CsvFile, model::Value}; - -use super::*; -use crate::logging::{ - DataRecord, MeasurementKey, MessageRecord, OrderRecord, ProtectionRecord, Thresholds, +use software_core::{ + logger::CsvFile, + model::{AdjId, MessagePacket, OrderPacket}, + net::Event, }; +use tokio::sync::oneshot; +use tokio::time::timeout; -type TestResult = Result<(), Box>; - -fn selection() -> SessionSelection { - SessionSelection { - measurements: vec![MeasurementKey { - board: "LCU".into(), - measurement_id: "speed".into(), - }], - connected_boards: vec!["LCU".into()], - selected_variables: json!({"LCU": ["speed"]}), - } -} +use super::*; +use crate::logging::{Config, test_support::*}; fn time(wall_time: &str) -> Result { Ok(RecordTime { - session_id: SessionId(1), instant: u128::MAX, wall_time: wall_time.parse()?, }) } #[test] -fn all_csv_formats_preserve_fields_without_headers() -> TestResult { +fn native_csv_formats_preserve_fields_without_headers() -> TestResult { let temp = tempfile::tempdir()?; - let mut files = SessionFiles::open(temp.path(), &selection())?; + let (adj, index) = definitions(); + let catalog = Catalog::new(adj, index); + let mut files = SessionFiles::open(temp.path(), &selection(), &catalog)?; let mut stamp = time("2026-07-15T13:30:05Z")?; stamp.instant = 35000; + files.write(stamp, &data(SystemTime::now(), 12.5), u64::MAX, &catalog)?; + files.write(stamp, &protection(LCU, ABOVE, 55.0), u64::MAX, &catalog)?; + files.write(stamp, &protection(LCU, RANGE, 105.0), u64::MAX, &catalog)?; files.write( stamp, - &Record::Data(DataRecord { - from: "LCU".into(), - to: "backend".into(), - measurement_id: "speed".into(), - value: Value::Number(12.5), - }), - u64::MAX, - )?; - files.write( - stamp, - &Record::Data(DataRecord { - from: "LCU".into(), - to: "backend".into(), - measurement_id: "unselected".into(), - value: Value::Bool(true), - }), - u64::MAX, - )?; - files.write( - stamp, - &Record::Order(OrderRecord { - from: "backend".into(), - to: "LCU".into(), - id: "start".into(), - payload: "{ \"mode\": \"run\" }".into(), - }), - u64::MAX, - )?; - let mut protection = ProtectionRecord { - board: "LCU".into(), - from: "LCU".into(), - to: "backend".into(), - protection_id: "42".into(), - severity: "fault".into(), - protection_type: "above".into(), - thresholds: Thresholds::Single(Value::Number(50.0)), - measurement_id: "temperature".into(), - value: Value::Number(55.0), - accumulated_time: Some("500ms".into()), - }; - files.write(stamp, &Record::Protection(protection.clone()), u64::MAX)?; - protection.protection_type = "range".into(); - protection.thresholds = Thresholds::Range { - min: Value::Number(0.0), - max: Value::Number(100.0), - }; - protection.accumulated_time = None; - files.write(stamp, &Record::Protection(protection), u64::MAX)?; - files.write( - stamp, - &Record::Message(MessageRecord { - from: "LCU".into(), - to: "backend".into(), - board: "LCU".into(), - source: "control.cpp:123".into(), - severity: "fault".into(), - message: "failed, \"overload\"\nagain".into(), - }), + &received( + LCU, + SystemTime::now(), + Event::Received(Packet::Message(MessagePacket { + id: FAULT_MESSAGE, + timestamp: short_timestamp(), + origin: "control.cpp:123".into(), + message: "failed, \"overload\"\nagain".into(), + })), + ), u64::MAX, + &catalog, )?; assert!(files.close().is_empty()); assert_eq!( @@ -110,13 +57,14 @@ fn all_csv_formats_preserve_fields_without_headers() -> TestResult { "35000,LCU,backend,12.5\n" ); assert!(!temp.path().join("data/LCU/unselected.csv").exists()); - assert_eq!( - fs::read_to_string(temp.path().join("order/order.csv"))?, - "35000,backend,LCU,start,\"{ \"\"mode\"\": \"\"run\"\" }\",2026-07-15T15-30-05+02:00\n" - ); + // The current event contract cannot supply the original frontend JSON. + assert!(fs::read(temp.path().join("order/order.csv"))?.is_empty()); assert_eq!( fs::read_to_string(temp.path().join("protections/LCU.csv"))?, - "35000,LCU,backend,42,fault,above,50,,temperature,55,500ms\n35000,LCU,backend,42,fault,range,0,100,temperature,55,0\n" + format!( + "35000,LCU,backend,{},fault,above,50,,3002,55,\n35000,LCU,backend,{},warning,range,0,100,3002,105,0\n", + ABOVE.0, RANGE.0 + ) ); assert_eq!( fs::read_to_string(temp.path().join("messages/messages.csv"))?, @@ -126,30 +74,58 @@ fn all_csv_formats_preserve_fields_without_headers() -> TestResult { } #[test] -fn winter_order_offset_and_large_integer_instants_are_preserved() -> TestResult { +fn order_formatter_preserves_original_json_summer_and_winter_offsets_and_large_instants() +-> TestResult { let temp = tempfile::tempdir()?; - let mut files = SessionFiles::open(temp.path(), &selection())?; - files.write( + let mut orders = OrderLogger::open(temp.path())?; + let mut summer = time("2026-07-15T13:30:05Z")?; + summer.instant = 35000; + // Exercise the formatter directly; OrderSent cannot yet supply this JSON. + orders.write( + summer, + AdjId(2000), + "LCU", + "{ \"mode\": \"run\" }", + u64::MAX, + )?; + orders.write( time("2026-11-27T14:30:05Z")?, - &Record::Order(OrderRecord { - from: "backend".into(), - to: "LCU".into(), - id: "off".into(), - payload: "{}".into(), - }), + AdjId(2001), + "LCU", + "{}", u64::MAX, )?; - assert!(files.close().is_empty()); + orders.file.close()?; assert_eq!( fs::read_to_string(temp.path().join("order/order.csv"))?, format!( - "{},backend,LCU,off,{{}},2026-11-27T15-30-05+01:00\n", + "35000,backend,LCU,2000,\"{{ \"\"mode\"\": \"\"run\"\" }}\",2026-07-15T15-30-05+02:00\n{},backend,LCU,2001,{{}},2026-11-27T15-30-05+01:00\n", u128::MAX ) ); Ok(()) } +#[test] +fn pending_order_contract_is_reported_without_writing_a_row() -> TestResult { + let temp = tempfile::tempdir()?; + let (adj, index) = definitions(); + let catalog = Catalog::new(adj, index); + let mut files = SessionFiles::open(temp.path(), &selection(), &catalog)?; + let order = ToLogging::OrderSent { + at: SystemTime::now(), + board: Some(LCU), + order: OrderPacket::new(AdjId(2000), vec![]), + }; + assert!(matches!( + files.write(time("2026-11-27T14:30:05Z")?, &order, u64::MAX, &catalog), + Err(Error::OrderContractPending) + )); + assert!(files.close().is_empty()); + assert!(fs::read(temp.path().join("order/order.csv"))?.is_empty()); + Ok(()) +} + #[test] fn close_attempts_every_file_even_when_one_flush_fails() -> TestResult { struct Destination { @@ -189,30 +165,125 @@ fn close_attempts_every_file_even_when_one_flush_fails() -> TestResult { &[], )?, ]; - let errors = close_files(files.into_iter()); - assert_eq!(errors.len(), 1); + assert_eq!(close_files(files.into_iter()).len(), 1); assert!(first.load(Ordering::SeqCst)); assert!(second.load(Ordering::SeqCst)); Ok(()) } +#[tokio::test] +async fn observed_full_input_stops_notifies_drains_and_keeps_the_receiver_alive() -> TestResult { + let temp = tempfile::tempdir()?; + let run = BackendRun::new( + Config { + logging_path: temp.path().into(), + ..Config::default() + }, + "adj", + )?; + let (adj, index) = definitions(); + let (sender, input) = mpsc::channel(2); + let (controls, control_rx) = mpsc::unbounded_channel(); + let (updates, mut status) = watch::channel(Status::default()); + let mut writer = Writer { + run, + input, + controls: control_rx, + updates, + status: Status::default(), + catalog: Catalog::new(adj, index), + options: WriterOptions::default(), + active: None, + next_id: 0, + order_contract_reported: false, + }; + let session = writer.start(selection()).await?; + // Fill the real channel before the consumer runs, so saturation is + // deterministic rather than dependent on OS thread scheduling. + sender.try_send(data(SystemTime::now(), 1.0))?; + sender.try_send(data(SystemTime::now(), 2.0))?; + let worker = tokio::spawn(writer.run()); + timeout(WAIT, async { + loop { + if status.borrow().last_stop.is_some() { + break; + } + status.changed().await?; + } + Ok::<(), watch::error::RecvError>(()) + }) + .await??; + assert_eq!(status.borrow().phase, Phase::Inactive); + assert_eq!( + status + .borrow() + .last_stop + .as_ref() + .map(|report| report.reason), + Some(StopReason::Saturation) + ); + assert_eq!( + fs::read_to_string(session.directory.join("data/LCU/speed.csv"))? + .lines() + .count(), + 2 + ); + assert!(!sender.is_closed()); + let (reply, response) = oneshot::channel(); + controls.send(Control::Play { + selection: selection(), + reply, + })?; + let next = timeout(WAIT, response).await???; + assert_ne!(session.id, next.id); + assert_eq!( + status + .borrow() + .last_stop + .as_ref() + .map(|report| report.reason), + Some(StopReason::Saturation) + ); + let (reply, response) = oneshot::channel(); + controls.send(Control::Shutdown { + at: SystemTime::now(), + reply: Some(reply), + })?; + timeout(WAIT, response).await??; + timeout(WAIT, worker).await??; + assert_eq!(status.borrow().phase, Phase::Closed); + Ok(()) +} + #[test] -fn unexpected_exit_releases_queued_start_replies() { - let shared = Arc::new(Shared::new(2)); - let (reply, mut response) = tokio::sync::oneshot::channel(); - { - let mut state = shared.lock(); - state.phase = Phase::Starting; - state.queue.push_back(Command::Start { - id: SessionId(1), - selection: selection(), - reply, - }); - } - drop(ExitGuard(shared.clone())); - assert_eq!(shared.lock().phase, Phase::Closed); +fn unexpected_exit_publishes_failure() { + let (updates, status) = watch::channel(Status { + phase: Phase::Starting, + ..Status::default() + }); + drop(ExitGuard(updates)); + assert_eq!(status.borrow().phase, Phase::Closed); + assert!( + status + .borrow() + .last_error + .as_deref() + .is_some_and(|error| error.contains("unexpectedly")) + ); +} + +#[test] +fn dropping_pending_controls_releases_start_replies() -> TestResult { + let (sender, receiver) = mpsc::unbounded_channel(); + let (reply, mut response) = oneshot::channel(); + sender.send(Control::Play { + selection: selection(), + reply, + })?; + drop(receiver); assert!(matches!( response.try_recv(), - Err(tokio::sync::oneshot::error::TryRecvError::Closed) + Err(oneshot::error::TryRecvError::Closed) )); + Ok(()) } From 0026070eed8371fcd8c217d30deea197d14765da Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Thu, 3 Dec 2026 13:31:38 +0100 Subject: [PATCH 179/225] fix(backent, logging): correct order logging to match OrderPacket --- backend/crates/station/src/logging/README.md | 47 ++++--- backend/crates/station/src/logging/catalog.rs | 19 ++- backend/crates/station/src/logging/error.rs | 4 +- backend/crates/station/src/logging/order.rs | 55 ++++++-- .../station/src/logging/service/tests.rs | 85 +++++++++++- backend/crates/station/src/logging/session.rs | 3 +- backend/crates/station/src/logging/writer.rs | 28 ++-- .../station/src/logging/writer/tests.rs | 122 ++++++++++++++---- 8 files changed, 280 insertions(+), 83 deletions(-) diff --git a/backend/crates/station/src/logging/README.md b/backend/crates/station/src/logging/README.md index 4748a9c69..381669ce8 100644 --- a/backend/crates/station/src/logging/README.md +++ b/backend/crates/station/src/logging/README.md @@ -49,6 +49,8 @@ internal controls. - `Received(Arc)`: carries `board: BoardId`, `at: SystemTime` and a connection event or a decoded `Packet`. - `OrderSent { at, board, order }`: confirms that an order was written to TCP. + Logging uses `at` for both elapsed and calendar time and stores the packet + as compact JSON in the order CSV's payload cell. `Catalog` keeps the supplied ADJ and protocol index shared. It builds a small measurement locator once, using `(BoardId, AdjId)` as keys. It resolves: @@ -119,10 +121,6 @@ fn start_logging_consumer( These are deliberately not filled in with reconstructed or guessed data: -- **Orders:** `OrderSent` is later than frontend reception and contains no - original JSON text. The consumer reports this pending contract once and - keeps draining. It does not write misleading order rows. The order file - and formatter are retained for the eventual original-payload input. - **Accumulated protection timing:** the current `ProtectionPacket` has no separate accumulated-time result. Untimed protections write `0`; timed protections temporarily leave that cell empty to mean unavailable. The @@ -238,8 +236,9 @@ startup, its `instant` will be `35` with `time_unit = "ms"`, or `35000` with `"us"`. The low-level session retains its monotonic clock for elapsed-time helpers. The -`ToLogging` path uses the upstream `Notification::at` (`SystemTime`) against -the session's wall-clock origin, so queue delays are not added to `instant`. +`ToLogging` path uses the upstream `Notification::at` or `OrderSent::at` +(`SystemTime`) against the session's wall-clock origin, so queue delays are +not added to `instant`. A monotonic timestamp at original reception is not available in the current event contract; immunity to wall-clock changes therefore remains pending. @@ -312,16 +311,28 @@ instant,from,to,id,payload,timestamp | Field | Content | | --- | --- | | `instant` | Time since the session started, in `time_unit`. | -| `from` | Order source. | -| `to` | Order destination. | +| `from` | `backend`. | +| `to` | ADJ board name, or `all` when `OrderSent.board` is `None`. | | `id` | Order ID. | -| `payload` | JSON received from the frontend over WebSocket, preserved as text. | -| `timestamp` | Order date and time, using the format and offset described above. | +| `payload` | The confirmed `OrderPacket` as compact JSON: numeric `id` and positional `values`. | +| `timestamp` | TCP confirmation date and time from `OrderSent.at`, using the format and offset described above. | -The required behavior is to record an order **when received from the frontend**, -with the original JSON. The current `ToLogging::OrderSent` cannot satisfy that -contract, so writing order rows is deferred rather than substituting a later -timestamp or reconstructed payload. +Orders are recorded from `event::ToLogging::OrderSent` while a session is +active. Its `at` supplies both the elapsed `instant` and calendar `timestamp`. +Only confirmed sends are recorded; incoming network `Packet::Order` events +produce no order row. Logger controls arrive separately from WebSocket. + +Each payload is a single-line JSON object inside the CSV cell, for example: + +```json +{"id":2000,"values":[1.5,true,"run"]} +``` + +Values retain their packet order and use JSON numbers, booleans and strings +for model `Number`, `Bool` and `Enum` values. JSON escapes embedded newlines; +`logger::Row::text` then escapes the JSON for the CSV cell. There is no separate +JSONL file or extra newline within this cell. Non-finite numeric values cannot +be represented as JSON and stop recording with an error before writing a row. ### Protections: protections/ @@ -559,7 +570,6 @@ buffers, and explicit flush and close operations. - Running `adj-validator` and obtaining its output. - Trace levels and filters, and their connection to the JSONL file. - Exact schema of `selected_variables` in JSON and the session-control channel. -- Original order JSON and frontend reception time in the input contract. - Board-supplied accumulated timing and monotonic reception timestamps. - Disconnection stop rule when multiple frontends are connected. - Frontend notification format and integration through the application modules. @@ -579,9 +589,10 @@ replies, fallback drop and input closure. An integration scenario connects sessions, then checks the persisted CSVs and orderly shutdown. Writer tests check headerless CSVs, escaping, protection metadata, missing -board timing, the order formatter's original JSON and timezone offsets, +board timing, serialized OrderPacket values and timezone offsets, large integer instants, deterministic full-channel handling and failed closes. -Pending `OrderSent` input is explicitly checked to leave the order CSV empty; -testing the formatter directly does not imply that order reception is wired. +Order tests also cover event routing, confirmation timestamps, broadcast +destinations and rejected non-finite numbers. Connecting the real logging +service to application startup remains pending. `rustfmt` and `git diff --check` validate formatting and whitespace. diff --git a/backend/crates/station/src/logging/catalog.rs b/backend/crates/station/src/logging/catalog.rs index 09ab9cc26..abca260a7 100644 --- a/backend/crates/station/src/logging/catalog.rs +++ b/backend/crates/station/src/logging/catalog.rs @@ -151,9 +151,16 @@ impl Catalog { /// `true` means the packet is structurally eligible for writing; measurement /// selection is applied separately by the CSV writer. pub fn validate(&self, incoming: &ToLogging) -> Result { - let ToLogging::Received(notification) = incoming else { - // OrderSent has neither the original JSON nor frontend reception time. - return Err(Error::OrderContractPending); + let notification = match incoming { + ToLogging::OrderSent { board, .. } => { + // Event confirms the packet was sent. Resolve its destination; + // the broadcast fault has no single owner or ADJ packet entry. + if let Some(board) = board { + validate_name(&self.board(*board)?.name)?; + } + return Ok(true); + } + ToLogging::Received(notification) => notification, }; // Board labels become directories or filenames, so validate the label // from the ADJ before it can reach a file writer. @@ -175,9 +182,9 @@ impl Catalog { Event::Received(Packet::Message(packet)) => { self.message_level(notification.board, packet.id)?; } - // Receiving a decoded order does not restore the missing original - // frontend JSON or establish its frontend reception timestamp. - Event::Received(Packet::Order(_)) => return Err(Error::OrderContractPending), + // Only OrderSent records outgoing orders; network reception is + // not a confirmation that this backend sent an order. + Event::Received(Packet::Order(_)) => return Ok(false), } Ok(true) } diff --git a/backend/crates/station/src/logging/error.rs b/backend/crates/station/src/logging/error.rs index 2083a9524..7896f8465 100644 --- a/backend/crates/station/src/logging/error.rs +++ b/backend/crates/station/src/logging/error.rs @@ -22,8 +22,8 @@ pub enum Error { UnexpectedPacketType(AdjId), #[error("packet {0:?} value count differs from its ADJ measurement count")] MeasurementCount(AdjId), - #[error("order logging awaits original frontend JSON and reception time in the event contract")] - OrderContractPending, + #[error("couldn't serialize the logged OrderPacket: {0}")] + OrderPayload(#[source] serde_json::Error), #[error("invalid logging file component: {0:?}")] InvalidName(String), #[error("flush interval and flush byte threshold must be positive")] diff --git a/backend/crates/station/src/logging/order.rs b/backend/crates/station/src/logging/order.rs index 078b06b59..b7d85d634 100644 --- a/backend/crates/station/src/logging/order.rs +++ b/backend/crates/station/src/logging/order.rs @@ -4,14 +4,18 @@ //! `timestamp` is the order's wall-clock time formatted as //! `YYYY-MM-DDTHH-MM-SS` followed by the applicable `Europe/Madrid` UTC offset //! (`+01:00` for CET or `+02:00` for CEST). -//! Orders are recorded when received from the frontend over WebSocket; -//! `payload` preserves the received JSON as text. There is no header. +//! Orders come from event's `OrderSent`, using its TCP confirmation time. +//! `payload` is the OrderPacket as compact JSON in one CSV cell. No header. //! //! This component owns a `software_core::logger::CsvFile` and formats rows. use std::path::Path; -use software_core::{logger::CsvFile, model::AdjId}; +use serde::{Serialize, Serializer, ser::SerializeSeq}; +use software_core::{ + logger::CsvFile, + model::{OrderPacket, Value}, +}; use super::{Error, output::flush_if_due, session::RecordTime}; @@ -28,17 +32,20 @@ impl OrderLogger { }) } - /// Pending input contract: only call with the original frontend JSON. - /// Writes a complete row in the order.csv file, following this order per columns - /// instant,from,to,order_id,payload,timestamp + /// Serialize the confirmed packet before starting a row, so a payload + /// failure cannot leave a partial CSV record. Values remain positional. pub fn write( &mut self, time: RecordTime, - id: AdjId, + order: &OrderPacket, to: &str, - payload: &str, threshold: u64, ) -> Result<(), Error> { + let payload = serde_json::to_string(&Payload { + id: order.id.0, + values: &order.values, + }) + .map_err(Error::OrderPayload)?; let timestamp = time .wall_time .in_tz("Europe/Madrid")? @@ -49,11 +56,39 @@ impl OrderLogger { .instant(time.instant) .text("backend") // orders will always come from the backend and never from the boards .text(to) - .int(i64::from(id.0)) - .text(payload) + .int(i64::from(order.id.0)) + .text(&payload) .text(×tamp) .end()?; // validates row and ends it flush_if_due(&mut self.file, threshold)?; Ok(()) } } + +/// A borrowed JSON view keeps logging's representation out of core's model +/// and avoids copying packet values or building an intermediate JSON tree. +#[derive(Serialize)] +struct Payload<'a> { + id: u16, + #[serde(serialize_with = "serialize_values")] + values: &'a [Value], +} + +fn serialize_values(values: &[Value], serializer: S) -> Result { + let mut sequence = serializer.serialize_seq(Some(values.len()))?; + for value in values { + match value { + Value::Number(value) => { + // JSON has no NaN/infinity; never silently replace a value + // with null and present that as the packet that was sent. + if !value.is_finite() { + return Err(serde::ser::Error::custom("non-finite order value")); + } + sequence.serialize_element(value)?; + } + Value::Bool(value) => sequence.serialize_element(value)?, + Value::Enum(value) => sequence.serialize_element(value)?, + } + } + sequence.end() +} diff --git a/backend/crates/station/src/logging/service/tests.rs b/backend/crates/station/src/logging/service/tests.rs index ad7bbd6b5..0f5cfb25e 100644 --- a/backend/crates/station/src/logging/service/tests.rs +++ b/backend/crates/station/src/logging/service/tests.rs @@ -402,7 +402,7 @@ async fn input_closure_flushes_the_session_and_releases_the_worker() -> TestResu } #[tokio::test] -async fn invalid_packets_and_pending_orders_do_not_write_partial_or_fabricated_rows() -> TestResult +async fn invalid_packets_and_received_orders_do_not_write_partial_or_duplicate_rows() -> TestResult { let (_temp, logger, sender) = logging(WriterOptions::default())?; let session = logger.play(selection()).await?; @@ -424,11 +424,11 @@ async fn invalid_packets_and_pending_orders_do_not_write_partial_or_fabricated_r .send(received(LCU, SystemTime::now(), Event::Connected)) .await?; sender - .send(ToLogging::OrderSent { - at: SystemTime::now(), - board: Some(LCU), - order: OrderPacket::new(AdjId(2000), vec![]), - }) + .send(received( + LCU, + SystemTime::now(), + Event::Received(Packet::Order(OrderPacket::new(AdjId(2000), vec![]))), + )) .await?; sender.send(data(SystemTime::now(), 42.0)).await?; logger.stop().await?; @@ -468,7 +468,21 @@ async fn event_routes_to_the_real_logger_across_session_stop_and_restart() -> Te "adj", )?; let logger = Logging::new(run, adj, index.clone(), input, WriterOptions::default())?; - let event_task = event::spawn(config, ends, pod_data, index, None); + struct Tcp; + impl event::TcpLink for Tcp { + fn send( + &self, + _order: OrderPacket, + ) -> event::BoxFuture<'_, Result> { + Box::pin(async { Ok(LCU) }) + } + fn send_fault( + &self, + ) -> event::BoxFuture<'_, Result<(), Vec>> { + Box::pin(async { Ok(()) }) + } + } + let event_task = event::spawn(config, ends, pod_data, index, Some(Arc::new(Tcp))); for recording in [true, false, true] { let session = if recording { @@ -508,6 +522,27 @@ async fn event_routes_to_the_real_logger_across_session_stop_and_restart() -> Te } assert!(!event_task.is_finished()); } + let session = logger.play(selection()).await?; + orders + .send(OrderPacket::new( + AdjId(2000), + vec![software_core::model::Value::Bool(true)], + )) + .await?; + let confirmed_at = match timeout(WAIT, pipeline.recv()).await? { + Some(ToPipeline::OrderSent { at, .. }) => at, + other => return Err(format!("expected a confirmed order, got {other:?}").into()), + }; + logger.stop().await?; + let timestamp = jiff::Timestamp::try_from(confirmed_at)? + .in_tz("Europe/Madrid")? + .strftime("%Y-%m-%dT%H-%M-%S%:z") + .to_string(); + let contents = fs::read_to_string(session.directory.join("order/order.csv"))?; + assert_eq!(contents.lines().count(), 1); + assert!(contents.ends_with(&format!( + ",backend,LCU,2000,\"{{\"\"id\"\":2000,\"\"values\"\":[true]}}\",{timestamp}\n" + ))); drop((udp, tcp, orders, problems)); assert!(matches!( timeout(WAIT, event_task).await??, @@ -517,3 +552,39 @@ async fn event_routes_to_the_real_logger_across_session_stop_and_restart() -> Te assert_eq!(logger.status().phase, Phase::Closed); Ok(()) } + +#[tokio::test] +async fn an_unrepresentable_order_payload_stops_recording_and_flushes_healthy_files() -> TestResult +{ + let (_temp, logger, sender) = logging(WriterOptions::default())?; + let session = logger.play(selection()).await?; + sender.send(data(SystemTime::now(), 7.0)).await?; + sender + .send(ToLogging::OrderSent { + at: SystemTime::now(), + board: Some(LCU), + order: OrderPacket::new( + AdjId(2000), + vec![software_core::model::Value::Number(f64::NAN)], + ), + }) + .await?; + assert!(matches!( + timeout(WAIT, logger.stop()).await?, + Err(Error::RecordingFailed(_)) + )); + assert_eq!( + logger.status().last_stop.map(|report| report.reason), + Some(StopReason::WriteError) + ); + assert!(fs::read(session.directory.join("order/order.csv"))?.is_empty()); + assert!( + fs::read_to_string(session.directory.join("data/LCU/speed.csv"))? + .ends_with(",LCU,backend,7\n") + ); + assert!(matches!( + logger.shutdown().await, + Err(Error::RecordingFailed(_)) + )); + Ok(()) +} diff --git a/backend/crates/station/src/logging/session.rs b/backend/crates/station/src/logging/session.rs index 3c7826b6e..3e8c703b8 100644 --- a/backend/crates/station/src/logging/session.rs +++ b/backend/crates/station/src/logging/session.rs @@ -71,7 +71,8 @@ impl SessionId { } } -/// Writer-private stamp, always derived from the incoming event's reception time. +/// Writer-private stamp derived from notification reception or OrderSent's +/// TCP confirmation time, as supplied by event. #[derive(Debug, Clone, Copy)] pub(super) struct RecordTime { pub instant: u128, diff --git a/backend/crates/station/src/logging/writer.rs b/backend/crates/station/src/logging/writer.rs index 0ecb9ef0a..e7ba54a68 100644 --- a/backend/crates/station/src/logging/writer.rs +++ b/backend/crates/station/src/logging/writer.rs @@ -21,10 +21,10 @@ use super::{ StopReason, StopReport, ToLogging, catalog::Catalog, control::Control, - output::{close_files, flush_files}, data::DataLogger, messages::MessagesLogger, order::OrderLogger, + output::{close_files, flush_files}, protections::ProtectionsLogger, session::RecordTime, status::checked_report, @@ -96,10 +96,15 @@ impl SessionFiles { threshold: u64, catalog: &Catalog, ) -> Result<(), Error> { - let ToLogging::Received(notification) = record else { - // OrderSent lacks the original frontend JSON and reception time. - // Keep that contract pending instead of inventing an order row. - return Err(Error::OrderContractPending); + let notification = match record { + ToLogging::OrderSent { board, order, .. } => { + let to = match board { + Some(board) => catalog.board(*board)?.name.as_str(), + None => "all", + }; + return self.orders.write(time, order, to, threshold); + } + ToLogging::Received(notification) => notification, }; let board = catalog.board(notification.board)?; match ¬ification.event { @@ -133,7 +138,7 @@ impl SessionFiles { catalog.message_level(notification.board, packet.id)?, threshold, ), - Event::Received(Packet::Order(_)) => Err(Error::OrderContractPending), + Event::Received(Packet::Order(_)) => Ok(()), } } @@ -194,7 +199,6 @@ struct Writer { options: WriterOptions, active: Option, next_id: u64, - order_contract_reported: bool, } enum Step { @@ -231,7 +235,6 @@ pub(super) fn run( status: Status::default(), active: None, next_id: 0, - order_contract_reported: false, } .run(), ), @@ -370,15 +373,6 @@ impl Writer { }; match self.catalog.validate(incoming) { Ok(false) => return false, - Err(Error::OrderContractPending) => { - if !self.order_contract_reported { - tracing::warn!( - "OrderSent logging pending: original frontend JSON and reception time are unavailable" - ); - self.order_contract_reported = true; - } - return false; - } Err(error) => { tracing::warn!(%error, "logging input could not be recorded"); return false; diff --git a/backend/crates/station/src/logging/writer/tests.rs b/backend/crates/station/src/logging/writer/tests.rs index 0cb5b50cb..69992eb94 100644 --- a/backend/crates/station/src/logging/writer/tests.rs +++ b/backend/crates/station/src/logging/writer/tests.rs @@ -9,7 +9,7 @@ use std::{ use software_core::{ logger::CsvFile, - model::{AdjId, MessagePacket, OrderPacket}, + model::{AdjId, MessagePacket, OrderPacket, Value}, net::Event, }; use tokio::sync::oneshot; @@ -57,7 +57,7 @@ fn native_csv_formats_preserve_fields_without_headers() -> TestResult { "35000,LCU,backend,12.5\n" ); assert!(!temp.path().join("data/LCU/unselected.csv").exists()); - // The current event contract cannot supply the original frontend JSON. + // These notifications contain no confirmed outgoing order. assert!(fs::read(temp.path().join("order/order.csv"))?.is_empty()); assert_eq!( fs::read_to_string(temp.path().join("protections/LCU.csv"))?, @@ -74,32 +74,33 @@ fn native_csv_formats_preserve_fields_without_headers() -> TestResult { } #[test] -fn order_formatter_preserves_original_json_summer_and_winter_offsets_and_large_instants() --> TestResult { +fn order_payload_offsets_and_large_instants_are_preserved() -> TestResult { let temp = tempfile::tempdir()?; let mut orders = OrderLogger::open(temp.path())?; let mut summer = time("2026-07-15T13:30:05Z")?; summer.instant = 35000; - // Exercise the formatter directly; OrderSent cannot yet supply this JSON. - orders.write( - summer, + let order = OrderPacket::new( AdjId(2000), - "LCU", - "{ \"mode\": \"run\" }", - u64::MAX, - )?; + vec![ + Value::Number(1.5), + Value::Bool(true), + Value::Enum("run, \"fast\"\nnext".into()), + ], + ); + orders.write(summer, &order, "LCU", u64::MAX)?; orders.write( time("2026-11-27T14:30:05Z")?, - AdjId(2001), + &OrderPacket::new(AdjId(2001), vec![]), "LCU", - "{}", u64::MAX, )?; orders.file.close()?; + let payload = r#"{"id":2000,"values":[1.5,true,"run, \"fast\"\nnext"]}"#; assert_eq!( fs::read_to_string(temp.path().join("order/order.csv"))?, format!( - "35000,backend,LCU,2000,\"{{ \"\"mode\"\": \"\"run\"\" }}\",2026-07-15T15-30-05+02:00\n{},backend,LCU,2001,{{}},2026-11-27T15-30-05+01:00\n", + "35000,backend,LCU,2000,\"{}\",2026-07-15T15-30-05+02:00\n{},backend,LCU,2001,\"{{\"\"id\"\":2001,\"\"values\"\":[]}}\",2026-11-27T15-30-05+01:00\n", + payload.replace('"', "\"\""), u128::MAX ) ); @@ -107,21 +108,45 @@ fn order_formatter_preserves_original_json_summer_and_winter_offsets_and_large_i } #[test] -fn pending_order_contract_is_reported_without_writing_a_row() -> TestResult { +fn confirmed_broadcast_orders_use_all_as_destination() -> TestResult { let temp = tempfile::tempdir()?; let (adj, index) = definitions(); let catalog = Catalog::new(adj, index); let mut files = SessionFiles::open(temp.path(), &selection(), &catalog)?; let order = ToLogging::OrderSent { at: SystemTime::now(), - board: Some(LCU), - order: OrderPacket::new(AdjId(2000), vec![]), + board: None, + order: OrderPacket::new(AdjId(0), vec![]), }; - assert!(matches!( - files.write(time("2026-11-27T14:30:05Z")?, &order, u64::MAX, &catalog), - Err(Error::OrderContractPending) - )); + assert!(catalog.validate(&order)?); + files.write(time("2026-11-27T14:30:05Z")?, &order, u64::MAX, &catalog)?; assert!(files.close().is_empty()); + assert_eq!( + fs::read_to_string(temp.path().join("order/order.csv"))?, + format!( + "{},backend,all,0,\"{{\"\"id\"\":0,\"\"values\"\":[]}}\",2026-11-27T15-30-05+01:00\n", + u128::MAX + ) + ); + Ok(()) +} + +#[test] +fn non_finite_order_values_are_rejected_before_starting_a_csv_row() -> TestResult { + let temp = tempfile::tempdir()?; + let mut orders = OrderLogger::open(temp.path())?; + for value in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] { + assert!(matches!( + orders.write( + time("2026-11-27T14:30:05Z")?, + &OrderPacket::new(AdjId(2000), vec![Value::Number(value)]), + "LCU", + u64::MAX + ), + Err(Error::OrderPayload(_)) + )); + } + orders.file.close()?; assert!(fs::read(temp.path().join("order/order.csv"))?.is_empty()); Ok(()) } @@ -195,7 +220,6 @@ async fn observed_full_input_stops_notifies_drains_and_keeps_the_receiver_alive( options: WriterOptions::default(), active: None, next_id: 0, - order_contract_reported: false, }; let session = writer.start(selection()).await?; // Fill the real channel before the consumer runs, so saturation is @@ -287,3 +311,57 @@ fn dropping_pending_controls_releases_start_replies() -> TestResult { )); Ok(()) } + +#[tokio::test] +async fn orders_use_confirmation_time_for_elapsed_and_wall_timestamps() -> TestResult { + let temp = tempfile::tempdir()?; + let run = BackendRun::new( + Config { + logging_path: temp.path().into(), + ..Config::default() + }, + "adj", + )?; + let (adj, index) = definitions(); + let (_sender, input) = mpsc::channel(16); + let (_controls, controls) = mpsc::unbounded_channel(); + let (updates, _status) = watch::channel(Status::default()); + let mut writer = Writer { + run, + input, + controls, + updates, + status: Status::default(), + catalog: Catalog::new(adj, index), + options: WriterOptions::default(), + active: None, + next_id: 0, + }; + let session = writer.start(selection()).await?; + let origin = writer + .active + .as_ref() + .ok_or("session was not opened")? + .session + .wall_origin(); + let at = origin + Duration::from_millis(35); + let order = |at| ToLogging::OrderSent { + at, + board: Some(LCU), + order: OrderPacket::new(AdjId(2000), vec![]), + }; + // An old confirmation cannot leak into this session. A later one must + // use its own stamp, even if the writer processes it immediately. + assert!(!writer.write(&order(origin - Duration::from_secs(1)), None)); + assert!(!writer.write(&order(at), None)); + writer.stop(StopReason::Requested, at).await; + let timestamp = jiff::Timestamp::try_from(at)? + .in_tz("Europe/Madrid")? + .strftime("%Y-%m-%dT%H-%M-%S%:z") + .to_string(); + assert_eq!( + fs::read_to_string(session.directory.join("order/order.csv"))?, + format!("35000,backend,LCU,2000,\"{{\"\"id\"\":2000,\"\"values\"\":[]}}\",{timestamp}\n") + ); + Ok(()) +} From 1c080ea8c1a7bc8d716660e506c600c868837e24 Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Thu, 3 Dec 2026 13:48:33 +0100 Subject: [PATCH 180/225] fix(backend, websockets): ensure turning off the broker --- backend/crates/station/src/http/server.rs | 50 +++++++++- backend/crates/station/src/websocket.rs | 29 ++++-- .../crates/station/src/websocket/README.md | 24 +++-- .../crates/station/src/websocket/broker.rs | 93 ++++++++++++++----- .../crates/station/src/websocket/handler.rs | 8 +- .../crates/station/src/websocket/receiver.rs | 16 ++-- 6 files changed, 175 insertions(+), 45 deletions(-) diff --git a/backend/crates/station/src/http/server.rs b/backend/crates/station/src/http/server.rs index a2f94877a..8c441950b 100644 --- a/backend/crates/station/src/http/server.rs +++ b/backend/crates/station/src/http/server.rs @@ -300,7 +300,7 @@ mod tests { let heartbeat_timeout = Duration::from_millis(500); let socket_task = tokio::spawn(websocket::run( receiver, - client.clone(), + client.subscriber(), commands, heartbeat_timeout, )); @@ -364,6 +364,54 @@ mod tests { Ok(()) } + #[tokio::test] + async fn stopping_the_broker_closes_sessions_and_ends_websocket() + -> Result<(), Box> { + let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("../core/src/adj/test/adj"); + let adj = load_from_dir(&path)?; + let (order_tx, mut orders) = mpsc::channel(1); + let commands = Commands { + orders: Some(OrderForwarder::new( + Arc::new(Index::new(&adj.pod_data, None)), + order_tx, + )), + ..Commands::default() + }; + let (broker, client) = Broker::new(); + let broker_task = tokio::spawn(broker.run()); + let (sockets, receiver) = mpsc::channel(1); + // Long enough that the test needs no heartbeats. + let socket_task = tokio::spawn(websocket::run( + receiver, + client.subscriber(), + commands, + Duration::from_secs(5), + )); + // The test server stops right after the handshake, which also closes + // the handoff channel: the open session must still be supervised. + let (headers, mut socket) = handshake(setup_router(&adj, Some(sockets))?).await?; + assert!(headers.starts_with("HTTP/1.1 101 Switching Protocols\r\n")); + + timeout(Duration::from_secs(5), async { + // The order reaching its queue confirms the session runs, with no subscriptions. + send_text( + &mut socket, + r#"{"topic":"order/send","payload":{"id":809,"fields":{"desired_current":{"value":12.5,"isEnabled":true,"type":"float32"},"lpu_id":{"value":2,"isEnabled":true,"type":"uint32"}}}}"#, + ) + .await?; + assert!(orders.recv().await.is_some()); + + // The last publisher leaving stops the broker, as when station shuts down. + drop(client); + broker_task.await?; + assert_eq!(socket_task.await?, Ok(())); + assert_eq!(socket.read_u8().await?, 0x88, "expected a close frame"); + Ok::<_, Box>(()) + }) + .await??; + Ok(()) + } + async fn send_text( socket: &mut TcpStream, text: &str, diff --git a/backend/crates/station/src/websocket.rs b/backend/crates/station/src/websocket.rs index 15ac5bcd7..2c29e55b3 100644 --- a/backend/crates/station/src/websocket.rs +++ b/backend/crates/station/src/websocket.rs @@ -13,7 +13,7 @@ use tokio::{ time::{Instant, sleep_until}, }; -use self::broker::BrokerClient; +use self::broker::Subscriber; use self::handler::SessionEnd; pub(crate) use self::order::OrderForwarder; @@ -110,30 +110,40 @@ pub struct FrontendDisconnected; /// Returns `FrontendDisconnected` once every session has ended and /// `heartbeat_timeout` has passed since the last valid application message /// of any of them. A frontend that reconnects within that period cancels it. -/// There is no deadline before the first frontend connects. Closing the HTTP -/// handoff channel ends socket intake. Existing sessions end independently. +/// There is no deadline before the first frontend connects. +/// +/// Returns `Ok(())` when the broker stops, which is how station shuts down: +/// every session closes its socket, and `run` waits for them before +/// returning. Closing the HTTP handoff channel only stops accepting sockets; +/// open sessions and the heartbeat timeout carry on. /// /// The caller should report `FrontendDisconnected` to `event` when station /// wires the two modules together. pub async fn run( mut connections: mpsc::Receiver, - broker: BrokerClient, + broker: Subscriber, commands: Commands, heartbeat_timeout: Duration, ) -> Result<(), FrontendDisconnected> { let (session_ends, mut ended) = mpsc::channel(16); let mut sessions = FrontendSessions::default(); + let mut accepting = true; loop { tokio::select! { biased; + // Stopping takes priority: the deadline no longer matters once station shuts down. + () = broker.closed() => break, _ = async { if let Some(deadline) = sessions.deadline { sleep_until(deadline).await; } }, if sessions.deadline.is_some() => return Err(FrontendDisconnected), - socket = connections.recv() => { - let Some(socket) = socket else { return Ok(()); }; + socket = connections.recv(), if accepting => { + let Some(socket) = socket else { + accepting = false; + continue; + }; sessions.connected(); let broker = broker.clone(); let commands = commands.clone(); @@ -145,6 +155,13 @@ pub async fn run( Some(end) = ended.recv() => sessions.ended(end, heartbeat_timeout), } } + + // New upgrades get 503 from now on. Each session sees the broker stop and + // closes its socket; the queue ends once every handler has finished. + drop(connections); + drop(session_ends); + while ended.recv().await.is_some() {} + Ok(()) } /// Tracks the active frontend sessions and the deadline after the last one ends. diff --git a/backend/crates/station/src/websocket/README.md b/backend/crates/station/src/websocket/README.md index 4b7f3aff7..1178c6ff7 100644 --- a/backend/crates/station/src/websocket/README.md +++ b/backend/crates/station/src/websocket/README.md @@ -1,12 +1,13 @@ # WebSocket -`broker.rs` provides `Broker` and the clonable `BrokerClient` for state and event topics, -using the types from `crate::payload`, exposed publicly as `station::payload`. +`broker.rs` provides `Broker`, the clonable `BrokerClient` that publishes to +its state and event topics, and the clonable `Subscriber` that subscribes to +them, using the types from `crate::payload`, exposed publicly as `station::payload`. See the [payload models README](../payload/README.md) for all topic payloads, JSON templates, and complete message examples. Their serialization helpers live in [`../payload/serialize.rs`](../payload/serialize.rs). -| Topic | Publish through `BrokerClient` | Subscribe through `BrokerClient` | Initial state | +| Topic | Publish through `BrokerClient` | Subscribe through `Subscriber` | Initial state | | --- | --- | --- | --- | | `connection/update` | `publish_connection(connection)` | `subscribe_connections()` | `{}` | | `order/stateOrders` | `publish_state_orders(orders)` | `subscribe_state_orders()` | `{}` | @@ -15,10 +16,12 @@ live in [`../payload/serialize.rs`](../payload/serialize.rs). | `message/update` | `publish_message(message)` | `subscribe_messages()` | No initial event | | `protection/update` | `publish_protection(protection)` | `subscribe_protections()` | No initial event | -- `Broker::new()` creates both objects and the initial topic states. +- `Broker::new()` creates the broker, a `BrokerClient` and the initial topic + states. `BrokerClient::subscriber()` returns a `Subscriber`. - `Broker::run()` consumes a bounded `mpsc` channel of typed updates and publishes state through `watch` and events through `broadcast`. It stops after all `BrokerClient` instances are dropped and pending updates have been processed. + A `Subscriber` does not keep it running; `Subscriber::closed()` waits until it stops. - Publication waits for capacity and returns `Error::BrokerClosed` if the broker closed. Connection updates merge one board into the current map; order updates replace the entire map, including empty lists or an empty map. @@ -49,13 +52,22 @@ The station binary currently runs a greeting demo. To expose `/backend/ws` from a caller, bind a listener and pass it and the sender of a bounded socket channel to `station::http::serve`. Create the broker and client with `station::websocket::broker::Broker::new()` and start `broker.run()` as a Tokio task. -Pass the socket receiver, the `BrokerClient`, the command destinations, and a +Pass the socket receiver, `client.subscriber()`, the command destinations, and a heartbeat timeout, normally `station::websocket::DEFAULT_HEARTBEAT_TIMEOUT`, to `station::websocket::run`. `Commands::default()` leaves the order and logger destinations unset. Each socket has independent reading and writing futures, coordinated by -`handler.rs`. Either future finishing closes the session. +`handler.rs`. Either future finishing closes the session, and so does the +broker stopping. + +Station shuts down in a cascade: each module stops when its input closes. +When the last `BrokerClient` is dropped, the broker processes what is queued +and stops, every session closes its socket, and `websocket::run` returns +`Ok(())` once all of them have ended. Until then `run` keeps the order and +logger senders in `Commands`, so their consumers stop on their own input +rather than waiting for those queues to close. Closing the HTTP handoff channel +only stops accepting sockets: open sessions and the heartbeat timeout carry on. `websocket::run` returns `FrontendDisconnected` when every session has ended and no frontend has sent a valid application message for the heartbeat timeout, diff --git a/backend/crates/station/src/websocket/broker.rs b/backend/crates/station/src/websocket/broker.rs index 6e3614d42..39b14c5d6 100644 --- a/backend/crates/station/src/websocket/broker.rs +++ b/backend/crates/station/src/websocket/broker.rs @@ -40,11 +40,18 @@ pub struct Broker { protections: broadcast::Sender, } -/// Clonable access to publication and subscriptions. +/// Clonable access to publication. The broker runs while any client exists. /// A successful publish means the update entered the broker's input queue. #[derive(Debug, Clone)] pub struct BrokerClient { updates: mpsc::Sender, + subscriber: Subscriber, +} + +/// Clonable access to subscriptions. Unlike `BrokerClient`, it does not keep +/// the broker running, so WebSocket sessions can end when the broker stops. +#[derive(Debug, Clone)] +pub struct Subscriber { connections: watch::Receiver, state_orders: watch::Receiver, logger: watch::Receiver, @@ -78,12 +85,14 @@ impl Broker { }, BrokerClient { updates, - connections: state, - state_orders: orders, - logger: recording, - data: telemetry, - messages: message_topic, - protections: protection_topic, + subscriber: Subscriber { + connections: state, + state_orders: orders, + logger: recording, + data: telemetry, + messages: message_topic, + protections: protection_topic, + }, }, ) } @@ -166,6 +175,20 @@ impl BrokerClient { .map_err(|_| Error::BrokerClosed) } + /// Returns a subscription handle that does not keep the broker running. + pub fn subscriber(&self) -> Subscriber { + self.subscriber.clone() + } +} + +impl Subscriber { + /// Waits until the broker stops, after its last `BrokerClient` is dropped. + pub async fn closed(&self) { + // Every topic closes together when the broker exits; any one of them tells. + let mut connections = self.connections.clone(); + while connections.changed().await.is_ok() {} + } + /// Subscribes to the complete connection map, starting at its current state. /// Read that state with `borrow_and_update()`, then wait on `changed()`. pub fn subscribe_connections(&self) -> watch::Receiver { @@ -220,8 +243,8 @@ mod tests { -> Result<(), Box> { let (broker, client) = Broker::new(); let publisher = client.clone(); - let mut first = client.subscribe_connections(); - let mut second = client.subscribe_connections(); + let mut first = client.subscriber().subscribe_connections(); + let mut second = client.subscriber().subscribe_connections(); assert!(first.borrow_and_update().is_empty()); assert!(second.borrow_and_update().is_empty()); let worker = tokio::spawn(broker.run()); @@ -241,7 +264,7 @@ mod tests { assert_eq!(state[name].name, name); } - let mut late = client.subscribe_connections(); + let mut late = client.subscriber().subscribe_connections(); assert!(!late.has_changed()?); let state = late.borrow_and_update().clone(); assert_eq!(state.len(), 2); @@ -284,8 +307,8 @@ mod tests { async fn telemetry_batches_latest_packets_and_keeps_the_complete_state() -> Result<(), Box> { let (broker, client) = Broker::new(); - let mut data = client.subscribe_data(); - let mut logger = client.subscribe_logger(); + let mut data = client.subscriber().subscribe_data(); + let mut logger = client.subscriber().subscribe_logger(); assert!(data.borrow_and_update().is_empty()); let worker = tokio::spawn(broker.run()); tokio::task::yield_now().await; @@ -306,7 +329,7 @@ mod tests { assert_eq!(snapshot[&1000].count, 2); assert_eq!(snapshot[&2000].count, 1); - let late = client.subscribe_data(); + let late = client.subscriber().subscribe_data(); assert_eq!(*late.borrow(), snapshot); assert!(!late.has_changed()?); advance(Duration::from_millis(100)).await; @@ -330,8 +353,8 @@ mod tests { async fn orders_and_logger_keep_independent_current_states() -> Result<(), Box> { let (broker, client) = Broker::new(); - let mut orders = client.subscribe_state_orders(); - let mut logger = client.subscribe_logger(); + let mut orders = client.subscriber().subscribe_state_orders(); + let mut logger = client.subscriber().subscribe_logger(); assert!(orders.borrow_and_update().is_empty()); assert!(!*logger.borrow_and_update()); let worker = tokio::spawn(broker.run()); @@ -352,8 +375,8 @@ mod tests { client.publish_state_orders(current.clone()).await?; timeout(Duration::from_secs(1), orders.changed()).await??; assert_eq!(*orders.borrow_and_update(), current); - let late_orders = client.subscribe_state_orders(); - let late_logger = client.subscribe_logger(); + let late_orders = client.subscriber().subscribe_state_orders(); + let late_logger = client.subscriber().subscribe_logger(); assert_eq!(*late_orders.borrow(), current); assert!(*late_logger.borrow()); assert!(!late_orders.has_changed()?); @@ -368,20 +391,20 @@ mod tests { async fn broker_drains_queued_updates_before_stopping() -> Result<(), Box> { let (broker, client) = Broker::new(); - let state = client.subscribe_connections(); + let state = client.subscriber().subscribe_connections(); client .publish_connection(Connection { name: "LCU".into(), is_connected: true, }) .await?; - let orders = client.subscribe_state_orders(); - let logger = client.subscribe_logger(); + let orders = client.subscriber().subscribe_state_orders(); + let logger = client.subscriber().subscribe_logger(); client .publish_state_orders(StateOrdersUpdate::from([("LCU".into(), vec![1001])])) .await?; client.publish_logger(true).await?; - let data = client.subscribe_data(); + let data = client.subscriber().subscribe_data(); client.publish_data(packet(1000, 1)).await?; drop(client); @@ -393,6 +416,34 @@ mod tests { Ok(()) } + #[tokio::test] + async fn subscribers_do_not_keep_the_broker_running() -> Result<(), Box> + { + let (broker, client) = Broker::new(); + let subscriber = client.subscriber(); + let worker = tokio::spawn(broker.run()); + let closed = tokio::spawn({ + let subscriber = subscriber.clone(); + async move { subscriber.closed().await } + }); + + // Publish once so `closed` also has to skip a state change. + client + .publish_connection(Connection { + name: "LCU".into(), + is_connected: true, + }) + .await?; + drop(client); + timeout(Duration::from_secs(1), worker).await??; + timeout(Duration::from_secs(1), closed).await??; + assert!(matches!( + subscriber.subscribe_messages(), + Err(Error::BrokerClosed) + )); + Ok(()) + } + fn packet(id: u16, count: u64) -> DataPacketUpdate { DataPacketUpdate { id: software_core::model::AdjId(id), diff --git a/backend/crates/station/src/websocket/handler.rs b/backend/crates/station/src/websocket/handler.rs index 57b5a2b10..48999eb26 100644 --- a/backend/crates/station/src/websocket/handler.rs +++ b/backend/crates/station/src/websocket/handler.rs @@ -7,7 +7,7 @@ use tokio::{ time::{Instant, timeout}, }; -use super::{Commands, broker::BrokerClient, receiver, sender}; +use super::{Commands, broker::Subscriber, receiver, sender}; /// Reported once per session so the supervisor can apply the heartbeat timeout across sessions. pub(super) struct SessionEnd { @@ -16,10 +16,11 @@ pub(super) struct SessionEnd { pub(super) last_message: Instant, } -/// Runs reading and writing concurrently. The first side to finish ends the session. +/// Runs reading and writing concurrently. The first side to finish ends the +/// session, and so does the broker stopping, even with no subscriptions. pub(super) async fn handle( socket: WebSocket, - broker: BrokerClient, + broker: Subscriber, commands: &Commands, heartbeat_timeout: Duration, session_ends: mpsc::Sender, @@ -31,6 +32,7 @@ pub(super) async fn handle( let result = tokio::select! { result = receiver::run(read, &broker, commands, changes, heartbeat_timeout, &mut last_message) => result, result = sender::run(&mut write, subscriptions) => result, + () = broker.closed() => Ok(()), }; // Report the end of the session before waiting on socket I/O. let _ = session_ends.send(SessionEnd { last_message }).await; diff --git a/backend/crates/station/src/websocket/receiver.rs b/backend/crates/station/src/websocket/receiver.rs index f6c8370c8..b02a9a38b 100644 --- a/backend/crates/station/src/websocket/receiver.rs +++ b/backend/crates/station/src/websocket/receiver.rs @@ -15,7 +15,7 @@ use crate::payload::{ use super::{ Commands, HEARTBEAT, LOGGER_ENABLE, LOGGER_VARIABLES, LoggerCommand, ORDER_SEND, Topic, WsMessage, - broker::BrokerClient, + broker::Subscriber, error::{Error, LoggerError, OrderError}, }; @@ -37,7 +37,7 @@ pub(super) enum SubscriptionChange { } impl SubscriptionChange { - fn new(broker: &BrokerClient, topic: Topic, enabled: bool) -> Result { + fn new(broker: &Subscriber, topic: Topic, enabled: bool) -> Result { Ok(match topic { Topic::Connections => { Self::Connections(enabled.then(|| broker.subscribe_connections())) @@ -66,7 +66,7 @@ impl SubscriptionChange { /// `heartbeat_timeout`. pub(super) async fn run( mut read: impl Stream> + Unpin, - broker: &BrokerClient, + broker: &Subscriber, commands: &Commands, changes: mpsc::Sender, heartbeat_timeout: Duration, @@ -168,7 +168,7 @@ mod tests { assert!(matches!( run( stream::pending(), - &client, + &client.subscriber(), &Commands::default(), changes, HEARTBEAT_TIMEOUT, @@ -189,7 +189,7 @@ mod tests { let worker = tokio::spawn(async move { run( read, - &client, + &client.subscriber(), &Commands::default(), changes, HEARTBEAT_TIMEOUT, @@ -228,7 +228,7 @@ mod tests { ]); run( frames, - &client, + &client.subscriber(), &Commands::default(), changes, HEARTBEAT_TIMEOUT, @@ -254,7 +254,7 @@ mod tests { ]); run( frames, - &client, + &client.subscriber(), &Commands::default(), changes, HEARTBEAT_TIMEOUT, @@ -297,7 +297,7 @@ mod tests { ]); run( frames, - &client, + &client.subscriber(), &Commands::default(), changes, HEARTBEAT_TIMEOUT, From 7e2ab8a46a544bb7dcbcf7f11c2b140d470acf4f Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Thu, 3 Dec 2026 15:03:47 +0100 Subject: [PATCH 181/225] fix(backend, logging): log protection durations and simplify session timing --- .../crates/station/src/logging/protections.rs | 27 +++++++-- backend/crates/station/src/logging/session.rs | 39 +++--------- .../station/src/logging/session/tests.rs | 35 ++++------- .../station/src/logging/writer/tests.rs | 59 ++++++++++++++++++- 4 files changed, 97 insertions(+), 63 deletions(-) diff --git a/backend/crates/station/src/logging/protections.rs b/backend/crates/station/src/logging/protections.rs index 22136e351..cc672fcc0 100644 --- a/backend/crates/station/src/logging/protections.rs +++ b/backend/crates/station/src/logging/protections.rs @@ -1,9 +1,10 @@ //! Protection rows resolved from a received packet and the ADJ definition. -//! Board-supplied accumulated timing is not present in the current packet model. +//! The final time field preserves the duration in the ADJ protection definition. use std::{ collections::HashMap, path::{Path, PathBuf}, + time::Duration, }; use software_core::{ @@ -80,10 +81,9 @@ impl ProtectionsLogger { None => row.text(""), }; let row = value_field(row.int(i64::from(measurement.id.0)), &packet.value); - // Never substitute the ADJ's configured duration for a board result. - // An empty timed-protection cell explicitly means unavailable for now. - row.text(if protection.time.is_zero() { "0" } else { "" }) - .end()?; + // This is a property of the protection, independent of the session + // clock and the board's timestamp in the received packet. + row.text(&format_time(protection.time)).end()?; flush_if_due(file, threshold)?; Ok(()) } @@ -95,3 +95,20 @@ impl ProtectionsLogger { self.files.into_values() } } + +/// Match the HTTP catalog's units without losing fractional milliseconds. +/// CSVs explicitly write zero where the catalog omits the optional property. +fn format_time(time: Duration) -> String { + if time.is_zero() { + return "0".into(); + } + let ns = time.as_nanos(); + let (value, unit) = if ns.is_multiple_of(1_000_000) { + (ns / 1_000_000, "ms") + } else if ns.is_multiple_of(1_000) { + (ns / 1_000, "us") + } else { + (ns, "ns") + }; + format!("{value}{unit}") +} diff --git a/backend/crates/station/src/logging/session.rs b/backend/crates/station/src/logging/session.rs index 3e8c703b8..ba60cb170 100644 --- a/backend/crates/station/src/logging/session.rs +++ b/backend/crates/station/src/logging/session.rs @@ -4,11 +4,11 @@ //! `YYYY-MM-DDTHH-MM-SS` below the backend startup directory. Each session has //! `logger_settings.json` and `data/`, `protections/`, `order/`, `messages/`. //! -//! A monotonic `std::time::Instant` establishes the session's zero point. -//! Recorded elapsed times use the configured time unit; the first event need -//! not occur at zero. Wall-clock time is used separately for directory names -//! and order timestamps. A new session with an existing directory name -//! overwrites that session, without retaining files from its old selection. +//! The session's SystemTime origin is subtracted from event's reception or +//! order-confirmation time to obtain elapsed instants in the configured unit. +//! These follow the machine's calendar clock, including any clock adjustments. +//! The first event need not occur at zero. A new session with an existing +//! directory name overwrites it without retaining files from its old selection. //! //! Planned states: inactive, starting, recording and stopping. A normal stop //! preserves the backend-wide `others/` files for subsequent sessions. @@ -16,7 +16,7 @@ use std::{ fs, io, path::{Path, PathBuf}, - time::{Instant, SystemTime}, + time::SystemTime, }; use jiff::Timestamp; @@ -163,15 +163,14 @@ impl BackendRun { &mut self, selected_variables: impl Serialize, ) -> Result { - self.prepare_session_at(selected_variables, Timestamp::now(), Instant::now()) + self.prepare_session_at(selected_variables, Timestamp::now()) } - /// Captures the wall and monotonic clocks at the same session boundary. + /// Use the same startup timestamp for the directory, metadata and time origin. fn prepare_session_at( &mut self, selected_variables: impl Serialize, started_at: Timestamp, - clock_origin: Instant, ) -> Result { // Validate serialization before removing any existing session. let selected_variables = serde_json::to_value(selected_variables)?; @@ -210,18 +209,16 @@ impl BackendRun { Ok(Session { directory, metadata, - clock_origin, wall_origin: started_at.into(), }) } } -/// Prepared session metadata and its monotonic clock; no CSVs are open yet. +/// Prepared session metadata and calendar time origin; no CSVs are open yet. #[derive(Debug)] pub struct Session { directory: PathBuf, metadata: SessionSettings, - clock_origin: Instant, wall_origin: SystemTime, } @@ -250,24 +247,6 @@ impl Session { pub fn selected_variables(&self) -> &Value { &self.metadata.selected_variables } - - /// Elapsed time for an externally supplied monotonic reception timestamp. - /// - /// An event predating this session returns `None`, not a fabricated zero. - /// The current ToLogging input supplies SystemTime instead of Instant. - pub fn instant_at(&self, received_at: Instant) -> Option { - received_at - .checked_duration_since(self.clock_origin) - .map(|elapsed| self.metadata.settings.time_unit.convert(elapsed)) - } - - /// Current elapsed session time in the configured unit. - pub fn elapsed(&self) -> u128 { - self.metadata - .settings - .time_unit - .convert(self.clock_origin.elapsed()) - } } fn directory_date(timestamp: Timestamp) -> Result { diff --git a/backend/crates/station/src/logging/session/tests.rs b/backend/crates/station/src/logging/session/tests.rs index d63345c62..a3b109fa9 100644 --- a/backend/crates/station/src/logging/session/tests.rs +++ b/backend/crates/station/src/logging/session/tests.rs @@ -1,4 +1,4 @@ -use std::{fs, time::Duration}; +use std::fs; use serde_json::json; use software_core::logger::read_json; @@ -28,9 +28,7 @@ fn backend_and_session_settings_have_their_own_dates_and_selection() -> TestResu assert!(backend_directory.join("others").is_dir()); let selected = json!({"LCU": ["speed", "temperature"]}); - let clock_origin = Instant::now(); - let session = - run.prepare_session_at(&selected, "2026-11-27T14:31:05Z".parse()?, clock_origin)?; + let session = run.prepare_session_at(&selected, "2026-11-27T14:31:05Z".parse()?)?; let backend_settings: Value = read_json(backend_directory.join("others").join(SETTINGS_FILE))?; let session_settings: Value = read_json(session.directory().join(SETTINGS_FILE))?; assert_eq!( @@ -52,14 +50,8 @@ fn backend_and_session_settings_have_their_own_dates_and_selection() -> TestResu assert!(session.directory().join(name).is_dir()); assert_eq!(fs::read_dir(session.directory().join(name))?.count(), 0); } - assert_eq!(session.instant_at(clock_origin), Some(0)); - assert_eq!( - session.instant_at(clock_origin + Duration::from_millis(35)), - Some(35000) - ); - if let Some(earlier) = clock_origin.checked_sub(Duration::from_millis(1)) { - assert_eq!(session.instant_at(earlier), None); - } + let started_at: Timestamp = "2026-11-27T14:31:05Z".parse()?; + assert_eq!(session.wall_origin(), SystemTime::from(started_at)); Ok(()) } @@ -68,11 +60,7 @@ fn session_replacement_removes_stale_files_and_keeps_backend_files() -> TestResu let temp = tempfile::tempdir()?; let mut run = BackendRun::new_at(config(temp.path()), "adj", "2026-07-15T13:30:00Z".parse()?)?; // Both calls fall in the same named second, despite different subsecond times. - let first = run.prepare_session_at( - json!(["LCU/old"]), - "2026-07-15T13:31:00.100Z".parse()?, - Instant::now(), - )?; + let first = run.prepare_session_at(json!(["LCU/old"]), "2026-07-15T13:31:00.100Z".parse()?)?; assert_eq!(first.settings().date, "2026-07-15T15-31-00"); fs::create_dir(first.directory().join("data/LCU"))?; fs::write(first.directory().join("data/LCU/old.csv"), "old data")?; @@ -81,11 +69,8 @@ fn session_replacement_removes_stale_files_and_keeps_backend_files() -> TestResu let trace = run.directory().join("others/existing-trace.jsonl"); fs::write(&trace, "preserve this")?; - let replacement = run.prepare_session_at( - json!(["PCU/new"]), - "2026-07-15T13:31:00.900Z".parse()?, - Instant::now(), - )?; + let replacement = + run.prepare_session_at(json!(["PCU/new"]), "2026-07-15T13:31:00.900Z".parse()?)?; assert_eq!(replacement.directory(), previous_directory); assert!(!replacement.directory().join("data/LCU").exists()); let settings: Value = read_json(replacement.directory().join(SETTINGS_FILE))?; @@ -126,14 +111,14 @@ fn invalid_selection_does_not_delete_an_existing_session() -> TestResult { let temp = tempfile::tempdir()?; let mut run = BackendRun::new_at(config(temp.path()), "adj", "2026-11-27T14:30:00Z".parse()?)?; let timestamp: Timestamp = "2026-11-27T14:31:00Z".parse()?; - let session = run.prepare_session_at(json!(["speed"]), timestamp, Instant::now())?; + let session = run.prepare_session_at(json!(["speed"]), timestamp)?; let settings_file = session.directory().join(SETTINGS_FILE); let before = fs::read(&settings_file)?; drop(session); // A JSON object cannot have an array as a key. let invalid = std::collections::BTreeMap::from([(vec![1, 2], "invalid")]); assert!(matches!( - run.prepare_session_at(invalid, timestamp, Instant::now()), + run.prepare_session_at(invalid, timestamp), Err(Error::Selection(_)) )); assert_eq!(fs::read(settings_file)?, before); @@ -150,7 +135,7 @@ fn session_replacement_does_not_follow_symlinks() -> TestResult { fs::write(outside.join("keep.txt"), "keep")?; std::os::unix::fs::symlink(&outside, run.directory().join("2026-11-27T15-31-00"))?; assert!(matches!( - run.prepare_session_at(json!([]), "2026-11-27T14:31:00Z".parse()?, Instant::now()), + run.prepare_session_at(json!([]), "2026-11-27T14:31:00Z".parse()?), Err(Error::InvalidSessionPath(_)) )); assert_eq!(fs::read_to_string(outside.join("keep.txt"))?, "keep"); diff --git a/backend/crates/station/src/logging/writer/tests.rs b/backend/crates/station/src/logging/writer/tests.rs index 69992eb94..bea32d8b1 100644 --- a/backend/crates/station/src/logging/writer/tests.rs +++ b/backend/crates/station/src/logging/writer/tests.rs @@ -9,7 +9,7 @@ use std::{ use software_core::{ logger::CsvFile, - model::{AdjId, MessagePacket, OrderPacket, Value}, + model::{AdjId, MessagePacket, OrderPacket, Protection, ProtectionPacket, Value}, net::Event, }; use tokio::sync::oneshot; @@ -62,7 +62,7 @@ fn native_csv_formats_preserve_fields_without_headers() -> TestResult { assert_eq!( fs::read_to_string(temp.path().join("protections/LCU.csv"))?, format!( - "35000,LCU,backend,{},fault,above,50,,3002,55,\n35000,LCU,backend,{},warning,range,0,100,3002,105,0\n", + "35000,LCU,backend,{},fault,above,50,,3002,55,500ms\n35000,LCU,backend,{},warning,range,0,100,3002,105,0\n", ABOVE.0, RANGE.0 ) ); @@ -313,7 +313,7 @@ fn dropping_pending_controls_releases_start_replies() -> TestResult { } #[tokio::test] -async fn orders_use_confirmation_time_for_elapsed_and_wall_timestamps() -> TestResult { +async fn events_use_at_for_elapsed_and_order_wall_timestamps() -> TestResult { let temp = tempfile::tempdir()?; let run = BackendRun::new( Config { @@ -354,7 +354,13 @@ async fn orders_use_confirmation_time_for_elapsed_and_wall_timestamps() -> TestR // use its own stamp, even if the writer processes it immediately. assert!(!writer.write(&order(origin - Duration::from_secs(1)), None)); assert!(!writer.write(&order(at), None)); + assert!(!writer.write(&data(origin - Duration::from_secs(1), 999.0), None)); + assert!(!writer.write(&data(at, 42.0), None)); writer.stop(StopReason::Requested, at).await; + assert_eq!( + fs::read_to_string(session.directory.join("data/LCU/speed.csv"))?, + "35000,LCU,backend,42\n" + ); let timestamp = jiff::Timestamp::try_from(at)? .in_tz("Europe/Madrid")? .strftime("%Y-%m-%dT%H-%M-%S%:z") @@ -365,3 +371,50 @@ async fn orders_use_confirmation_time_for_elapsed_and_wall_timestamps() -> TestR ); Ok(()) } + +#[test] +fn protection_time_preserves_the_adj_duration_and_its_precision() -> TestResult { + let temp = tempfile::tempdir()?; + let (adj, index) = definitions(); + let catalog = Catalog::new(adj, index); + let mut logger = ProtectionsLogger::open(temp.path(), &[LCU], &catalog)?; + let (measurement, definition) = catalog.protection(LCU, ABOVE)?; + let packet = ProtectionPacket { + id: ABOVE, + timestamp: short_timestamp(), + value: Value::Number(55.0), + }; + let cases = [ + (Duration::ZERO, "0"), + (Duration::from_millis(500), "500ms"), + (Duration::from_secs(1), "1000ms"), + (Duration::from_micros(1500), "1500us"), + (Duration::from_nanos(1501), "1501ns"), + (Duration::from_nanos(1), "1ns"), + ]; + for (time, _) in cases { + // Changing the definition's duration must change the final CSV cell; + // the instant and timestamp in the received event stay unchanged. + let protection = Protection { + time, + ..*definition + }; + logger.write( + 35000, + catalog.board(LCU)?, + &packet, + measurement, + &protection, + u64::MAX, + )?; + } + assert!(close_files(logger.into_files()).is_empty()); + let contents = fs::read_to_string(temp.path().join("protections/LCU.csv"))?; + assert_eq!(contents.lines().count(), cases.len()); + for (row, (_, expected)) in contents.lines().zip(cases) { + assert_eq!(row.split(',').count(), 11); + assert!(row.starts_with("35000,LCU,backend,")); + assert_eq!(row.rsplit(',').next(), Some(expected)); + } + Ok(()) +} From ada1427d4c05ca116b1bd23e6633aac521fab98f Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Thu, 3 Dec 2026 15:04:00 +0100 Subject: [PATCH 182/225] docs(backend, logging): document WebSocket integration plan --- backend/crates/station/src/logging/README.md | 49 ++-- .../src/logging/WEBSOCKET_INTEGRATION.md | 273 ++++++++++++++++++ 2 files changed, 299 insertions(+), 23 deletions(-) create mode 100644 backend/crates/station/src/logging/WEBSOCKET_INTEGRATION.md diff --git a/backend/crates/station/src/logging/README.md b/backend/crates/station/src/logging/README.md index 381669ce8..3d1f1ede1 100644 --- a/backend/crates/station/src/logging/README.md +++ b/backend/crates/station/src/logging/README.md @@ -5,6 +5,9 @@ starts and ends, how its files are organized, and when buffers are flushed. Write operations use [software_core::logger](../../../core/src/logger/README.md). +The agreed WebSocket wiring and remaining integration work are collected in +[WEBSOCKET_INTEGRATION.md](WEBSOCKET_INTEGRATION.md). + ## Current Status The module uses the native `event` and `core::net` types now present in this @@ -121,15 +124,6 @@ fn start_logging_consumer( These are deliberately not filled in with reconstructed or guessed data: -- **Accumulated protection timing:** the current `ProtectionPacket` has no - separate accumulated-time result. Untimed protections write `0`; timed - protections temporarily leave that cell empty to mean unavailable. The - configured ADJ duration is not presented as a result sent by the board. -- **Reception clock:** upstream supplies `SystemTime`, not a monotonic stamp. - The event path calculates elapsed time from the supplied reception time and - the session's wall-clock origin. Events older than the session are rejected. - This preserves queue delay correctly but inherits wall-clock adjustments; - adding monotonic reception time remains an event-contract follow-up. - **Saturation:** the writer stops recording when it observes event's data channel at full capacity. Event currently uses awaited sends with backpressure: a transient full condition can clear before the writer observes @@ -235,12 +229,16 @@ the first row to contain zero: if the first measurement arrives 35 ms after startup, its `instant` will be `35` with `time_unit = "ms"`, or `35000` with `"us"`. -The low-level session retains its monotonic clock for elapsed-time helpers. The -`ToLogging` path uses the upstream `Notification::at` or `OrderSent::at` -(`SystemTime`) against the session's wall-clock origin, so queue delays are -not added to `instant`. -A monotonic timestamp at original reception is not available in the current -event contract; immunity to wall-clock changes therefore remains pending. +The session stores its startup time as `SystemTime`. The writer subtracts that +origin from the upstream `Notification::at` or `OrderSent::at`, then converts +the duration to `time_unit`. Queue delays are not added to `instant`. An event +whose `at` precedes the session origin is discarded instead of receiving a +fabricated zero. + +Using the machine's calendar clock is intentional: changing that clock during +a session may make elapsed instants jump. No additional monotonic clock or +timestamp field is required by this contract. The board's `ShortTimestamp` +is separate from the backend reception time used for `instant`. The units verified in the frontend are: @@ -360,15 +358,21 @@ instant,from,to,protection_id,severity,protection_type,threshold_1,threshold_2,m | `threshold_2` | Second threshold for `range` protections; empty for other types. | | `measurement_id` | ID of the associated measurement. | | `value` | Measurement value that triggered the protection. | -| `time` | Timing result sent by the board for `timeacumulation`, as a string containing time and units; `0` for other types. | +| `time` | The resolved ADJ definition's `Protection.time`, formatted as duration and unit; `0` when the duration is zero. | Both threshold fields are always present, even when the second one is empty. The thresholds and the value that triggered the event are separate fields. -The required `timeacumulation` result must come from the board, not the session -clock, `time_unit`, or the configured ADJ duration. The current model lacks -that result: for now a timed protection's cell is empty (unavailable), while -an untimed protection still writes `0`. Completing this field remains pending. +The time-accumulation field is a property of the protection definition resolved +from the received compound ID. Logging records it without measuring an elapsed +accumulation or changing the packet protocol. It is independent of the session +clock, `time_unit` and the packet's time-of-day timestamp. A duration can +accompany any protection kind, such as `above` or `range`. + +Nonzero durations follow the HTTP catalog's formatting rule without losing +precision: use `ms` for multiples of a millisecond, otherwise `us` for multiples +of a microsecond, otherwise `ns`. For example, 500 ms becomes `500ms`, one second +becomes `1000ms`, and 1500 microseconds becomes `1500us`. Zero is written as `0`. ### Messages: messages/messages.csv @@ -570,7 +574,6 @@ buffers, and explicit flush and close operations. - Running `adj-validator` and obtaining its output. - Trace levels and filters, and their connection to the JSONL file. - Exact schema of `selected_variables` in JSON and the session-control channel. -- Board-supplied accumulated timing and monotonic reception timestamps. - Disconnection stop rule when multiple frontends are connected. - Frontend notification format and integration through the application modules. - Wiring `WriterOptions` into application configuration if these defaults need UI controls. @@ -588,8 +591,8 @@ replies, fallback drop and input closure. An integration scenario connects `event::channels` and the real event router to `Logging`, stops and restarts sessions, then checks the persisted CSVs and orderly shutdown. -Writer tests check headerless CSVs, escaping, protection metadata, missing -board timing, serialized OrderPacket values and timezone offsets, +Writer tests check headerless CSVs, escaping, protection metadata and duration +precision, event-supplied reception times, serialized OrderPacket values and timezone offsets, large integer instants, deterministic full-channel handling and failed closes. Order tests also cover event routing, confirmation timestamps, broadcast destinations and rejected non-finite numbers. Connecting the real logging diff --git a/backend/crates/station/src/logging/WEBSOCKET_INTEGRATION.md b/backend/crates/station/src/logging/WEBSOCKET_INTEGRATION.md new file mode 100644 index 000000000..3fc6e7b01 --- /dev/null +++ b/backend/crates/station/src/logging/WEBSOCKET_INTEGRATION.md @@ -0,0 +1,273 @@ +# Logging Integration with WebSocket + +This document collects the agreed behavior and remaining work for integrating +both branches. It describes the planned adaptation; creating this file does not +connect the modules. File organization and CSV formats are documented in the +[README](README.md). + +Reviewed references: `backend/websocket` and `origin/backend/websocket`, both at +commit `152ad49d`, on December 3, 2026. Check the types again if the branch changes +before the merge. + +## 1. Agreed Behavior + +- Logging starts once with the backend and keeps running throughout its lifetime. +- The service consumes events even when no session is recording. +- A session starts when the frontend enables the logger, using the variable + selection for that session. +- Stopping a session drains its buffers and closes its files. The service remains + available to start another session. +- Variables may change between sessions. A selection received while recording is + saved for the next session. +- Backend shutdown must flush buffers and wait for the writer to finish. + +**Service running** and **session recording** are separate states. +`logger/response = false` means no session is recording; the logging service may +still be running and consuming events. + +## 2. Topics and Channels + +| Topic | Direction | Payload | Meaning | +| --- | --- | --- | --- | +| `logger/enable` | Frontend → backend | `bool` | Request a session start or stop. | +| `logger/variables` | Frontend → backend | `Vec` | Select variables for the next session. | +| `logger/response` | Backend → frontend | `bool` | Report the actual recording state. | + +WebSocket combines both incoming requests into one bounded channel: + +```rust +enum LoggerCommand { + Enable(bool), + Variables(Vec), +} +``` + +In the reviewed branch, `Commands.logger` holds an +`Option>`. Logging must consume the corresponding +receiver. `LoggerCommand` and that field have `pub(crate)` visibility, so other +`station` modules can use them. + +Responses are published through `BrokerClient::publish_logger(bool)`. This uses +the broker's shared input and its logger `watch` state; it is not another dedicated +command `mpsc` between logging and WebSocket. The frontend subscribes to +`logger/response` to receive the initial state and subsequent updates. + +The planned connections are: + +```text +event ── bounded mpsc ───────────────────▶ writer +WebSocket ── bounded mpsc ────────────▶ writer +backend ── independent stop/shutdown signal ────────▶ writer +writer ── watch ──▶ integration ──▶ broker ──▶ WebSocket/frontend +``` + +All recorded content, including orders, arrives from `event`. WebSocket supplies +the logger commands. + +## 3. Changes to the Current Code + +| Element | Current implementation | Planned change | +| --- | --- | --- | +| `writer.input` | `mpsc::Receiver` | Keep the channel from `event`. | +| `writer.controls` | Internal `mpsc::UnboundedReceiver` | Replace it with the bounded `LoggerCommand` receiver. | +| `writer.updates` | `watch::Sender` | Keep the complete state for observers. | +| `Control::{Play, Stop, Shutdown}` | Internal requests with `oneshot` replies | Remove or adapt them when changing the control input; avoid a second queue forwarding the same commands. | +| `Logging::{play, stop, emergency_stop, shutdown}` | API built on that internal channel | Review its implementation and callers alongside the channel change. | +| Startup in `main` | Uses `stand_in_logging` | Construct the real service and pass it the receivers. | + +The logic that prepares, stops and closes sessions remains necessary. Changing +the channel does not mean removing those operations. + +`LoggerCommand` includes neither `Shutdown` nor an emergency-stop request. +Those cases need an independent signal that remains usable when the frontend +queue is full and during synchronous `Drop`. The specific mechanism remains to +be chosen; do not introduce another unbounded channel by default. + +## 4. Backend Startup + +- [ ] Retain and share the complete `Arc` and its `Arc`, consistent + with networking. The current `main` moves `adj.pod_data` out of the ADJ. +- [ ] Supply the ADJ hash and the `logging_path`/`time_unit` configuration. +- [ ] Create `BackendRun` and `others/logger_settings.json` at startup. To reflect + a startup time captured before loading the ADJ, capture that timestamp and use + `BackendRun::new_at`. +- [ ] Create a single bounded `LoggerCommand` queue and connect both ends. + Define its capacity in the startup configuration. +- [ ] Start the writer with the event receiver, command receiver, shutdown signal + and observable state, without opening a recording session yet. +- [ ] Start the broker and state publication with `false`. +- [ ] Replace the stand-in without introducing two consumers for the same receiver. + +## 5. Variable Selection and Session Start + +In `testing-view`, `startLogging()` sends `logger/variables` first, followed by +`logger/enable = true`. These are separate messages, not an atomic request. +Both enter the same `mpsc` if WebSocket accepts the sends. + +In `competition-view`, only `logger/enable = true` is sent. The frontend expects +all variables to be recorded when there is no explicit selection. + +When receiving `Variables(...)`: + +- Resolve the board and measurement through the ADJ and validate the selection. +- Prepare the `MeasurementKey { board: BoardId, measurement_id: AdjId }` entries. +- Retain the selection for the next start and its representation in + `logger_settings.json`. +- Keep an already recording session's selection unchanged. + +The frontend builds entries as `${boardName}/${m.id}`. Check the catalog it +actually consumes: the backend HTTP catalog distinguishes numeric `id` from +textual `alias`. Do not assume `"LCU/speed"` and `"LCU/3000"` are equivalent +without agreeing on and testing their resolution. + +When receiving `Enable(true)`: + +1. Take a snapshot of the validated selection for that session. +2. Discard the inactive backlog and establish the session's time origin. +3. Prepare directories, metadata and files for the selected variables. +4. Publish `Recording` and respond with `true` after successful preparation. + +A repeated start while recording retains the existing session. A new start in +the same second as a previously stopped session replaces its directory, as +agreed, after the previous files have been closed. + +## 6. Session Stop and Shutdown + +When receiving `Enable(false)`, drain the session's pending input prefix, flush +buffers, close all session files and publish the final state. The stop must +finish even if events keep arriving. + +Keep the event receiver open after a normal stop, session emergency stop, +saturation or write failure. `event` treats losing the logging consumer as fatal. +While the service remains alive, it must consume events without recording them +when inactive. + +Coordinate backend shutdown in this order: + +1. Stop producers and allow `event` to deliver pending data. +2. Let logging process its input and close the session files. +3. Wait for the writer and collect write or close errors. +4. Keep the broker available for final state publication while useful; then close + the adapters and broker. + +The independent signal allows shutdown requests even when the command queue is +full. Using it must not close the event input prematurely while `event` still +needs to deliver data. `Drop` retains a fallback exit path; explicit shutdown +must allow errors to be collected. + +## 7. Responses and Errors + +`updates` holds `Status`: phase, session, last stop and last error. +The integration observes that state and publishes the `logger/response` boolean. +The writer must keep draining data without waiting for frontend network I/O. + +| Situation | Expected response | +| --- | --- | +| Service started without a session | `false`. | +| Session preparation completed | `true`. | +| Start rejected while inactive | `false`, retaining the error. | +| Stop completed | `false`. | +| Session stopped by an error or saturation | `false`, retaining the reason. | + +Do not confirm a start before opening the files or a stop before attempting to +drain and close the buffers. During stopping, retain the previous state until +completion. Repeated `Enable` requests need a response even if the state does +not change, because the frontend waits for confirmation. + +`logger/response` contains only a boolean: it cannot explain an error or confirm +which variables were accepted. Define how those details are reported through +the existing problem/message mechanisms. + +The `watch` retains the latest state and may coalesce intermediate changes. +If every incident must be reported, do not rely solely on observing boolean +transitions. Also publish the current state when creating the observer to avoid +missing a startup change. + +## 8. Cases Requiring an Explicit Decision + +| Case | What needs to be resolved | +| --- | --- | +| `Variables` has never been received | Support competition-view's behavior: all variables; specify which boards this includes. | +| `Variables([])` | Decide whether this means no variables or all variables. Distinguish it from never receiving a selection. | +| Unknown or malformed variable | Define the response and avoid silently starting with an older selection. | +| Switching frontend between sessions | Prevent competition-view from unintentionally inheriting testing-view's filter. The current command does not identify its sender. | +| Two frontends send commands | Define the global scope of the selection and session; the shared channel does not guarantee that one client's `Variables` and `Enable` stay together. | +| Command queue fills up | WebSocket uses `try_send`: it logs rejection and keeps the socket open. Agree on reporting and preventing a start with an outdated selection if only one of the two messages is accepted. | +| Command channel closes | Decide whether to stop just the session or the service. Do not automatically equate this with a frontend disconnection. | +| Stop timestamp | `LoggerCommand` carries no timestamp. Define whether the cutoff is taken at WebSocket reception or when logging processes the command. | + +### Frontend Disconnection + +The WebSocket branch returns `FrontendDisconnected` when the last frontend is +lost, according to its heartbeat and reconnection policy. With the documented +three-second timeout, the last client's heartbeat expiration ends supervision +immediately; other closures allow a reconnection window. The timeout is +configurable. + +Disconnection does not arrive as a `LoggerCommand`. The supervisor must connect +it to emergency stop and, when appropriate, backend shutdown. Confirm whether +logging stops when any frontend closes or when the last one is lost after that +window; the reviewed branch uses the latter policy to detect frontend loss. + +If a session is tied to a specific client, the current contract needs additional +identity information. + +### Data-Channel Saturation + +The `event → logging` channel is separate from the command channel. Currently, +`event` waits with `send().await`, and the writer stops the session when it +observes a full input. A transient full condition can escape that check. + +To guarantee “channel fills → stop logging and notify”, agree on detection at +the producer and signaling to the writer while keeping the receiver alive and +draining pending data. Avoid letting logging's wait unnecessarily block delivery +to pipeline. Distinguish this saturation from rejecting frontend commands. + +## 9. Settled Contracts and Independent Pending Work + +Orders arrive from `event` as `ToLogging::OrderSent`. The CSV uses its `at` for +`instant` and `timestamp`, and the `OrderPacket` as compact JSON in the `payload` +cell: `{"id":2000,"values":[...]}`. `from` is `backend`; `to` is the board's name +or `all` when the destination is `None`. + +This is already implemented in logging and tested with the event router. +Do not require the original frontend JSON or frontend reception time again. + +Protection CSVs record the resolved ADJ definition's `Protection.time`: `0` +for a zero duration, otherwise a duration with units such as `500ms`. This is +a property of the protection; logging does not calculate an accumulation or +require a new field in `ProtectionPacket`. Nonzero durations follow the HTTP +catalog's precision-preserving `ms`/`us`/`ns` formatting rule. + +Elapsed `instant` uses the event's `Notification.at` or `OrderSent.at` minus +the session's startup time, converted to `time_unit`. Both use `SystemTime`. +Calendar-clock adjustments can affect the result; this is an accepted +limitation. Unused monotonic session helpers have been removed, and the +WebSocket merge does not need to add monotonic timestamps to `event`. + +The JSONL trace and validator output in `others/` remain pending independently +of the WebSocket merge. + +## 10. Implementation Checks + +- [ ] Startup without a session: service alive, state `false`, no session CSVs. +- [ ] `Variables` followed by `Enable(true)`: correct selection and metadata. +- [ ] Start without a selection, with an empty selection and with an invalid + selection: agreed behavior. +- [ ] Selection changes while recording: affect only the next session. +- [ ] Repeated starts and stops: no accidental truncation, and a response is sent. +- [ ] Stop with pending data and active producers: finite drain and flush. +- [ ] New session after stop: no old events or files for unselected variables. +- [ ] Full command queue: observable rejection and consistent selection. +- [ ] Saturation or write failure: session stopped, state `false`, reason retained + and event input still available. +- [ ] Disconnection, reconnection and multiple frontends: agreed policy. +- [ ] Backend shutdown with a full command queue: independent signal, pending data + processed and writer finished. +- [ ] Slow or closed broker: the writer does not wait for the frontend. +- [ ] Confirmed orders: JSON in one cell and timing from `OrderSent.at`. +- [ ] Update tests, README examples and callers of the previous API. + +Integration is complete when the backend uses the real service and these paths +have been tested together. Having the types in both branches does not replace +connecting them at startup. From 192cd8dbf23f0da756221ed1eac570c640b9c142 Mon Sep 17 00:00:00 2001 From: GaziH Date: Thu, 3 Dec 2026 17:32:58 +0100 Subject: [PATCH 183/225] Feat(backend, pipeline): Added management of frontend connection. More Comments. --- backend/crates/station/src/pipeline.rs | 109 +++++++++++--- .../station/src/pipeline/accumulator.rs | 29 ++-- .../crates/station/src/pipeline/frontend.rs | 103 +++++++++++++ .../crates/station/src/pipeline/message.rs | 1 - backend/crates/station/src/pipeline/tests.rs | 140 +++++++++++++++++- .../crates/station/src/pipeline/timestamp.rs | 18 ++- 6 files changed, 352 insertions(+), 48 deletions(-) create mode 100644 backend/crates/station/src/pipeline/frontend.rs diff --git a/backend/crates/station/src/pipeline.rs b/backend/crates/station/src/pipeline.rs index c94b2b805..14787ec46 100644 --- a/backend/crates/station/src/pipeline.rs +++ b/backend/crates/station/src/pipeline.rs @@ -1,5 +1,6 @@ -//! Transforms [`crate::event::ToPipeline`] items into frontend WebSocket payloads -//! and publishes them through [`crate::websocket::broker::BrokerClient`]. +//! Transforms [`crate::event::ToPipeline`] items into frontend WebSocket payloads, +//! publishes them through [`crate::websocket::broker::BrokerClient`], and monitors +//! the `websocket ↔ front` connection state. //! //! # Contract //! @@ -9,12 +10,14 @@ //! packet ID in memory (cumulative `count`, mean `cycle_time` over the //! window, and per-measurement `last` + window `average`) and flushed to //! `podData/update` on a fixed interval. Idle packets are not republished. +//! - **Frontend connection watchdog.** Tracks active frontend sessions reported +//! by `websocket`. Losing the last frontend starts a reconnect grace period +//! (default 3 s); a heartbeat timeout on the last client or expiration of +//! that grace period sends a [`ProblemKind::Fatal`] to `event`. //! - **Wait, don't drop.** Reads continuously from `channels.pipeline` and //! awaits broker capacity instead of dropping decoded events. //! - **Clean shutdown.** When `event` closes the input channel (`None`), any //! pending telemetry is flushed to the broker before the task exits. -//! - **No error policy.** `event` already decides what is silent, shown, or -//! fatal; `pipeline` only formats and publishes. //! //! # Topics not handled here //! @@ -25,25 +28,29 @@ //! `software_core::model::Packet` yet. mod accumulator; +mod frontend; mod message; mod timestamp; #[cfg(test)] mod tests; +pub use frontend::FrontendEvent; + use std::sync::Arc; use std::time::Duration; use accumulator::DataAccumulator; -use crate::event::ToPipeline; +use crate::event::{Problem, ProblemKind, ToPipeline}; use crate::payload::{Connection, ProtectionUpdate}; use crate::websocket::broker::BrokerClient; +use frontend::FrontendWatchdog; use software_core::model::{Packet, PodData}; use software_core::net::{Event, Notification}; use software_core::protocol::Index; use tokio::sync::mpsc; use tokio::task::JoinHandle; -use tokio::time::{Instant, MissedTickBehavior, interval_at}; +use tokio::time::{Instant, MissedTickBehavior, interval_at, sleep_until}; use tracing::{error, warn}; /// Configuration for the pipeline task. @@ -51,38 +58,53 @@ use tracing::{error, warn}; pub struct Config { /// How often accumulated `Data` telemetry is flushed to the broker. pub data_flush_interval: Duration, + /// Grace period allowed for a frontend client to reconnect after the last + /// active frontend socket closes before reporting a fatal problem to `event`. + pub frontend_disconnect_timeout: Duration, } impl Default for Config { fn default() -> Self { Self { data_flush_interval: Duration::from_millis(100), + frontend_disconnect_timeout: Duration::from_secs(3), } } } -/// Spawns the pipeline task consuming `rx` and publishing to `broker`. +/// Spawns the pipeline task consuming `rx` (`event`) and `frontend_rx` +/// (`websocket`), publishing payloads to `broker`, and reporting frontend +/// disconnects on `problems`. /// /// The task exits cleanly once `rx` closes and pending telemetry is flushed, /// or immediately if `broker` has already shut down. pub fn spawn( config: Config, rx: mpsc::Receiver, + frontend_rx: mpsc::Receiver, + problems: mpsc::Sender, broker: BrokerClient, pod_data: Arc, index: Arc, ) -> JoinHandle<()> { - tokio::spawn(run_loop(config, rx, broker, pod_data, index)) + tokio::spawn(run_loop( + config, + rx, + frontend_rx, + problems, + broker, + pod_data, + index, + )) } -/// Runs the main pipeline event loop, interleaving incoming `ToPipeline` -/// events with periodic flushes of accumulated telemetry. -/// -/// Exits cleanly once `rx` closes (after a final telemetry flush) or -/// immediately if the WebSocket broker shuts down. +/// Runs the main pipeline event loop, interleaving frontend connection checks, +/// periodic 100 ms telemetry flushes, and incoming [`ToPipeline`] events. async fn run_loop( config: Config, mut rx: mpsc::Receiver, + mut frontend_rx: mpsc::Receiver, + problems: mpsc::Sender, broker: BrokerClient, pod_data: Arc, index: Arc, @@ -91,22 +113,53 @@ async fn run_loop( let period = config.data_flush_interval.max(Duration::from_millis(1)); // Start the first tick after one full period rather than immediately at t = 0. let mut tick = interval_at(Instant::now() + period, period); - // If the runtime stalls, skip missed ticks instead of firing a burst of catch-up flushes. + // Skip missed ticks instead of firing a burst of catch-up flushes after a stall. tick.set_missed_tick_behavior(MissedTickBehavior::Skip); let mut accumulator = DataAccumulator::default(); + let mut watchdog = FrontendWatchdog::new(config.frontend_disconnect_timeout); + let mut frontend_open = true; loop { + let frontend_deadline = watchdog.deadline(); + // `biased;` polls branches in top-to-bottom order instead of randomly. - // Checking the flush tick first guarantees sustained high-rate UDP traffic - // cannot starve the 100 ms telemetry publication. + // Checking frontend liveness and the 100 ms flush tick first prevents + // sustained high-rate UDP traffic from starving disconnects or flushes. tokio::select! { biased; + // 1. Frontend reconnect grace timer expired (only polled while a deadline is active). + _ = async { + if let Some(deadline) = frontend_deadline { + sleep_until(deadline).await; + } + }, if frontend_deadline.is_some() => { + if let Some(reason) = watchdog.on_timeout() { + report_frontend_fatal(&problems, reason).await; + } + } + // 2. Frontend session lifecycle events forwarded from `websocket`. + fe = frontend_rx.recv(), if frontend_open => { + match fe { + Some(event) => { + if let Some(reason) = watchdog.on_event(event, Instant::now()) { + report_frontend_fatal(&problems, reason).await; + } + } + None => { + // Stop polling once `websocket` drops its sender so a closed + // channel does not win every `biased;` round. + frontend_open = false; + } + } + } + // 3. Periodic 100 ms telemetry flush. _ = tick.tick() => { if !flush_data(&broker, &index, &mut accumulator).await { return; } } + // 4. Incoming routed items from `event`. item = rx.recv() => { match item { Some(msg) => { @@ -138,6 +191,7 @@ async fn handle_item( ToPipeline::Received(notification) => { handle_notification(¬ification, broker, pod_data, index, accumulator).await } + // TODO(websocket-merge): If `websocket` / `payload` splits backend problem onto a dedicated `problem/update` topic. ToPipeline::Problem(problem) => match message::from_problem(problem, pod_data) { Some(update) => publish_or_log(broker.publish_message(update).await), None => true, @@ -153,8 +207,8 @@ async fn handle_item( } } -/// Maps a wire-level [`Notification`] (connection state change or decoded -/// packet) to its corresponding WebSocket topic or telemetry accumulator. +/// Maps a wire-level [`Notification`] (connection transition or decoded packet) +/// to its WebSocket topic or the 100 ms telemetry accumulator. /// /// Returns `false` if publishing fails because the broker closed. async fn handle_notification( @@ -188,8 +242,13 @@ async fn handle_notification( publish_or_log(broker.publish_protection(update).await) } Event::Received(Packet::Message(msg)) => { - let update = - message::from_board_message(notification.board, notification.at, msg, pod_data, index); + let update = message::from_board_message( + notification.board, + notification.at, + msg, + pod_data, + index, + ); publish_or_log(broker.publish_message(update).await) } Event::Received(Packet::Order(order)) => { @@ -199,6 +258,16 @@ async fn handle_notification( } } +/// Reports a fatal frontend-disconnect [`Problem`] to `event` so it propagates +/// the pod fault and performs an ordered shutdown. +async fn report_frontend_fatal(problems: &mpsc::Sender, reason: &'static str) { + error!(reason, "frontend connection lost, reporting fatal problem to event"); + let problem = Problem::now(ProblemKind::Fatal, None, reason); + if problems.send(problem).await.is_err() { + warn!("event problems channel closed before frontend disconnect could be reported"); + } +} + /// Drains all telemetry packets updated during the current window and /// publishes each [`crate::payload::DataPacketUpdate`] to the broker. /// diff --git a/backend/crates/station/src/pipeline/accumulator.rs b/backend/crates/station/src/pipeline/accumulator.rs index 1e694f60d..7aacf82e7 100644 --- a/backend/crates/station/src/pipeline/accumulator.rs +++ b/backend/crates/station/src/pipeline/accumulator.rs @@ -38,7 +38,6 @@ enum MeasurementAccumulator { } impl MeasurementAccumulator { - /// Initializes an accumulator from the first decoded [`Value`] observed in /// the current flush window. fn from_value(value: &Value) -> Self { @@ -59,7 +58,7 @@ impl MeasurementAccumulator { fn update(&mut self, value: &Value) { match (self, value) { ( - Self::Numeric { // If Numeric, update last, add to sum and 1 sample to calculate rolling average + Self::Numeric { last, sum, samples, @@ -70,24 +69,27 @@ impl MeasurementAccumulator { *sum += *v; *samples += 1; } - (Self::Boolean(last), Value::Bool(b)) => //If Bool just change last variable - { + (Self::Boolean(last), Value::Bool(b)) => { *last = *b; } - (Self::Enum(last), Value::Enum(s)) => { //If Enum just change value if different + (Self::Enum(last), Value::Enum(s)) => { + // `clone_from` reuses `last`'s existing heap buffer when the + // variant changes, avoiding a fresh String allocation. if last != s { last.clone_from(s); } } (slot, other) => { + // Defensive fallback if a measurement's runtime variant ever + // disagrees with the previous sample in the same slot. *slot = Self::from_value(other); } } } /// Finalizes the window accumulator into the serialized - /// [`MeasurementUpdate`] payload, computes rolling average - /// for numeric measurements. + /// [`MeasurementUpdate`] payload, computing the arithmetic mean for + /// numeric measurements. fn into_update(self) -> MeasurementUpdate { match self { Self::Numeric { @@ -105,7 +107,6 @@ impl MeasurementAccumulator { } impl DataAccumulator { - /// Records one incoming [`DataPacket`] into its per-ID window, updating /// cumulative packet count, inter-arrival timing, and per-measurement stats. pub(super) fn record(&mut self, packet: &DataPacket, at: SystemTime, index: &Index) { @@ -130,9 +131,8 @@ impl DataAccumulator { ); } - // Lazily initialize the packet's window on first arrival. Using a map - // over `0..defs.len()` avoids requiring `Clone` on `MeasurementAccumulator` - // (which `vec![None; defs.len()]` would need). + // Lazily initialize the packet's window on first arrival. Mapping over + // `0..defs.len()` avoids requiring `Clone` on `MeasurementAccumulator`. let window = self.packets.entry(packet.id).or_insert_with(|| PacketWindow { count: 0, last_at: None, @@ -143,11 +143,9 @@ impl DataAccumulator { dirty: false, }); - window.count = window.count.saturating_add(1); // Rust 2024 let-chain: only accumulate cycle time when a previous - // timestamp exists and the system clock did not step backwards - // (`duration_since` returns `Err` on backwards clock jumps). + // timestamp exists and the system clock did not step backwards. if let Some(prev) = window.last_at && let Ok(delta) = at.duration_since(prev) { @@ -196,10 +194,9 @@ impl DataAccumulator { continue; }; - let mut measurement_updates = HashMap::with_capacity(defs.len()); - // `slot.take()` moves the accumulator out and resets the slot to // `None` in one step, preparing it cleanly for the next 100 ms window. + let mut measurement_updates = HashMap::with_capacity(defs.len()); for (measurement_def, slot) in defs.iter().zip(window.measurements.iter_mut()) { if let Some(acc) = slot.take() { measurement_updates.insert(measurement_def.alias.clone(), acc.into_update()); diff --git a/backend/crates/station/src/pipeline/frontend.rs b/backend/crates/station/src/pipeline/frontend.rs new file mode 100644 index 000000000..5fd0709d1 --- /dev/null +++ b/backend/crates/station/src/pipeline/frontend.rs @@ -0,0 +1,103 @@ +//! Tracks the `websocket ↔ front` connection state inside `pipeline`. +//! +//! `websocket` forwards session lifecycle transitions via [`FrontendEvent`], +//! and [`FrontendWatchdog`] decides when the loss of the last frontend client +//! becomes a fatal backend problem. + +use std::time::Duration; + +use tokio::time::Instant; + +/// Frontend session lifecycle events sent by `websocket` to `pipeline`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum FrontendEvent { + /// A frontend WebSocket client connected. + Connected, + /// A frontend WebSocket client disconnected normally or dropped its socket. + /// If it was the last active client, the reconnect grace window starts. + Disconnected, + /// A frontend WebSocket client timed out waiting for a heartbeat. + /// If it was the last active client, the heartbeat timeout already + /// satisfies the reconnect period, so it is fatal immediately. + HeartbeatTimeout, +} + +/// Tracks active frontend connections and the post-disconnect reconnect deadline. +#[derive(Debug)] +pub(super) struct FrontendWatchdog { + grace_timeout: Duration, + active_clients: usize, + /// True once at least one frontend has connected (startup with 0 clients is not fatal). + had_client: bool, + /// Active reconnect deadline while waiting for a client to return after dropping to 0. + reconnect_deadline: Option, + /// Ensures a fatal disconnect problem is reported at most once. + reported_fatal: bool, +} + +impl FrontendWatchdog { + /// Creates a watchdog that allows `grace_timeout` for reconnection after + /// the last frontend disconnects normally. + pub(super) fn new(grace_timeout: Duration) -> Self { + Self { + grace_timeout, + active_clients: 0, + had_client: false, + reconnect_deadline: None, + reported_fatal: false, + } + } + + /// Returns the currently armed reconnect deadline, if any. + pub(super) fn deadline(&self) -> Option { + self.reconnect_deadline + } + + /// Processes a [`FrontendEvent`] at `now`. + /// + /// Returns `Some(reason)` when the event triggers an immediate fatal + /// disconnect (e.g. heartbeat timeout on the last client). + pub(super) fn on_event(&mut self, event: FrontendEvent, now: Instant) -> Option<&'static str> { + match event { + FrontendEvent::Connected => { + self.active_clients = self.active_clients.saturating_add(1); + self.had_client = true; + // A returning client cancels any pending reconnect deadline. + self.reconnect_deadline = None; + None + } + FrontendEvent::Disconnected => { + self.active_clients = self.active_clients.saturating_sub(1); + if self.had_client && self.active_clients == 0 && !self.reported_fatal { + if self.grace_timeout.is_zero() { + self.reported_fatal = true; + return Some("all frontend connections lost"); + } + self.reconnect_deadline = Some(now + self.grace_timeout); + } + None + } + FrontendEvent::HeartbeatTimeout => { + self.active_clients = self.active_clients.saturating_sub(1); + if self.had_client && self.active_clients == 0 && !self.reported_fatal { + // The heartbeat timeout already elapsed the disconnect window. + self.reconnect_deadline = None; + self.reported_fatal = true; + return Some("last frontend connection timed out on heartbeat"); + } + None + } + } + } + + /// Fires when [`Self::deadline`] elapses without any client reconnecting. + pub(super) fn on_timeout(&mut self) -> Option<&'static str> { + self.reconnect_deadline = None; + if self.had_client && self.active_clients == 0 && !self.reported_fatal { + self.reported_fatal = true; + Some("all frontend connections lost (reconnect timeout expired)") + } else { + None + } + } +} \ No newline at end of file diff --git a/backend/crates/station/src/pipeline/message.rs b/backend/crates/station/src/pipeline/message.rs index aa1e937b2..5dd77775b 100644 --- a/backend/crates/station/src/pipeline/message.rs +++ b/backend/crates/station/src/pipeline/message.rs @@ -10,7 +10,6 @@ use tracing::warn; /// Looks up a board's human-readable name from [`PodData`], falling back to /// `"board-"` if the ID is absent. pub(super) fn board_name(pod_data: &PodData, board: BoardId) -> String { - // `map_or_else` evaluates the fallback closure lazily so `"board-"` is // only allocated when the lookup misses. pod_data diff --git a/backend/crates/station/src/pipeline/tests.rs b/backend/crates/station/src/pipeline/tests.rs index 30c3f074e..3930a3610 100644 --- a/backend/crates/station/src/pipeline/tests.rs +++ b/backend/crates/station/src/pipeline/tests.rs @@ -13,13 +13,16 @@ use software_core::protocol::Index; use tokio::sync::mpsc; use tokio::time::{advance, timeout}; -use super::{Config, spawn, timestamp}; +use super::{Config, FrontendEvent, spawn, timestamp}; use crate::event::{Problem, ProblemKind, ToPipeline}; use crate::payload::{ MeasurementUpdate, MessageKind, MessagePayload, MessageTimestamp, ProtectionUpdate, }; use crate::websocket::broker::Broker; +/// Builds a minimal ADJ fixture with one board (`PCU`, ID 5) containing a +/// 3-measurement `Data` packet (ID 551), an `Order` packet (ID 1001), and a +/// `Warning` message definition (ID 10). fn sample_fixture() -> (Arc, Arc) { let voltage_a = Measurement { id: AdjId(3001), @@ -88,6 +91,8 @@ fn sample_fixture() -> (Arc, Arc) { (pod_data, index) } +/// Verifies that every non-telemetry `ToPipeline` variant is transformed and +/// forwarded to its corresponding broker topic immediately. #[tokio::test] async fn forwards_connections_protections_messages_problems_and_orders_immediately() -> Result<(), Box> { @@ -99,7 +104,17 @@ async fn forwards_connections_protections_messages_problems_and_orders_immediate let broker_task = tokio::spawn(broker.run()); let (tx, rx) = mpsc::channel(32); - let pipe_task = spawn(Config::default(), rx, client, pod_data, index); + let (_fe_tx, fe_rx) = mpsc::channel(16); + let (problems_tx, _problems_rx) = mpsc::channel(16); + let pipe_task = spawn( + Config::default(), + rx, + fe_rx, + problems_tx, + client, + pod_data, + index, + ); // 1. Connection update tx.send(ToPipeline::Received(Arc::new(Notification { @@ -112,6 +127,7 @@ async fn forwards_connections_protections_messages_problems_and_orders_immediate assert!(conn_sub.borrow_and_update()["PCU"].is_connected); // 2. Protection event + // Compound ADJv3 protection ID: high 3 bits = protection slot (1), low 13 bits = measurement ID (3001). let protection = ProtectionPacket { id: AdjId((1 << 13) | 3001), timestamp: ShortTimestamp { @@ -204,6 +220,11 @@ async fn forwards_connections_protections_messages_problems_and_orders_immediate Ok(()) } +/// Verifies 100 ms telemetry windowing (cumulative count, mean cycle time, +/// per-measurement last and average) and final flush when the input channel closes. +/// +/// `start_paused = true` freezes Tokio's virtual clock so 100 ms intervals run +/// deterministically and instantaneously via `tokio::time::advance`. #[tokio::test(start_paused = true)] async fn batches_data_every_100ms_with_window_average_last_and_cycle_time() -> Result<(), Box> { @@ -213,7 +234,17 @@ async fn batches_data_every_100ms_with_window_average_last_and_cycle_time() let broker_task = tokio::spawn(broker.run()); let (tx, rx) = mpsc::channel(32); - let pipe_task = spawn(Config::default(), rx, client, pod_data, index); + let (_fe_tx, fe_rx) = mpsc::channel(16); + let (problems_tx, _problems_rx) = mpsc::channel(16); + let pipe_task = spawn( + Config::default(), + rx, + fe_rx, + problems_tx, + client, + pod_data, + index, + ); tokio::task::yield_now().await; let t0 = UNIX_EPOCH + Duration::from_secs(1_700_000_000); @@ -240,7 +271,9 @@ async fn batches_data_every_100ms_with_window_average_last_and_cycle_time() } tokio::task::yield_now().await; - // First 100 ms tick flushes pipeline -> broker; next 100 ms tick flushes broker -> watch. + // Advance once to trigger pipeline's 100 ms flush into the broker, yield + // twice so both tasks process the queued update, then advance again to + // trigger the broker's own 100 ms batch flush to `watch` subscribers. advance(Duration::from_millis(100)).await; tokio::task::yield_now().await; tokio::task::yield_now().await; @@ -300,6 +333,105 @@ async fn batches_data_every_100ms_with_window_average_last_and_cycle_time() Ok(()) } +/// Verifies that reconnecting within the 3 s grace window cancels the fatal +/// disconnect, while staying disconnected past 3 s reports `ProblemKind::Fatal`. +#[tokio::test(start_paused = true)] +async fn frontend_disconnect_allows_reconnect_and_reports_fatal_after_grace_period() + -> Result<(), Box> { + let (pod_data, index) = sample_fixture(); + let (broker, client) = Broker::new(); + let broker_task = tokio::spawn(broker.run()); + + let (tx, rx) = mpsc::channel(16); + let (fe_tx, fe_rx) = mpsc::channel(16); + let (problems_tx, mut problems_rx) = mpsc::channel(16); + let pipe_task = spawn( + Config::default(), + rx, + fe_rx, + problems_tx, + client, + pod_data, + index, + ); + tokio::task::yield_now().await; + + // Client connects, disconnects, then reconnects after 2 s (within 3 s grace). + fe_tx.send(FrontendEvent::Connected).await?; + fe_tx.send(FrontendEvent::Disconnected).await?; + advance(Duration::from_secs(2)).await; + fe_tx.send(FrontendEvent::Connected).await?; + advance(Duration::from_secs(5)).await; + assert!( + problems_rx.try_recv().is_err(), + "reconnecting within the grace period must cancel the fatal problem" + ); + + // Client disconnects again and does not return within 3 s. + fe_tx.send(FrontendEvent::Disconnected).await?; + tokio::task::yield_now().await; + advance(Duration::from_millis(2_999)).await; + assert!(problems_rx.try_recv().is_err()); + + advance(Duration::from_millis(1)).await; + let problem = timeout(Duration::from_millis(10), problems_rx.recv()) + .await? + .ok_or("expected fatal problem on reconnect timeout")?; + assert_eq!(problem.kind, ProblemKind::Fatal); + assert_eq!(problem.board, None); + + drop(tx); + timeout(Duration::from_secs(1), pipe_task).await??; + timeout(Duration::from_secs(1), broker_task).await??; + Ok(()) +} + +/// Verifies that a heartbeat timeout on the last active frontend client reports +/// `ProblemKind::Fatal` immediately without waiting for another 3 s grace period. +#[tokio::test(start_paused = true)] +async fn frontend_heartbeat_timeout_on_last_client_is_fatal_immediately() + -> Result<(), Box> { + let (pod_data, index) = sample_fixture(); + let (broker, client) = Broker::new(); + let broker_task = tokio::spawn(broker.run()); + + let (tx, rx) = mpsc::channel(16); + let (fe_tx, fe_rx) = mpsc::channel(16); + let (problems_tx, mut problems_rx) = mpsc::channel(16); + let pipe_task = spawn( + Config::default(), + rx, + fe_rx, + problems_tx, + client, + pod_data, + index, + ); + tokio::task::yield_now().await; + + // Two clients connect; one times out -> still alive because one remains. + fe_tx.send(FrontendEvent::Connected).await?; + fe_tx.send(FrontendEvent::Connected).await?; + fe_tx.send(FrontendEvent::HeartbeatTimeout).await?; + tokio::task::yield_now().await; + assert!(problems_rx.try_recv().is_err()); + + // Last client times out -> immediate fatal without advancing virtual time. + fe_tx.send(FrontendEvent::HeartbeatTimeout).await?; + let problem = timeout(Duration::from_millis(10), problems_rx.recv()) + .await? + .ok_or("expected immediate fatal problem on last heartbeat timeout")?; + assert_eq!(problem.kind, ProblemKind::Fatal); + assert_eq!(problem.board, None); + + drop(tx); + timeout(Duration::from_secs(1), pipe_task).await??; + timeout(Duration::from_secs(1), broker_task).await??; + Ok(()) +} + +/// Verifies `timestamp::from_system_time` on boundary dates (Unix epoch and +/// a Gregorian leap day with millisecond counter). #[test] fn utc_calendar_conversion_handles_epoch_and_leap_day() { let epoch = timestamp::from_system_time(UNIX_EPOCH); diff --git a/backend/crates/station/src/pipeline/timestamp.rs b/backend/crates/station/src/pipeline/timestamp.rs index e4bd2f42a..cc82da4c8 100644 --- a/backend/crates/station/src/pipeline/timestamp.rs +++ b/backend/crates/station/src/pipeline/timestamp.rs @@ -8,7 +8,7 @@ pub(super) fn from_system_time(at: SystemTime) -> MessageTimestamp { // Clamp timestamps before 1970-01-01 to the Unix epoch rather than panicking. let dur = at.duration_since(UNIX_EPOCH).unwrap_or(Duration::ZERO); let total_secs = dur.as_secs(); - // 86_400 seconds per UTC day (POSIX/Unix time ignores leap seconds). + // 86,400 seconds per UTC day (POSIX/Unix time ignores leap seconds). let days = i64::try_from(total_secs / 86_400).unwrap_or(0); let secs_of_day = total_secs % 86_400; @@ -49,15 +49,19 @@ pub(super) fn from_short(received_at: SystemTime, short: ShortTimestamp) -> Mess /// Converts days since 1970-01-01 (UTC) to `(year, month, day)` using /// Howard Hinnant's civil calendar algorithm. fn civil_from_days(days_since_epoch: i64) -> (u16, u8, u8) { + // Shift epoch from 1970-01-01 to 0000-03-01 so leap day (Feb 29) falls at + // the very end of the year, simplifying leap-year arithmetic. let z = days_since_epoch + 719_468; + // Split into 400-year Gregorian eras (exactly 146,097 days each). let era = if z >= 0 { z } else { z - 146_096 } / 146_097; - let doe = u64::try_from(z - era * 146_097).unwrap_or(0); - let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365; + let doe = u64::try_from(z - era * 146_097).unwrap_or(0); // day of era [0, 146096] + let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365; // year of era [0, 399] let y = i64::try_from(yoe).unwrap_or(0) + era * 400; - let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); - let mp = (5 * doy + 2) / 153; - let d = doy - (153 * mp + 2) / 5 + 1; - let m = if mp < 10 { mp + 3 } else { mp - 9 }; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); // day of year from Mar 1 [0, 365] + let mp = (5 * doy + 2) / 153; // shifted month index [0, 11] (Mar = 0 .. Feb = 11) + let d = doy - (153 * mp + 2) / 5 + 1; // day of month [1, 31] + let m = if mp < 10 { mp + 3 } else { mp - 9 }; // calendar month [1, 12] + // Months Jan and Feb belong to the following calendar year relative to the Mar 1 base. let year = y + i64::from(m <= 2); ( From eb908a525652a893b374b1892d3854c02482a12e Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Thu, 3 Dec 2026 17:55:12 +0100 Subject: [PATCH 184/225] fix(backend, ws): remove timers --- .../crates/station/src/websocket/README.md | 25 +- .../crates/station/src/websocket/broker.rs | 219 ++++++++---------- 2 files changed, 115 insertions(+), 129 deletions(-) diff --git a/backend/crates/station/src/websocket/README.md b/backend/crates/station/src/websocket/README.md index 1178c6ff7..d6fbdf776 100644 --- a/backend/crates/station/src/websocket/README.md +++ b/backend/crates/station/src/websocket/README.md @@ -9,22 +9,26 @@ live in [`../payload/serialize.rs`](../payload/serialize.rs). | Topic | Publish through `BrokerClient` | Subscribe through `Subscriber` | Initial state | | --- | --- | --- | --- | -| `connection/update` | `publish_connection(connection)` | `subscribe_connections()` | `{}` | +| `connection/update` | `publish_connections(connections)` | `subscribe_connections()` | `{}` | | `order/stateOrders` | `publish_state_orders(orders)` | `subscribe_state_orders()` | `{}` | | `logger/response` | `publish_logger(recording)` | `subscribe_logger()` | `false` | -| `podData/update` | `publish_data(packet)` | `subscribe_data()` | `{}` | +| `podData/update` | `publish_data(data)` | `subscribe_data()` | `{}` | | `message/update` | `publish_message(message)` | `subscribe_messages()` | No initial event | | `protection/update` | `publish_protection(protection)` | `subscribe_protections()` | No initial event | - `Broker::new()` creates the broker, a `BrokerClient` and the initial topic states. `BrokerClient::subscriber()` returns a `Subscriber`. - `Broker::run()` consumes a bounded `mpsc` channel of typed updates and - publishes state through `watch` and events through `broadcast`. It stops after all + relays them as received, state through `watch` and events through + `broadcast`. It neither merges nor batches: publishers decide what each + update holds and how often to send it. It stops after all `BrokerClient` instances are dropped and pending updates have been processed. A `Subscriber` does not keep it running; `Subscriber::closed()` waits until it stops. - Publication waits for capacity and returns `Error::BrokerClosed` if the - broker closed. Connection updates merge one board into the current map; - order updates replace the entire map, including empty lists or an empty map. + broker closed. Every state publication carries the complete value and + replaces the previous one: a board or packet missing from a map is no longer + published, and an empty map clears the topic. Every publication notifies the + subscribers, even if the value did not change. - State subscriptions return a `watch` receiver. Read the initial state with `borrow_and_update()`, then await `changed()` and read again. Intermediate changes may be coalesced; each value contains the complete current state. @@ -39,13 +43,10 @@ bounded `mpsc` queue. Invalid payloads and requests that cannot be queued are logged, and the WebSocket session stays open. The logger reports its applied state through `BrokerClient::publish_logger`, which feeds `logger/response`. -`publish_data` accepts a complete, prepared `DataPacketUpdate`. The broker -buffers the latest update per packet id and merges it into the published -telemetry map every 100 ms when changes exist. Unchanged packets remain in -that map; repeated updates for one id within a batch are coalesced. Idle ticks -do not publish, and missed ticks are skipped rather than sent in a burst. -Pending telemetry is flushed when the broker finishes processing its input. -The publisher supplies packet counts, cycle times, measurement values and +`publish_data` accepts the complete telemetry map, keyed by packet id. Each +session serializes the whole map for every update it sends, so the publisher +keeps the last value of quiet packets and limits the update rate itself. The +publisher also supplies packet counts, cycle times, measurement values and averages; the broker preserves them as received. The station binary currently runs a greeting demo. To expose `/backend/ws` diff --git a/backend/crates/station/src/websocket/broker.rs b/backend/crates/station/src/websocket/broker.rs index 39b14c5d6..8d8ca2563 100644 --- a/backend/crates/station/src/websocket/broker.rs +++ b/backend/crates/station/src/websocket/broker.rs @@ -1,18 +1,15 @@ -//! Publishes current state and forwards messages and protection events. +//! Relays complete state snapshots and forwards message and protection events. //! -//! Each `watch` topic holds a complete snapshot and may coalesce intermediate -//! updates. Each event topic has its own bounded `broadcast` backlog for live subscribers. - -use std::time::Duration; +//! The broker neither merges nor batches: publishers decide what each snapshot +//! holds and when to send it. Each `watch` topic holds the latest snapshot and +//! may coalesce intermediate ones. Each event topic has its own bounded +//! `broadcast` backlog for live subscribers. use crate::payload::{ - Connection, ConnectionUpdate, DataPacketUpdate, DataUpdate, LoggerResponse, MessageUpdate, - ProtectionUpdate, StateOrdersUpdate, -}; -use tokio::{ - sync::{broadcast, mpsc, watch}, - time::{Instant, MissedTickBehavior, interval_at}, + ConnectionUpdate, DataUpdate, LoggerResponse, MessageUpdate, ProtectionUpdate, + StateOrdersUpdate, }; +use tokio::sync::{broadcast, mpsc, watch}; pub use super::error::Error; @@ -20,15 +17,15 @@ const EVENT_CAPACITY: usize = 128; #[derive(Debug)] enum Update { - Connection(Connection), + Connections(ConnectionUpdate), StateOrders(StateOrdersUpdate), Logger(LoggerResponse), - Data(DataPacketUpdate), + Data(DataUpdate), Message(MessageUpdate), Protection(ProtectionUpdate), } -/// Owns the topic states and processes incoming updates. +/// Owns the topic channels and relays incoming updates. #[derive(Debug)] pub struct Broker { updates: mpsc::Receiver, @@ -97,50 +94,40 @@ impl Broker { ) } - /// Processes updates as they arrive. After the last client drops, drains the input - /// queue and flushes any pending telemetry before exiting. + /// Relays updates in arrival order. After the last client drops, processes + /// the queued updates and returns. pub async fn run(mut self) { - let period = Duration::from_millis(100); - let mut tick = interval_at(Instant::now() + period, period); - // Skip catch-up ticks and keep only the latest packet per ID in each batch. - tick.set_missed_tick_behavior(MissedTickBehavior::Skip); - let mut pending = DataUpdate::new(); - loop { - tokio::select! { - update = self.updates.recv() => { - match update { - Some(Update::Connection(connection)) => self.connections.send_modify(|state| { - state.insert(connection.name.clone(), connection); - }), - Some(Update::StateOrders(orders)) => { self.state_orders.send_replace(orders); } - Some(Update::Logger(recording)) => { self.logger.send_replace(recording); } - Some(Update::Data(packet)) => { pending.insert(packet.id.0, packet); } - // Zero subscribers is normal for a live event. - Some(Update::Message(message)) => { let _ = self.messages.send(message); } - Some(Update::Protection(protection)) => { let _ = self.protections.send(protection); } - None => { - self.flush_data(&mut pending); - return; - } - } + while let Some(update) = self.updates.recv().await { + match update { + Update::Connections(connections) => { + self.connections.send_replace(connections); + } + Update::StateOrders(orders) => { + self.state_orders.send_replace(orders); + } + Update::Logger(recording) => { + self.logger.send_replace(recording); + } + Update::Data(data) => { + self.data.send_replace(data); + } + // Zero subscribers is normal for a live event. + Update::Message(message) => { + let _ = self.messages.send(message); + } + Update::Protection(protection) => { + let _ = self.protections.send(protection); } - _ = tick.tick() => self.flush_data(&mut pending), } } } - - fn flush_data(&self, pending: &mut DataUpdate) { - if !pending.is_empty() { - // Preserve the last value for packets that were quiet during this batch. - self.data.send_modify(|state| state.extend(pending.drain())); - } - } } impl BrokerClient { - /// Queues a board connection update, waiting if the input channel is full. - pub async fn publish_connection(&self, connection: Connection) -> Result<(), Error> { - self.publish(Update::Connection(connection)).await + /// Queues the complete connection map, replacing the previous map. Waits + /// if the input channel is full. + pub async fn publish_connections(&self, connections: ConnectionUpdate) -> Result<(), Error> { + self.publish(Update::Connections(connections)).await } /// Queues the complete map of enabled orders, replacing the previous map. @@ -153,9 +140,10 @@ impl BrokerClient { self.publish(Update::Logger(recording)).await } - /// Queues a complete, prepared packet update for the next 100 ms batch. - pub async fn publish_data(&self, packet: DataPacketUpdate) -> Result<(), Error> { - self.publish(Update::Data(packet)).await + /// Queues the complete telemetry map, replacing the previous map. Every + /// call reaches the subscribers, so the publisher sets the update rate. + pub async fn publish_data(&self, data: DataUpdate) -> Result<(), Error> { + self.publish(Update::Data(data)).await } /// Queues a message for current subscribers. @@ -234,9 +222,10 @@ fn subscribe(state: &watch::Receiver) -> watch::Receiver { mod tests { use std::time::Duration; - use tokio::time::{advance, timeout}; + use tokio::time::{Instant, timeout}; use super::*; + use crate::payload::{Connection, DataPacketUpdate}; #[tokio::test] async fn subscribers_receive_complete_state_and_late_subscribers_start_current() @@ -249,27 +238,23 @@ mod tests { assert!(second.borrow_and_update().is_empty()); let worker = tokio::spawn(broker.run()); - for (name, is_connected) in [("LCU", true), ("HVBMS", true), ("LCU", false)] { - publisher - .publish_connection(Connection { - name: name.into(), - is_connected, - }) - .await?; + let snapshots = [ + connections(&[("LCU", true)]), + connections(&[("LCU", true), ("HVBMS", true)]), + // A board missing from the snapshot is no longer published. + connections(&[("HVBMS", false)]), + ]; + for snapshot in &snapshots { + publisher.publish_connections(snapshot.clone()).await?; timeout(Duration::from_secs(1), first.changed()).await??; timeout(Duration::from_secs(1), second.changed()).await??; - let state = first.borrow_and_update().clone(); - assert_eq!(state, *second.borrow_and_update()); - assert_eq!(state[name].is_connected, is_connected); - assert_eq!(state[name].name, name); + assert_eq!(*first.borrow_and_update(), *snapshot); + assert_eq!(*second.borrow_and_update(), *snapshot); } let mut late = client.subscriber().subscribe_connections(); assert!(!late.has_changed()?); - let state = late.borrow_and_update().clone(); - assert_eq!(state.len(), 2); - assert!(!state["LCU"].is_connected); - assert!(state["HVBMS"].is_connected); + assert_eq!(*late.borrow_and_update(), snapshots[2]); drop(publisher); drop(client); @@ -282,13 +267,10 @@ mod tests { async fn publication_fails_when_broker_is_closed() { let (broker, client) = Broker::new(); drop(broker); - let result = client - .publish_connection(Connection { - name: "LCU".into(), - is_connected: true, - }) - .await; - assert!(matches!(result, Err(Error::BrokerClosed))); + assert!(matches!( + client.publish_connections(ConnectionUpdate::new()).await, + Err(Error::BrokerClosed) + )); assert!(matches!( client.publish_state_orders(StateOrdersUpdate::new()).await, Err(Error::BrokerClosed) @@ -298,51 +280,38 @@ mod tests { Err(Error::BrokerClosed) )); assert!(matches!( - client.publish_data(packet(1000, 1)).await, + client.publish_data(DataUpdate::new()).await, Err(Error::BrokerClosed) )); } #[tokio::test(start_paused = true)] - async fn telemetry_batches_latest_packets_and_keeps_the_complete_state() + async fn telemetry_is_relayed_as_published_without_batching_or_merging() -> Result<(), Box> { let (broker, client) = Broker::new(); let mut data = client.subscriber().subscribe_data(); - let mut logger = client.subscriber().subscribe_logger(); assert!(data.borrow_and_update().is_empty()); let worker = tokio::spawn(broker.run()); - tokio::task::yield_now().await; - - client.publish_data(packet(1000, 1)).await?; - client.publish_data(packet(2000, 1)).await?; - client.publish_data(packet(1000, 2)).await?; - // The logger update is a barrier: the preceding inputs have been processed. - client.publish_logger(true).await?; - logger.changed().await?; - assert!(!data.has_changed()?); - advance(Duration::from_millis(99)).await; - assert!(!data.has_changed()?); - advance(Duration::from_millis(1)).await; - timeout(Duration::from_millis(1), data.changed()).await??; - let snapshot = data.borrow_and_update().clone(); - assert_eq!(snapshot.len(), 2); - assert_eq!(snapshot[&1000].count, 2); - assert_eq!(snapshot[&2000].count, 1); + let start = Instant::now(); + + let first = telemetry(&[packet(1000, 1), packet(2000, 1)]); + client.publish_data(first.clone()).await?; + timeout(Duration::from_secs(1), data.changed()).await??; + // The paused clock only moves when every task waits on a timer, so a + // batching period would have advanced it. + assert_eq!(Instant::now(), start); + assert_eq!(*data.borrow_and_update(), first); + + // Packet 1000 is missing from the next snapshot, so it is no longer published. + let second = telemetry(&[packet(2000, 2)]); + client.publish_data(second.clone()).await?; + timeout(Duration::from_secs(1), data.changed()).await??; + assert_eq!(Instant::now(), start); + assert_eq!(*data.borrow_and_update(), second); let late = client.subscriber().subscribe_data(); - assert_eq!(*late.borrow(), snapshot); + assert_eq!(*late.borrow(), second); assert!(!late.has_changed()?); - advance(Duration::from_millis(100)).await; - tokio::task::yield_now().await; - assert!(!data.has_changed()?, "idle ticks must not publish"); - - client.publish_data(packet(2000, 2)).await?; - client.publish_logger(false).await?; - logger.changed().await?; - advance(Duration::from_millis(100)).await; - timeout(Duration::from_millis(1), data.changed()).await??; - assert_eq!(data.borrow()[&1000].count, 2); - assert_eq!(data.borrow()[&2000].count, 2); drop(client); timeout(Duration::from_secs(1), worker).await??; @@ -393,10 +362,7 @@ mod tests { let (broker, client) = Broker::new(); let state = client.subscriber().subscribe_connections(); client - .publish_connection(Connection { - name: "LCU".into(), - is_connected: true, - }) + .publish_connections(connections(&[("LCU", true)])) .await?; let orders = client.subscriber().subscribe_state_orders(); let logger = client.subscriber().subscribe_logger(); @@ -405,7 +371,7 @@ mod tests { .await?; client.publish_logger(true).await?; let data = client.subscriber().subscribe_data(); - client.publish_data(packet(1000, 1)).await?; + client.publish_data(telemetry(&[packet(1000, 1)])).await?; drop(client); timeout(Duration::from_secs(1), broker.run()).await?; @@ -429,10 +395,7 @@ mod tests { // Publish once so `closed` also has to skip a state change. client - .publish_connection(Connection { - name: "LCU".into(), - is_connected: true, - }) + .publish_connections(connections(&[("LCU", true)])) .await?; drop(client); timeout(Duration::from_secs(1), worker).await??; @@ -444,6 +407,28 @@ mod tests { Ok(()) } + fn connections(boards: &[(&str, bool)]) -> ConnectionUpdate { + boards + .iter() + .map(|&(name, is_connected)| { + ( + name.to_owned(), + Connection { + name: name.to_owned(), + is_connected, + }, + ) + }) + .collect() + } + + fn telemetry(packets: &[DataPacketUpdate]) -> DataUpdate { + packets + .iter() + .map(|packet| (packet.id.0, packet.clone())) + .collect() + } + fn packet(id: u16, count: u64) -> DataPacketUpdate { DataPacketUpdate { id: software_core::model::AdjId(id), From 204e9b034a070d43a70d438ae828b9523c4106b6 Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Thu, 3 Dec 2026 20:02:17 +0100 Subject: [PATCH 185/225] feat(backend, logging): add lifecycle and error tracing --- backend/crates/station/src/logging/README.md | 27 ++++++++++++++++ backend/crates/station/src/logging/service.rs | 20 +++++++----- backend/crates/station/src/logging/writer.rs | 31 ++++++++++++++----- 3 files changed, 64 insertions(+), 14 deletions(-) diff --git a/backend/crates/station/src/logging/README.md b/backend/crates/station/src/logging/README.md index 3d1f1ede1..beb11a275 100644 --- a/backend/crates/station/src/logging/README.md +++ b/backend/crates/station/src/logging/README.md @@ -132,6 +132,33 @@ These are deliberately not filled in with reconstructed or guessed data: - **Controls:** the session-control channel and multi-frontend disconnect rule remain pending. +## Module Diagnostics + +Logging emits structured `tracing` events at three levels: + +| Level | Events | +| --- | --- | +| `INFO` | Writer ready, session started after opening files, session stopped after draining and attempting every file close, and service closed. | +| `WARN` | Rejected configuration or selection, discarded invalid input, and observed queue saturation that stops a session. | +| `ERROR` | Writer startup/runtime failure, session creation failure, file write/flush/close failure, exhausted session IDs, or unexpected writer exit. | + +Events include session IDs, directories, stop reasons and full error chains +where applicable. Saturation includes queue occupancy and capacity. Identical +file failures are reported once per session; the final stop event summarizes +the reason and error count without repeating their causes. A closed service +event includes whether the retained status contains an error; closure alone +does not imply that recording succeeded. + +Repeated play/stop calls with no state change do not emit lifecycle events. +Successful measurements, orders, protections and messages do not each emit a +diagnostic event, and periodic successful flushes remain silent. The module +does not emit `DEBUG` or `TRACE` events. + +The application owns the subscriber and its filter. For example, +`RUST_LOG=station::logging=info` enables these module events with an +`EnvFilter` subscriber. The module neither installs a subscriber nor writes +the pending `others/` JSONL trace itself. + ## File Structure for a Backend Run Each backend startup creates a directory named after its start date and time, diff --git a/backend/crates/station/src/logging/service.rs b/backend/crates/station/src/logging/service.rs index 02275e411..56455e3d9 100644 --- a/backend/crates/station/src/logging/service.rs +++ b/backend/crates/station/src/logging/service.rs @@ -34,7 +34,10 @@ impl Logging { input: mpsc::Receiver, options: WriterOptions, ) -> Result { - options.validate()?; + if let Err(error) = options.validate() { + tracing::warn!(%error, "logging configuration rejected"); + return Err(error); + } let directory = run.directory().to_path_buf(); let catalog = Catalog::new(adj, index); let (controls, control_rx) = mpsc::unbounded_channel(); @@ -42,10 +45,13 @@ impl Logging { let worker = std::thread::Builder::new() .name("logging-writer".into()) .spawn(move || writer::run(run, input, control_rx, status_tx, catalog, options)) - .map_err(|source| Error::Io { - operation: "spawn the logging writer", - path: directory, - source, + .map_err(|source| { + tracing::error!(directory = %directory.display(), error = %source, "could not spawn logging writer"); + Error::Io { + operation: "spawn the logging writer", + path: directory, + source, + } })?; Ok(Self { controls, @@ -138,9 +144,9 @@ impl Drop for Logging { .get_mut() .unwrap_or_else(|e| e.into_inner()) .take() - && worker.join().is_err() { - tracing::error!("logging writer exited unexpectedly during close"); + // The writer's exit guard traces an unexpected exit at its source. + let _ = worker.join(); } } } diff --git a/backend/crates/station/src/logging/writer.rs b/backend/crates/station/src/logging/writer.rs index e7ba54a68..98e389436 100644 --- a/backend/crates/station/src/logging/writer.rs +++ b/backend/crates/station/src/logging/writer.rs @@ -183,6 +183,7 @@ impl Recording { for error in errors { let text = error_chain(&error); if !self.errors.contains(&text) { + tracing::error!(session_id = self.info.id.get(), directory = %self.info.directory.display(), error = %text, "logging file operation failed"); self.errors.push(text); } } @@ -239,6 +240,7 @@ pub(super) fn run( .run(), ), Err(error) => { + tracing::error!(directory = %run.directory().display(), error = %error_chain(&error), "could not start logging writer runtime"); updates.send_replace(Status { phase: Phase::Closed, last_error: Some(format!("couldn't start the logging timer runtime: {error}")), @@ -253,6 +255,7 @@ impl Writer { let mut timer = tokio::time::interval(self.options.flush_interval); timer.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); timer.tick().await; // Consume the interval's immediate first tick. + tracing::info!(directory = %self.run.directory().display(), queue_capacity = self.input.max_capacity(), flush_interval = ?self.options.flush_interval, flush_bytes = self.options.flush_bytes, "logging service ready"); loop { let saturated = self.active.is_some() && self.input.len() == self.input.max_capacity(); // Controls win over data, including when input is full. recv is @@ -272,6 +275,7 @@ impl Writer { if let Err(error) = &result && self.status.phase == Phase::Starting { + tracing::error!(directory = %self.run.directory().display(), error = %error_chain(error), "could not start logging session"); self.status.phase = Phase::Inactive; self.status.last_error = Some(error_chain(error)); self.publish(); @@ -294,6 +298,12 @@ impl Writer { break; } Step::Saturated => { + tracing::warn!( + session_id = self.status.session.as_ref().map(|session| session.id.get()), + queue_len = self.input.len(), + queue_capacity = self.input.max_capacity(), + "logging input saturated; stopping session" + ); self.stop(StopReason::Saturation, SystemTime::now()).await; } Step::Flush => { @@ -318,12 +328,14 @@ impl Writer { if let Some(recording) = &self.active { return Ok(recording.info.clone()); } - selection.validate(&self.catalog)?; - let id = SessionId( - self.next_id - .checked_add(1) - .ok_or(Error::SessionIdExhausted)?, - ); + if let Err(error) = selection.validate(&self.catalog) { + tracing::warn!(error = %error_chain(&error), "logging session selection rejected"); + return Err(error); + } + let id = SessionId(self.next_id.checked_add(1).ok_or_else(|| { + tracing::error!("could not start logging session: session IDs exhausted"); + Error::SessionIdExhausted + })?); self.next_id = id.0; // Clear only the finite inactive backlog. New arrivals are not allowed // to keep a start waiting forever, and older timestamps are also filtered. @@ -353,6 +365,7 @@ impl Writer { self.status.phase = Phase::Recording; self.status.session = Some(info.clone()); self.publish(); + tracing::info!(session_id = info.id.get(), directory = %info.directory.display(), measurements = selection.measurements.len(), boards = selection.connected_boards.len(), time_unit = ?info.time_unit, "logging session started"); Ok(info) } @@ -374,7 +387,7 @@ impl Writer { match self.catalog.validate(incoming) { Ok(false) => return false, Err(error) => { - tracing::warn!(%error, "logging input could not be recorded"); + tracing::warn!(session_id = recording.info.id.get(), error = %error_chain(&error), "logging input discarded"); return false; } Ok(true) => {} @@ -425,6 +438,7 @@ impl Writer { for error in files.close() { let text = error_chain(&error); if !errors.contains(&text) { + tracing::error!(session_id = info.id.get(), directory = %info.directory.display(), error = %text, "logging file close failed"); errors.push(text); } } @@ -436,6 +450,7 @@ impl Writer { if let Some(error) = errors.first() { self.status.last_error = Some(error.clone()); } + tracing::info!(session_id = info.id.get(), directory = %info.directory.display(), ?reason, errors = errors.len(), "logging session stopped after draining and closing files"); self.status.last_stop = Some(StopReport { session: info, reason, @@ -456,6 +471,7 @@ impl Writer { self.stop(StopReason::Shutdown, cutoff).await; self.status.phase = Phase::Closed; self.publish(); + tracing::info!(directory = %self.run.directory().display(), failed = self.status.last_error.is_some(), "logging service closed"); } fn publish(&self) { @@ -482,6 +498,7 @@ impl Drop for ExitGuard { fn drop(&mut self) { let mut status = self.0.borrow().clone(); if status.phase != Phase::Closed { + tracing::error!(session_id = status.session.as_ref().map(|session| session.id.get()), phase = ?status.phase, "logging writer exited unexpectedly"); status.phase = Phase::Closed; status.last_error = Some("logging writer exited unexpectedly".into()); self.0.send_replace(status); From 3a3baebac5f279f5c90053062b948927b567e352 Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Thu, 3 Dec 2026 20:48:04 +0100 Subject: [PATCH 186/225] fix(backend, logging): orders payload enriched with Index metadata --- backend/crates/station/src/logging/README.md | 19 +++- .../src/logging/WEBSOCKET_INTEGRATION.md | 5 +- backend/crates/station/src/logging/catalog.rs | 42 ++++++- backend/crates/station/src/logging/order.rs | 102 +++++++++++++---- .../station/src/logging/service/tests.rs | 4 +- .../station/src/logging/test_support.rs | 35 +++++- backend/crates/station/src/logging/writer.rs | 8 +- .../station/src/logging/writer/tests.rs | 103 +++++++++++++++--- 8 files changed, 274 insertions(+), 44 deletions(-) diff --git a/backend/crates/station/src/logging/README.md b/backend/crates/station/src/logging/README.md index beb11a275..e269a45fa 100644 --- a/backend/crates/station/src/logging/README.md +++ b/backend/crates/station/src/logging/README.md @@ -53,7 +53,7 @@ internal controls. and a connection event or a decoded `Packet`. - `OrderSent { at, board, order }`: confirms that an order was written to TCP. Logging uses `at` for both elapsed and calendar time and stores the packet - as compact JSON in the order CSV's payload cell. + as compact JSON enriched with Index metadata in the order CSV's payload cell. `Catalog` keeps the supplied ADJ and protocol index shared. It builds a small measurement locator once, using `(BoardId, AdjId)` as keys. It resolves: @@ -339,7 +339,7 @@ instant,from,to,id,payload,timestamp | `from` | `backend`. | | `to` | ADJ board name, or `all` when `OrderSent.board` is `None`. | | `id` | Order ID. | -| `payload` | The confirmed `OrderPacket` as compact JSON: numeric `id` and positional `values`. | +| `payload` | Compact JSON with order `id`, ADJ `name`, and ordered `parameters`, each containing `id`, `alias`, `type` and `value`. | | `timestamp` | TCP confirmation date and time from `OrderSent.at`, using the format and offset described above. | Orders are recorded from `event::ToLogging::OrderSent` while a session is @@ -350,9 +350,22 @@ produce no order row. Logger controls arrive separately from WebSocket. Each payload is a single-line JSON object inside the CSV cell, for example: ```json -{"id":2000,"values":[1.5,true,"run"]} +{"id":1002,"name":"Duty","parameters":[{"id":3032,"alias":"duty_command","type":"uint32","value":75}]} ``` +Names and parameter definitions are resolved with `Index::packet(order.id)`; +parameter values are paired positionally with `PacketType::Order` fields. +The CSV's existing columns remain unchanged. The payload replaces the former +`values` array, so readers of that JSON must use `parameters[*].value` instead. +Types use ADJ names (`uint8` through `uint64`, `int8` through `int64`, `float32`, +`float64`, `bool`, `enum`). Metadata is borrowed from the shared Index rather +than copied into core's OrderPacket or a second per-event JSON tree. + +Unknown orders, wrong packet kinds, mismatched destinations and incorrect +parameter counts are discarded with a warning before writing. The reserved +broadcast fault (ID 0, destination `all`) requires no Index entry and is recorded +as `{"id":0,"name":"Fault","parameters":[]}`; it must have no values. + Values retain their packet order and use JSON numbers, booleans and strings for model `Number`, `Bool` and `Enum` values. JSON escapes embedded newlines; `logger::Row::text` then escapes the JSON for the CSV cell. There is no separate diff --git a/backend/crates/station/src/logging/WEBSOCKET_INTEGRATION.md b/backend/crates/station/src/logging/WEBSOCKET_INTEGRATION.md index 3fc6e7b01..05cc07c67 100644 --- a/backend/crates/station/src/logging/WEBSOCKET_INTEGRATION.md +++ b/backend/crates/station/src/logging/WEBSOCKET_INTEGRATION.md @@ -226,8 +226,9 @@ to pipeline. Distinguish this saturation from rejecting frontend commands. ## 9. Settled Contracts and Independent Pending Work Orders arrive from `event` as `ToLogging::OrderSent`. The CSV uses its `at` for -`instant` and `timestamp`, and the `OrderPacket` as compact JSON in the `payload` -cell: `{"id":2000,"values":[...]}`. `from` is `backend`; `to` is the board's name +`instant` and `timestamp`, and enriches the `OrderPacket` using `Index::packet(order.id)` for the JSON +`payload` cell: `{"id":2000,"name":"Enable","parameters":[...]}`. Each parameter +has its measurement `id`, `alias`, ADJ `type` and confirmed `value`. `from` is `backend`; `to` is the board's name or `all` when the destination is `None`. This is already implemented in logging and tested with the event router. diff --git a/backend/crates/station/src/logging/catalog.rs b/backend/crates/station/src/logging/catalog.rs index abca260a7..e91a3b191 100644 --- a/backend/crates/station/src/logging/catalog.rs +++ b/backend/crates/station/src/logging/catalog.rs @@ -9,7 +9,10 @@ use std::{collections::HashMap, sync::Arc}; use software_core::{ adj::Adj, - model::{AdjId, Board, BoardId, Measurement, MessageLevel, Packet, PacketType, Protection}, + model::{ + AdjId, Board, BoardId, Measurement, MessageLevel, OrderPacket, Packet, PacketDef, + PacketType, Protection, + }, net::Event, protocol::Index, }; @@ -146,18 +149,53 @@ impl Catalog { } } + /// Resolve confirmed orders through the same Index as networking. Only the + /// reserved broadcast fault has no ADJ definition. + pub fn order( + &self, + board: Option, + order: &OrderPacket, + ) -> Result, Error> { + if board.is_none() && order.id == AdjId(0) { + if !order.values.is_empty() { + return Err(Error::MeasurementCount(order.id)); + } + return Ok(None); + } + let definition = self + .index + .packet(order.id) + .ok_or(Error::UnknownPacket(order.id))?; + let PacketType::Order(fields) = &definition.packet_type else { + return Err(Error::UnexpectedPacketType(order.id)); + }; + let board = board.unwrap_or(BoardId(0)); + self.board(board)?; + if definition.board != board { + return Err(Error::PacketBoardMismatch { + board, + id: order.id, + }); + } + if fields.len() != order.values.len() { + return Err(Error::MeasurementCount(order.id)); + } + Ok(Some(definition)) + } + /// Validate a received packet before writing any of its CSV rows. /// Connection notifications have no CSV row. /// `true` means the packet is structurally eligible for writing; measurement /// selection is applied separately by the CSV writer. pub fn validate(&self, incoming: &ToLogging) -> Result { let notification = match incoming { - ToLogging::OrderSent { board, .. } => { + ToLogging::OrderSent { board, order, .. } => { // Event confirms the packet was sent. Resolve its destination; // the broadcast fault has no single owner or ADJ packet entry. if let Some(board) = board { validate_name(&self.board(*board)?.name)?; } + self.order(*board, order)?; return Ok(true); } ToLogging::Received(notification) => notification, diff --git a/backend/crates/station/src/logging/order.rs b/backend/crates/station/src/logging/order.rs index b7d85d634..923ff8f3c 100644 --- a/backend/crates/station/src/logging/order.rs +++ b/backend/crates/station/src/logging/order.rs @@ -5,7 +5,8 @@ //! `YYYY-MM-DDTHH-MM-SS` followed by the applicable `Europe/Madrid` UTC offset //! (`+01:00` for CET or `+02:00` for CEST). //! Orders come from event's `OrderSent`, using its TCP confirmation time. -//! `payload` is the OrderPacket as compact JSON in one CSV cell. No header. +//! `payload` contains the order ID/name and ADJ parameter metadata with values, +//! as compact JSON in one CSV cell. No header. //! //! This component owns a `software_core::logger::CsvFile` and formats rows. @@ -14,7 +15,9 @@ use std::path::Path; use serde::{Serialize, Serializer, ser::SerializeSeq}; use software_core::{ logger::CsvFile, - model::{OrderPacket, Value}, + model::{ + AdjId, Measurement, MeasurementKind, NumericKind, OrderPacket, PacketDef, PacketType, Value, + }, }; use super::{Error, output::flush_if_due, session::RecordTime}; @@ -33,17 +36,35 @@ impl OrderLogger { } /// Serialize the confirmed packet before starting a row, so a payload - /// failure cannot leave a partial CSV record. Values remain positional. + /// failure cannot leave a partial CSV record. ADJ parameters retain their order. pub fn write( &mut self, time: RecordTime, order: &OrderPacket, to: &str, + definition: Option<&PacketDef>, threshold: u64, ) -> Result<(), Error> { + let (name, fields) = match definition { + Some(PacketDef { + id, + name, + packet_type: PacketType::Order(fields), + .. + }) if *id == order.id => (name.as_str(), fields.as_slice()), + None if order.id == AdjId(0) => ("Fault", &[][..]), + _ => return Err(Error::UnexpectedPacketType(order.id)), + }; + if fields.len() != order.values.len() { + return Err(Error::MeasurementCount(order.id)); + } let payload = serde_json::to_string(&Payload { id: order.id.0, - values: &order.values, + name, + parameters: Parameters { + fields, + values: &order.values, + }, }) .map_err(Error::OrderPayload)?; let timestamp = time @@ -70,25 +91,66 @@ impl OrderLogger { #[derive(Serialize)] struct Payload<'a> { id: u16, - #[serde(serialize_with = "serialize_values")] + name: &'a str, + parameters: Parameters<'a>, +} + +struct Parameters<'a> { + fields: &'a [Measurement], values: &'a [Value], } -fn serialize_values(values: &[Value], serializer: S) -> Result { - let mut sequence = serializer.serialize_seq(Some(values.len()))?; - for value in values { - match value { - Value::Number(value) => { - // JSON has no NaN/infinity; never silently replace a value - // with null and present that as the packet that was sent. - if !value.is_finite() { - return Err(serde::ser::Error::custom("non-finite order value")); - } - sequence.serialize_element(value)?; - } - Value::Bool(value) => sequence.serialize_element(value)?, - Value::Enum(value) => sequence.serialize_element(value)?, +impl Serialize for Parameters<'_> { + fn serialize(&self, serializer: S) -> Result { + let mut sequence = serializer.serialize_seq(Some(self.fields.len()))?; + for (field, value) in self.fields.iter().zip(self.values) { + sequence.serialize_element(&Parameter { + id: field.id.0, + alias: &field.alias, + kind: type_name(&field.kind), + value, + })?; + } + sequence.end() + } +} + +#[derive(Serialize)] +struct Parameter<'a> { + id: u16, + alias: &'a str, + #[serde(rename = "type")] + kind: &'static str, + #[serde(serialize_with = "serialize_value")] + value: &'a Value, +} + +fn serialize_value(value: &Value, serializer: S) -> Result { + match value { + Value::Number(value) if !value.is_finite() => { + Err(serde::ser::Error::custom("non-finite order value")) } + Value::Number(value) => serializer.serialize_f64(*value), + Value::Bool(value) => serializer.serialize_bool(*value), + Value::Enum(value) => serializer.serialize_str(value), + } +} + +fn type_name(kind: &MeasurementKind) -> &'static str { + match kind { + MeasurementKind::Boolean => "bool", + MeasurementKind::Enum { .. } => "enum", + MeasurementKind::Numeric { wire_type } => match wire_type { + NumericKind::U8 => "uint8", + NumericKind::U16 => "uint16", + NumericKind::U32 => "uint32", + NumericKind::U64 => "uint64", + NumericKind::I8 => "int8", + NumericKind::I16 => "int16", + NumericKind::I32 => "int32", + NumericKind::I64 => "int64", + NumericKind::F32 => "float32", + NumericKind::F64 => "float64", + }, } - sequence.end() } diff --git a/backend/crates/station/src/logging/service/tests.rs b/backend/crates/station/src/logging/service/tests.rs index 0f5cfb25e..cda69f9f4 100644 --- a/backend/crates/station/src/logging/service/tests.rs +++ b/backend/crates/station/src/logging/service/tests.rs @@ -541,7 +541,7 @@ async fn event_routes_to_the_real_logger_across_session_stop_and_restart() -> Te let contents = fs::read_to_string(session.directory.join("order/order.csv"))?; assert_eq!(contents.lines().count(), 1); assert!(contents.ends_with(&format!( - ",backend,LCU,2000,\"{{\"\"id\"\":2000,\"\"values\"\":[true]}}\",{timestamp}\n" + ",backend,LCU,2000,\"{{\"\"id\"\":2000,\"\"name\"\":\"\"Enable\"\",\"\"parameters\"\":[{{\"\"id\"\":4000,\"\"alias\"\":\"\"enabled_command\"\",\"\"type\"\":\"\"bool\"\",\"\"value\"\":true}}]}}\",{timestamp}\n" ))); drop((udp, tcp, orders, problems)); assert!(matches!( @@ -564,7 +564,7 @@ async fn an_unrepresentable_order_payload_stops_recording_and_flushes_healthy_fi at: SystemTime::now(), board: Some(LCU), order: OrderPacket::new( - AdjId(2000), + AdjId(2002), vec![software_core::model::Value::Number(f64::NAN)], ), }) diff --git a/backend/crates/station/src/logging/test_support.rs b/backend/crates/station/src/logging/test_support.rs index 47d4d6cbe..789663172 100644 --- a/backend/crates/station/src/logging/test_support.rs +++ b/backend/crates/station/src/logging/test_support.rs @@ -96,11 +96,44 @@ pub(super) fn definitions() -> (Arc, Arc) { ..temperature.clone() }), }; + let command = |id, alias, kind| Measurement { + kind, + ..measurement(AdjId(id), alias) + }; + let enabled = command(4000, "enabled_command", MeasurementKind::Boolean); + let speed = command( + 4001, + "speed_command", + MeasurementKind::Numeric { + wire_type: NumericKind::F64, + }, + ); + let mode = command( + 4002, + "mode_command", + MeasurementKind::Enum { + options: vec!["Idle".into(), "run, \"fast\"\nnext".into()], + }, + ); + let order = |id, name: &str, fields| PacketDef { + id: AdjId(id), + board: LCU, + name: name.into(), + packet_type: PacketType::Order(fields), + }; let boards = [ board( LCU, "LCU", - vec![telemetry, protection(LCU, ABOVE), protection(LCU, RANGE)], + vec![ + telemetry, + protection(LCU, ABOVE), + protection(LCU, RANGE), + order(2000, "Enable", vec![enabled.clone()]), + order(2001, "Brake", vec![]), + order(2002, "Set speed", vec![speed.clone()]), + order(2003, "Configure, \"drive\"", vec![speed, enabled, mode]), + ], ), board(PCU, "PCU", vec![pcu_protection]), ]; diff --git a/backend/crates/station/src/logging/writer.rs b/backend/crates/station/src/logging/writer.rs index 98e389436..ec6a5eebf 100644 --- a/backend/crates/station/src/logging/writer.rs +++ b/backend/crates/station/src/logging/writer.rs @@ -102,7 +102,13 @@ impl SessionFiles { Some(board) => catalog.board(*board)?.name.as_str(), None => "all", }; - return self.orders.write(time, order, to, threshold); + return self.orders.write( + time, + order, + to, + catalog.order(*board, order)?, + threshold, + ); } ToLogging::Received(notification) => notification, }; diff --git a/backend/crates/station/src/logging/writer/tests.rs b/backend/crates/station/src/logging/writer/tests.rs index bea32d8b1..404a78130 100644 --- a/backend/crates/station/src/logging/writer/tests.rs +++ b/backend/crates/station/src/logging/writer/tests.rs @@ -77,33 +77,56 @@ fn native_csv_formats_preserve_fields_without_headers() -> TestResult { fn order_payload_offsets_and_large_instants_are_preserved() -> TestResult { let temp = tempfile::tempdir()?; let mut orders = OrderLogger::open(temp.path())?; + let (_, index) = definitions(); let mut summer = time("2026-07-15T13:30:05Z")?; summer.instant = 35000; let order = OrderPacket::new( - AdjId(2000), + AdjId(2003), vec![ Value::Number(1.5), Value::Bool(true), Value::Enum("run, \"fast\"\nnext".into()), ], ); - orders.write(summer, &order, "LCU", u64::MAX)?; + orders.write(summer, &order, "LCU", index.packet(order.id), u64::MAX)?; orders.write( time("2026-11-27T14:30:05Z")?, &OrderPacket::new(AdjId(2001), vec![]), "LCU", + index.packet(AdjId(2001)), u64::MAX, )?; orders.file.close()?; - let payload = r#"{"id":2000,"values":[1.5,true,"run, \"fast\"\nnext"]}"#; + let payload = serde_json::json!({"id":2003,"name":"Configure, \"drive\"","parameters":[ + {"id":4001,"alias":"speed_command","type":"float64","value":1.5}, + {"id":4000,"alias":"enabled_command","type":"bool","value":true}, + {"id":4002,"alias":"mode_command","type":"enum","value":"run, \"fast\"\nnext"} + ]}); + // Decode the JSON cell and verify CSV escaping of + // commas, quotes and JSON-escaped newlines in both names and values. + let contents = fs::read_to_string(temp.path().join("order/order.csv"))?; + let lines: Vec<_> = contents.lines().collect(); + assert_eq!(lines.len(), 2); + let read_payload = + |line: &str| -> Result> { + let escaped = line + .split_once(",\"") + .ok_or("missing CSV payload")? + .1 + .rsplit_once("\",") + .ok_or("missing CSV timestamp")? + .0; + Ok(serde_json::from_str(&escaped.replace("\"\"", "\""))?) + }; + assert_eq!(read_payload(lines[0])?, payload); + assert!(lines[0].starts_with("35000,backend,LCU,2003,")); + assert!(lines[0].ends_with(",2026-07-15T15-30-05+02:00")); assert_eq!( - fs::read_to_string(temp.path().join("order/order.csv"))?, - format!( - "35000,backend,LCU,2000,\"{}\",2026-07-15T15-30-05+02:00\n{},backend,LCU,2001,\"{{\"\"id\"\":2001,\"\"values\"\":[]}}\",2026-11-27T15-30-05+01:00\n", - payload.replace('"', "\"\""), - u128::MAX - ) + read_payload(lines[1])?, + serde_json::json!({"id":2001,"name":"Brake","parameters":[]}) ); + assert!(lines[1].starts_with(&format!("{},backend,LCU,2001,", u128::MAX))); + assert!(lines[1].ends_with(",2026-11-27T15-30-05+01:00")); Ok(()) } @@ -124,7 +147,7 @@ fn confirmed_broadcast_orders_use_all_as_destination() -> TestResult { assert_eq!( fs::read_to_string(temp.path().join("order/order.csv"))?, format!( - "{},backend,all,0,\"{{\"\"id\"\":0,\"\"values\"\":[]}}\",2026-11-27T15-30-05+01:00\n", + "{},backend,all,0,\"{{\"\"id\"\":0,\"\"name\"\":\"\"Fault\"\",\"\"parameters\"\":[]}}\",2026-11-27T15-30-05+01:00\n", u128::MAX ) ); @@ -135,12 +158,14 @@ fn confirmed_broadcast_orders_use_all_as_destination() -> TestResult { fn non_finite_order_values_are_rejected_before_starting_a_csv_row() -> TestResult { let temp = tempfile::tempdir()?; let mut orders = OrderLogger::open(temp.path())?; + let (_, index) = definitions(); for value in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] { assert!(matches!( orders.write( time("2026-11-27T14:30:05Z")?, - &OrderPacket::new(AdjId(2000), vec![Value::Number(value)]), + &OrderPacket::new(AdjId(2002), vec![Value::Number(value)]), "LCU", + index.packet(AdjId(2002)), u64::MAX ), Err(Error::OrderPayload(_)) @@ -348,7 +373,7 @@ async fn events_use_at_for_elapsed_and_order_wall_timestamps() -> TestResult { let order = |at| ToLogging::OrderSent { at, board: Some(LCU), - order: OrderPacket::new(AdjId(2000), vec![]), + order: OrderPacket::new(AdjId(2001), vec![]), }; // An old confirmation cannot leak into this session. A later one must // use its own stamp, even if the writer processes it immediately. @@ -367,7 +392,9 @@ async fn events_use_at_for_elapsed_and_order_wall_timestamps() -> TestResult { .to_string(); assert_eq!( fs::read_to_string(session.directory.join("order/order.csv"))?, - format!("35000,backend,LCU,2000,\"{{\"\"id\"\":2000,\"\"values\"\":[]}}\",{timestamp}\n") + format!( + "35000,backend,LCU,2001,\"{{\"\"id\"\":2001,\"\"name\"\":\"\"Brake\"\",\"\"parameters\"\":[]}}\",{timestamp}\n" + ) ); Ok(()) } @@ -418,3 +445,53 @@ fn protection_time_preserves_the_adj_duration_and_its_precision() -> TestResult } Ok(()) } + +#[test] +fn orders_require_matching_index_metadata_before_writing() -> TestResult { + let temp = tempfile::tempdir()?; + let (adj, index) = definitions(); + let catalog = Catalog::new(adj, index); + let mut files = SessionFiles::open(temp.path(), &selection(), &catalog)?; + let sent = |board, id, values| ToLogging::OrderSent { + at: SystemTime::now(), + board, + order: OrderPacket::new(AdjId(id), values), + }; + assert!(matches!( + catalog.validate(&sent(Some(LCU), 999, vec![])), + Err(Error::UnknownPacket(_)) + )); + assert!(matches!( + catalog.validate(&sent(Some(LCU), TELEMETRY.0, vec![])), + Err(Error::UnexpectedPacketType(_)) + )); + assert!(matches!( + catalog.validate(&sent(Some(PCU), 2000, vec![Value::Bool(true)])), + Err(Error::PacketBoardMismatch { .. }) + )); + assert!( + catalog + .validate(&sent(None, 2000, vec![Value::Bool(true)])) + .is_err() + ); + assert!(matches!( + catalog.validate(&sent(None, 0, vec![Value::Bool(true)])), + Err(Error::MeasurementCount(_)) + )); + // Too few and too many values must fail before zip could silently drop a + // parameter or its value, including at the file writer's own boundary. + for values in [vec![], vec![Value::Bool(true), Value::Bool(false)]] { + let incoming = sent(Some(LCU), 2000, values); + assert!(matches!( + catalog.validate(&incoming), + Err(Error::MeasurementCount(_)) + )); + assert!(matches!( + files.write(time("2026-07-15T13:30:05Z")?, &incoming, u64::MAX, &catalog), + Err(Error::MeasurementCount(_)) + )); + } + assert!(files.close().is_empty()); + assert!(fs::read(temp.path().join("order/order.csv"))?.is_empty()); + Ok(()) +} From b0c3126dde0c9e294d7d842aa57dd7d970d8110c Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Thu, 3 Dec 2026 21:10:21 +0100 Subject: [PATCH 187/225] fix(backend, logging): add order name field and rethink of payload (now parameters) --- backend/crates/station/src/logging/README.md | 31 ++++++----- .../src/logging/WEBSOCKET_INTEGRATION.md | 15 +++--- backend/crates/station/src/logging/error.rs | 2 +- backend/crates/station/src/logging/order.rs | 54 ++++--------------- .../station/src/logging/service/tests.rs | 2 +- .../station/src/logging/writer/tests.rs | 52 ++++++++---------- 6 files changed, 61 insertions(+), 95 deletions(-) diff --git a/backend/crates/station/src/logging/README.md b/backend/crates/station/src/logging/README.md index e269a45fa..ed2181713 100644 --- a/backend/crates/station/src/logging/README.md +++ b/backend/crates/station/src/logging/README.md @@ -53,7 +53,7 @@ internal controls. and a connection event or a decoded `Packet`. - `OrderSent { at, board, order }`: confirms that an order was written to TCP. Logging uses `at` for both elapsed and calendar time and stores the packet - as compact JSON enriched with Index metadata in the order CSV's payload cell. + with its ADJ name in a CSV column and its resolved parameters as a JSON array. `Catalog` keeps the supplied ADJ and protocol index shared. It builds a small measurement locator once, using `(BoardId, AdjId)` as keys. It resolves: @@ -330,7 +330,7 @@ There is a single `order.csv` file inside `order/`. Columns, in order: ```text -instant,from,to,id,payload,timestamp +instant,from,to,id,name,parameters,timestamp ``` | Field | Content | @@ -339,7 +339,8 @@ instant,from,to,id,payload,timestamp | `from` | `backend`. | | `to` | ADJ board name, or `all` when `OrderSent.board` is `None`. | | `id` | Order ID. | -| `payload` | Compact JSON with order `id`, ADJ `name`, and ordered `parameters`, each containing `id`, `alias`, `type` and `value`. | +| `name` | Order name from the ADJ. | +| `parameters` | Compact JSON array of objects containing only measurement `id`, `alias` and confirmed `value`, in ADJ parameter order. | | `timestamp` | TCP confirmation date and time from `OrderSent.at`, using the format and offset described above. | Orders are recorded from `event::ToLogging::OrderSent` while a session is @@ -347,30 +348,32 @@ active. Its `at` supplies both the elapsed `instant` and calendar `timestamp`. Only confirmed sends are recorded; incoming network `Packet::Order` events produce no order row. Logger controls arrive separately from WebSocket. -Each payload is a single-line JSON object inside the CSV cell, for example: +The `parameters` cell is directly a JSON array, for example: ```json -{"id":1002,"name":"Duty","parameters":[{"id":3032,"alias":"duty_command","type":"uint32","value":75}]} +[{"id":3032,"alias":"duty_command","value":75}] ``` Names and parameter definitions are resolved with `Index::packet(order.id)`; parameter values are paired positionally with `PacketType::Order` fields. -The CSV's existing columns remain unchanged. The payload replaces the former -`values` array, so readers of that JSON must use `parameters[*].value` instead. -Types use ADJ names (`uint8` through `uint64`, `int8` through `int64`, `float32`, -`float64`, `bool`, `enum`). Metadata is borrowed from the shared Index rather -than copied into core's OrderPacket or a second per-event JSON tree. +The order ID and name appear only in their CSV columns. Each parameter's `id` +is its measurement ID, not the order ID. The array has no enclosing object, +repeated order metadata or `type` field. Orders without parameters use `[]`. + +This seven-column layout replaces the previous six-column layout with a +`payload` object. Readers must handle the new `name` and `parameters` columns; +existing recordings are not rewritten. Unknown orders, wrong packet kinds, mismatched destinations and incorrect parameter counts are discarded with a warning before writing. The reserved broadcast fault (ID 0, destination `all`) requires no Index entry and is recorded -as `{"id":0,"name":"Fault","parameters":[]}`; it must have no values. +with `name` equal to `Fault` and `parameters` equal to `[]`; it must have no values. Values retain their packet order and use JSON numbers, booleans and strings for model `Number`, `Bool` and `Enum` values. JSON escapes embedded newlines; -`logger::Row::text` then escapes the JSON for the CSV cell. There is no separate -JSONL file or extra newline within this cell. Non-finite numeric values cannot -be represented as JSON and stop recording with an error before writing a row. +`logger::Row::text` then escapes the JSON array and the order name for CSV. +There is no separate JSONL file or extra newline within the JSON array cell. +Non-finite numeric values stop recording with an error before writing a row. ### Protections: protections/ diff --git a/backend/crates/station/src/logging/WEBSOCKET_INTEGRATION.md b/backend/crates/station/src/logging/WEBSOCKET_INTEGRATION.md index 05cc07c67..445943e20 100644 --- a/backend/crates/station/src/logging/WEBSOCKET_INTEGRATION.md +++ b/backend/crates/station/src/logging/WEBSOCKET_INTEGRATION.md @@ -225,11 +225,14 @@ to pipeline. Distinguish this saturation from rejecting frontend commands. ## 9. Settled Contracts and Independent Pending Work -Orders arrive from `event` as `ToLogging::OrderSent`. The CSV uses its `at` for -`instant` and `timestamp`, and enriches the `OrderPacket` using `Index::packet(order.id)` for the JSON -`payload` cell: `{"id":2000,"name":"Enable","parameters":[...]}`. Each parameter -has its measurement `id`, `alias`, ADJ `type` and confirmed `value`. `from` is `backend`; `to` is the board's name -or `all` when the destination is `None`. +Orders arrive from `event` as `ToLogging::OrderSent`. The CSV columns are +`instant,from,to,id,name,parameters,timestamp`. Its `at` supplies `instant` and +`timestamp`. `Index::packet(order.id)` supplies the order `name` and parameter +metadata. `parameters` is directly a JSON array: +`[{"id":4000,"alias":"enabled_command","value":true}]`. Each object has only +measurement `id`, `alias` and confirmed `value`; order ID/name are not repeated +inside it. An order without parameters uses `[]`. `from` is `backend`; `to` is +the board's name or `all` for the reserved fault broadcast, whose name is `Fault`. This is already implemented in logging and tested with the event router. Do not require the original frontend JSON or frontend reception time again. @@ -266,7 +269,7 @@ of the WebSocket merge. - [ ] Backend shutdown with a full command queue: independent signal, pending data processed and writer finished. - [ ] Slow or closed broker: the writer does not wait for the frontend. -- [ ] Confirmed orders: JSON in one cell and timing from `OrderSent.at`. +- [ ] Confirmed orders: name column, parameters array in one cell, and timing from `OrderSent.at`. - [ ] Update tests, README examples and callers of the previous API. Integration is complete when the backend uses the real service and these paths diff --git a/backend/crates/station/src/logging/error.rs b/backend/crates/station/src/logging/error.rs index 7896f8465..f47f3cee2 100644 --- a/backend/crates/station/src/logging/error.rs +++ b/backend/crates/station/src/logging/error.rs @@ -22,7 +22,7 @@ pub enum Error { UnexpectedPacketType(AdjId), #[error("packet {0:?} value count differs from its ADJ measurement count")] MeasurementCount(AdjId), - #[error("couldn't serialize the logged OrderPacket: {0}")] + #[error("couldn't serialize the logged order parameters: {0}")] OrderPayload(#[source] serde_json::Error), #[error("invalid logging file component: {0:?}")] InvalidName(String), diff --git a/backend/crates/station/src/logging/order.rs b/backend/crates/station/src/logging/order.rs index 923ff8f3c..190e8fb7f 100644 --- a/backend/crates/station/src/logging/order.rs +++ b/backend/crates/station/src/logging/order.rs @@ -1,12 +1,12 @@ //! Order recording in the session's single `order/order.csv` file. //! -//! Columns, in order: `instant,from,to,order_id,payload,timestamp`. +//! Columns, in order: `instant,from,to,id,name,parameters,timestamp`. //! `timestamp` is the order's wall-clock time formatted as //! `YYYY-MM-DDTHH-MM-SS` followed by the applicable `Europe/Madrid` UTC offset //! (`+01:00` for CET or `+02:00` for CEST). //! Orders come from event's `OrderSent`, using its TCP confirmation time. -//! `payload` contains the order ID/name and ADJ parameter metadata with values, -//! as compact JSON in one CSV cell. No header. +//! `name` comes from the ADJ. `parameters` is a compact JSON array of +//! measurement IDs, aliases and values in one CSV cell. No header. //! //! This component owns a `software_core::logger::CsvFile` and formats rows. @@ -15,9 +15,7 @@ use std::path::Path; use serde::{Serialize, Serializer, ser::SerializeSeq}; use software_core::{ logger::CsvFile, - model::{ - AdjId, Measurement, MeasurementKind, NumericKind, OrderPacket, PacketDef, PacketType, Value, - }, + model::{AdjId, Measurement, OrderPacket, PacketDef, PacketType, Value}, }; use super::{Error, output::flush_if_due, session::RecordTime}; @@ -35,7 +33,7 @@ impl OrderLogger { }) } - /// Serialize the confirmed packet before starting a row, so a payload + /// Serialize the confirmed packet before starting a row, so a parameters serialization /// failure cannot leave a partial CSV record. ADJ parameters retain their order. pub fn write( &mut self, @@ -58,13 +56,9 @@ impl OrderLogger { if fields.len() != order.values.len() { return Err(Error::MeasurementCount(order.id)); } - let payload = serde_json::to_string(&Payload { - id: order.id.0, - name, - parameters: Parameters { - fields, - values: &order.values, - }, + let parameters = serde_json::to_string(&Parameters { + fields, + values: &order.values, }) .map_err(Error::OrderPayload)?; let timestamp = time @@ -78,7 +72,8 @@ impl OrderLogger { .text("backend") // orders will always come from the backend and never from the boards .text(to) .int(i64::from(order.id.0)) - .text(&payload) + .text(name) + .text(¶meters) .text(×tamp) .end()?; // validates row and ends it flush_if_due(&mut self.file, threshold)?; @@ -88,13 +83,6 @@ impl OrderLogger { /// A borrowed JSON view keeps logging's representation out of core's model /// and avoids copying packet values or building an intermediate JSON tree. -#[derive(Serialize)] -struct Payload<'a> { - id: u16, - name: &'a str, - parameters: Parameters<'a>, -} - struct Parameters<'a> { fields: &'a [Measurement], values: &'a [Value], @@ -107,7 +95,6 @@ impl Serialize for Parameters<'_> { sequence.serialize_element(&Parameter { id: field.id.0, alias: &field.alias, - kind: type_name(&field.kind), value, })?; } @@ -119,8 +106,6 @@ impl Serialize for Parameters<'_> { struct Parameter<'a> { id: u16, alias: &'a str, - #[serde(rename = "type")] - kind: &'static str, #[serde(serialize_with = "serialize_value")] value: &'a Value, } @@ -135,22 +120,3 @@ fn serialize_value(value: &Value, serializer: S) -> Result serializer.serialize_str(value), } } - -fn type_name(kind: &MeasurementKind) -> &'static str { - match kind { - MeasurementKind::Boolean => "bool", - MeasurementKind::Enum { .. } => "enum", - MeasurementKind::Numeric { wire_type } => match wire_type { - NumericKind::U8 => "uint8", - NumericKind::U16 => "uint16", - NumericKind::U32 => "uint32", - NumericKind::U64 => "uint64", - NumericKind::I8 => "int8", - NumericKind::I16 => "int16", - NumericKind::I32 => "int32", - NumericKind::I64 => "int64", - NumericKind::F32 => "float32", - NumericKind::F64 => "float64", - }, - } -} diff --git a/backend/crates/station/src/logging/service/tests.rs b/backend/crates/station/src/logging/service/tests.rs index cda69f9f4..e4cd64206 100644 --- a/backend/crates/station/src/logging/service/tests.rs +++ b/backend/crates/station/src/logging/service/tests.rs @@ -541,7 +541,7 @@ async fn event_routes_to_the_real_logger_across_session_stop_and_restart() -> Te let contents = fs::read_to_string(session.directory.join("order/order.csv"))?; assert_eq!(contents.lines().count(), 1); assert!(contents.ends_with(&format!( - ",backend,LCU,2000,\"{{\"\"id\"\":2000,\"\"name\"\":\"\"Enable\"\",\"\"parameters\"\":[{{\"\"id\"\":4000,\"\"alias\"\":\"\"enabled_command\"\",\"\"type\"\":\"\"bool\"\",\"\"value\"\":true}}]}}\",{timestamp}\n" + ",backend,LCU,2000,Enable,\"[{{\"\"id\"\":4000,\"\"alias\"\":\"\"enabled_command\"\",\"\"value\"\":true}}]\",{timestamp}\n" ))); drop((udp, tcp, orders, problems)); assert!(matches!( diff --git a/backend/crates/station/src/logging/writer/tests.rs b/backend/crates/station/src/logging/writer/tests.rs index 404a78130..83e4ae4f4 100644 --- a/backend/crates/station/src/logging/writer/tests.rs +++ b/backend/crates/station/src/logging/writer/tests.rs @@ -97,36 +97,32 @@ fn order_payload_offsets_and_large_instants_are_preserved() -> TestResult { u64::MAX, )?; orders.file.close()?; - let payload = serde_json::json!({"id":2003,"name":"Configure, \"drive\"","parameters":[ - {"id":4001,"alias":"speed_command","type":"float64","value":1.5}, - {"id":4000,"alias":"enabled_command","type":"bool","value":true}, - {"id":4002,"alias":"mode_command","type":"enum","value":"run, \"fast\"\nnext"} - ]}); - // Decode the JSON cell and verify CSV escaping of - // commas, quotes and JSON-escaped newlines in both names and values. + let parameters = serde_json::json!([ + {"id":4001,"alias":"speed_command","value":1.5}, + {"id":4000,"alias":"enabled_command","value":true}, + {"id":4002,"alias":"mode_command","value":"run, \"fast\"\nnext"} + ]); let contents = fs::read_to_string(temp.path().join("order/order.csv"))?; let lines: Vec<_> = contents.lines().collect(); assert_eq!(lines.len(), 2); - let read_payload = - |line: &str| -> Result> { - let escaped = line - .split_once(",\"") - .ok_or("missing CSV payload")? - .1 - .rsplit_once("\",") - .ok_or("missing CSV timestamp")? - .0; - Ok(serde_json::from_str(&escaped.replace("\"\"", "\""))?) - }; - assert_eq!(read_payload(lines[0])?, payload); - assert!(lines[0].starts_with("35000,backend,LCU,2003,")); - assert!(lines[0].ends_with(",2026-07-15T15-30-05+02:00")); + // Extract the seven-column layout independently: verify the name's CSV + // quoting, decode the array cell, and check the timestamp separately. + let prefix = "35000,backend,LCU,2003,\"Configure, \"\"drive\"\"\",\""; + let suffix = "\",2026-07-15T15-30-05+02:00"; + let cell = lines[0] + .strip_prefix(prefix) + .ok_or("incorrect order/name columns")? + .strip_suffix(suffix) + .ok_or("incorrect timestamp column")?; + let decoded: serde_json::Value = serde_json::from_str(&cell.replace("\"\"", "\""))?; + assert_eq!(decoded, parameters); assert_eq!( - read_payload(lines[1])?, - serde_json::json!({"id":2001,"name":"Brake","parameters":[]}) + lines[1], + format!( + "{},backend,LCU,2001,Brake,[],2026-11-27T15-30-05+01:00", + u128::MAX + ) ); - assert!(lines[1].starts_with(&format!("{},backend,LCU,2001,", u128::MAX))); - assert!(lines[1].ends_with(",2026-11-27T15-30-05+01:00")); Ok(()) } @@ -147,7 +143,7 @@ fn confirmed_broadcast_orders_use_all_as_destination() -> TestResult { assert_eq!( fs::read_to_string(temp.path().join("order/order.csv"))?, format!( - "{},backend,all,0,\"{{\"\"id\"\":0,\"\"name\"\":\"\"Fault\"\",\"\"parameters\"\":[]}}\",2026-11-27T15-30-05+01:00\n", + "{},backend,all,0,Fault,[],2026-11-27T15-30-05+01:00\n", u128::MAX ) ); @@ -392,9 +388,7 @@ async fn events_use_at_for_elapsed_and_order_wall_timestamps() -> TestResult { .to_string(); assert_eq!( fs::read_to_string(session.directory.join("order/order.csv"))?, - format!( - "35000,backend,LCU,2001,\"{{\"\"id\"\":2001,\"\"name\"\":\"\"Brake\"\",\"\"parameters\"\":[]}}\",{timestamp}\n" - ) + format!("35000,backend,LCU,2001,Brake,[],{timestamp}\n") ); Ok(()) } From b0e8847ecc9319d7cc43419e022f29ad5112d296 Mon Sep 17 00:00:00 2001 From: GaziH Date: Thu, 3 Dec 2026 22:14:32 +0100 Subject: [PATCH 188/225] Feat(backend, pipeline): Added /heartbeat management. --- backend/crates/station/src/pipeline.rs | 11 +- .../crates/station/src/pipeline/frontend.rs | 110 ++++++++++-------- backend/crates/station/src/pipeline/tests.rs | 51 +++++--- 3 files changed, 107 insertions(+), 65 deletions(-) diff --git a/backend/crates/station/src/pipeline.rs b/backend/crates/station/src/pipeline.rs index 14787ec46..e9e52961e 100644 --- a/backend/crates/station/src/pipeline.rs +++ b/backend/crates/station/src/pipeline.rs @@ -58,6 +58,9 @@ use tracing::{error, warn}; pub struct Config { /// How often accumulated `Data` telemetry is flushed to the broker. pub data_flush_interval: Duration, + /// Maximum time allowed between `connection/heartbeat` keep-alives for a + /// frontend session before it is considered dead. + pub frontend_heartbeat_timeout: Duration, /// Grace period allowed for a frontend client to reconnect after the last /// active frontend socket closes before reporting a fatal problem to `event`. pub frontend_disconnect_timeout: Duration, @@ -67,6 +70,7 @@ impl Default for Config { fn default() -> Self { Self { data_flush_interval: Duration::from_millis(100), + frontend_heartbeat_timeout: Duration::from_secs(3), frontend_disconnect_timeout: Duration::from_secs(3), } } @@ -117,7 +121,10 @@ async fn run_loop( tick.set_missed_tick_behavior(MissedTickBehavior::Skip); let mut accumulator = DataAccumulator::default(); - let mut watchdog = FrontendWatchdog::new(config.frontend_disconnect_timeout); + let mut watchdog = FrontendWatchdog::new( + config.frontend_heartbeat_timeout, + config.frontend_disconnect_timeout, + ); let mut frontend_open = true; loop { @@ -134,7 +141,7 @@ async fn run_loop( sleep_until(deadline).await; } }, if frontend_deadline.is_some() => { - if let Some(reason) = watchdog.on_timeout() { + if let Some(reason) = watchdog.on_timeout(Instant::now()) { report_frontend_fatal(&problems, reason).await; } } diff --git a/backend/crates/station/src/pipeline/frontend.rs b/backend/crates/station/src/pipeline/frontend.rs index 5fd0709d1..c690b4f98 100644 --- a/backend/crates/station/src/pipeline/frontend.rs +++ b/backend/crates/station/src/pipeline/frontend.rs @@ -1,74 +1,84 @@ -//! Tracks the `websocket ↔ front` connection state inside `pipeline`. +//! Tracks `websocket ↔ front` session liveness and keep-alives (`connection/heartbeat`). //! -//! `websocket` forwards session lifecycle transitions via [`FrontendEvent`], -//! and [`FrontendWatchdog`] decides when the loss of the last frontend client -//! becomes a fatal backend problem. +//! `websocket` forwards session lifecycle transitions and keep-alive signals via +//! [`FrontendEvent`], and [`FrontendWatchdog`] owns both the per-session +//! heartbeat timer and the post-disconnect reconnect grace timer. +use std::collections::HashMap; use std::time::Duration; use tokio::time::Instant; -/// Frontend session lifecycle events sent by `websocket` to `pipeline`. +/// Frontend session events forwarded from `websocket` to `pipeline`. +/// +/// Each active WebSocket connection is identified by a unique session ID (`u64`) +/// so a silently dead tab expires on its own without blocking disconnect detection. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum FrontendEvent { /// A frontend WebSocket client connected. - Connected, - /// A frontend WebSocket client disconnected normally or dropped its socket. - /// If it was the last active client, the reconnect grace window starts. - Disconnected, - /// A frontend WebSocket client timed out waiting for a heartbeat. - /// If it was the last active client, the heartbeat timeout already - /// satisfies the reconnect period, so it is fatal immediately. - HeartbeatTimeout, + Connected(u64), + /// A keep-alive (`connection/heartbeat`) arrived from this frontend session. + Heartbeat(u64), + /// A frontend WebSocket client disconnected. If it was the last live + /// session, the reconnect grace window starts. + Disconnected(u64), } -/// Tracks active frontend connections and the post-disconnect reconnect deadline. +/// Tracks active frontend sessions, their keep-alive deadlines, and the +/// post-disconnect reconnect deadline. #[derive(Debug)] pub(super) struct FrontendWatchdog { + heartbeat_timeout: Duration, grace_timeout: Duration, - active_clients: usize, + /// Active sessions mapped to the instant their keep-alive expires. + sessions: HashMap, /// True once at least one frontend has connected (startup with 0 clients is not fatal). had_client: bool, - /// Active reconnect deadline while waiting for a client to return after dropping to 0. + /// Armed while waiting for a client to reconnect after all sessions closed cleanly. reconnect_deadline: Option, /// Ensures a fatal disconnect problem is reported at most once. reported_fatal: bool, } impl FrontendWatchdog { - /// Creates a watchdog that allows `grace_timeout` for reconnection after - /// the last frontend disconnects normally. - pub(super) fn new(grace_timeout: Duration) -> Self { + /// Creates a watchdog with separate keep-alive and post-disconnect grace timeouts. + pub(super) fn new(heartbeat_timeout: Duration, grace_timeout: Duration) -> Self { Self { + heartbeat_timeout, grace_timeout, - active_clients: 0, + sessions: HashMap::new(), had_client: false, reconnect_deadline: None, reported_fatal: false, } } - /// Returns the currently armed reconnect deadline, if any. + /// Returns the next timer deadline that `run_loop` should wake up for: + /// either the reconnect grace deadline or the earliest session heartbeat expiry. pub(super) fn deadline(&self) -> Option { + if self.reported_fatal { + return None; + } self.reconnect_deadline + .or_else(|| self.sessions.values().copied().min()) } /// Processes a [`FrontendEvent`] at `now`. /// - /// Returns `Some(reason)` when the event triggers an immediate fatal - /// disconnect (e.g. heartbeat timeout on the last client). + /// Returns `Some(reason)` only when a zero-duration grace timeout makes a + /// disconnect fatal immediately. pub(super) fn on_event(&mut self, event: FrontendEvent, now: Instant) -> Option<&'static str> { match event { - FrontendEvent::Connected => { - self.active_clients = self.active_clients.saturating_add(1); + FrontendEvent::Connected(id) | FrontendEvent::Heartbeat(id) => { + self.sessions.insert(id, now + self.heartbeat_timeout); self.had_client = true; - // A returning client cancels any pending reconnect deadline. + // A live or returning client cancels any pending reconnect deadline. self.reconnect_deadline = None; None } - FrontendEvent::Disconnected => { - self.active_clients = self.active_clients.saturating_sub(1); - if self.had_client && self.active_clients == 0 && !self.reported_fatal { + FrontendEvent::Disconnected(id) => { + self.sessions.remove(&id); + if self.had_client && self.sessions.is_empty() && !self.reported_fatal { if self.grace_timeout.is_zero() { self.reported_fatal = true; return Some("all frontend connections lost"); @@ -77,27 +87,35 @@ impl FrontendWatchdog { } None } - FrontendEvent::HeartbeatTimeout => { - self.active_clients = self.active_clients.saturating_sub(1); - if self.had_client && self.active_clients == 0 && !self.reported_fatal { - // The heartbeat timeout already elapsed the disconnect window. - self.reconnect_deadline = None; - self.reported_fatal = true; - return Some("last frontend connection timed out on heartbeat"); - } - None - } } } - /// Fires when [`Self::deadline`] elapses without any client reconnecting. - pub(super) fn on_timeout(&mut self) -> Option<&'static str> { - self.reconnect_deadline = None; - if self.had_client && self.active_clients == 0 && !self.reported_fatal { + /// Processes an elapsed timer at `now`, expiring stale heartbeats and + /// checking the reconnect grace deadline. + pub(super) fn on_timeout(&mut self, now: Instant) -> Option<&'static str> { + if self.reported_fatal { + return None; + } + + if let Some(deadline) = self.reconnect_deadline + && now >= deadline + { + self.reconnect_deadline = None; + if self.had_client && self.sessions.is_empty() { + self.reported_fatal = true; + return Some("all frontend connections lost (reconnect timeout expired)"); + } + } + + let before = self.sessions.len(); + self.sessions.retain(|_, expires_at| *expires_at > now); + if before > 0 && self.sessions.is_empty() { + // The heartbeat timeout already elapsed the disconnect window, so + // losing the last live session to a missed keep-alive is fatal immediately. self.reported_fatal = true; - Some("all frontend connections lost (reconnect timeout expired)") - } else { - None + return Some("last frontend connection timed out on heartbeat"); } + + None } } \ No newline at end of file diff --git a/backend/crates/station/src/pipeline/tests.rs b/backend/crates/station/src/pipeline/tests.rs index 3930a3610..e0b3d778d 100644 --- a/backend/crates/station/src/pipeline/tests.rs +++ b/backend/crates/station/src/pipeline/tests.rs @@ -356,19 +356,23 @@ async fn frontend_disconnect_allows_reconnect_and_reports_fatal_after_grace_peri ); tokio::task::yield_now().await; - // Client connects, disconnects, then reconnects after 2 s (within 3 s grace). - fe_tx.send(FrontendEvent::Connected).await?; - fe_tx.send(FrontendEvent::Disconnected).await?; + // Session 1 connects, disconnects, then session 2 connects after 2 s (within 3 s grace). + fe_tx.send(FrontendEvent::Connected(1)).await?; + fe_tx.send(FrontendEvent::Disconnected(1)).await?; + tokio::task::yield_now().await; + advance(Duration::from_secs(2)).await; + fe_tx.send(FrontendEvent::Connected(2)).await?; + tokio::task::yield_now().await; + + // Advance 2 s (past session 1's old 3 s grace deadline, before session 2's heartbeat expiry). advance(Duration::from_secs(2)).await; - fe_tx.send(FrontendEvent::Connected).await?; - advance(Duration::from_secs(5)).await; assert!( problems_rx.try_recv().is_err(), "reconnecting within the grace period must cancel the fatal problem" ); - // Client disconnects again and does not return within 3 s. - fe_tx.send(FrontendEvent::Disconnected).await?; + // Session 2 disconnects and does not return within 3 s. + fe_tx.send(FrontendEvent::Disconnected(2)).await?; tokio::task::yield_now().await; advance(Duration::from_millis(2_999)).await; assert!(problems_rx.try_recv().is_err()); @@ -386,10 +390,11 @@ async fn frontend_disconnect_allows_reconnect_and_reports_fatal_after_grace_peri Ok(()) } -/// Verifies that a heartbeat timeout on the last active frontend client reports -/// `ProblemKind::Fatal` immediately without waiting for another 3 s grace period. +/// Verifies that `connection/heartbeat` keep-alives renew a session's 3 s +/// deadline, stale sessions expire independently, and losing the last live +/// session to a heartbeat timeout reports `ProblemKind::Fatal` immediately. #[tokio::test(start_paused = true)] -async fn frontend_heartbeat_timeout_on_last_client_is_fatal_immediately() +async fn frontend_heartbeat_renews_liveness_and_expires_last_session_as_fatal() -> Result<(), Box> { let (pod_data, index) = sample_fixture(); let (broker, client) = Broker::new(); @@ -409,18 +414,30 @@ async fn frontend_heartbeat_timeout_on_last_client_is_fatal_immediately() ); tokio::task::yield_now().await; - // Two clients connect; one times out -> still alive because one remains. - fe_tx.send(FrontendEvent::Connected).await?; - fe_tx.send(FrontendEvent::Connected).await?; - fe_tx.send(FrontendEvent::HeartbeatTimeout).await?; + // Two sessions connect at t = 0 (both expire at t = 3 s). + fe_tx.send(FrontendEvent::Connected(1)).await?; + fe_tx.send(FrontendEvent::Connected(2)).await?; + tokio::task::yield_now().await; + + // At t = 2 s, session 1 sends a keep-alive (now expires at t = 5 s); session 2 goes silent. + advance(Duration::from_secs(2)).await; + fe_tx.send(FrontendEvent::Heartbeat(1)).await?; + tokio::task::yield_now().await; + + // At t = 3 s, session 2 times out, but session 1 is still alive -> not fatal. + advance(Duration::from_secs(1)).await; tokio::task::yield_now().await; assert!(problems_rx.try_recv().is_err()); - // Last client times out -> immediate fatal without advancing virtual time. - fe_tx.send(FrontendEvent::HeartbeatTimeout).await?; + // At t = 4.999 s, session 1 is still within its keep-alive window. + advance(Duration::from_millis(1_999)).await; + assert!(problems_rx.try_recv().is_err()); + + // At t = 5.000 s, session 1 expires -> last live frontend lost, fatal immediately. + advance(Duration::from_millis(1)).await; let problem = timeout(Duration::from_millis(10), problems_rx.recv()) .await? - .ok_or("expected immediate fatal problem on last heartbeat timeout")?; + .ok_or("expected fatal problem when last frontend heartbeat expires")?; assert_eq!(problem.kind, ProblemKind::Fatal); assert_eq!(problem.board, None); From 0099c45ea1f8cc7cce1a42d2d112b7f24e12b102 Mon Sep 17 00:00:00 2001 From: Gazi Al Saad Halawani Date: Thu, 3 Dec 2026 23:01:34 +0100 Subject: [PATCH 189/225] Feat(backend, pipeline): Added board connection tracking --- backend/crates/station/src/pipeline.rs | 41 ++++++++++++++++++-------- 1 file changed, 29 insertions(+), 12 deletions(-) diff --git a/backend/crates/station/src/pipeline.rs b/backend/crates/station/src/pipeline.rs index e9e52961e..190faabc7 100644 --- a/backend/crates/station/src/pipeline.rs +++ b/backend/crates/station/src/pipeline.rs @@ -35,6 +35,7 @@ mod timestamp; #[cfg(test)] mod tests; +use std::collections::HashMap; pub use frontend::FrontendEvent; use std::sync::Arc; @@ -45,7 +46,7 @@ use crate::event::{Problem, ProblemKind, ToPipeline}; use crate::payload::{Connection, ProtectionUpdate}; use crate::websocket::broker::BrokerClient; use frontend::FrontendWatchdog; -use software_core::model::{Packet, PodData}; +use software_core::model::{BoardId, Packet, PodData}; use software_core::net::{Event, Notification}; use software_core::protocol::Index; use tokio::sync::mpsc; @@ -127,6 +128,21 @@ async fn run_loop( ); let mut frontend_open = true; + // Track connection state for every board declared in the ADJ (all start disconnected). + let mut board_connections: HashMap = + pod_data.boards.keys().map(|&id| (id, false)).collect(); + + // Publish initial `false` states so the frontend immediately sees all boards. + for (&id, &is_connected) in &board_connections { + let update = Connection { + name: message::board_name(&pod_data, id), + is_connected, + }; + if !publish_or_log(broker.publish_connection(update).await) { + return; + } + } + loop { let frontend_deadline = watchdog.deadline(); @@ -170,7 +186,7 @@ async fn run_loop( item = rx.recv() => { match item { Some(msg) => { - if !handle_item(msg, &broker, &pod_data, &index, &mut accumulator).await { + if !handle_item(msg, &broker, &pod_data, &index, &mut accumulator, &mut board_connections).await { return; } } @@ -193,10 +209,11 @@ async fn handle_item( pod_data: &PodData, index: &Index, accumulator: &mut DataAccumulator, + board_connections: &mut HashMap, ) -> bool { match item { ToPipeline::Received(notification) => { - handle_notification(¬ification, broker, pod_data, index, accumulator).await + handle_notification(¬ification, broker, pod_data, index, accumulator, board_connections).await } // TODO(websocket-merge): If `websocket` / `payload` splits backend problem onto a dedicated `problem/update` topic. ToPipeline::Problem(problem) => match message::from_problem(problem, pod_data) { @@ -217,6 +234,7 @@ async fn handle_item( /// Maps a wire-level [`Notification`] (connection transition or decoded packet) /// to its WebSocket topic or the 100 ms telemetry accumulator. /// +/// /// Returns `false` if publishing fails because the broker closed. async fn handle_notification( notification: &Notification, @@ -224,19 +242,18 @@ async fn handle_notification( pod_data: &PodData, index: &Index, accumulator: &mut DataAccumulator, + board_connections: &mut HashMap, ) -> bool { match ¬ification.event { - Event::Connected => { - let update = Connection { - name: message::board_name(pod_data, notification.board), - is_connected: true, - }; - publish_or_log(broker.publish_connection(update).await) - } - Event::Disconnected => { + Event::Connected | Event::Disconnected => { + let is_connected = matches!(notification.event, Event::Connected); + // Only publish when a board's connection state actually changes. + if board_connections.insert(notification.board, is_connected) == Some(is_connected) { + return true; + } let update = Connection { name: message::board_name(pod_data, notification.board), - is_connected: false, + is_connected, }; publish_or_log(broker.publish_connection(update).await) } From 450d6f3b90c60a8e11bff103a0cfa2ac8ac8ea5e Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Fri, 4 Dec 2026 00:32:31 +0100 Subject: [PATCH 190/225] fix(backend, ws): indicate that send problem is missing --- backend/crates/station/src/main.rs | 5 ++-- backend/crates/station/src/websocket.rs | 27 +++++++++++++++---- .../crates/station/src/websocket/README.md | 9 ++++++- 3 files changed, 33 insertions(+), 8 deletions(-) diff --git a/backend/crates/station/src/main.rs b/backend/crates/station/src/main.rs index 40cba4f65..305824231 100644 --- a/backend/crates/station/src/main.rs +++ b/backend/crates/station/src/main.rs @@ -6,8 +6,9 @@ fn main() { let filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info")); tracing_subscriber::fmt().with_env_filter(filter).init(); - // TODO(event): When starting the backend here, convert FrontendDisconnected - // into a ProblemKind::Fatal with no board and send it on channels.problems. + // TODO(event): When starting the backend here, give websocket a clone of + // channels.problems so it reports FrontendDisconnected to event itself + // (see the TODO in websocket::run). tracing::info!("iniciando demo de station"); let name = std::env::args().nth(1).unwrap_or_else(|| "World".into()); let _greeting = software_core::hello_world::greet(&name); diff --git a/backend/crates/station/src/websocket.rs b/backend/crates/station/src/websocket.rs index 2c29e55b3..2b1263e62 100644 --- a/backend/crates/station/src/websocket.rs +++ b/backend/crates/station/src/websocket.rs @@ -117,8 +117,9 @@ pub struct FrontendDisconnected; /// returning. Closing the HTTP handoff channel only stops accepting sockets; /// open sessions and the heartbeat timeout carry on. /// -/// The caller should report `FrontendDisconnected` to `event` when station -/// wires the two modules together. +/// `run` traces `FrontendDisconnected` as an error and returns it as soon as the +/// deadline passes, without waiting for sockets to close. The caller should +/// report it to `event` when station wires the two modules together. pub async fn run( mut connections: mpsc::Receiver, broker: Subscriber, @@ -133,18 +134,31 @@ pub async fn run( tokio::select! { biased; // Stopping takes priority: the deadline no longer matters once station shuts down. - () = broker.closed() => break, + () = broker.closed() => { + tracing::info!(active = sessions.active, "broker stopped, closing WebSocket sessions"); + break; + } _ = async { if let Some(deadline) = sessions.deadline { sleep_until(deadline).await; } - }, if sessions.deadline.is_some() => return Err(FrontendDisconnected), + }, if sessions.deadline.is_some() => { + tracing::error!(timeout = ?heartbeat_timeout, "{FrontendDisconnected}: no message within the heartbeat timeout"); + // TODO(event): nothing sends the fault yet. Once `station::event` + // is in this branch, take a clone of `channels.problems` and, + // right here, send it + // `Problem::now(ProblemKind::Fatal, None, )`. + // `event` then sends the fault to every board, shows the problem + // on the front and stops the backend. + return Err(FrontendDisconnected); + } socket = connections.recv(), if accepting => { let Some(socket) = socket else { accepting = false; continue; }; sessions.connected(); + tracing::info!(active = sessions.active, "frontend connected"); let broker = broker.clone(); let commands = commands.clone(); let session_ends = session_ends.clone(); @@ -152,7 +166,10 @@ pub async fn run( handler::handle(socket, broker, &commands, heartbeat_timeout, session_ends).await; }); } - Some(end) = ended.recv() => sessions.ended(end, heartbeat_timeout), + Some(end) = ended.recv() => { + sessions.ended(end, heartbeat_timeout); + tracing::info!(active = sessions.active, "frontend session ended"); + } } } diff --git a/backend/crates/station/src/websocket/README.md b/backend/crates/station/src/websocket/README.md index d6fbdf776..b370d76f7 100644 --- a/backend/crates/station/src/websocket/README.md +++ b/backend/crates/station/src/websocket/README.md @@ -77,10 +77,17 @@ of any session, not from the moment a socket closes: a frontend that disconnects has only the rest of that period to reconnect, and a session that timed out leaves none. Sessions the backend closes, such as one that lags behind an event topic, count like any other closure. There is no deadline before the first -frontend connects. The station startup task can report this error as a +frontend connects. `run` traces this error with `tracing::error!` and returns +it as soon as the period ends: a session reports its end before waiting for +its socket to close. The station startup task can report this error as a `ProblemKind::Fatal` on `channels.problems` so `event` requests the fault and stops the backend. +`run` also traces, at `info`, each frontend that connects, each session that +ends with the number still active, and the broker stopping. A session that +ends with an error, including its own heartbeat timeout, is traced at `warn` +with the cause. + Connect to `/backend/ws` on the listener's address and port and send this message to subscribe to `connection/update`. From 380967ce98f99b743e70c7b2fba07a1ff438eaf2 Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Fri, 4 Dec 2026 00:38:38 +0100 Subject: [PATCH 191/225] fix(backend, ws & payload): remove state orders --- backend/crates/station/src/payload.rs | 2 +- backend/crates/station/src/payload/README.md | 17 +----- .../src/payload/example/state_orders.json | 10 ---- backend/crates/station/src/payload/order.rs | 3 - backend/crates/station/src/websocket.rs | 4 -- .../crates/station/src/websocket/README.md | 1 - .../crates/station/src/websocket/broker.rs | 55 ++----------------- .../crates/station/src/websocket/receiver.rs | 5 -- .../crates/station/src/websocket/sender.rs | 4 +- 9 files changed, 7 insertions(+), 94 deletions(-) delete mode 100644 backend/crates/station/src/payload/example/state_orders.json diff --git a/backend/crates/station/src/payload.rs b/backend/crates/station/src/payload.rs index a2f6d5069..6f1124ca5 100644 --- a/backend/crates/station/src/payload.rs +++ b/backend/crates/station/src/payload.rs @@ -14,7 +14,7 @@ mod serialize; pub use connection::{Connection, ConnectionUpdate}; pub use data::{DataPacketUpdate, DataUpdate}; pub use message::{MessageUpdate}; -pub use order::{OrderField, OrderSend, StateOrdersUpdate}; +pub use order::{OrderField, OrderSend}; pub use protection::{ProtectionPayload, ProtectionUpdate}; /// Payload of `logger/enable`: the requested recording state. diff --git a/backend/crates/station/src/payload/README.md b/backend/crates/station/src/payload/README.md index 85ce46480..a37cfff00 100644 --- a/backend/crates/station/src/payload/README.md +++ b/backend/crates/station/src/payload/README.md @@ -18,7 +18,7 @@ such as `AdjId`, `Value` and `ProtectionPacket` come from `software_core::model` | [`../payload.rs`](../payload.rs) | Public re-exports and logger payload aliases. | | [`data.rs`](data.rs) | `DataUpdate`, `DataPacketUpdate` and measurement values. | | [`connection.rs`](connection.rs) | `ConnectionUpdate` and `Connection`. | -| [`order.rs`](order.rs) | `OrderSend`, `OrderField` and `StateOrdersUpdate`. | +| [`order.rs`](order.rs) | `OrderSend` and `OrderField`. | | [`message.rs`](message.rs) | `MessageUpdate`, its severity, content and calendar timestamp. | | [`protection.rs`](protection.rs) | `ProtectionUpdate`, conversion from `ProtectionPacket` and legacy `ProtectionPayload`. | | [`serialize.rs`](serialize.rs) | Internal Serde adapters for `AdjId` and `Value`. | @@ -30,7 +30,6 @@ such as `AdjId`, `Value` and `ProtectionPacket` come from `software_core::model` | `podData/update` | `DataUpdate` | Backend → frontend | [data.json](example/data.json) | | `connection/update` | `ConnectionUpdate` | Backend → frontend | [connection.json](example/connection.json) | | `order/send` | `OrderSend` | Frontend → backend | [order.json](example/order.json) | -| `order/stateOrders` | `StateOrdersUpdate` | Backend → frontend | [state_orders.json](example/state_orders.json) | | `message/update` | `MessageUpdate` | Backend → frontend | [message.json](example/message.json) | | `protection/update` | `ProtectionUpdate` | Backend → frontend | [protection.json](example/protection.json) | | `logger/enable` | `LoggerEnable` | Frontend → backend | [logger_enable.json](example/logger_enable.json) | @@ -161,20 +160,6 @@ Numeric `type` names are `"uint8"`, `"uint16"`, `"uint32"`, `"uint64"`, `"int8"`, `"int16"`, `"int32"`, `"int64"`, `"float32"` and `"float64"`. Boolean and enum parameters use `"bool"` and `"enum"`, respectively. -### Enabled Orders (`StateOrdersUpdate`) - -```jsonc -{ - "topic": "order/stateOrders", - "payload": { - "": [number] - } -} -``` - -Each array contains the IDs of the board's currently enabled orders. A board -with no enabled orders is represented by an empty array. - ### Messages (`MessageUpdate`) ```jsonc diff --git a/backend/crates/station/src/payload/example/state_orders.json b/backend/crates/station/src/payload/example/state_orders.json deleted file mode 100644 index 0ee68edda..000000000 --- a/backend/crates/station/src/payload/example/state_orders.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "topic": "order/stateOrders", - "payload": { - "LCU": [ - 1001, - 1002 - ], - "HVBMS": [] - } -} diff --git a/backend/crates/station/src/payload/order.rs b/backend/crates/station/src/payload/order.rs index 615b1a0ca..3e4a597f9 100644 --- a/backend/crates/station/src/payload/order.rs +++ b/backend/crates/station/src/payload/order.rs @@ -27,9 +27,6 @@ pub struct OrderField { pub field_type: String, } -/// Payload of `order/stateOrders`: board names mapped to enabled order ids. -pub type StateOrdersUpdate = HashMap>; - #[cfg(test)] mod tests { use serde_json::json; diff --git a/backend/crates/station/src/websocket.rs b/backend/crates/station/src/websocket.rs index 2b1263e62..60f5cad98 100644 --- a/backend/crates/station/src/websocket.rs +++ b/backend/crates/station/src/websocket.rs @@ -29,7 +29,6 @@ mod sender; pub const DEFAULT_HEARTBEAT_TIMEOUT: Duration = Duration::from_millis(100); const CONNECTION_UPDATE: &str = "connection/update"; -const STATE_ORDERS: &str = "order/stateOrders"; const LOGGER_ENABLE: &str = "logger/enable"; const LOGGER_RESPONSE: &str = "logger/response"; const LOGGER_VARIABLES: &str = "logger/variables"; @@ -59,7 +58,6 @@ pub struct Commands { #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] enum Topic { Connections, - StateOrders, Logger, Data, Messages, @@ -70,7 +68,6 @@ impl Topic { fn from_name(name: &str) -> Option { match name { CONNECTION_UPDATE => Some(Self::Connections), - STATE_ORDERS => Some(Self::StateOrders), LOGGER_RESPONSE => Some(Self::Logger), DATA_UPDATE => Some(Self::Data), MESSAGE_UPDATE => Some(Self::Messages), @@ -82,7 +79,6 @@ impl Topic { fn name(self) -> &'static str { match self { Self::Connections => CONNECTION_UPDATE, - Self::StateOrders => STATE_ORDERS, Self::Logger => LOGGER_RESPONSE, Self::Data => DATA_UPDATE, Self::Messages => MESSAGE_UPDATE, diff --git a/backend/crates/station/src/websocket/README.md b/backend/crates/station/src/websocket/README.md index b370d76f7..0d8417674 100644 --- a/backend/crates/station/src/websocket/README.md +++ b/backend/crates/station/src/websocket/README.md @@ -10,7 +10,6 @@ live in [`../payload/serialize.rs`](../payload/serialize.rs). | Topic | Publish through `BrokerClient` | Subscribe through `Subscriber` | Initial state | | --- | --- | --- | --- | | `connection/update` | `publish_connections(connections)` | `subscribe_connections()` | `{}` | -| `order/stateOrders` | `publish_state_orders(orders)` | `subscribe_state_orders()` | `{}` | | `logger/response` | `publish_logger(recording)` | `subscribe_logger()` | `false` | | `podData/update` | `publish_data(data)` | `subscribe_data()` | `{}` | | `message/update` | `publish_message(message)` | `subscribe_messages()` | No initial event | diff --git a/backend/crates/station/src/websocket/broker.rs b/backend/crates/station/src/websocket/broker.rs index 8d8ca2563..1bd8dc01a 100644 --- a/backend/crates/station/src/websocket/broker.rs +++ b/backend/crates/station/src/websocket/broker.rs @@ -7,7 +7,6 @@ use crate::payload::{ ConnectionUpdate, DataUpdate, LoggerResponse, MessageUpdate, ProtectionUpdate, - StateOrdersUpdate, }; use tokio::sync::{broadcast, mpsc, watch}; @@ -18,7 +17,6 @@ const EVENT_CAPACITY: usize = 128; #[derive(Debug)] enum Update { Connections(ConnectionUpdate), - StateOrders(StateOrdersUpdate), Logger(LoggerResponse), Data(DataUpdate), Message(MessageUpdate), @@ -30,7 +28,6 @@ enum Update { pub struct Broker { updates: mpsc::Receiver, connections: watch::Sender, - state_orders: watch::Sender, logger: watch::Sender, data: watch::Sender, messages: broadcast::Sender, @@ -50,7 +47,6 @@ pub struct BrokerClient { #[derive(Debug, Clone)] pub struct Subscriber { connections: watch::Receiver, - state_orders: watch::Receiver, logger: watch::Receiver, data: watch::Receiver, // Weak handles let event channels close when the broker exits. @@ -63,7 +59,6 @@ impl Broker { pub fn new() -> (Self, BrokerClient) { let (updates, receiver) = mpsc::channel(32); let (connections, state) = watch::channel(ConnectionUpdate::new()); - let (state_orders, orders) = watch::channel(StateOrdersUpdate::new()); let (logger, recording) = watch::channel(false); let (data, telemetry) = watch::channel(DataUpdate::new()); let (messages, _) = broadcast::channel(EVENT_CAPACITY); @@ -74,7 +69,6 @@ impl Broker { Self { updates: receiver, connections, - state_orders, logger, data, messages, @@ -84,7 +78,6 @@ impl Broker { updates, subscriber: Subscriber { connections: state, - state_orders: orders, logger: recording, data: telemetry, messages: message_topic, @@ -102,9 +95,6 @@ impl Broker { Update::Connections(connections) => { self.connections.send_replace(connections); } - Update::StateOrders(orders) => { - self.state_orders.send_replace(orders); - } Update::Logger(recording) => { self.logger.send_replace(recording); } @@ -130,11 +120,6 @@ impl BrokerClient { self.publish(Update::Connections(connections)).await } - /// Queues the complete map of enabled orders, replacing the previous map. - pub async fn publish_state_orders(&self, orders: StateOrdersUpdate) -> Result<(), Error> { - self.publish(Update::StateOrders(orders)).await - } - /// Queues the actual logger state reported by the backend. pub async fn publish_logger(&self, recording: LoggerResponse) -> Result<(), Error> { self.publish(Update::Logger(recording)).await @@ -183,11 +168,6 @@ impl Subscriber { subscribe(&self.connections) } - /// Subscribes to the complete map of enabled order ids by board name. - pub fn subscribe_state_orders(&self) -> watch::Receiver { - subscribe(&self.state_orders) - } - /// Subscribes to the actual recording state, initially `false`. pub fn subscribe_logger(&self) -> watch::Receiver { subscribe(&self.logger) @@ -271,10 +251,6 @@ mod tests { client.publish_connections(ConnectionUpdate::new()).await, Err(Error::BrokerClosed) )); - assert!(matches!( - client.publish_state_orders(StateOrdersUpdate::new()).await, - Err(Error::BrokerClosed) - )); assert!(matches!( client.publish_logger(true).await, Err(Error::BrokerClosed) @@ -319,37 +295,19 @@ mod tests { } #[tokio::test] - async fn orders_and_logger_keep_independent_current_states() + async fn logger_keeps_the_current_state_for_late_subscribers() -> Result<(), Box> { let (broker, client) = Broker::new(); - let mut orders = client.subscriber().subscribe_state_orders(); let mut logger = client.subscriber().subscribe_logger(); - assert!(orders.borrow_and_update().is_empty()); assert!(!*logger.borrow_and_update()); let worker = tokio::spawn(broker.run()); - let initial = StateOrdersUpdate::from([("LCU".into(), vec![1001, 1002])]); - client.publish_state_orders(initial.clone()).await?; - timeout(Duration::from_secs(1), orders.changed()).await??; - assert_eq!(*orders.borrow_and_update(), initial); - assert!(!logger.has_changed()?); - client.publish_logger(true).await?; timeout(Duration::from_secs(1), logger.changed()).await??; assert!(*logger.borrow_and_update()); - assert!(!orders.has_changed()?); - - // A full snapshot replaces previous boards and can clear enabled orders. - let current = StateOrdersUpdate::from([("HVBMS".into(), vec![])]); - client.publish_state_orders(current.clone()).await?; - timeout(Duration::from_secs(1), orders.changed()).await??; - assert_eq!(*orders.borrow_and_update(), current); - let late_orders = client.subscriber().subscribe_state_orders(); - let late_logger = client.subscriber().subscribe_logger(); - assert_eq!(*late_orders.borrow(), current); - assert!(*late_logger.borrow()); - assert!(!late_orders.has_changed()?); - assert!(!late_logger.has_changed()?); + let late = client.subscriber().subscribe_logger(); + assert!(*late.borrow()); + assert!(!late.has_changed()?); drop(client); timeout(Duration::from_secs(1), worker).await??; @@ -364,11 +322,7 @@ mod tests { client .publish_connections(connections(&[("LCU", true)])) .await?; - let orders = client.subscriber().subscribe_state_orders(); let logger = client.subscriber().subscribe_logger(); - client - .publish_state_orders(StateOrdersUpdate::from([("LCU".into(), vec![1001])])) - .await?; client.publish_logger(true).await?; let data = client.subscriber().subscribe_data(); client.publish_data(telemetry(&[packet(1000, 1)])).await?; @@ -376,7 +330,6 @@ mod tests { timeout(Duration::from_secs(1), broker.run()).await?; assert!(state.borrow()["LCU"].is_connected); - assert_eq!(orders.borrow()["LCU"], [1001]); assert!(*logger.borrow()); assert_eq!(data.borrow()[&1000].count, 1); Ok(()) diff --git a/backend/crates/station/src/websocket/receiver.rs b/backend/crates/station/src/websocket/receiver.rs index b02a9a38b..05446e1dc 100644 --- a/backend/crates/station/src/websocket/receiver.rs +++ b/backend/crates/station/src/websocket/receiver.rs @@ -9,7 +9,6 @@ use tokio::{ use crate::payload::{ ConnectionUpdate, DataUpdate, LoggerResponse, MessageUpdate, ProtectionUpdate, - StateOrdersUpdate, }; use super::{ @@ -29,7 +28,6 @@ struct Subscription { #[derive(Debug)] pub(super) enum SubscriptionChange { Connections(Option>), - StateOrders(Option>), Logger(Option>), Data(Option>), Messages(Option>), @@ -42,9 +40,6 @@ impl SubscriptionChange { Topic::Connections => { Self::Connections(enabled.then(|| broker.subscribe_connections())) } - Topic::StateOrders => { - Self::StateOrders(enabled.then(|| broker.subscribe_state_orders())) - } Topic::Logger => Self::Logger(enabled.then(|| broker.subscribe_logger())), Topic::Data => Self::Data(enabled.then(|| broker.subscribe_data())), Topic::Messages => { diff --git a/backend/crates/station/src/websocket/sender.rs b/backend/crates/station/src/websocket/sender.rs index cbccbe07e..895f70a0b 100644 --- a/backend/crates/station/src/websocket/sender.rs +++ b/backend/crates/station/src/websocket/sender.rs @@ -12,7 +12,7 @@ pub(super) async fn run( write: &mut SplitSink, mut subscriptions: mpsc::Receiver, ) -> Result<(), Error> { - let (mut connections, mut orders, mut logger, mut data) = (None, None, None, None); + let (mut connections, mut logger, mut data) = (None, None, None); let (mut messages, mut protections) = (None, None); loop { let frame = tokio::select! { @@ -22,7 +22,6 @@ pub(super) async fn run( let Some(change) = change else { return Ok(()); }; let snapshot = match change { SubscriptionChange::Connections(next) => subscribe_state(Topic::Connections, &mut connections, next)?, - SubscriptionChange::StateOrders(next) => subscribe_state(Topic::StateOrders, &mut orders, next)?, SubscriptionChange::Logger(next) => subscribe_state(Topic::Logger, &mut logger, next)?, SubscriptionChange::Data(next) => subscribe_state(Topic::Data, &mut data, next)?, SubscriptionChange::Messages(next) => { messages = next; None } @@ -34,7 +33,6 @@ pub(super) async fn run( next = next_event(Topic::Protections, &mut protections) => next?, next = next_event(Topic::Messages, &mut messages) => next?, next = next_state(Topic::Connections, &mut connections) => next?, - next = next_state(Topic::StateOrders, &mut orders) => next?, next = next_state(Topic::Logger, &mut logger) => next?, next = next_state(Topic::Data, &mut data) => next?, }; From ced6d2cc33f874cabf6fb0d609346c204331e1aa Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Fri, 4 Dec 2026 01:13:15 +0100 Subject: [PATCH 192/225] refactor(backend, payload): remiplement using traits --- backend/crates/station/src/payload.rs | 301 +++++++++++++++++- backend/crates/station/src/payload/README.md | 32 +- .../crates/station/src/payload/connection.rs | 15 +- backend/crates/station/src/payload/data.rs | 16 +- backend/crates/station/src/payload/message.rs | 50 +-- .../crates/station/src/payload/protection.rs | 9 +- .../crates/station/src/payload/serialize.rs | 10 +- backend/crates/station/src/websocket.rs | 62 ++-- .../crates/station/src/websocket/README.md | 8 +- .../crates/station/src/websocket/broker.rs | 123 +++++-- .../crates/station/src/websocket/sender.rs | 121 ++++--- 11 files changed, 598 insertions(+), 149 deletions(-) diff --git a/backend/crates/station/src/payload.rs b/backend/crates/station/src/payload.rs index 6f1124ca5..7592f7c70 100644 --- a/backend/crates/station/src/payload.rs +++ b/backend/crates/station/src/payload.rs @@ -1,9 +1,13 @@ //! JSON payloads for station's frontend topics. //! //! Each model describes the `payload` inside a `{topic, payload}` message. +//! Payloads the backend sends implement `TopicPayload`, which names their topic +//! and builds the complete message. //! Serde adapters define the frontend JSON representation for shared domain types. //! See `websocket/payload/README.md` for the wire shapes and examples. +use serde::Serialize; + mod connection; mod data; mod message; @@ -12,8 +16,8 @@ mod protection; mod serialize; pub use connection::{Connection, ConnectionUpdate}; -pub use data::{DataPacketUpdate, DataUpdate}; -pub use message::{MessageUpdate}; +pub use data::{DataPacketUpdate, DataUpdate, MeasurementUpdate}; +pub use message::{MessagePayload, MessageTimestamp, MessageUpdate, protection_level}; pub use order::{OrderField, OrderSend}; pub use protection::{ProtectionPayload, ProtectionUpdate}; @@ -21,7 +25,298 @@ pub use protection::{ProtectionPayload, ProtectionUpdate}; pub type LoggerEnable = bool; /// Payload of `logger/response`: the actual recording state. -pub type LoggerResponse = bool; +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize)] +#[serde(transparent)] +pub struct LoggerResponse(pub bool); + +impl From for LoggerResponse { + fn from(recording: bool) -> Self { + Self(recording) + } +} + +impl TopicPayload for LoggerResponse { + const TOPIC: &'static str = "logger/response"; +} /// Payload of `logger/variables`: selected measurement names. pub type LoggerVariables = Vec; + +/// A payload the backend sends to the frontend on its own topic. +/// +/// Implementors only name their topic; `to_message` builds the message. +pub trait TopicPayload: Serialize { + /// Wire name of the topic, such as `connection/update`. + const TOPIC: &'static str; + + /// Serializes `{"topic": TOPIC, "payload": self}` in a single pass. + fn to_message(&self) -> Result { + serde_json::to_string(&Envelope { + topic: Self::TOPIC, + payload: self, + }) + } +} + +/// The `{topic, payload}` message the frontend reads, borrowing the payload. +#[derive(Serialize)] +struct Envelope<'a, T: ?Sized> { + topic: &'static str, + payload: &'a T, +} + +#[cfg(test)] +mod tests { + use std::collections::HashMap; + + use serde_json::json; + use software_core::model::{ + AdjId, MessageLevel, ProtectionPacket, Severity, ShortTimestamp, Value, + }; + + use super::*; + + /// Parses what `to_message` produces, so tests compare JSON values rather than text. + fn message(payload: &impl TopicPayload) -> Result { + serde_json::from_str(&payload.to_message()?) + } + + /// The documented example files are the wire contract: compare field by field. + fn assert_matches_example( + payload: &impl TopicPayload, + example: &str, + ) -> Result<(), serde_json::Error> { + let example: serde_json::Value = serde_json::from_str(example)?; + assert_eq!(message(payload)?, example); + Ok(()) + } + + const TIME: ShortTimestamp = ShortTimestamp { + hour: 12, + minute: 30, + second: 6, + subsecond: 0, + }; + + #[test] + fn connection_update_matches_its_example() -> Result<(), serde_json::Error> { + let update = ConnectionUpdate(HashMap::from([ + ( + "LCU".to_owned(), + Connection { + name: "LCU".into(), + is_connected: true, + }, + ), + ( + "HVBMS".to_owned(), + Connection { + name: "HVBMS".into(), + is_connected: false, + }, + ), + ])); + assert_matches_example(&update, include_str!("payload/example/connection.json")) + } + + #[test] + fn data_update_matches_its_example() -> Result<(), serde_json::Error> { + let packet = |id, hex_value: &str, count, alias: &str, value| { + ( + id, + DataPacketUpdate { + id: AdjId(id), + hex_value: hex_value.into(), + count, + cycle_time: 100_000_000, + measurement_updates: HashMap::from([(alias.to_owned(), value)]), + }, + ) + }; + let update = DataUpdate(HashMap::from([ + packet( + 936, + "a80300000e42", + 124, + "temperature_1", + MeasurementUpdate::Numeric { + last: 35.5, + average: 35.0, + }, + ), + packet( + 1201, + "b10401", + 58, + "contactor_closed", + MeasurementUpdate::Boolean(true), + ), + packet( + 1202, + "b20401", + 58, + "state", + MeasurementUpdate::Enum("Operational".into()), + ), + ])); + assert_matches_example(&update, include_str!("payload/example/data.json")) + } + + #[test] + fn logger_response_matches_its_example() -> Result<(), serde_json::Error> { + assert_matches_example( + &LoggerResponse(true), + include_str!("payload/example/logger_response.json"), + ) + } + + #[test] + fn message_update_matches_its_example() -> Result<(), serde_json::Error> { + let message = MessageUpdate { + kind: MessageLevel::Info, + payload: MessagePayload::Text("Order Sent".into()), + board: "LCU".into(), + name: "1001".into(), + timestamp: MessageTimestamp { + counter: 0, + second: 5, + minute: 30, + hour: 12, + day: 24, + month: 11, + year: 2026, + }, + }; + assert_matches_example(&message, include_str!("payload/example/message.json")) + } + + #[test] + fn protection_update_matches_its_example() -> Result<(), serde_json::Error> { + let protection = ProtectionUpdate { + id: AdjId(11192), + value: Value::Number(105.5), + timestamp: TIME, + }; + assert_matches_example(&protection, include_str!("payload/example/protection.json")) + } + + #[test] + fn initial_states_are_an_empty_object_or_false() -> Result<(), serde_json::Error> { + assert_eq!( + message(&ConnectionUpdate::default())?, + json!({"topic": "connection/update", "payload": {}}) + ); + assert_eq!( + message(&DataUpdate::default())?, + json!({"topic": "podData/update", "payload": {}}) + ); + assert_eq!( + message(&LoggerResponse::default())?, + json!({"topic": "logger/response", "payload": false}) + ); + Ok(()) + } + + #[test] + fn message_protection_details_have_their_own_kind_and_data() -> Result<(), serde_json::Error> { + let details = |payload| MessageUpdate { + kind: MessageLevel::Fault, + payload: MessagePayload::Protection(payload), + board: "HVBMS".into(), + name: "cell_temperature".into(), + timestamp: MessageTimestamp { + counter: 0, + second: 6, + minute: 30, + hour: 12, + day: 24, + month: 11, + year: 2026, + }, + }; + + let out_of_bounds = message(&details(ProtectionPayload::OutOfBounds { + bounds: [json!(10), json!(90)], + value: json!(95.5), + }))?; + // The outer kind is the severity; the inner kind is the condition. + assert_eq!(out_of_bounds["payload"]["kind"], "fault"); + assert_eq!( + out_of_bounds["payload"]["payload"], + json!({"kind": "OUT_OF_BOUNDS", "data": {"bounds": [10, 90], "value": 95.5}}) + ); + + let error_handler = message(&details(ProtectionPayload::ErrorHandler( + "stack overflow".into(), + )))?; + assert_eq!( + error_handler["payload"]["payload"], + json!({"kind": "ERROR_HANDLER", "data": "stack overflow"}) + ); + Ok(()) + } + + #[test] + fn protection_values_keep_their_json_type() -> Result<(), serde_json::Error> { + for (value, expected) in [ + (Value::Number(1.5), json!(1.5)), + (Value::Bool(true), json!(true)), + (Value::Enum("Fault".into()), json!("Fault")), + ] { + let protection = ProtectionUpdate { + id: AdjId(1), + value, + timestamp: TIME, + }; + assert_eq!(message(&protection)?["payload"]["value"], expected); + } + Ok(()) + } + + #[test] + fn protection_update_keeps_the_packet_fields() { + let packet = ProtectionPacket { + id: AdjId(11192), + timestamp: TIME, + value: Value::Bool(false), + }; + let update = ProtectionUpdate::from(packet.clone()); + assert_eq!(update.id, packet.id); + assert_eq!(update.timestamp, packet.timestamp); + assert_eq!(update.value, packet.value); + } + + #[test] + fn message_kind_is_the_adj_name_of_the_level() -> Result<(), serde_json::Error> { + for (level, name) in [ + (MessageLevel::Fault, "fault"), + (MessageLevel::Warning, "warning"), + (MessageLevel::Info, "info"), + (MessageLevel::Panic, "panic"), + ] { + let update = MessageUpdate { + kind: level, + payload: MessagePayload::Text("text".into()), + board: "LCU".into(), + name: "name".into(), + timestamp: MessageTimestamp { + counter: 0, + second: 0, + minute: 0, + hour: 0, + day: 1, + month: 1, + year: 2026, + }, + }; + assert_eq!(message(&update)?["payload"]["kind"], name); + } + Ok(()) + } + + #[test] + fn protections_are_shown_with_the_level_of_their_severity() { + assert_eq!(protection_level(Severity::Fault), MessageLevel::Fault); + assert_eq!(protection_level(Severity::Warning), MessageLevel::Warning); + } +} diff --git a/backend/crates/station/src/payload/README.md b/backend/crates/station/src/payload/README.md index a37cfff00..4183f73b5 100644 --- a/backend/crates/station/src/payload/README.md +++ b/backend/crates/station/src/payload/README.md @@ -15,13 +15,13 @@ such as `AdjId`, `Value` and `ProtectionPacket` come from `software_core::model` | File | Models and responsibility | | --- | --- | -| [`../payload.rs`](../payload.rs) | Public re-exports and logger payload aliases. | +| [`../payload.rs`](../payload.rs) | Public re-exports, the `TopicPayload` trait and logger payloads. | | [`data.rs`](data.rs) | `DataUpdate`, `DataPacketUpdate` and measurement values. | | [`connection.rs`](connection.rs) | `ConnectionUpdate` and `Connection`. | | [`order.rs`](order.rs) | `OrderSend` and `OrderField`. | -| [`message.rs`](message.rs) | `MessageUpdate`, its severity, content and calendar timestamp. | +| [`message.rs`](message.rs) | `MessageUpdate`, its content and calendar timestamp, and `protection_level`. | | [`protection.rs`](protection.rs) | `ProtectionUpdate`, conversion from `ProtectionPacket` and legacy `ProtectionPayload`. | -| [`serialize.rs`](serialize.rs) | Internal Serde adapters for `AdjId` and `Value`. | +| [`serialize.rs`](serialize.rs) | Internal Serde adapters for `AdjId`, `Value` and `MessageLevel`. | ## Topics @@ -38,7 +38,8 @@ such as `AdjId`, `Value` and `ProtectionPacket` come from `software_core::model` Directions describe the topic's data flow. A subscription request is handled separately by the broker. Each example is an illustrative complete message, -independent of the bundled ADJ fixture and HTTP catalog examples. +independent of the bundled ADJ fixture and HTTP catalog examples. Tests check +that `to_message()` produces each backend → frontend example exactly. ## Usage @@ -46,16 +47,23 @@ The payload module is compiled as part of station, without a separate feature. With a decoded `packet: software_core::model::ProtectionPacket`: ```rust -use station::payload::{OrderSend, ProtectionUpdate}; +use station::payload::{OrderSend, ProtectionUpdate, TopicPayload}; let request: OrderSend = serde_json::from_str(r#"{"id":1002,"fields":{}}"#)?; let protection = ProtectionUpdate::from(packet); -let payload_json = serde_json::to_string(&protection)?; +// {"topic":"protection/update","payload":{...}} +let message = protection.to_message()?; ``` -Published structures implement `serde::Serialize`; `OrderSend` and `OrderField` -implement `serde::Deserialize`. The logger aliases use the primitive types' -Serde implementations. Within station itself, import these types through +Every backend → frontend payload (`DataUpdate`, `ConnectionUpdate`, +`MessageUpdate`, `ProtectionUpdate` and `LoggerResponse`) implements +`TopicPayload`. Its `TOPIC` constant is the topic name, and `to_message()` +serializes the complete `{topic, payload}` message in one pass: the text the +WebSocket sends. `ConnectionUpdate`, `DataUpdate` and `LoggerResponse` wrap a +map or a `bool` in their own type, so each type belongs to exactly one topic; +their JSON is the wrapped value. `OrderSend` and `OrderField` implement +`serde::Deserialize`; `LoggerEnable` and `LoggerVariables` are aliases of +`bool` and `Vec`. Within station itself, import these types through `crate::payload`. The implementation submodules are private; use the types re-exported by `payload`. @@ -166,7 +174,7 @@ Boolean and enum parameters use `"bool"` and `"enum"`, respectively. { "topic": "message/update", "payload": { - "kind": string, // "info", "warning", "fault", "ok" or "panic". + "kind": string, // "info", "warning", "fault" or "panic". "payload": string, // Alternatively, the detailed object shown below. "board": string, "name": string, @@ -183,6 +191,10 @@ Boolean and enum parameters use `"bool"` and `"enum"`, respectively. } ``` +The outer `kind` is a `software_core::model::MessageLevel`, written with its +ADJ name (`MessageLevel::name`). A protection shown as a message takes the level +of its severity, given by `protection_level`. + `MessagePayload::Text` is a JSON string. `MessagePayload::Protection` is an object with its own `kind` and `data`. The outer `kind` always describes severity; the inner `kind` describes the condition: diff --git a/backend/crates/station/src/payload/connection.rs b/backend/crates/station/src/payload/connection.rs index 93ca602c2..fd7c3d711 100644 --- a/backend/crates/station/src/payload/connection.rs +++ b/backend/crates/station/src/payload/connection.rs @@ -1,9 +1,22 @@ +use super::TopicPayload; use serde::Serialize; use std::collections::HashMap; /// Payload of `connection/update`, keyed by board name. /// Boards remain in the snapshot with `isConnected: false` after a disconnect. -pub type ConnectionUpdate = HashMap; +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)] +#[serde(transparent)] +pub struct ConnectionUpdate(pub HashMap); + +impl From> for ConnectionUpdate { + fn from(boards: HashMap) -> Self { + Self(boards) + } +} + +impl TopicPayload for ConnectionUpdate { + const TOPIC: &'static str = "connection/update"; +} /// Whether a board is connected to the backend. #[derive(Debug, Clone, PartialEq, Eq, Serialize)] diff --git a/backend/crates/station/src/payload/data.rs b/backend/crates/station/src/payload/data.rs index c410a1469..832aeefeb 100644 --- a/backend/crates/station/src/payload/data.rs +++ b/backend/crates/station/src/payload/data.rs @@ -1,10 +1,22 @@ -use super::serialize::serialize_adj_id; +use super::{TopicPayload, serialize::serialize_adj_id}; use serde::Serialize; use software_core::model::AdjId; use std::collections::HashMap; /// Latest telemetry per packet for `podData/update`. Packet IDs are JSON object keys. -pub type DataUpdate = HashMap; +#[derive(Debug, Clone, Default, PartialEq, Serialize)] +#[serde(transparent)] +pub struct DataUpdate(pub HashMap); + +impl From> for DataUpdate { + fn from(packets: HashMap) -> Self { + Self(packets) + } +} + +impl TopicPayload for DataUpdate { + const TOPIC: &'static str = "podData/update"; +} /// Current telemetry and statistics for one packet. #[derive(Debug, Clone, PartialEq, Serialize)] diff --git a/backend/crates/station/src/payload/message.rs b/backend/crates/station/src/payload/message.rs index 8cb6496c8..a1dde0d05 100644 --- a/backend/crates/station/src/payload/message.rs +++ b/backend/crates/station/src/payload/message.rs @@ -1,12 +1,14 @@ -use super::ProtectionPayload; +use super::{ProtectionPayload, TopicPayload, serialize::serialize_message_level}; use serde::Serialize; use software_core::model::{MessageLevel, Severity}; /// Payload of `message/update`, preserving the legacy event envelope. #[derive(Debug, Clone, PartialEq, Serialize)] pub struct MessageUpdate { - /// Event severity, represented by the legacy JSON field `kind`. - pub kind: MessageKind, + /// Event severity, in the legacy JSON field `kind`, written with the ADJ's + /// name for the level: `"fault"`, `"warning"`, `"info"` or `"panic"`. + #[serde(serialize_with = "serialize_message_level")] + pub kind: MessageLevel, /// Text or protection details. pub payload: MessagePayload, /// Name of the board that produced the event. @@ -17,6 +19,10 @@ pub struct MessageUpdate { pub timestamp: MessageTimestamp, } +impl TopicPayload for MessageUpdate { + const TOPIC: &'static str = "message/update"; +} + /// Both message shapes accepted by the existing frontend. #[derive(Debug, Clone, PartialEq, Serialize)] #[serde(untagged)] @@ -27,39 +33,11 @@ pub enum MessagePayload { Protection(ProtectionPayload), } -/// Event severity: legacy values plus ADJv3's `panic` message level. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] -#[serde(rename_all = "lowercase")] -pub enum MessageKind { - /// Informational message. - Info, - /// Unexpected condition. - Warning, - /// Fault condition. - Fault, - /// A legacy protection returned to its appropriate range. - Ok, - /// Unrecoverable firmware error. - Panic, -} - -impl From for MessageKind { - fn from(level: MessageLevel) -> Self { - match level { - MessageLevel::Fault => Self::Fault, - MessageLevel::Warning => Self::Warning, - MessageLevel::Info => Self::Info, - MessageLevel::Panic => Self::Panic, - } - } -} - -impl From for MessageKind { - fn from(severity: Severity) -> Self { - match severity { - Severity::Fault => Self::Fault, - Severity::Warning => Self::Warning, - } +/// The message level that shows a triggered protection of this severity. +pub fn protection_level(severity: Severity) -> MessageLevel { + match severity { + Severity::Fault => MessageLevel::Fault, + Severity::Warning => MessageLevel::Warning, } } diff --git a/backend/crates/station/src/payload/protection.rs b/backend/crates/station/src/payload/protection.rs index d6eb1bd47..0146ac8b4 100644 --- a/backend/crates/station/src/payload/protection.rs +++ b/backend/crates/station/src/payload/protection.rs @@ -1,4 +1,7 @@ -use super::serialize::{serialize_adj_id, serialize_value}; +use super::{ + TopicPayload, + serialize::{serialize_adj_id, serialize_value}, +}; use serde::Serialize; use serde_json::Value as JsonValue; @@ -18,6 +21,10 @@ pub struct ProtectionUpdate { pub timestamp: ShortTimestamp, } +impl TopicPayload for ProtectionUpdate { + const TOPIC: &'static str = "protection/update"; +} + impl From for ProtectionUpdate { fn from(packet: ProtectionPacket) -> Self { Self { diff --git a/backend/crates/station/src/payload/serialize.rs b/backend/crates/station/src/payload/serialize.rs index 395f31bc4..bc828f525 100644 --- a/backend/crates/station/src/payload/serialize.rs +++ b/backend/crates/station/src/payload/serialize.rs @@ -1,5 +1,5 @@ use serde::{Deserialize, Deserializer, Serializer}; -use software_core::model::{AdjId, Value}; +use software_core::model::{AdjId, MessageLevel, Value}; /// Emits a scalar JSON value for a protection event. Enums use the variant name. pub(super) fn serialize_value( @@ -20,6 +20,14 @@ pub(super) fn deserialize_adj_id<'de, D: Deserializer<'de>>( u16::deserialize(deserializer).map(AdjId) } +/// Writes a message level with its ADJ name, such as `"fault"`. +pub(super) fn serialize_message_level( + level: &MessageLevel, + serializer: S, +) -> Result { + serializer.serialize_str(level.name()) +} + /// Writes an ADJ ID as a JSON integer. pub(super) fn serialize_adj_id( id: &AdjId, diff --git a/backend/crates/station/src/websocket.rs b/backend/crates/station/src/websocket.rs index 60f5cad98..2b75a3beb 100644 --- a/backend/crates/station/src/websocket.rs +++ b/backend/crates/station/src/websocket.rs @@ -5,7 +5,10 @@ use std::time::Duration; -use super::payload::{LoggerEnable, LoggerVariables}; +use super::payload::{ + ConnectionUpdate, DataUpdate, LoggerEnable, LoggerResponse, LoggerVariables, MessageUpdate, + ProtectionUpdate, TopicPayload, +}; use axum::extract::ws::WebSocket; use serde::{Deserialize, Serialize}; use tokio::{ @@ -28,13 +31,9 @@ mod sender; /// `run` returns `FrontendDisconnected`. pub const DEFAULT_HEARTBEAT_TIMEOUT: Duration = Duration::from_millis(100); -const CONNECTION_UPDATE: &str = "connection/update"; +// Outgoing topic names live with their payloads, in `TopicPayload::TOPIC`. const LOGGER_ENABLE: &str = "logger/enable"; -const LOGGER_RESPONSE: &str = "logger/response"; const LOGGER_VARIABLES: &str = "logger/variables"; -const DATA_UPDATE: &str = "podData/update"; -const MESSAGE_UPDATE: &str = "message/update"; -const PROTECTION_UPDATE: &str = "protection/update"; const ORDER_SEND: &str = "order/send"; const HEARTBEAT: &str = "connection/heartbeat"; @@ -67,27 +66,18 @@ enum Topic { impl Topic { fn from_name(name: &str) -> Option { match name { - CONNECTION_UPDATE => Some(Self::Connections), - LOGGER_RESPONSE => Some(Self::Logger), - DATA_UPDATE => Some(Self::Data), - MESSAGE_UPDATE => Some(Self::Messages), - PROTECTION_UPDATE => Some(Self::Protections), + ConnectionUpdate::TOPIC => Some(Self::Connections), + LoggerResponse::TOPIC => Some(Self::Logger), + DataUpdate::TOPIC => Some(Self::Data), + MessageUpdate::TOPIC => Some(Self::Messages), + ProtectionUpdate::TOPIC => Some(Self::Protections), _ => None, } } - - fn name(self) -> &'static str { - match self { - Self::Connections => CONNECTION_UPDATE, - Self::Logger => LOGGER_RESPONSE, - Self::Data => DATA_UPDATE, - Self::Messages => MESSAGE_UPDATE, - Self::Protections => PROTECTION_UPDATE, - } - } } -/// JSON envelope shared with the frontend. +/// JSON envelope shared with the frontend. The reader decodes incoming +/// messages with it; outgoing payloads build theirs with `TopicPayload::to_message`. #[derive(Debug, Serialize, Deserialize)] pub struct WsMessage { /// Wire name used to route the message, such as `connection/update`. @@ -209,6 +199,34 @@ impl FrontendSessions { mod tests { use super::*; + #[test] + fn subscriptions_route_by_the_payload_topic_names() { + assert_eq!( + Topic::from_name(ConnectionUpdate::TOPIC), + Some(Topic::Connections) + ); + assert_eq!(Topic::from_name(LoggerResponse::TOPIC), Some(Topic::Logger)); + assert_eq!(Topic::from_name(DataUpdate::TOPIC), Some(Topic::Data)); + assert_eq!( + Topic::from_name(MessageUpdate::TOPIC), + Some(Topic::Messages) + ); + assert_eq!( + Topic::from_name(ProtectionUpdate::TOPIC), + Some(Topic::Protections) + ); + // Commands, heartbeats and removed topics are not subscriptions. + for name in [ + ORDER_SEND, + LOGGER_ENABLE, + LOGGER_VARIABLES, + HEARTBEAT, + "order/stateOrders", + ] { + assert_eq!(Topic::from_name(name), None, "{name}"); + } + } + #[test] fn reconnect_cancels_the_deadline_after_the_last_session_ends() { let mut sessions = FrontendSessions::default(); diff --git a/backend/crates/station/src/websocket/README.md b/backend/crates/station/src/websocket/README.md index 0d8417674..39be8ad95 100644 --- a/backend/crates/station/src/websocket/README.md +++ b/backend/crates/station/src/websocket/README.md @@ -4,8 +4,9 @@ its state and event topics, and the clonable `Subscriber` that subscribes to them, using the types from `crate::payload`, exposed publicly as `station::payload`. See the [payload models README](../payload/README.md) for all topic payloads, -JSON templates, and complete message examples. Their serialization helpers -live in [`../payload/serialize.rs`](../payload/serialize.rs). +JSON templates, and complete message examples. Every payload sent to the +frontend implements `TopicPayload`, whose `to_message()` builds the JSON +message the sender writes. | Topic | Publish through `BrokerClient` | Subscribe through `Subscriber` | Initial state | | --- | --- | --- | --- | @@ -109,7 +110,8 @@ The frontend kit sends a heartbeat as soon as the socket opens and then every 25 ms, several within each 100 ms period. Unknown topics are logged and ignored while their handlers are implemented. -`sender.rs` releases each watch borrow before awaiting socket I/O. +`sender.rs` turns each update into a text frame with `TopicPayload::to_message()` +and releases each watch borrow before awaiting socket I/O. `order/send` checks parameter aliases, types and wire ranges against the ADJ. It arranges values in ADJ order and queues the resulting `OrderPacket` for diff --git a/backend/crates/station/src/websocket/broker.rs b/backend/crates/station/src/websocket/broker.rs index 1bd8dc01a..babf0c104 100644 --- a/backend/crates/station/src/websocket/broker.rs +++ b/backend/crates/station/src/websocket/broker.rs @@ -58,9 +58,9 @@ impl Broker { /// Starts with empty state maps and a stopped logger. pub fn new() -> (Self, BrokerClient) { let (updates, receiver) = mpsc::channel(32); - let (connections, state) = watch::channel(ConnectionUpdate::new()); - let (logger, recording) = watch::channel(false); - let (data, telemetry) = watch::channel(DataUpdate::new()); + let (connections, state) = watch::channel(ConnectionUpdate::default()); + let (logger, recording) = watch::channel(LoggerResponse::default()); + let (data, telemetry) = watch::channel(DataUpdate::default()); let (messages, _) = broadcast::channel(EVENT_CAPACITY); let (protections, _) = broadcast::channel(EVENT_CAPACITY); let message_topic = messages.downgrade(); @@ -214,8 +214,8 @@ mod tests { let publisher = client.clone(); let mut first = client.subscriber().subscribe_connections(); let mut second = client.subscriber().subscribe_connections(); - assert!(first.borrow_and_update().is_empty()); - assert!(second.borrow_and_update().is_empty()); + assert!(first.borrow_and_update().0.is_empty()); + assert!(second.borrow_and_update().0.is_empty()); let worker = tokio::spawn(broker.run()); let snapshots = [ @@ -248,17 +248,57 @@ mod tests { let (broker, client) = Broker::new(); drop(broker); assert!(matches!( - client.publish_connections(ConnectionUpdate::new()).await, + client + .publish_connections(ConnectionUpdate::default()) + .await, Err(Error::BrokerClosed) )); assert!(matches!( - client.publish_logger(true).await, + client.publish_logger(LoggerResponse(true)).await, Err(Error::BrokerClosed) )); assert!(matches!( - client.publish_data(DataUpdate::new()).await, + client.publish_data(DataUpdate::default()).await, Err(Error::BrokerClosed) )); + assert!(matches!( + client.publish_protection(protection(1)).await, + Err(Error::BrokerClosed) + )); + } + + #[tokio::test] + async fn events_reach_current_subscribers_in_order() -> Result<(), Box> { + let (broker, client) = Broker::new(); + let mut early = client.subscriber().subscribe_protections()?; + let worker = tokio::spawn(broker.run()); + + client.publish_protection(protection(1)).await?; + client.publish_protection(protection(2)).await?; + assert_eq!( + timeout(Duration::from_secs(1), early.recv()).await??, + protection(1) + ); + assert_eq!( + timeout(Duration::from_secs(1), early.recv()).await??, + protection(2) + ); + + // A late subscriber starts with the next event, not the earlier ones. + let mut late = client.subscriber().subscribe_protections()?; + client.publish_protection(protection(3)).await?; + assert_eq!( + timeout(Duration::from_secs(1), late.recv()).await??, + protection(3) + ); + assert_eq!( + timeout(Duration::from_secs(1), early.recv()).await??, + protection(3) + ); + + drop(client); + timeout(Duration::from_secs(1), worker).await??; + Ok(()) } #[tokio::test(start_paused = true)] @@ -266,7 +306,7 @@ mod tests { -> Result<(), Box> { let (broker, client) = Broker::new(); let mut data = client.subscriber().subscribe_data(); - assert!(data.borrow_and_update().is_empty()); + assert!(data.borrow_and_update().0.is_empty()); let worker = tokio::spawn(broker.run()); let start = Instant::now(); @@ -299,14 +339,14 @@ mod tests { -> Result<(), Box> { let (broker, client) = Broker::new(); let mut logger = client.subscriber().subscribe_logger(); - assert!(!*logger.borrow_and_update()); + assert!(!logger.borrow_and_update().0); let worker = tokio::spawn(broker.run()); - client.publish_logger(true).await?; + client.publish_logger(LoggerResponse(true)).await?; timeout(Duration::from_secs(1), logger.changed()).await??; - assert!(*logger.borrow_and_update()); + assert!(logger.borrow_and_update().0); let late = client.subscriber().subscribe_logger(); - assert!(*late.borrow()); + assert!(late.borrow().0); assert!(!late.has_changed()?); drop(client); @@ -323,15 +363,15 @@ mod tests { .publish_connections(connections(&[("LCU", true)])) .await?; let logger = client.subscriber().subscribe_logger(); - client.publish_logger(true).await?; + client.publish_logger(LoggerResponse(true)).await?; let data = client.subscriber().subscribe_data(); client.publish_data(telemetry(&[packet(1000, 1)])).await?; drop(client); timeout(Duration::from_secs(1), broker.run()).await?; - assert!(state.borrow()["LCU"].is_connected); - assert!(*logger.borrow()); - assert_eq!(data.borrow()[&1000].count, 1); + assert!(state.borrow().0["LCU"].is_connected); + assert!(logger.borrow().0); + assert_eq!(data.borrow().0[&1000].count, 1); Ok(()) } @@ -361,25 +401,42 @@ mod tests { } fn connections(boards: &[(&str, bool)]) -> ConnectionUpdate { - boards - .iter() - .map(|&(name, is_connected)| { - ( - name.to_owned(), - Connection { - name: name.to_owned(), - is_connected, - }, - ) - }) - .collect() + ConnectionUpdate( + boards + .iter() + .map(|&(name, is_connected)| { + ( + name.to_owned(), + Connection { + name: name.to_owned(), + is_connected, + }, + ) + }) + .collect(), + ) } fn telemetry(packets: &[DataPacketUpdate]) -> DataUpdate { - packets - .iter() - .map(|packet| (packet.id.0, packet.clone())) - .collect() + DataUpdate( + packets + .iter() + .map(|packet| (packet.id.0, packet.clone())) + .collect(), + ) + } + + fn protection(id: u16) -> ProtectionUpdate { + ProtectionUpdate { + id: software_core::model::AdjId(id), + value: software_core::model::Value::Number(1.0), + timestamp: software_core::model::ShortTimestamp { + hour: 12, + minute: 30, + second: 6, + subsecond: 0, + }, + } } fn packet(id: u16, count: u64) -> DataPacketUpdate { diff --git a/backend/crates/station/src/websocket/sender.rs b/backend/crates/station/src/websocket/sender.rs index 895f70a0b..d27043b4d 100644 --- a/backend/crates/station/src/websocket/sender.rs +++ b/backend/crates/station/src/websocket/sender.rs @@ -2,10 +2,10 @@ use std::future::pending; use axum::extract::ws::{Message as Frame, WebSocket}; use futures_util::{SinkExt, stream::SplitSink}; -use serde::Serialize; use tokio::sync::{broadcast, mpsc, watch}; -use super::{Topic, WsMessage, error::Error, receiver::SubscriptionChange}; +use super::{error::Error, receiver::SubscriptionChange}; +use crate::payload::TopicPayload; /// Sends subscribed state snapshots and events over the socket. pub(super) async fn run( @@ -21,40 +21,35 @@ pub(super) async fn run( change = subscriptions.recv() => { let Some(change) = change else { return Ok(()); }; let snapshot = match change { - SubscriptionChange::Connections(next) => subscribe_state(Topic::Connections, &mut connections, next)?, - SubscriptionChange::Logger(next) => subscribe_state(Topic::Logger, &mut logger, next)?, - SubscriptionChange::Data(next) => subscribe_state(Topic::Data, &mut data, next)?, + SubscriptionChange::Connections(next) => subscribe_state(&mut connections, next)?, + SubscriptionChange::Logger(next) => subscribe_state(&mut logger, next)?, + SubscriptionChange::Data(next) => subscribe_state(&mut data, next)?, SubscriptionChange::Messages(next) => { messages = next; None } SubscriptionChange::Protections(next) => { protections = next; None } }; let Some(snapshot) = snapshot else { continue; }; snapshot } - next = next_event(Topic::Protections, &mut protections) => next?, - next = next_event(Topic::Messages, &mut messages) => next?, - next = next_state(Topic::Connections, &mut connections) => next?, - next = next_state(Topic::Logger, &mut logger) => next?, - next = next_state(Topic::Data, &mut data) => next?, + next = next_event(&mut protections) => next?, + next = next_event(&mut messages) => next?, + next = next_state(&mut connections) => next?, + next = next_state(&mut logger) => next?, + next = next_state(&mut data) => next?, }; write.send(frame).await?; } } /// Installs a subscription and builds its initial snapshot, or drops it on unsubscribe. -fn subscribe_state( - topic: Topic, +fn subscribe_state( state: &mut Option>, subscription: Option>, ) -> Result, Error> { *state = subscription; - state - .as_mut() - .map(|state| state_frame(topic, state)) - .transpose() + state.as_mut().map(state_frame).transpose() } -async fn next_state( - topic: Topic, +async fn next_state( state: &mut Option>, ) -> Result { let Some(state) = state else { @@ -62,16 +57,15 @@ async fn next_state( return pending().await; }; state.changed().await.map_err(|_| Error::BrokerClosed)?; - state_frame(topic, state) + state_frame(state) } -fn state_frame(topic: Topic, state: &mut watch::Receiver) -> Result { +fn state_frame(state: &mut watch::Receiver) -> Result { // Build an owned frame so the watch borrow ends before the socket write awaits. - encode(topic, &*state.borrow_and_update()) + encode(&*state.borrow_and_update()) } -async fn next_event( - topic: Topic, +async fn next_event( events: &mut Option>, ) -> Result { let Some(events) = events else { @@ -80,24 +74,76 @@ async fn next_event( let event = events.recv().await.map_err(|error| match error { broadcast::error::RecvError::Closed => Error::BrokerClosed, broadcast::error::RecvError::Lagged(missed) => Error::EventLagged { - topic: topic.name(), + topic: T::TOPIC, missed, }, })?; - encode(topic, &event) + encode(&event) } -fn encode(topic: Topic, payload: &impl Serialize) -> Result { - let message = WsMessage { - topic: topic.name().into(), - payload: serde_json::to_value(payload)?, - }; - Ok(Frame::Text(serde_json::to_string(&message)?.into())) +fn encode(payload: &impl TopicPayload) -> Result { + Ok(Frame::Text(payload.to_message()?.into())) } #[cfg(test)] mod tests { + use futures_util::FutureExt; + use serde::Serialize; + use serde_json::json; + use super::*; + use crate::payload::LoggerResponse; + use crate::websocket::WsMessage; + + fn decode(frame: &Frame) -> Result> { + Ok(serde_json::from_str(frame.to_text()?)?) + } + + #[tokio::test] + async fn state_subscription_sends_the_current_snapshot_then_only_the_latest() + -> Result<(), Box> { + let (publisher, receiver) = watch::channel(LoggerResponse(false)); + let mut state = None; + + let initial = subscribe_state(&mut state, Some(receiver))?.ok_or("no initial snapshot")?; + let initial = decode(&initial)?; + assert_eq!(initial.topic, LoggerResponse::TOPIC); + assert_eq!(initial.payload, json!(false)); + + // Two updates before the writer reads: only the latest is sent. + publisher.send_replace(LoggerResponse(true)); + publisher.send_replace(LoggerResponse(false)); + assert_eq!( + decode(&next_state(&mut state).await?)?.payload, + json!(false) + ); + assert!(next_state(&mut state).now_or_never().is_none()); + + // After unsubscribing, updates are no longer sent. + assert!(subscribe_state(&mut state, None)?.is_none()); + publisher.send_replace(LoggerResponse(true)); + assert!(next_state(&mut state).now_or_never().is_none()); + Ok(()) + } + + #[tokio::test] + async fn a_closed_state_topic_ends_the_writer() { + let (publisher, receiver) = watch::channel(LoggerResponse(false)); + let mut state = Some(receiver); + drop(publisher); + assert!(matches!( + next_state(&mut state).await, + Err(Error::BrokerClosed) + )); + } + + /// An event payload with a topic of its own, so the test stays independent of real topics. + #[derive(Debug, Clone, Serialize)] + struct Count(u32); + + impl TopicPayload for Count { + const TOPIC: &'static str = "test/count"; + } #[tokio::test] async fn lagged_event_receiver_reports_its_loss_without_affecting_another_subscriber() @@ -107,22 +153,23 @@ mod tests { let mut current = Some(events.subscribe()); for count in 1..=3 { - events.send(count)?; - let frame = next_event(Topic::Messages, &mut current).await?; + events.send(Count(count))?; + let frame = next_event(&mut current).await?; let message: WsMessage = serde_json::from_str(frame.to_text()?)?; + assert_eq!(message.topic, Count::TOPIC); assert_eq!(message.payload, count); } assert!(matches!( - next_event(Topic::Messages, &mut stalled).await, + next_event(&mut stalled).await, Err(Error::EventLagged { - topic: "message/update", + topic: Count::TOPIC, missed: 1 }) )); drop(stalled); - events.send(4)?; - let frame = next_event(Topic::Messages, &mut current).await?; + events.send(Count(4))?; + let frame = next_event(&mut current).await?; let message: WsMessage = serde_json::from_str(frame.to_text()?)?; assert_eq!(message.payload, 4); Ok(()) From 55e4699373bed582d3dc8af50e0f8f5ef77c150b Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Fri, 4 Dec 2026 01:24:07 +0100 Subject: [PATCH 193/225] feat(frontend,ws): change mesurement old id (alias) for id --- .../competition-view/scripts/mock-backend.mjs | 1 - frontend/frontend-kit/kit/src/core/types.ts | 1 - frontend/logging-view/src/types/telemetry.ts | 1 - frontend/testing-view/src/mocks/telemetry.ts | 36 ------------------- .../src/types/data/telemetryCatalogItem.ts | 2 -- 5 files changed, 41 deletions(-) diff --git a/frontend/competition-view/scripts/mock-backend.mjs b/frontend/competition-view/scripts/mock-backend.mjs index 24027e0cf..e34180dad 100644 --- a/frontend/competition-view/scripts/mock-backend.mjs +++ b/frontend/competition-view/scripts/mock-backend.mjs @@ -298,7 +298,6 @@ server.on("upgrade", (req, socket) => { id: STATE_PACKET_ID, count: 0, cycleTime: 0, - hexValue: "", measurementUpdates: { state: VEHICLE_STATE }, }, }); diff --git a/frontend/frontend-kit/kit/src/core/types.ts b/frontend/frontend-kit/kit/src/core/types.ts index 342d7f7f4..0a5ec8eed 100644 --- a/frontend/frontend-kit/kit/src/core/types.ts +++ b/frontend/frontend-kit/kit/src/core/types.ts @@ -30,7 +30,6 @@ export type Variables = Record; export interface TelemetryPacket { count: number; cycleTime: number; - hexValue: string; id: number; measurementUpdates: Variables; } diff --git a/frontend/logging-view/src/types/telemetry.ts b/frontend/logging-view/src/types/telemetry.ts index 9cbf175d0..696149d9e 100644 --- a/frontend/logging-view/src/types/telemetry.ts +++ b/frontend/logging-view/src/types/telemetry.ts @@ -13,7 +13,6 @@ export interface TelemetryData { id: number; count: number; cycleTime: number; - hexValue: string; measurementUpdates: Variables; } diff --git a/frontend/testing-view/src/mocks/telemetry.ts b/frontend/testing-view/src/mocks/telemetry.ts index 7e97277ac..c2a7c184a 100644 --- a/frontend/testing-view/src/mocks/telemetry.ts +++ b/frontend/testing-view/src/mocks/telemetry.ts @@ -9,7 +9,6 @@ export const MOCK_TELEMETRY_CATALOG: Record = name: "Motor Driver", label: "Motor driver", type: "data", - hexValue: "000000", count: 0, cycleTime: 0, measurements: [ @@ -60,7 +59,6 @@ export const MOCK_TELEMETRY_CATALOG: Record = name: "State", label: "State", type: "data", - hexValue: "000000", count: 0, cycleTime: 0, measurements: [ @@ -101,7 +99,6 @@ export const MOCK_TELEMETRY_CATALOG: Record = name: "Space Vector", label: "Space vector", type: "data", - hexValue: "000000", count: 0, cycleTime: 0, measurements: [ @@ -136,7 +133,6 @@ export const MOCK_TELEMETRY_CATALOG: Record = name: "DC Link", label: "Dc link", type: "data", - hexValue: "000000", count: 0, cycleTime: 0, measurements: [ @@ -171,7 +167,6 @@ export const MOCK_TELEMETRY_CATALOG: Record = name: "Motor Currents", label: "Motor currents", type: "data", - hexValue: "000000", count: 0, cycleTime: 0, measurements: [ @@ -233,7 +228,6 @@ export const MOCK_TELEMETRY_CATALOG: Record = name: "pwm_packet", label: "Pwm Packet", type: "data", - hexValue: "000000", count: 0, cycleTime: 0, measurements: [ @@ -284,7 +278,6 @@ export const MOCK_TELEMETRY_CATALOG: Record = name: "Batteries_Voltage", label: "Batteries Voltage", type: "data", - hexValue: "000000", count: 0, cycleTime: 0, measurements: [ @@ -311,7 +304,6 @@ export const MOCK_TELEMETRY_CATALOG: Record = name: "Current_sensors", label: "Current Sensors", type: "data", - hexValue: "000000", count: 0, cycleTime: 0, measurements: [ @@ -370,7 +362,6 @@ export const MOCK_TELEMETRY_CATALOG: Record = name: "StateMachine_states", label: "Statemachine States", type: "data", - hexValue: "000000", count: 0, cycleTime: 0, measurements: [ @@ -417,7 +408,6 @@ export const MOCK_TELEMETRY_CATALOG: Record = name: "Encoder_data", label: "Encoder Data", type: "data", - hexValue: "000000", count: 0, cycleTime: 0, measurements: [ @@ -469,7 +459,6 @@ export const MOCK_TELEMETRY_CATALOG: Record = name: "lcu_coil_current", label: "Coil Current", type: "data", - hexValue: "000000", count: 0, cycleTime: 0, measurements: [ @@ -528,7 +517,6 @@ export const MOCK_TELEMETRY_CATALOG: Record = name: "lcu_airgap", label: "Airgap", type: "data", - hexValue: "000000", count: 0, cycleTime: 0, measurements: [ @@ -595,7 +583,6 @@ export const MOCK_TELEMETRY_CATALOG: Record = name: "OperationalState", label: "Operational state", type: "data", - hexValue: "000000", count: 0, cycleTime: 0, measurements: [ @@ -624,7 +611,6 @@ export const MOCK_TELEMETRY_CATALOG: Record = name: "lcu_voltage", label: "LCU Voltage", type: "data", - hexValue: "000000", count: 0, cycleTime: 0, measurements: [ @@ -667,7 +653,6 @@ export const MOCK_TELEMETRY_CATALOG: Record = name: "lcu_control_references", label: "LCU Control References", type: "data", - hexValue: "000000", count: 0, cycleTime: 0, measurements: [ @@ -721,7 +706,6 @@ export const MOCK_TELEMETRY_CATALOG: Record = name: "FAULT", label: "Fault", type: "data", - hexValue: "000000", count: 0, cycleTime: 0, measurements: [], @@ -731,7 +715,6 @@ export const MOCK_TELEMETRY_CATALOG: Record = name: "battery_1", label: "Battery 1", type: "data", - hexValue: "000000", count: 0, cycleTime: 0, measurements: [ @@ -790,7 +773,6 @@ export const MOCK_TELEMETRY_CATALOG: Record = name: "battery_2", label: "Battery 2", type: "data", - hexValue: "000000", count: 0, cycleTime: 0, measurements: [ @@ -833,7 +815,6 @@ export const MOCK_TELEMETRY_CATALOG: Record = name: "general_state_machine", label: "General State Machine", type: "data", - hexValue: "000000", count: 0, cycleTime: 0, measurements: [ @@ -850,7 +831,6 @@ export const MOCK_TELEMETRY_CATALOG: Record = name: "imd", label: "IMD", type: "data", - hexValue: "000000", count: 0, cycleTime: 0, measurements: [ @@ -887,7 +867,6 @@ export const MOCK_TELEMETRY_CATALOG: Record = name: "sdc", label: "SDC", type: "data", - hexValue: "000000", count: 0, cycleTime: 0, measurements: [ @@ -907,7 +886,6 @@ export const MOCK_TELEMETRY_CATALOG: Record = name: "Battery Data", label: "Battery data", type: "data", - hexValue: "000000", count: 0, cycleTime: 0, measurements: [ @@ -990,7 +968,6 @@ export const MOCK_TELEMETRY_CATALOG: Record = name: "Current State", label: "Current state", type: "data", - hexValue: "000000", count: 0, cycleTime: 0, measurements: [ @@ -1007,7 +984,6 @@ export const MOCK_TELEMETRY_CATALOG: Record = name: "DCLV Data", label: "Dclv data", type: "data", - hexValue: "000000", count: 0, cycleTime: 0, measurements: [ @@ -1070,7 +1046,6 @@ export const MOCK_TELEMETRY_CATALOG: Record = name: "Temperature Data", label: "Temperature data", type: "data", - hexValue: "000000", count: 0, cycleTime: 0, measurements: [ @@ -1129,7 +1104,6 @@ export const MOCK_TELEMETRY_CATALOG: Record = name: "Cell Voltages", label: "Cell voltages", type: "data", - hexValue: "000000", count: 0, cycleTime: 0, measurements: [ @@ -1191,7 +1165,6 @@ export const MOCK_TELEMETRY_CATALOG: Record = name: "Current State", label: "Current state", type: "data", - hexValue: "000000", count: 0, cycleTime: 0, measurements: [ @@ -1220,7 +1193,6 @@ export const MOCK_TELEMETRY_CATALOG: Record = name: "Reeds", label: "Reeds", type: "data", - hexValue: "000000", count: 0, cycleTime: 0, measurements: [ @@ -1260,7 +1232,6 @@ export const MOCK_TELEMETRY_CATALOG: Record = name: "Flow", label: "Flow", type: "data", - hexValue: "000000", count: 0, cycleTime: 0, measurements: [ @@ -1283,7 +1254,6 @@ export const MOCK_TELEMETRY_CATALOG: Record = name: "Regulator", label: "Regulator", type: "data", - hexValue: "000000", count: 0, cycleTime: 0, measurements: [ @@ -1310,7 +1280,6 @@ export const MOCK_TELEMETRY_CATALOG: Record = name: "Pressure", label: "Pressure", type: "data", - hexValue: "000000", count: 0, cycleTime: 0, measurements: [ @@ -1356,7 +1325,6 @@ export const MOCK_TELEMETRY_CATALOG: Record = name: "Supercaps Voltage Overview", label: "Supercaps voltage overview", type: "data", - hexValue: "000000", count: 0, cycleTime: 0, measurements: [ @@ -1375,7 +1343,6 @@ export const MOCK_TELEMETRY_CATALOG: Record = name: "Module 1 Overview", label: "Module 1 overview", type: "data", - hexValue: "000000", count: 0, cycleTime: 0, measurements: [ @@ -1434,7 +1401,6 @@ export const MOCK_TELEMETRY_CATALOG: Record = name: "Module 2 Overview", label: "Module 2 overview", type: "data", - hexValue: "000000", count: 0, cycleTime: 0, measurements: [ @@ -1493,7 +1459,6 @@ export const MOCK_TELEMETRY_CATALOG: Record = name: "SDC State", label: "Sdc state", type: "data", - hexValue: "000000", count: 0, cycleTime: 0, measurements: [ @@ -1510,7 +1475,6 @@ export const MOCK_TELEMETRY_CATALOG: Record = name: "Contactors State", label: "Contactors state", type: "data", - hexValue: "000000", count: 0, cycleTime: 0, measurements: [ diff --git a/frontend/testing-view/src/types/data/telemetryCatalogItem.ts b/frontend/testing-view/src/types/data/telemetryCatalogItem.ts index 25e98ec11..3d8532a11 100644 --- a/frontend/testing-view/src/types/data/telemetryCatalogItem.ts +++ b/frontend/testing-view/src/types/data/telemetryCatalogItem.ts @@ -34,8 +34,6 @@ export type RawPacket = Item & { cycleTime: number; type: string; measurements: TelemetryVariable[]; - /** Currently unused (always equals to "000000" placeholder on the backend) */ - hexValue: string; }; /** From cb09ecba766c4dd8e44e16520374bf978775bf59 Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Fri, 4 Dec 2026 01:25:15 +0100 Subject: [PATCH 194/225] fix(backend, ws): remove unused things --- backend/crates/core/src/hello.rs | 47 +++++++++++++++++++ backend/crates/station/src/payload.rs | 19 ++------ backend/crates/station/src/payload/README.md | 13 ++--- backend/crates/station/src/payload/data.rs | 6 +-- .../station/src/payload/example/data.json | 9 ++-- .../crates/station/src/websocket/broker.rs | 1 - 6 files changed, 64 insertions(+), 31 deletions(-) create mode 100644 backend/crates/core/src/hello.rs diff --git a/backend/crates/core/src/hello.rs b/backend/crates/core/src/hello.rs new file mode 100644 index 000000000..70d67c4bc --- /dev/null +++ b/backend/crates/core/src/hello.rs @@ -0,0 +1,47 @@ +//! Módulo de ejemplo, sin ninguna lógica real del backend. +//! +//! Muestra las cuatro cosas que todo módulo de `software-core` debe tener: +//! +//! 1. Documentación (`//!` para el módulo, `///` para cada función pública). +//! 2. Trazas con `tracing`, a nivel `debug` porque este código no decide +//! nada por sí mismo (ver `LOGGING.md`, en la raíz del workspace). +//! 3. Tests unitarios, en un `mod tests` al final del archivo. +//! 4. Un ejemplo en la documentación que se ejecuta como test (doc-test). + +use tracing::debug; + +/// Suma dos números enteros. +/// +/// # Ejemplos +/// +/// ``` +/// use software_core::hello::suma; +/// +/// assert_eq!(suma(2, 3), 5); +/// assert_eq!(suma(-2, 3), 1); +/// ``` +pub fn suma(a: i64, b: i64) -> i64 { + let resultado = a + b; + debug!(a, b, resultado, "suma calculada"); + resultado +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn suma_dos_positivos() { + assert_eq!(suma(2, 3), 5); + } + + #[test] + fn suma_con_negativos() { + assert_eq!(suma(-2, 3), 1); + } + + #[test] + fn suma_con_cero_es_identidad() { + assert_eq!(suma(42, 0), 42); + } +} diff --git a/backend/crates/station/src/payload.rs b/backend/crates/station/src/payload.rs index 7592f7c70..09d05d716 100644 --- a/backend/crates/station/src/payload.rs +++ b/backend/crates/station/src/payload.rs @@ -121,41 +121,32 @@ mod tests { #[test] fn data_update_matches_its_example() -> Result<(), serde_json::Error> { - let packet = |id, hex_value: &str, count, alias: &str, value| { + let packet = |id, count, measurement, value| { ( id, DataPacketUpdate { id: AdjId(id), - hex_value: hex_value.into(), count, cycle_time: 100_000_000, - measurement_updates: HashMap::from([(alias.to_owned(), value)]), + measurement_updates: HashMap::from([(measurement, value)]), }, ) }; let update = DataUpdate(HashMap::from([ packet( 936, - "a80300000e42", 124, - "temperature_1", + 3000, MeasurementUpdate::Numeric { last: 35.5, average: 35.0, }, ), - packet( - 1201, - "b10401", - 58, - "contactor_closed", - MeasurementUpdate::Boolean(true), - ), + packet(1201, 58, 3001, MeasurementUpdate::Boolean(true)), packet( 1202, - "b20401", 58, - "state", + 3002, MeasurementUpdate::Enum("Operational".into()), ), ])); diff --git a/backend/crates/station/src/payload/README.md b/backend/crates/station/src/payload/README.md index 4183f73b5..1f0e4dd82 100644 --- a/backend/crates/station/src/payload/README.md +++ b/backend/crates/station/src/payload/README.md @@ -94,26 +94,27 @@ it as a string. "payload": { "": { "id": number, - "hexValue": string, "count": number, "cycleTime": number, "measurementUpdates": { - "": { + "": { "last": number, "average": number }, - "": boolean, - "": string + "": boolean, + "": string } } } } ``` -The outer key matches the packet's `id`. `count` is the received packet count; +The outer key matches the packet's `id`. Each `measurementUpdates` key is a +measurement's numeric ADJ `id`, the same `id` the HTTP data catalog lists for +it, not its textual alias. `count` is the received packet count; `cycleTime` is the averaged interval between packet receptions, in the legacy timestamp's units. This module does not convert it. The publisher supplies -these statistics and the hexadecimal packet representation. +these statistics. `MeasurementUpdate` has three JSON forms: `{last, average}` for a number, a boolean, or an enum variant string. There is no additional discriminator diff --git a/backend/crates/station/src/payload/data.rs b/backend/crates/station/src/payload/data.rs index 832aeefeb..b08df9e9c 100644 --- a/backend/crates/station/src/payload/data.rs +++ b/backend/crates/station/src/payload/data.rs @@ -25,14 +25,12 @@ pub struct DataPacketUpdate { /// ADJ packet id, serialized as a number. #[serde(serialize_with = "serialize_adj_id")] pub id: AdjId, - /// Hexadecimal representation of the received packet. - pub hex_value: String, /// Number of packets received under this id. pub count: u64, /// Averaged interval between packets, in the legacy timestamp's units. pub cycle_time: u64, - /// Updates keyed by the measurement's textual alias. - pub measurement_updates: HashMap, + /// Updates keyed by the measurement's numeric ADJ id, a string key in JSON. + pub measurement_updates: HashMap, } /// Numeric measurements carry statistics. Booleans and enum names use JSON primitives. diff --git a/backend/crates/station/src/payload/example/data.json b/backend/crates/station/src/payload/example/data.json index 312fdc7ba..15b791146 100644 --- a/backend/crates/station/src/payload/example/data.json +++ b/backend/crates/station/src/payload/example/data.json @@ -3,11 +3,10 @@ "payload": { "936": { "id": 936, - "hexValue": "a80300000e42", "count": 124, "cycleTime": 100000000, "measurementUpdates": { - "temperature_1": { + "3000": { "last": 35.5, "average": 35.0 } @@ -15,20 +14,18 @@ }, "1201": { "id": 1201, - "hexValue": "b10401", "count": 58, "cycleTime": 100000000, "measurementUpdates": { - "contactor_closed": true + "3001": true } }, "1202": { "id": 1202, - "hexValue": "b20401", "count": 58, "cycleTime": 100000000, "measurementUpdates": { - "state": "Operational" + "3002": "Operational" } } } diff --git a/backend/crates/station/src/websocket/broker.rs b/backend/crates/station/src/websocket/broker.rs index babf0c104..609b3968d 100644 --- a/backend/crates/station/src/websocket/broker.rs +++ b/backend/crates/station/src/websocket/broker.rs @@ -442,7 +442,6 @@ mod tests { fn packet(id: u16, count: u64) -> DataPacketUpdate { DataPacketUpdate { id: software_core::model::AdjId(id), - hex_value: String::new(), count, cycle_time: 100_000_000, measurement_updates: Default::default(), From eaada86eef214525911de477afabe8db16cfb713 Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Fri, 4 Dec 2026 01:35:18 +0100 Subject: [PATCH 195/225] fix(backend, ws): remove counter --- backend/crates/station/src/http/server.rs | 14 ++++---- backend/crates/station/src/payload.rs | 27 ++++++++------ backend/crates/station/src/payload/README.md | 35 ++++++++++--------- .../station/src/payload/example/message.json | 1 - .../src/payload/example/protection.json | 8 +++-- backend/crates/station/src/payload/message.rs | 8 ++--- .../crates/station/src/payload/protection.rs | 28 ++++++--------- .../crates/station/src/websocket/broker.rs | 10 +++--- 8 files changed, 67 insertions(+), 64 deletions(-) diff --git a/backend/crates/station/src/http/server.rs b/backend/crates/station/src/http/server.rs index 8c441950b..78bdc26e5 100644 --- a/backend/crates/station/src/http/server.rs +++ b/backend/crates/station/src/http/server.rs @@ -57,7 +57,7 @@ mod tests { }; use software_core::{ adj::{Adj, load_from_dir}, - model::{AdjId, OrderPacket, ShortTimestamp, Value}, + model::{AdjId, OrderPacket, Value}, protocol::Index, }; use tokio::{ @@ -70,7 +70,7 @@ mod tests { use super::setup_router; use crate::{ - payload::ProtectionUpdate, + payload::{MessageTimestamp, ProtectionUpdate}, websocket::{self, Commands, OrderForwarder, broker::Broker}, }; @@ -320,11 +320,13 @@ mod tests { .publish_protection(ProtectionUpdate { id: AdjId(11192), value: Value::Number(105.5), - timestamp: ShortTimestamp { - hour: 12, - minute: 30, + timestamp: MessageTimestamp { second: 6, - subsecond: 0, + minute: 30, + hour: 12, + day: 24, + month: 11, + year: 2026, }, }) .await?; diff --git a/backend/crates/station/src/payload.rs b/backend/crates/station/src/payload.rs index 09d05d716..1c7197dce 100644 --- a/backend/crates/station/src/payload.rs +++ b/backend/crates/station/src/payload.rs @@ -91,11 +91,14 @@ mod tests { Ok(()) } - const TIME: ShortTimestamp = ShortTimestamp { - hour: 12, - minute: 30, + /// The calendar time of `example/protection.json`. + const TIME: MessageTimestamp = MessageTimestamp { second: 6, - subsecond: 0, + minute: 30, + hour: 12, + day: 24, + month: 11, + year: 2026, }; #[test] @@ -169,7 +172,6 @@ mod tests { board: "LCU".into(), name: "1001".into(), timestamp: MessageTimestamp { - counter: 0, second: 5, minute: 30, hour: 12, @@ -216,7 +218,6 @@ mod tests { board: "HVBMS".into(), name: "cell_temperature".into(), timestamp: MessageTimestamp { - counter: 0, second: 6, minute: 30, hour: 12, @@ -265,16 +266,21 @@ mod tests { } #[test] - fn protection_update_keeps_the_packet_fields() { + fn protection_update_takes_id_and_value_from_the_packet() { let packet = ProtectionPacket { id: AdjId(11192), - timestamp: TIME, + timestamp: ShortTimestamp { + hour: 12, + minute: 30, + second: 6, + subsecond: 0, + }, value: Value::Bool(false), }; - let update = ProtectionUpdate::from(packet.clone()); + let update = ProtectionUpdate::new(packet.clone(), TIME); assert_eq!(update.id, packet.id); - assert_eq!(update.timestamp, packet.timestamp); assert_eq!(update.value, packet.value); + assert_eq!(update.timestamp, TIME); } #[test] @@ -291,7 +297,6 @@ mod tests { board: "LCU".into(), name: "name".into(), timestamp: MessageTimestamp { - counter: 0, second: 0, minute: 0, hour: 0, diff --git a/backend/crates/station/src/payload/README.md b/backend/crates/station/src/payload/README.md index 1f0e4dd82..141382efb 100644 --- a/backend/crates/station/src/payload/README.md +++ b/backend/crates/station/src/payload/README.md @@ -20,7 +20,7 @@ such as `AdjId`, `Value` and `ProtectionPacket` come from `software_core::model` | [`connection.rs`](connection.rs) | `ConnectionUpdate` and `Connection`. | | [`order.rs`](order.rs) | `OrderSend` and `OrderField`. | | [`message.rs`](message.rs) | `MessageUpdate`, its content and calendar timestamp, and `protection_level`. | -| [`protection.rs`](protection.rs) | `ProtectionUpdate`, conversion from `ProtectionPacket` and legacy `ProtectionPayload`. | +| [`protection.rs`](protection.rs) | `ProtectionUpdate`, built from a `ProtectionPacket`, and legacy `ProtectionPayload`. | | [`serialize.rs`](serialize.rs) | Internal Serde adapters for `AdjId`, `Value` and `MessageLevel`. | ## Topics @@ -50,7 +50,8 @@ With a decoded `packet: software_core::model::ProtectionPacket`: use station::payload::{OrderSend, ProtectionUpdate, TopicPayload}; let request: OrderSend = serde_json::from_str(r#"{"id":1002,"fields":{}}"#)?; -let protection = ProtectionUpdate::from(packet); +// `timestamp` is a `MessageTimestamp` built from the packet's time and the receive date. +let protection = ProtectionUpdate::new(packet, timestamp); // {"topic":"protection/update","payload":{...}} let message = protection.to_message()?; ``` @@ -180,7 +181,6 @@ Boolean and enum parameters use `"bool"` and `"enum"`, respectively. "board": string, "name": string, "timestamp": { - "counter": number, "second": number, "minute": number, "hour": number, @@ -237,19 +237,23 @@ values against the ADJ. "id": number, "value": number, // A boolean or enum string is also possible. "timestamp": { - "hour": number, - "minute": number, "second": number, - "subsecond": number + "minute": number, + "hour": number, + "day": number, + "month": number, + "year": number } } } ``` The payload contains only the compound protection ID, the value that triggered -it and the board's timestamp. The ADJ catalog supplies the protection's name, -condition and severity. `ProtectionUpdate::from(packet)` builds this payload -directly from a domain `ProtectionPacket`. +it and when it triggered, in the same timestamp format as `message/update`. +The ADJ catalog supplies the protection's name, condition and severity. +`ProtectionUpdate::new(packet, timestamp)` takes the id and value from a domain +`ProtectionPacket`; the publisher builds `timestamp` from the packet's time of +day and the receive date. ### Logger Control (`LoggerEnable`, `LoggerResponse`, `LoggerVariables`) @@ -287,10 +291,9 @@ Select the measurement names to record: 13 bits identify the watched measurement. - Map keys have no guaranteed order. An empty map is `{}` and an empty list is `[]`. Declared structure fields remain present. -- `message/update` uses `MessageTimestamp`, with RTC counter and calendar - fields. These values are represented without timezone conversion. -- `protection/update` uses `ShortTimestamp`, containing the time of day and - a raw `subsecond` byte. That byte's unit is unresolved and is not converted - to milliseconds. It carries no calendar date. -- Constructing a `MessageTimestamp` from a `ShortTimestamp` requires receive - context for the date and an explicit policy for the counter. +- `message/update` and `protection/update` both use `MessageTimestamp`, with + calendar date and time of day down to the second. These values are + represented without timezone conversion. +- Boards send a `ShortTimestamp`: the time of day and a raw `subsecond` byte, + with no calendar date. That byte's unit is unresolved, and `MessageTimestamp` + does not carry it. The publisher adds the date from the receive context. diff --git a/backend/crates/station/src/payload/example/message.json b/backend/crates/station/src/payload/example/message.json index 65d1f75cb..58119b6a2 100644 --- a/backend/crates/station/src/payload/example/message.json +++ b/backend/crates/station/src/payload/example/message.json @@ -6,7 +6,6 @@ "board": "LCU", "name": "1001", "timestamp": { - "counter": 0, "second": 5, "minute": 30, "hour": 12, diff --git a/backend/crates/station/src/payload/example/protection.json b/backend/crates/station/src/payload/example/protection.json index 8ae2375a1..b53361841 100644 --- a/backend/crates/station/src/payload/example/protection.json +++ b/backend/crates/station/src/payload/example/protection.json @@ -4,10 +4,12 @@ "id": 11192, "value": 105.5, "timestamp": { - "hour": 12, - "minute": 30, "second": 6, - "subsecond": 0 + "minute": 30, + "hour": 12, + "day": 24, + "month": 11, + "year": 2026 } } } diff --git a/backend/crates/station/src/payload/message.rs b/backend/crates/station/src/payload/message.rs index a1dde0d05..20c8a56a0 100644 --- a/backend/crates/station/src/payload/message.rs +++ b/backend/crates/station/src/payload/message.rs @@ -41,14 +41,12 @@ pub fn protection_level(severity: Severity) -> MessageLevel { } } -/// Calendar timestamp used by the frontend's event display. +/// Calendar timestamp used by `message/update` and `protection/update`. /// -/// The event publisher supplies the date and RTC counter. The board's -/// `ShortTimestamp` contains the time of day and a raw subsecond byte. +/// The event publisher supplies the date. The board's `ShortTimestamp` +/// contains only the time of day and a raw subsecond byte. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] pub struct MessageTimestamp { - /// RTC counter supplied by the publisher. - pub counter: u16, /// Second of the minute. pub second: u8, /// Minute of the hour. diff --git a/backend/crates/station/src/payload/protection.rs b/backend/crates/station/src/payload/protection.rs index 0146ac8b4..e64d1efd1 100644 --- a/backend/crates/station/src/payload/protection.rs +++ b/backend/crates/station/src/payload/protection.rs @@ -1,11 +1,11 @@ use super::{ - TopicPayload, + MessageTimestamp, TopicPayload, serialize::{serialize_adj_id, serialize_value}, }; use serde::Serialize; use serde_json::Value as JsonValue; -use software_core::model::{AdjId, ProtectionPacket, ShortTimestamp, Value}; +use software_core::model::{AdjId, ProtectionPacket, Value}; /// Payload of `protection/update`: the triggered id, measured value and time. #[derive(Debug, Clone, PartialEq, Serialize)] @@ -16,35 +16,27 @@ pub struct ProtectionUpdate { /// Value that triggered the protection, serialized as a JSON primitive. #[serde(serialize_with = "serialize_value")] pub value: Value, - /// Time of day supplied by the board, with its original subsecond byte. - #[serde(with = "ShortTimestampJson")] - pub timestamp: ShortTimestamp, + /// When it triggered, in the same calendar format as `message/update`. + pub timestamp: MessageTimestamp, } impl TopicPayload for ProtectionUpdate { const TOPIC: &'static str = "protection/update"; } -impl From for ProtectionUpdate { - fn from(packet: ProtectionPacket) -> Self { +impl ProtectionUpdate { + /// Takes the id and value from the packet. The packet's `ShortTimestamp` + /// has no date, so the publisher builds `timestamp` from it and the receive + /// date, as it does for `message/update`. + pub fn new(packet: ProtectionPacket, timestamp: MessageTimestamp) -> Self { Self { id: packet.id, value: packet.value, - timestamp: packet.timestamp, + timestamp, } } } -// Defines the frontend timestamp fields locally via Serde's remote derive. -#[derive(Serialize)] -#[serde(remote = "ShortTimestamp")] -struct ShortTimestampJson { - hour: u8, - minute: u8, - second: u8, - subsecond: u8, -} - /// Legacy protection details used only by `message/update`. /// /// Values retain their JSON number or boolean representation. ADJ validation diff --git a/backend/crates/station/src/websocket/broker.rs b/backend/crates/station/src/websocket/broker.rs index 609b3968d..f5ea40853 100644 --- a/backend/crates/station/src/websocket/broker.rs +++ b/backend/crates/station/src/websocket/broker.rs @@ -430,11 +430,13 @@ mod tests { ProtectionUpdate { id: software_core::model::AdjId(id), value: software_core::model::Value::Number(1.0), - timestamp: software_core::model::ShortTimestamp { - hour: 12, - minute: 30, + timestamp: crate::payload::MessageTimestamp { second: 6, - subsecond: 0, + minute: 30, + hour: 12, + day: 24, + month: 11, + year: 2026, }, } } From 1c9bb707bdf48cf6d203c39d141753b7723a96af Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Fri, 4 Dec 2026 01:39:35 +0100 Subject: [PATCH 196/225] fix(frontend): update messages --- frontend/competition-view/scripts/mock-backend.mjs | 1 - frontend/competition-view/src/types/message.ts | 1 - frontend/testing-view/src/lib/utils.test.ts | 1 - frontend/testing-view/src/types/data/message.ts | 9 ++------- 4 files changed, 2 insertions(+), 10 deletions(-) diff --git a/frontend/competition-view/scripts/mock-backend.mjs b/frontend/competition-view/scripts/mock-backend.mjs index e34180dad..844e93648 100644 --- a/frontend/competition-view/scripts/mock-backend.mjs +++ b/frontend/competition-view/scripts/mock-backend.mjs @@ -39,7 +39,6 @@ const NO_BURST = args.includes("--no-burst"); const timestamp = () => { const d = new Date(); return { - counter: 0, second: d.getSeconds(), minute: d.getMinutes(), hour: d.getHours(), diff --git a/frontend/competition-view/src/types/message.ts b/frontend/competition-view/src/types/message.ts index e6a360edd..d995db0f1 100644 --- a/frontend/competition-view/src/types/message.ts +++ b/frontend/competition-view/src/types/message.ts @@ -7,7 +7,6 @@ export type MessageKind = "info" | "warning" | "fault" | "ok"; * as-is rather than routing through `Date`/UTC conversion. */ export interface MessageTimestamp { - counter: number; second: number; minute: number; hour: number; diff --git a/frontend/testing-view/src/lib/utils.test.ts b/frontend/testing-view/src/lib/utils.test.ts index b7ef3df5b..7c3e14b0b 100644 --- a/frontend/testing-view/src/lib/utils.test.ts +++ b/frontend/testing-view/src/lib/utils.test.ts @@ -29,7 +29,6 @@ describe("formatTimestamp", () => { it("should return the correct formatted timestamp", () => { expect( formatTimestamp({ - counter: 0, day: 1, month: 1, year: 2021, diff --git a/frontend/testing-view/src/types/data/message.ts b/frontend/testing-view/src/types/data/message.ts index 5f4fb695f..87f5f0645 100644 --- a/frontend/testing-view/src/types/data/message.ts +++ b/frontend/testing-view/src/types/data/message.ts @@ -2,15 +2,10 @@ import type { BoardName } from "./board"; /** * Defines current moment in time.\ - * **Be careful** as there is no way to check if a timestamp is unique.\ - * Because seconds basically don't tell us anything in the context of high-frequency systems - * and counter only means uniqueness considering the same packet type + * **Be careful** as there is no way to check if a timestamp is unique, + * because seconds basically don't tell us anything in the context of high-frequency systems. */ export type MessageTimestamp = { - /** Counter which is incremented by 1 every time packet of one type is generated,\ - * but it can be the same between different packet types - */ - counter: number; second: number; minute: number; hour: number; From 6227b23b410a67901f7b4c63483abca22e526a23 Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Fri, 4 Dec 2026 01:44:36 +0100 Subject: [PATCH 197/225] fix(backend, ws & topic): add message origin --- backend/crates/station/src/payload.rs | 19 +++++++++++++++++++ backend/crates/station/src/payload/README.md | 6 ++++++ .../station/src/payload/example/message.json | 1 + backend/crates/station/src/payload/message.rs | 4 ++++ 4 files changed, 30 insertions(+) diff --git a/backend/crates/station/src/payload.rs b/backend/crates/station/src/payload.rs index 1c7197dce..aff960eaa 100644 --- a/backend/crates/station/src/payload.rs +++ b/backend/crates/station/src/payload.rs @@ -170,6 +170,7 @@ mod tests { kind: MessageLevel::Info, payload: MessagePayload::Text("Order Sent".into()), board: "LCU".into(), + origin: String::new(), name: "1001".into(), timestamp: MessageTimestamp { second: 5, @@ -216,6 +217,7 @@ mod tests { kind: MessageLevel::Fault, payload: MessagePayload::Protection(payload), board: "HVBMS".into(), + origin: String::new(), name: "cell_temperature".into(), timestamp: MessageTimestamp { second: 6, @@ -295,6 +297,7 @@ mod tests { kind: level, payload: MessagePayload::Text("text".into()), board: "LCU".into(), + origin: String::new(), name: "name".into(), timestamp: MessageTimestamp { second: 0, @@ -315,4 +318,20 @@ mod tests { assert_eq!(protection_level(Severity::Fault), MessageLevel::Fault); assert_eq!(protection_level(Severity::Warning), MessageLevel::Warning); } + + #[test] + fn board_messages_carry_where_the_board_produced_them() -> Result<(), serde_json::Error> { + let update = MessageUpdate { + kind: MessageLevel::Warning, + payload: MessagePayload::Text("something went wrong".into()), + board: "VCU".into(), + origin: "main.c".into(), + name: "warning".into(), + timestamp: TIME, + }; + let message = message(&update)?; + assert_eq!(message["payload"]["origin"], "main.c"); + assert_eq!(message["payload"]["payload"], "something went wrong"); + Ok(()) + } } diff --git a/backend/crates/station/src/payload/README.md b/backend/crates/station/src/payload/README.md index 141382efb..80da87dc8 100644 --- a/backend/crates/station/src/payload/README.md +++ b/backend/crates/station/src/payload/README.md @@ -179,6 +179,7 @@ Boolean and enum parameters use `"bool"` and `"enum"`, respectively. "kind": string, // "info", "warning", "fault" or "panic". "payload": string, // Alternatively, the detailed object shown below. "board": string, + "origin": string, "name": string, "timestamp": { "second": number, @@ -196,6 +197,11 @@ The outer `kind` is a `software_core::model::MessageLevel`, written with its ADJ name (`MessageLevel::name`). A protection shown as a message takes the level of its severity, given by `protection_level`. +`origin` repeats the `origin` field of the board's message packet: where on the +board the message was produced, such as a source file, at most 47 characters. +It is empty for messages the backend produces itself, such as order notices +and protections shown as messages. + `MessagePayload::Text` is a JSON string. `MessagePayload::Protection` is an object with its own `kind` and `data`. The outer `kind` always describes severity; the inner `kind` describes the condition: diff --git a/backend/crates/station/src/payload/example/message.json b/backend/crates/station/src/payload/example/message.json index 58119b6a2..294a4d9d4 100644 --- a/backend/crates/station/src/payload/example/message.json +++ b/backend/crates/station/src/payload/example/message.json @@ -4,6 +4,7 @@ "kind": "info", "payload": "Order Sent", "board": "LCU", + "origin": "", "name": "1001", "timestamp": { "second": 5, diff --git a/backend/crates/station/src/payload/message.rs b/backend/crates/station/src/payload/message.rs index 20c8a56a0..7d7f6a8cd 100644 --- a/backend/crates/station/src/payload/message.rs +++ b/backend/crates/station/src/payload/message.rs @@ -13,6 +13,10 @@ pub struct MessageUpdate { pub payload: MessagePayload, /// Name of the board that produced the event. pub board: String, + /// Where on the board the message was produced, as the board sends it in + /// the packet's `origin` field, such as a source file. Empty for messages + /// the backend produces itself, such as order notices and protections. + pub origin: String, /// Display name of the event; order-sent notices use the order id as text. pub name: String, /// Original RTC fields, without a timezone conversion. From 041d0a901c7bf598d3ae65fbf6eb67b352305c5b Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Fri, 4 Dec 2026 02:01:29 +0100 Subject: [PATCH 198/225] feat(backend, payload & ws): new backend message --- backend/crates/station/src/payload.rs | 45 ++++++++++- backend/crates/station/src/payload/README.md | 43 ++++++++-- backend/crates/station/src/payload/backend.rs | 24 ++++++ .../src/payload/example/backend_message.json | 16 ++++ backend/crates/station/src/payload/message.rs | 3 +- backend/crates/station/src/websocket.rs | 10 ++- .../crates/station/src/websocket/README.md | 1 + .../crates/station/src/websocket/broker.rs | 81 ++++++++++++++++++- .../crates/station/src/websocket/receiver.rs | 17 +++- .../crates/station/src/websocket/sender.rs | 7 +- 10 files changed, 231 insertions(+), 16 deletions(-) create mode 100644 backend/crates/station/src/payload/backend.rs create mode 100644 backend/crates/station/src/payload/example/backend_message.json diff --git a/backend/crates/station/src/payload.rs b/backend/crates/station/src/payload.rs index aff960eaa..fd7510eed 100644 --- a/backend/crates/station/src/payload.rs +++ b/backend/crates/station/src/payload.rs @@ -8,6 +8,7 @@ use serde::Serialize; +mod backend; mod connection; mod data; mod message; @@ -15,6 +16,7 @@ mod order; mod protection; mod serialize; +pub use backend::BackendMessage; pub use connection::{Connection, ConnectionUpdate}; pub use data::{DataPacketUpdate, DataUpdate, MeasurementUpdate}; pub use message::{MessagePayload, MessageTimestamp, MessageUpdate, protection_level}; @@ -91,7 +93,7 @@ mod tests { Ok(()) } - /// The calendar time of `example/protection.json`. + /// The calendar time of `example/protection.json` and `example/backend_message.json`. const TIME: MessageTimestamp = MessageTimestamp { second: 6, minute: 30, @@ -194,6 +196,20 @@ mod tests { assert_matches_example(&protection, include_str!("payload/example/protection.json")) } + #[test] + fn backend_message_matches_its_example() -> Result<(), serde_json::Error> { + let message = BackendMessage { + kind: MessageLevel::Fault, + board: Some("HVSCU".into()), + text: "HVSCU: could not send the keep-alive: connection reset by peer".into(), + timestamp: TIME, + }; + assert_matches_example( + &message, + include_str!("payload/example/backend_message.json"), + ) + } + #[test] fn initial_states_are_an_empty_object_or_false() -> Result<(), serde_json::Error> { assert_eq!( @@ -334,4 +350,31 @@ mod tests { assert_eq!(message["payload"]["payload"], "something went wrong"); Ok(()) } + + #[test] + fn a_backend_message_without_a_board_has_a_null_board() -> Result<(), serde_json::Error> { + let message = message(&BackendMessage { + kind: MessageLevel::Panic, + board: None, + text: "the pipeline stopped".into(), + timestamp: TIME, + })?; + assert_eq!(message["payload"]["board"], serde_json::Value::Null); + assert_eq!(message["payload"]["kind"], "panic"); + Ok(()) + } + + #[test] + fn backend_message_kind_is_the_adj_name_of_the_level() -> Result<(), serde_json::Error> { + for level in MessageLevel::ALL { + let update = BackendMessage { + kind: level, + board: None, + text: "text".into(), + timestamp: TIME, + }; + assert_eq!(message(&update)?["payload"]["kind"], level.name()); + } + Ok(()) + } } diff --git a/backend/crates/station/src/payload/README.md b/backend/crates/station/src/payload/README.md index 80da87dc8..fd9bdb39a 100644 --- a/backend/crates/station/src/payload/README.md +++ b/backend/crates/station/src/payload/README.md @@ -1,7 +1,7 @@ # WebSocket Message Models (`payload`) -JSON models for telemetry, connections, orders, messages, protection events -and logger control. The public module is `station::payload`, declared in +JSON models for telemetry, connections, orders, messages, protection events, +the backend's own messages and logger control. The public module is `station::payload`, declared in [`../payload.rs`](../payload.rs), with its implementation in `src/payload/`. The Rust types describe the payload of each topic. Messages sent over the @@ -21,6 +21,7 @@ such as `AdjId`, `Value` and `ProtectionPacket` come from `software_core::model` | [`order.rs`](order.rs) | `OrderSend` and `OrderField`. | | [`message.rs`](message.rs) | `MessageUpdate`, its content and calendar timestamp, and `protection_level`. | | [`protection.rs`](protection.rs) | `ProtectionUpdate`, built from a `ProtectionPacket`, and legacy `ProtectionPayload`. | +| [`backend.rs`](backend.rs) | `BackendMessage`, a message the backend itself produces. | | [`serialize.rs`](serialize.rs) | Internal Serde adapters for `AdjId`, `Value` and `MessageLevel`. | ## Topics @@ -32,6 +33,7 @@ such as `AdjId`, `Value` and `ProtectionPacket` come from `software_core::model` | `order/send` | `OrderSend` | Frontend → backend | [order.json](example/order.json) | | `message/update` | `MessageUpdate` | Backend → frontend | [message.json](example/message.json) | | `protection/update` | `ProtectionUpdate` | Backend → frontend | [protection.json](example/protection.json) | +| `backend/message` | `BackendMessage` | Backend → frontend | [backend_message.json](example/backend_message.json) | | `logger/enable` | `LoggerEnable` | Frontend → backend | [logger_enable.json](example/logger_enable.json) | | `logger/response` | `LoggerResponse` | Backend → frontend | [logger_response.json](example/logger_response.json) | | `logger/variables` | `LoggerVariables` | Frontend → backend | [logger_variables.json](example/logger_variables.json) | @@ -57,7 +59,7 @@ let message = protection.to_message()?; ``` Every backend → frontend payload (`DataUpdate`, `ConnectionUpdate`, -`MessageUpdate`, `ProtectionUpdate` and `LoggerResponse`) implements +`MessageUpdate`, `ProtectionUpdate`, `BackendMessage` and `LoggerResponse`) implements `TopicPayload`. Its `TOPIC` constant is the topic name, and `to_message()` serializes the complete `{topic, payload}` message in one pass: the text the WebSocket sends. `ConnectionUpdate`, `DataUpdate` and `LoggerResponse` wrap a @@ -261,6 +263,35 @@ The ADJ catalog supplies the protection's name, condition and severity. `ProtectionPacket`; the publisher builds `timestamp` from the packet's time of day and the receive date. +### Backend Messages (`BackendMessage`) + +```jsonc +{ + "topic": "backend/message", + "payload": { + "kind": string, // info, warning, fault or panic + "board": string, // null when it concerns no single board + "text": string, + "timestamp": { + "second": number, + "minute": number, + "hour": number, + "day": number, + "month": number, + "year": number + } + } +} +``` + +A message the backend itself produces for the operator, such as a problem it +detected, rather than one a board sent. `kind` is a `MessageLevel` written with +its ADJ name, as in `message/update`. `board` names the board it concerns and +is `null` when it concerns no single board or the board is not known. `text` +carries the message with all its causes. The timestamp has the same format as +`message/update`; the publisher builds it from the moment the backend produced +the message. + ### Logger Control (`LoggerEnable`, `LoggerResponse`, `LoggerVariables`) Request the desired recording state: @@ -297,9 +328,9 @@ Select the measurement names to record: 13 bits identify the watched measurement. - Map keys have no guaranteed order. An empty map is `{}` and an empty list is `[]`. Declared structure fields remain present. -- `message/update` and `protection/update` both use `MessageTimestamp`, with - calendar date and time of day down to the second. These values are - represented without timezone conversion. +- `message/update`, `protection/update` and `backend/message` use + `MessageTimestamp`, with calendar date and time of day down to the second. + These values are represented without timezone conversion. - Boards send a `ShortTimestamp`: the time of day and a raw `subsecond` byte, with no calendar date. That byte's unit is unresolved, and `MessageTimestamp` does not carry it. The publisher adds the date from the receive context. diff --git a/backend/crates/station/src/payload/backend.rs b/backend/crates/station/src/payload/backend.rs new file mode 100644 index 000000000..2b51f5273 --- /dev/null +++ b/backend/crates/station/src/payload/backend.rs @@ -0,0 +1,24 @@ +use super::{MessageTimestamp, TopicPayload, serialize::serialize_message_level}; +use serde::Serialize; +use software_core::model::MessageLevel; + +/// Payload of `backend/message`: a message the backend itself produces for the +/// operator, such as a problem it detected. +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct BackendMessage { + /// Severity, written with the ADJ's name for the level, as in + /// `message/update`: `"fault"`, `"warning"`, `"info"` or `"panic"`. + #[serde(serialize_with = "serialize_message_level")] + pub kind: MessageLevel, + /// Name of the board it concerns; `null` when it concerns no single board + /// or the board is not known. + pub board: Option, + /// The message, with all its causes. + pub text: String, + /// When it happened, in the same calendar format as `message/update`. + pub timestamp: MessageTimestamp, +} + +impl TopicPayload for BackendMessage { + const TOPIC: &'static str = "backend/message"; +} diff --git a/backend/crates/station/src/payload/example/backend_message.json b/backend/crates/station/src/payload/example/backend_message.json new file mode 100644 index 000000000..efb3c5db8 --- /dev/null +++ b/backend/crates/station/src/payload/example/backend_message.json @@ -0,0 +1,16 @@ +{ + "topic": "backend/message", + "payload": { + "kind": "fault", + "board": "HVSCU", + "text": "HVSCU: could not send the keep-alive: connection reset by peer", + "timestamp": { + "second": 6, + "minute": 30, + "hour": 12, + "day": 24, + "month": 11, + "year": 2026 + } + } +} diff --git a/backend/crates/station/src/payload/message.rs b/backend/crates/station/src/payload/message.rs index 7d7f6a8cd..425984c63 100644 --- a/backend/crates/station/src/payload/message.rs +++ b/backend/crates/station/src/payload/message.rs @@ -45,7 +45,8 @@ pub fn protection_level(severity: Severity) -> MessageLevel { } } -/// Calendar timestamp used by `message/update` and `protection/update`. +/// Calendar timestamp used by `message/update`, `protection/update` and +/// `backend/message`. /// /// The event publisher supplies the date. The board's `ShortTimestamp` /// contains only the time of day and a raw subsecond byte. diff --git a/backend/crates/station/src/websocket.rs b/backend/crates/station/src/websocket.rs index 2b75a3beb..2d49ed89f 100644 --- a/backend/crates/station/src/websocket.rs +++ b/backend/crates/station/src/websocket.rs @@ -6,8 +6,8 @@ use std::time::Duration; use super::payload::{ - ConnectionUpdate, DataUpdate, LoggerEnable, LoggerResponse, LoggerVariables, MessageUpdate, - ProtectionUpdate, TopicPayload, + BackendMessage, ConnectionUpdate, DataUpdate, LoggerEnable, LoggerResponse, LoggerVariables, + MessageUpdate, ProtectionUpdate, TopicPayload, }; use axum::extract::ws::WebSocket; use serde::{Deserialize, Serialize}; @@ -61,6 +61,7 @@ enum Topic { Data, Messages, Protections, + BackendMessages, } impl Topic { @@ -71,6 +72,7 @@ impl Topic { DataUpdate::TOPIC => Some(Self::Data), MessageUpdate::TOPIC => Some(Self::Messages), ProtectionUpdate::TOPIC => Some(Self::Protections), + BackendMessage::TOPIC => Some(Self::BackendMessages), _ => None, } } @@ -215,6 +217,10 @@ mod tests { Topic::from_name(ProtectionUpdate::TOPIC), Some(Topic::Protections) ); + assert_eq!( + Topic::from_name(BackendMessage::TOPIC), + Some(Topic::BackendMessages) + ); // Commands, heartbeats and removed topics are not subscriptions. for name in [ ORDER_SEND, diff --git a/backend/crates/station/src/websocket/README.md b/backend/crates/station/src/websocket/README.md index 39be8ad95..d2f1e78d6 100644 --- a/backend/crates/station/src/websocket/README.md +++ b/backend/crates/station/src/websocket/README.md @@ -15,6 +15,7 @@ message the sender writes. | `podData/update` | `publish_data(data)` | `subscribe_data()` | `{}` | | `message/update` | `publish_message(message)` | `subscribe_messages()` | No initial event | | `protection/update` | `publish_protection(protection)` | `subscribe_protections()` | No initial event | +| `backend/message` | `publish_backend_message(message)` | `subscribe_backend_messages()` | No initial event | - `Broker::new()` creates the broker, a `BrokerClient` and the initial topic states. `BrokerClient::subscriber()` returns a `Subscriber`. diff --git a/backend/crates/station/src/websocket/broker.rs b/backend/crates/station/src/websocket/broker.rs index f5ea40853..d09fd7b14 100644 --- a/backend/crates/station/src/websocket/broker.rs +++ b/backend/crates/station/src/websocket/broker.rs @@ -1,4 +1,5 @@ -//! Relays complete state snapshots and forwards message and protection events. +//! Relays complete state snapshots and forwards message, protection and backend +//! message events. //! //! The broker neither merges nor batches: publishers decide what each snapshot //! holds and when to send it. Each `watch` topic holds the latest snapshot and @@ -6,7 +7,7 @@ //! `broadcast` backlog for live subscribers. use crate::payload::{ - ConnectionUpdate, DataUpdate, LoggerResponse, MessageUpdate, ProtectionUpdate, + BackendMessage, ConnectionUpdate, DataUpdate, LoggerResponse, MessageUpdate, ProtectionUpdate, }; use tokio::sync::{broadcast, mpsc, watch}; @@ -21,6 +22,7 @@ enum Update { Data(DataUpdate), Message(MessageUpdate), Protection(ProtectionUpdate), + BackendMessage(BackendMessage), } /// Owns the topic channels and relays incoming updates. @@ -32,6 +34,7 @@ pub struct Broker { data: watch::Sender, messages: broadcast::Sender, protections: broadcast::Sender, + backend_messages: broadcast::Sender, } /// Clonable access to publication. The broker runs while any client exists. @@ -52,6 +55,7 @@ pub struct Subscriber { // Weak handles let event channels close when the broker exits. messages: broadcast::WeakSender, protections: broadcast::WeakSender, + backend_messages: broadcast::WeakSender, } impl Broker { @@ -63,8 +67,10 @@ impl Broker { let (data, telemetry) = watch::channel(DataUpdate::default()); let (messages, _) = broadcast::channel(EVENT_CAPACITY); let (protections, _) = broadcast::channel(EVENT_CAPACITY); + let (backend_messages, _) = broadcast::channel(EVENT_CAPACITY); let message_topic = messages.downgrade(); let protection_topic = protections.downgrade(); + let backend_message_topic = backend_messages.downgrade(); ( Self { updates: receiver, @@ -73,6 +79,7 @@ impl Broker { data, messages, protections, + backend_messages, }, BrokerClient { updates, @@ -82,6 +89,7 @@ impl Broker { data: telemetry, messages: message_topic, protections: protection_topic, + backend_messages: backend_message_topic, }, }, ) @@ -108,6 +116,9 @@ impl Broker { Update::Protection(protection) => { let _ = self.protections.send(protection); } + Update::BackendMessage(message) => { + let _ = self.backend_messages.send(message); + } } } } @@ -141,6 +152,11 @@ impl BrokerClient { self.publish(Update::Protection(protection)).await } + /// Queues a message from the backend itself for current subscribers. + pub async fn publish_backend_message(&self, message: BackendMessage) -> Result<(), Error> { + self.publish(Update::BackendMessage(message)).await + } + async fn publish(&self, update: Update) -> Result<(), Error> { self.updates .send(update) @@ -189,6 +205,12 @@ impl Subscriber { let sender = self.protections.upgrade().ok_or(Error::BrokerClosed)?; Ok(sender.subscribe()) } + + /// Subscribes to future messages from the backend itself. + pub fn subscribe_backend_messages(&self) -> Result, Error> { + let sender = self.backend_messages.upgrade().ok_or(Error::BrokerClosed)?; + Ok(sender.subscribe()) + } } fn subscribe(state: &watch::Receiver) -> watch::Receiver { @@ -265,6 +287,12 @@ mod tests { client.publish_protection(protection(1)).await, Err(Error::BrokerClosed) )); + assert!(matches!( + client + .publish_backend_message(backend_message("lost")) + .await, + Err(Error::BrokerClosed) + )); } #[tokio::test] @@ -301,6 +329,39 @@ mod tests { Ok(()) } + #[tokio::test] + async fn backend_messages_reach_only_their_own_subscribers_in_order() + -> Result<(), Box> { + let (broker, client) = Broker::new(); + let mut backend = client.subscriber().subscribe_backend_messages()?; + let mut boards = client.subscriber().subscribe_messages()?; + let worker = tokio::spawn(broker.run()); + + client + .publish_backend_message(backend_message("first")) + .await?; + client + .publish_backend_message(backend_message("second")) + .await?; + assert_eq!( + timeout(Duration::from_secs(1), backend.recv()).await??, + backend_message("first") + ); + assert_eq!( + timeout(Duration::from_secs(1), backend.recv()).await??, + backend_message("second") + ); + + drop(client); + timeout(Duration::from_secs(1), worker).await??; + // Board messages are a separate topic: they got nothing. + assert!(matches!( + boards.recv().await, + Err(broadcast::error::RecvError::Closed) + )); + Ok(()) + } + #[tokio::test(start_paused = true)] async fn telemetry_is_relayed_as_published_without_batching_or_merging() -> Result<(), Box> { @@ -441,6 +502,22 @@ mod tests { } } + fn backend_message(text: &str) -> BackendMessage { + BackendMessage { + kind: software_core::model::MessageLevel::Warning, + board: None, + text: text.into(), + timestamp: crate::payload::MessageTimestamp { + second: 6, + minute: 30, + hour: 12, + day: 24, + month: 11, + year: 2026, + }, + } + } + fn packet(id: u16, count: u64) -> DataPacketUpdate { DataPacketUpdate { id: software_core::model::AdjId(id), diff --git a/backend/crates/station/src/websocket/receiver.rs b/backend/crates/station/src/websocket/receiver.rs index 05446e1dc..629f2aede 100644 --- a/backend/crates/station/src/websocket/receiver.rs +++ b/backend/crates/station/src/websocket/receiver.rs @@ -8,7 +8,7 @@ use tokio::{ }; use crate::payload::{ - ConnectionUpdate, DataUpdate, LoggerResponse, MessageUpdate, ProtectionUpdate, + BackendMessage, ConnectionUpdate, DataUpdate, LoggerResponse, MessageUpdate, ProtectionUpdate, }; use super::{ @@ -32,6 +32,7 @@ pub(super) enum SubscriptionChange { Data(Option>), Messages(Option>), Protections(Option>), + BackendMessages(Option>), } impl SubscriptionChange { @@ -50,6 +51,11 @@ impl SubscriptionChange { .then(|| broker.subscribe_protections()) .transpose()?, ), + Topic::BackendMessages => Self::BackendMessages( + enabled + .then(|| broker.subscribe_backend_messages()) + .transpose()?, + ), }) } } @@ -271,7 +277,7 @@ mod tests { #[tokio::test] async fn repeated_event_subscriptions_keep_the_existing_receiver() -> Result<(), Error> { let (_broker, client) = Broker::new(); - let (changes, mut subscriptions) = mpsc::channel(4); + let (changes, mut subscriptions) = mpsc::channel(8); let frames = stream::iter([ Ok(Frame::Text( r#"{"topic":"message/update","payload":{}}"#.into(), @@ -279,6 +285,9 @@ mod tests { Ok(Frame::Text( r#"{"topic":"protection/update","payload":{"subscribe":true}}"#.into(), )), + Ok(Frame::Text( + r#"{"topic":"backend/message","payload":{"subscribe":true}}"#.into(), + )), Ok(Frame::Text( r#"{"topic":"message/update","payload":{"subscribe":true}}"#.into(), )), @@ -307,6 +316,10 @@ mod tests { subscriptions.recv().await, Some(SubscriptionChange::Protections(Some(_))) )); + assert!(matches!( + subscriptions.recv().await, + Some(SubscriptionChange::BackendMessages(Some(_))) + )); assert!(matches!( subscriptions.recv().await, Some(SubscriptionChange::Messages(None)) diff --git a/backend/crates/station/src/websocket/sender.rs b/backend/crates/station/src/websocket/sender.rs index d27043b4d..a842afdc7 100644 --- a/backend/crates/station/src/websocket/sender.rs +++ b/backend/crates/station/src/websocket/sender.rs @@ -13,10 +13,11 @@ pub(super) async fn run( mut subscriptions: mpsc::Receiver, ) -> Result<(), Error> { let (mut connections, mut logger, mut data) = (None, None, None); - let (mut messages, mut protections) = (None, None); + let (mut messages, mut protections, mut backend_messages) = (None, None, None); loop { let frame = tokio::select! { - // Apply subscription changes first, then give ready protection events priority. + // Apply subscription changes first, then give ready protection events + // priority, then the backend's own messages. biased; change = subscriptions.recv() => { let Some(change) = change else { return Ok(()); }; @@ -26,11 +27,13 @@ pub(super) async fn run( SubscriptionChange::Data(next) => subscribe_state(&mut data, next)?, SubscriptionChange::Messages(next) => { messages = next; None } SubscriptionChange::Protections(next) => { protections = next; None } + SubscriptionChange::BackendMessages(next) => { backend_messages = next; None } }; let Some(snapshot) = snapshot else { continue; }; snapshot } next = next_event(&mut protections) => next?, + next = next_event(&mut backend_messages) => next?, next = next_event(&mut messages) => next?, next = next_state(&mut connections) => next?, next = next_state(&mut logger) => next?, From 4268d3062d8381de5fc03a1e69792d77bb570cc0 Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Fri, 4 Dec 2026 16:58:09 +0100 Subject: [PATCH 199/225] fix(backend, payload & ws): use model adj.id --- backend/crates/station/src/payload.rs | 17 ++++++--- backend/crates/station/src/payload/data.rs | 21 ++++++---- .../crates/station/src/payload/serialize.rs | 11 +++++- .../crates/station/src/websocket/broker.rs | 38 ++++++++++--------- 4 files changed, 56 insertions(+), 31 deletions(-) diff --git a/backend/crates/station/src/payload.rs b/backend/crates/station/src/payload.rs index fd7510eed..a86fcb69a 100644 --- a/backend/crates/station/src/payload.rs +++ b/backend/crates/station/src/payload.rs @@ -130,7 +130,7 @@ mod tests { ( id, DataPacketUpdate { - id: AdjId(id), + id, count, cycle_time: 100_000_000, measurement_updates: HashMap::from([(measurement, value)]), @@ -139,19 +139,24 @@ mod tests { }; let update = DataUpdate(HashMap::from([ packet( - 936, + AdjId(936), 124, - 3000, + AdjId(3000), MeasurementUpdate::Numeric { last: 35.5, average: 35.0, }, ), - packet(1201, 58, 3001, MeasurementUpdate::Boolean(true)), packet( - 1202, + AdjId(1201), 58, - 3002, + AdjId(3001), + MeasurementUpdate::Boolean(true), + ), + packet( + AdjId(1202), + 58, + AdjId(3002), MeasurementUpdate::Enum("Operational".into()), ), ])); diff --git a/backend/crates/station/src/payload/data.rs b/backend/crates/station/src/payload/data.rs index b08df9e9c..959bc2553 100644 --- a/backend/crates/station/src/payload/data.rs +++ b/backend/crates/station/src/payload/data.rs @@ -1,15 +1,21 @@ -use super::{TopicPayload, serialize::serialize_adj_id}; +use super::{ + TopicPayload, + serialize::{serialize_adj_id, serialize_adj_id_keys}, +}; use serde::Serialize; use software_core::model::AdjId; use std::collections::HashMap; -/// Latest telemetry per packet for `podData/update`. Packet IDs are JSON object keys. +/// Latest telemetry per packet for `podData/update`, keyed by the packet's ADJ id, +/// a decimal string key in JSON. #[derive(Debug, Clone, Default, PartialEq, Serialize)] #[serde(transparent)] -pub struct DataUpdate(pub HashMap); +pub struct DataUpdate( + #[serde(serialize_with = "serialize_adj_id_keys")] pub HashMap, +); -impl From> for DataUpdate { - fn from(packets: HashMap) -> Self { +impl From> for DataUpdate { + fn from(packets: HashMap) -> Self { Self(packets) } } @@ -29,8 +35,9 @@ pub struct DataPacketUpdate { pub count: u64, /// Averaged interval between packets, in the legacy timestamp's units. pub cycle_time: u64, - /// Updates keyed by the measurement's numeric ADJ id, a string key in JSON. - pub measurement_updates: HashMap, + /// Updates keyed by the measurement's ADJ id, a decimal string key in JSON. + #[serde(serialize_with = "serialize_adj_id_keys")] + pub measurement_updates: HashMap, } /// Numeric measurements carry statistics. Booleans and enum names use JSON primitives. diff --git a/backend/crates/station/src/payload/serialize.rs b/backend/crates/station/src/payload/serialize.rs index bc828f525..f21e71d78 100644 --- a/backend/crates/station/src/payload/serialize.rs +++ b/backend/crates/station/src/payload/serialize.rs @@ -1,5 +1,6 @@ -use serde::{Deserialize, Deserializer, Serializer}; +use serde::{Deserialize, Deserializer, Serialize, Serializer}; use software_core::model::{AdjId, MessageLevel, Value}; +use std::collections::HashMap; /// Emits a scalar JSON value for a protection event. Enums use the variant name. pub(super) fn serialize_value( @@ -35,3 +36,11 @@ pub(super) fn serialize_adj_id( ) -> Result { serializer.serialize_u16(id.0) } + +/// Writes a map keyed by ADJ ID as a JSON object whose keys are the IDs in decimal. +pub(super) fn serialize_adj_id_keys( + map: &HashMap, + serializer: S, +) -> Result { + serializer.collect_map(map.iter().map(|(id, value)| (id.0, value))) +} diff --git a/backend/crates/station/src/websocket/broker.rs b/backend/crates/station/src/websocket/broker.rs index d09fd7b14..bb881da7b 100644 --- a/backend/crates/station/src/websocket/broker.rs +++ b/backend/crates/station/src/websocket/broker.rs @@ -226,6 +226,8 @@ mod tests { use tokio::time::{Instant, timeout}; + use software_core::model::AdjId; + use super::*; use crate::payload::{Connection, DataPacketUpdate}; @@ -284,7 +286,7 @@ mod tests { Err(Error::BrokerClosed) )); assert!(matches!( - client.publish_protection(protection(1)).await, + client.publish_protection(protection(AdjId(1))).await, Err(Error::BrokerClosed) )); assert!(matches!( @@ -301,27 +303,27 @@ mod tests { let mut early = client.subscriber().subscribe_protections()?; let worker = tokio::spawn(broker.run()); - client.publish_protection(protection(1)).await?; - client.publish_protection(protection(2)).await?; + client.publish_protection(protection(AdjId(1))).await?; + client.publish_protection(protection(AdjId(2))).await?; assert_eq!( timeout(Duration::from_secs(1), early.recv()).await??, - protection(1) + protection(AdjId(1)) ); assert_eq!( timeout(Duration::from_secs(1), early.recv()).await??, - protection(2) + protection(AdjId(2)) ); // A late subscriber starts with the next event, not the earlier ones. let mut late = client.subscriber().subscribe_protections()?; - client.publish_protection(protection(3)).await?; + client.publish_protection(protection(AdjId(3))).await?; assert_eq!( timeout(Duration::from_secs(1), late.recv()).await??, - protection(3) + protection(AdjId(3)) ); assert_eq!( timeout(Duration::from_secs(1), early.recv()).await??, - protection(3) + protection(AdjId(3)) ); drop(client); @@ -371,7 +373,7 @@ mod tests { let worker = tokio::spawn(broker.run()); let start = Instant::now(); - let first = telemetry(&[packet(1000, 1), packet(2000, 1)]); + let first = telemetry(&[packet(AdjId(1000), 1), packet(AdjId(2000), 1)]); client.publish_data(first.clone()).await?; timeout(Duration::from_secs(1), data.changed()).await??; // The paused clock only moves when every task waits on a timer, so a @@ -380,7 +382,7 @@ mod tests { assert_eq!(*data.borrow_and_update(), first); // Packet 1000 is missing from the next snapshot, so it is no longer published. - let second = telemetry(&[packet(2000, 2)]); + let second = telemetry(&[packet(AdjId(2000), 2)]); client.publish_data(second.clone()).await?; timeout(Duration::from_secs(1), data.changed()).await??; assert_eq!(Instant::now(), start); @@ -426,13 +428,15 @@ mod tests { let logger = client.subscriber().subscribe_logger(); client.publish_logger(LoggerResponse(true)).await?; let data = client.subscriber().subscribe_data(); - client.publish_data(telemetry(&[packet(1000, 1)])).await?; + client + .publish_data(telemetry(&[packet(AdjId(1000), 1)])) + .await?; drop(client); timeout(Duration::from_secs(1), broker.run()).await?; assert!(state.borrow().0["LCU"].is_connected); assert!(logger.borrow().0); - assert_eq!(data.borrow().0[&1000].count, 1); + assert_eq!(data.borrow().0[&AdjId(1000)].count, 1); Ok(()) } @@ -482,14 +486,14 @@ mod tests { DataUpdate( packets .iter() - .map(|packet| (packet.id.0, packet.clone())) + .map(|packet| (packet.id, packet.clone())) .collect(), ) } - fn protection(id: u16) -> ProtectionUpdate { + fn protection(id: AdjId) -> ProtectionUpdate { ProtectionUpdate { - id: software_core::model::AdjId(id), + id, value: software_core::model::Value::Number(1.0), timestamp: crate::payload::MessageTimestamp { second: 6, @@ -518,9 +522,9 @@ mod tests { } } - fn packet(id: u16, count: u64) -> DataPacketUpdate { + fn packet(id: AdjId, count: u64) -> DataPacketUpdate { DataPacketUpdate { - id: software_core::model::AdjId(id), + id, count, cycle_time: 100_000_000, measurement_updates: Default::default(), From 759848ab92774ee2668733e31d2d61dc799168a8 Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Fri, 4 Dec 2026 17:03:00 +0100 Subject: [PATCH 200/225] fix( backend, ws & payload): add constructor --- backend/crates/station/src/payload.rs | 24 +++++++++---------- backend/crates/station/src/payload/README.md | 2 +- backend/crates/station/src/payload/backend.rs | 17 +++++++++++++ 3 files changed, 30 insertions(+), 13 deletions(-) diff --git a/backend/crates/station/src/payload.rs b/backend/crates/station/src/payload.rs index a86fcb69a..4bd72cc06 100644 --- a/backend/crates/station/src/payload.rs +++ b/backend/crates/station/src/payload.rs @@ -203,12 +203,12 @@ mod tests { #[test] fn backend_message_matches_its_example() -> Result<(), serde_json::Error> { - let message = BackendMessage { - kind: MessageLevel::Fault, - board: Some("HVSCU".into()), - text: "HVSCU: could not send the keep-alive: connection reset by peer".into(), - timestamp: TIME, - }; + let message = BackendMessage::new( + MessageLevel::Fault, + Some("HVSCU".into()), + "HVSCU: could not send the keep-alive: connection reset by peer", + TIME, + ); assert_matches_example( &message, include_str!("payload/example/backend_message.json"), @@ -358,12 +358,12 @@ mod tests { #[test] fn a_backend_message_without_a_board_has_a_null_board() -> Result<(), serde_json::Error> { - let message = message(&BackendMessage { - kind: MessageLevel::Panic, - board: None, - text: "the pipeline stopped".into(), - timestamp: TIME, - })?; + let message = message(&BackendMessage::new( + MessageLevel::Panic, + None, + "the pipeline stopped", + TIME, + ))?; assert_eq!(message["payload"]["board"], serde_json::Value::Null); assert_eq!(message["payload"]["kind"], "panic"); Ok(()) diff --git a/backend/crates/station/src/payload/README.md b/backend/crates/station/src/payload/README.md index fd9bdb39a..ade0d4558 100644 --- a/backend/crates/station/src/payload/README.md +++ b/backend/crates/station/src/payload/README.md @@ -290,7 +290,7 @@ its ADJ name, as in `message/update`. `board` names the board it concerns and is `null` when it concerns no single board or the board is not known. `text` carries the message with all its causes. The timestamp has the same format as `message/update`; the publisher builds it from the moment the backend produced -the message. +the message. `BackendMessage::new(kind, board, text, timestamp)` builds one. ### Logger Control (`LoggerEnable`, `LoggerResponse`, `LoggerVariables`) diff --git a/backend/crates/station/src/payload/backend.rs b/backend/crates/station/src/payload/backend.rs index 2b51f5273..2dbdb1a14 100644 --- a/backend/crates/station/src/payload/backend.rs +++ b/backend/crates/station/src/payload/backend.rs @@ -22,3 +22,20 @@ pub struct BackendMessage { impl TopicPayload for BackendMessage { const TOPIC: &'static str = "backend/message"; } + +impl BackendMessage { + /// A message from the backend, about `board` if it concerns a single one. + pub fn new( + kind: MessageLevel, + board: Option, + text: impl Into, + timestamp: MessageTimestamp, + ) -> Self { + Self { + kind, + board, + text: text.into(), + timestamp, + } + } +} From 822f6ee1e4b577ab6f10db67769ecebd1df8b409 Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Fri, 4 Dec 2026 17:03:36 +0100 Subject: [PATCH 201/225] fix(backend, core): untrack accidentally committed hello.rs --- backend/crates/core/src/hello.rs | 47 -------------------------------- 1 file changed, 47 deletions(-) delete mode 100644 backend/crates/core/src/hello.rs diff --git a/backend/crates/core/src/hello.rs b/backend/crates/core/src/hello.rs deleted file mode 100644 index 70d67c4bc..000000000 --- a/backend/crates/core/src/hello.rs +++ /dev/null @@ -1,47 +0,0 @@ -//! Módulo de ejemplo, sin ninguna lógica real del backend. -//! -//! Muestra las cuatro cosas que todo módulo de `software-core` debe tener: -//! -//! 1. Documentación (`//!` para el módulo, `///` para cada función pública). -//! 2. Trazas con `tracing`, a nivel `debug` porque este código no decide -//! nada por sí mismo (ver `LOGGING.md`, en la raíz del workspace). -//! 3. Tests unitarios, en un `mod tests` al final del archivo. -//! 4. Un ejemplo en la documentación que se ejecuta como test (doc-test). - -use tracing::debug; - -/// Suma dos números enteros. -/// -/// # Ejemplos -/// -/// ``` -/// use software_core::hello::suma; -/// -/// assert_eq!(suma(2, 3), 5); -/// assert_eq!(suma(-2, 3), 1); -/// ``` -pub fn suma(a: i64, b: i64) -> i64 { - let resultado = a + b; - debug!(a, b, resultado, "suma calculada"); - resultado -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn suma_dos_positivos() { - assert_eq!(suma(2, 3), 5); - } - - #[test] - fn suma_con_negativos() { - assert_eq!(suma(-2, 3), 1); - } - - #[test] - fn suma_con_cero_es_identidad() { - assert_eq!(suma(42, 0), 42); - } -} From 4970360e90e6c0e2333a6354f3b5fbd329b36a6c Mon Sep 17 00:00:00 2001 From: GaziH Date: Fri, 4 Dec 2026 17:08:04 +0100 Subject: [PATCH 202/225] Feat(backend, pipeline): Fixed rust formatting with rustfmt --- backend/crates/station/src/lib.rs | 4 +- backend/crates/station/src/pipeline.rs | 21 +++++++--- .../station/src/pipeline/accumulator.rs | 38 ++++++++----------- .../crates/station/src/pipeline/frontend.rs | 2 +- .../crates/station/src/pipeline/message.rs | 2 +- backend/crates/station/src/pipeline/tests.rs | 31 ++++++++------- .../crates/station/src/pipeline/timestamp.rs | 2 +- backend/crates/station/src/vehicle.rs | 1 + backend/crates/station/src/websocket.rs | 2 +- 9 files changed, 55 insertions(+), 48 deletions(-) diff --git a/backend/crates/station/src/lib.rs b/backend/crates/station/src/lib.rs index 3c53fc30c..a8a0126eb 100644 --- a/backend/crates/station/src/lib.rs +++ b/backend/crates/station/src/lib.rs @@ -1,8 +1,8 @@ pub mod http; +pub mod payload; mod vehicle; pub mod websocket; -pub mod payload; pub mod pipeline; -pub mod event; \ No newline at end of file +pub mod event; diff --git a/backend/crates/station/src/pipeline.rs b/backend/crates/station/src/pipeline.rs index 190faabc7..ab7931c4c 100644 --- a/backend/crates/station/src/pipeline.rs +++ b/backend/crates/station/src/pipeline.rs @@ -35,16 +35,16 @@ mod timestamp; #[cfg(test)] mod tests; -use std::collections::HashMap; pub use frontend::FrontendEvent; +use std::collections::HashMap; use std::sync::Arc; use std::time::Duration; -use accumulator::DataAccumulator; use crate::event::{Problem, ProblemKind, ToPipeline}; use crate::payload::{Connection, ProtectionUpdate}; use crate::websocket::broker::BrokerClient; +use accumulator::DataAccumulator; use frontend::FrontendWatchdog; use software_core::model::{BoardId, Packet, PodData}; use software_core::net::{Event, Notification}; @@ -213,7 +213,15 @@ async fn handle_item( ) -> bool { match item { ToPipeline::Received(notification) => { - handle_notification(¬ification, broker, pod_data, index, accumulator, board_connections).await + handle_notification( + ¬ification, + broker, + pod_data, + index, + accumulator, + board_connections, + ) + .await } // TODO(websocket-merge): If `websocket` / `payload` splits backend problem onto a dedicated `problem/update` topic. ToPipeline::Problem(problem) => match message::from_problem(problem, pod_data) { @@ -285,7 +293,10 @@ async fn handle_notification( /// Reports a fatal frontend-disconnect [`Problem`] to `event` so it propagates /// the pod fault and performs an ordered shutdown. async fn report_frontend_fatal(problems: &mpsc::Sender, reason: &'static str) { - error!(reason, "frontend connection lost, reporting fatal problem to event"); + error!( + reason, + "frontend connection lost, reporting fatal problem to event" + ); let problem = Problem::now(ProblemKind::Fatal, None, reason); if problems.send(problem).await.is_err() { warn!("event problems channel closed before frontend disconnect could be reported"); @@ -319,4 +330,4 @@ fn publish_or_log(result: Result<(), crate::websocket::broker::Error>) -> bool { false } } -} \ No newline at end of file +} diff --git a/backend/crates/station/src/pipeline/accumulator.rs b/backend/crates/station/src/pipeline/accumulator.rs index 7aacf82e7..247d0d157 100644 --- a/backend/crates/station/src/pipeline/accumulator.rs +++ b/backend/crates/station/src/pipeline/accumulator.rs @@ -57,14 +57,7 @@ impl MeasurementAccumulator { /// latest value for booleans and enums. fn update(&mut self, value: &Value) { match (self, value) { - ( - Self::Numeric { - last, - sum, - samples, - }, - Value::Number(v), - ) => { + (Self::Numeric { last, sum, samples }, Value::Number(v)) => { *last = *v; *sum += *v; *samples += 1; @@ -92,11 +85,7 @@ impl MeasurementAccumulator { /// numeric measurements. fn into_update(self) -> MeasurementUpdate { match self { - Self::Numeric { - last, - sum, - samples, - } => MeasurementUpdate::Numeric { + Self::Numeric { last, sum, samples } => MeasurementUpdate::Numeric { last, average: sum / (samples as f64), }, @@ -133,15 +122,18 @@ impl DataAccumulator { // Lazily initialize the packet's window on first arrival. Mapping over // `0..defs.len()` avoids requiring `Clone` on `MeasurementAccumulator`. - let window = self.packets.entry(packet.id).or_insert_with(|| PacketWindow { - count: 0, - last_at: None, - last_cycle_time_ns: 0, - cycle_sum_ns: 0, - cycle_samples: 0, - measurements: (0..defs.len()).map(|_| None).collect(), - dirty: false, - }); + let window = self + .packets + .entry(packet.id) + .or_insert_with(|| PacketWindow { + count: 0, + last_at: None, + last_cycle_time_ns: 0, + cycle_sum_ns: 0, + cycle_samples: 0, + measurements: (0..defs.len()).map(|_| None).collect(), + dirty: false, + }); window.count = window.count.saturating_add(1); // Rust 2024 let-chain: only accumulate cycle time when a previous @@ -215,4 +207,4 @@ impl DataAccumulator { updates } -} \ No newline at end of file +} diff --git a/backend/crates/station/src/pipeline/frontend.rs b/backend/crates/station/src/pipeline/frontend.rs index c690b4f98..d7d33dcf5 100644 --- a/backend/crates/station/src/pipeline/frontend.rs +++ b/backend/crates/station/src/pipeline/frontend.rs @@ -118,4 +118,4 @@ impl FrontendWatchdog { None } -} \ No newline at end of file +} diff --git a/backend/crates/station/src/pipeline/message.rs b/backend/crates/station/src/pipeline/message.rs index 5dd77775b..52ca96dca 100644 --- a/backend/crates/station/src/pipeline/message.rs +++ b/backend/crates/station/src/pipeline/message.rs @@ -125,4 +125,4 @@ pub(super) fn from_order_failed( name: order.id.0.to_string(), timestamp: timestamp::from_system_time(at), } -} \ No newline at end of file +} diff --git a/backend/crates/station/src/pipeline/tests.rs b/backend/crates/station/src/pipeline/tests.rs index e0b3d778d..bbd483339 100644 --- a/backend/crates/station/src/pipeline/tests.rs +++ b/backend/crates/station/src/pipeline/tests.rs @@ -95,7 +95,7 @@ fn sample_fixture() -> (Arc, Arc) { /// forwarded to its corresponding broker topic immediately. #[tokio::test] async fn forwards_connections_protections_messages_problems_and_orders_immediately() - -> Result<(), Box> { +-> Result<(), Box> { let (pod_data, index) = sample_fixture(); let (broker, client) = Broker::new(); let mut conn_sub = client.subscribe_connections(); @@ -122,7 +122,7 @@ async fn forwards_connections_protections_messages_problems_and_orders_immediate at: UNIX_EPOCH + Duration::from_secs(1_700_000_000), event: Event::Connected, }))) - .await?; + .await?; timeout(Duration::from_secs(1), conn_sub.changed()).await??; assert!(conn_sub.borrow_and_update()["PCU"].is_connected); @@ -143,7 +143,7 @@ async fn forwards_connections_protections_messages_problems_and_orders_immediate at: UNIX_EPOCH + Duration::from_secs(1_700_000_001), event: Event::Received(Packet::Protection(protection.clone())), }))) - .await?; + .await?; let got_prot = timeout(Duration::from_secs(1), prot_sub.recv()).await??; assert_eq!(got_prot, ProtectionUpdate::from(protection)); @@ -163,12 +163,15 @@ async fn forwards_connections_protections_messages_problems_and_orders_immediate message: "temp high".to_string(), })), }))) - .await?; + .await?; let got_msg = timeout(Duration::from_secs(1), msg_sub.recv()).await??; assert_eq!(got_msg.kind, MessageKind::Warning); assert_eq!(got_msg.board, "PCU"); assert_eq!(got_msg.name, "pcu.c"); - assert_eq!(got_msg.payload, MessagePayload::Text("temp high".to_string())); + assert_eq!( + got_msg.payload, + MessagePayload::Text("temp high".to_string()) + ); assert_eq!(got_msg.timestamp.hour, 1); assert_eq!(got_msg.timestamp.counter, 4); @@ -179,7 +182,7 @@ async fn forwards_connections_protections_messages_problems_and_orders_immediate kind: ProblemKind::Fatal, text: "decode failed".to_string(), })) - .await?; + .await?; let got_problem = timeout(Duration::from_secs(1), msg_sub.recv()).await??; assert_eq!(got_problem.kind, MessageKind::Fault); assert_eq!(got_problem.board, "PCU"); @@ -194,7 +197,7 @@ async fn forwards_connections_protections_messages_problems_and_orders_immediate board: Some(BoardId(5)), order: OrderPacket::new(AdjId(1001), vec![]), }) - .await?; + .await?; let got_sent = timeout(Duration::from_secs(1), msg_sub.recv()).await??; assert_eq!(got_sent.kind, MessageKind::Info); assert_eq!(got_sent.name, "1001"); @@ -205,7 +208,7 @@ async fn forwards_connections_protections_messages_problems_and_orders_immediate order: OrderPacket::new(AdjId(1001), vec![]), reason: "board disconnected".to_string(), }) - .await?; + .await?; let got_failed = timeout(Duration::from_secs(1), msg_sub.recv()).await??; assert_eq!(got_failed.kind, MessageKind::Warning); assert_eq!(got_failed.name, "1001"); @@ -227,7 +230,7 @@ async fn forwards_connections_protections_messages_problems_and_orders_immediate /// deterministically and instantaneously via `tokio::time::advance`. #[tokio::test(start_paused = true)] async fn batches_data_every_100ms_with_window_average_last_and_cycle_time() - -> Result<(), Box> { +-> Result<(), Box> { let (pod_data, index) = sample_fixture(); let (broker, client) = Broker::new(); let mut data_sub = client.subscribe_data(); @@ -267,7 +270,7 @@ async fn batches_data_every_100ms_with_window_average_last_and_cycle_time() ], ))), }))) - .await?; + .await?; } tokio::task::yield_now().await; @@ -313,7 +316,7 @@ async fn batches_data_every_100ms_with_window_average_last_and_cycle_time() ], ))), }))) - .await?; + .await?; // Dropping `tx` flushes remaining data immediately and stops both tasks cleanly. drop(tx); @@ -337,7 +340,7 @@ async fn batches_data_every_100ms_with_window_average_last_and_cycle_time() /// disconnect, while staying disconnected past 3 s reports `ProblemKind::Fatal`. #[tokio::test(start_paused = true)] async fn frontend_disconnect_allows_reconnect_and_reports_fatal_after_grace_period() - -> Result<(), Box> { +-> Result<(), Box> { let (pod_data, index) = sample_fixture(); let (broker, client) = Broker::new(); let broker_task = tokio::spawn(broker.run()); @@ -395,7 +398,7 @@ async fn frontend_disconnect_allows_reconnect_and_reports_fatal_after_grace_peri /// session to a heartbeat timeout reports `ProblemKind::Fatal` immediately. #[tokio::test(start_paused = true)] async fn frontend_heartbeat_renews_liveness_and_expires_last_session_as_fatal() - -> Result<(), Box> { +-> Result<(), Box> { let (pod_data, index) = sample_fixture(); let (broker, client) = Broker::new(); let broker_task = tokio::spawn(broker.run()); @@ -481,4 +484,4 @@ fn utc_calendar_conversion_handles_epoch_and_leap_day() { year: 2024, } ); -} \ No newline at end of file +} diff --git a/backend/crates/station/src/pipeline/timestamp.rs b/backend/crates/station/src/pipeline/timestamp.rs index cc82da4c8..912f09226 100644 --- a/backend/crates/station/src/pipeline/timestamp.rs +++ b/backend/crates/station/src/pipeline/timestamp.rs @@ -69,4 +69,4 @@ fn civil_from_days(days_since_epoch: i64) -> (u16, u8, u8) { u8::try_from(m).unwrap_or(1), u8::try_from(d).unwrap_or(1), ) -} \ No newline at end of file +} diff --git a/backend/crates/station/src/vehicle.rs b/backend/crates/station/src/vehicle.rs index e69de29bb..8b1378917 100644 --- a/backend/crates/station/src/vehicle.rs +++ b/backend/crates/station/src/vehicle.rs @@ -0,0 +1 @@ + diff --git a/backend/crates/station/src/websocket.rs b/backend/crates/station/src/websocket.rs index 0b71c4a29..e23fb32d6 100644 --- a/backend/crates/station/src/websocket.rs +++ b/backend/crates/station/src/websocket.rs @@ -5,13 +5,13 @@ use std::time::Duration; +use super::payload::{LoggerEnable, LoggerVariables}; use axum::extract::ws::WebSocket; use serde::{Deserialize, Serialize}; use tokio::{ sync::mpsc, time::{Instant, sleep_until}, }; -use super::payload::{LoggerEnable, LoggerVariables}; use self::broker::BrokerClient; use self::handler::SessionEnd; From b675ae8bbd35810bfc6c00b42ec540c6322f206c Mon Sep 17 00:00:00 2001 From: GaziH Date: Fri, 4 Dec 2026 17:09:37 +0100 Subject: [PATCH 203/225] Feat(backend, pipeline): Updated ReadMe --- backend/crates/station/src/pipeline/README.md | 126 +++++++++++++----- 1 file changed, 94 insertions(+), 32 deletions(-) diff --git a/backend/crates/station/src/pipeline/README.md b/backend/crates/station/src/pipeline/README.md index ee1ee5f57..816937652 100644 --- a/backend/crates/station/src/pipeline/README.md +++ b/backend/crates/station/src/pipeline/README.md @@ -1,60 +1,77 @@ # Pipeline (`station::pipeline`) Transforms [`crate::event::ToPipeline`] items into frontend WebSocket payloads -(`station::payload`) and publishes them through [`crate::websocket::broker::BrokerClient`]. +(`station::payload`), publishes them through +[`crate::websocket::broker::BrokerClient`], and monitors `websocket ↔ front` +session liveness (`connection/heartbeat`). `event` routes decoded packets and backend outcomes without inspecting their contents. `pipeline` is the stage that turns those domain events into the exact -shapes the frontend expects: publishing discrete events immediately and -aggregating high-rate UDP telemetry into 100 ms windows. +shapes the frontend expects: publishing discrete events immediately, tracking +per-board connection state, aggregating high-rate UDP telemetry into 100 ms +windows, and reporting fatal frontend disconnects back to `event`. ## Overview ```text - event ──(channels.pipeline: ToPipeline)──► pipeline - ├── immediate ──► BrokerClient - │ ├── connection/update - │ ├── protection/update - │ └── message/update - └── 100 ms tick ─► BrokerClient - └── podData/update + event ─────(channels.pipeline: ToPipeline)────► pipeline + websocket ─(frontend_rx: FrontendEvent)───────► ├── immediate ──► BrokerClient + │ ├── connection/update + │ ├── protection/update + │ └── message/update + ├── 100 ms tick ─► BrokerClient + │ └── podData/update + └── fatal loss ──► event (channels.problems) ``` ## Files ```text -pipeline.rs # module root: Config, spawn, select! loop, routing +pipeline.rs # module root: Config, spawn, biased select! loop, routing pipeline/ ├── accumulator.rs # 100 ms telemetry windowing (count, cycle_time, last, average) +├── frontend.rs # websocket <-> front keep-alive & reconnect grace watchdog ├── message.rs # MessageUpdate builders (board messages, problems, order outcomes) ├── timestamp.rs # SystemTime / ShortTimestamp -> UTC MessageTimestamp -├── tests.rs # unit tests against a real Broker +├── tests.rs # unit tests against a real Broker (no sockets) └── README.md ``` ## Input-to-Topic Mapping -| `ToPipeline` variant | Condition / inner event | Target topic | `BrokerClient` method | Delivery | +| Input | Condition / inner event | Target | Action / method | Delivery | | --- | --- | --- | --- | --- | -| `Received(Notification)` | `Event::Connected` / `Event::Disconnected` | `connection/update` | `publish_connection` | Immediate | -| `Received(Notification)` | `Event::Received(Packet::Data(_))` | `podData/update` | `publish_data` | 100 ms window | -| `Received(Notification)` | `Event::Received(Packet::Protection(_))` | `protection/update` | `publish_protection` | Immediate | -| `Received(Notification)` | `Event::Received(Packet::Message(_))` | `message/update` | `publish_message` | Immediate | -| `Received(Notification)` | `Event::Received(Packet::Order(_))` | — | Ignored (logged as warning) | — | -| `Problem(Problem)` | `ProblemKind::Shown` → `warning` | `message/update` | `publish_message` | Immediate | -| `Problem(Problem)` | `ProblemKind::Fatal` → `fault` | `message/update` | `publish_message` | Immediate | -| `Problem(Problem)` | `ProblemKind::Silent` | — | Ignored | — | -| `OrderSent` | Confirmed TCP write → `info` | `message/update` | `publish_message` | Immediate | -| `OrderFailed` | Failed TCP write → `warning` | `message/update` | `publish_message` | Immediate | +| `ToPipeline::Received` | `Event::Connected` / `Event::Disconnected` | `connection/update` | Updates `board_connections`; calls `publish_connection` on change | Immediate | +| `ToPipeline::Received` | `Event::Received(Packet::Data(_))` | `podData/update` | Accumulated; `publish_data` | 100 ms window | +| `ToPipeline::Received` | `Event::Received(Packet::Protection(_))` | `protection/update` | `publish_protection` | Immediate | +| `ToPipeline::Received` | `Event::Received(Packet::Message(_))` | `message/update` | `publish_message` | Immediate | +| `ToPipeline::Received` | `Event::Received(Packet::Order(_))` | — | Ignored (logged as warning) | — | +| `ToPipeline::Problem` | `ProblemKind::Shown` → `warning` | `message/update` | `publish_message` | Immediate | +| `ToPipeline::Problem` | `ProblemKind::Fatal` → `fault` | `message/update` | `publish_message` | Immediate | +| `ToPipeline::Problem` | `ProblemKind::Silent` | — | Ignored | — | +| `ToPipeline::OrderSent` | Confirmed TCP write → `info` | `message/update` | `publish_message` | Immediate | +| `ToPipeline::OrderFailed` | Failed TCP write → `warning` | `message/update` | `publish_message` | Immediate | +| `FrontendEvent` | `Connected(id)` / `Heartbeat(id)` / `Disconnected(id)` | `channels.problems` | Renews/tracks liveness; sends `ProblemKind::Fatal` on fatal loss | Immediate / Timer | ### Topics not handled by `pipeline` -- **Frontend-to-backend topics** (`order/send`, `logger/enable`, - `logger/variables`, `connection/heartbeat`) are handled directly by `websocket`. +- **Frontend-to-backend control topics** (`order/send`, `logger/enable`, + `logger/variables`) are handled directly by `websocket`. - **`logger/response`** is published directly by `logging`. - **`order/stateOrders`** is not produced yet because `software_core::model::Packet` has no state-orders packet variant. +## Board Connections (`pipeline.rs`) + +`pipeline` maintains a `HashMap` seeded at startup with every +board declared in `PodData::boards` set to `false` (disconnected). + +- On startup, all initial `false` states are published to `connection/update` so + the frontend immediately sees the full board list. +- Subsequent `Event::Connected` and `Event::Disconnected` notifications update + the map and only publish to `BrokerClient` when a board's state actually + changes. + ## 100 ms Data Aggregation (`accumulator.rs`) High-frequency telemetry (`Packet::Data`) is accumulated in place per packet ID @@ -72,8 +89,29 @@ and flushed every `Config::data_flush_interval` (default `100 ms`). - Boolean and enum measurements emit their latest value directly. - **Idle packets** (no frames received during a window) are skipped on flush; the WebSocket broker retains their previous snapshot. -- **Starvation protection:** the main `tokio::select!` uses `biased;` with the - flush timer polled first so sustained UDP rates cannot delay telemetry flushes. + +## Frontend Liveness & Keep-Alives (`frontend.rs`) + +`FrontendWatchdog` tracks `websocket ↔ front` session health via `FrontendEvent` +messages keyed by a per-connection session ID (`u64`): + +- **`FrontendEvent::Connected(id)` / `FrontendEvent::Heartbeat(id)`:** registers + or renews session `id`'s keep-alive deadline (`Config::frontend_heartbeat_timeout`, + default `3 s`) and cancels any armed reconnect grace deadline. +- **`FrontendEvent::Disconnected(id)`:** removes session `id`. If it was the + last active session, arms a reconnect grace window + (`Config::frontend_disconnect_timeout`, default `3 s`). +- **Independent session expiry:** if one tab goes silent without closing TCP + while another remains active, only the stale session expires after `3 s`. +- **Fatal reporting:** + - Startup with `0` connected frontends is not fatal; monitoring activates once + at least one frontend connects. + - Losing the last live session to a heartbeat timeout reports + `ProblemKind::Fatal` to `event` (`channels.problems`) immediately (the + heartbeat window already elapsed). + - Failing to reconnect before the post-disconnect grace deadline expires + reports `ProblemKind::Fatal` to `event`. + - Fatal disconnect is reported at most once. ## Messages & Timestamps (`message.rs`, `timestamp.rs`) @@ -90,12 +128,21 @@ and flushed every `Config::data_flush_interval` (default `100 ms`). `Notification::at` with the board's `ShortTimestamp` (`hour`, `minute`, `second`) and store its raw `subsecond` byte in `counter`. -## Contract & Shutdown +## Loop Priority, Contract & Shutdown +- **Biased `select!` priority:** `run_loop` polls branches in fixed order: + 1. Frontend heartbeat / reconnect timer (`sleep_until`) + 2. Incoming `FrontendEvent` messages from `websocket` + 3. 100 ms telemetry flush tick + 4. Incoming `ToPipeline` items from `event` + + Sustained high-rate UDP traffic cannot starve frontend disconnect detection or + telemetry flushes. - **Wait, don't drop.** `pipeline` reads continuously from `channels.pipeline` and awaits `BrokerClient` capacity rather than dropping decoded events. -- **No error policy.** Error classification and fault propagation belong solely - to `event`. +- **No network error policy.** Board/socket error classification and fault + propagation belong solely to `event`; `pipeline` only reports frontend loss as + a `ProblemKind::Fatal`. - **Clean shutdown.** - When `event` closes `channels.pipeline` (`recv()` returns `None`), `pipeline` flushes any dirty telemetry in the accumulator to the broker and exits. @@ -110,21 +157,36 @@ use station::pipeline::{self, Config}; let pipeline_handle = pipeline::spawn( Config::default(), channels.pipeline, + frontend_rx, + channels.problems.clone(), broker_client, pod_data, index, ); ``` +## Pending Integration (after `websocket` merges) + +- Wire `websocket` session transitions (`Connected(id)`, `Disconnected(id)`) and + inbound `connection/heartbeat` messages (`Heartbeat(id)`) into `frontend_rx`, + and remove duplicate liveness timers from `websocket`. +- If `websocket` / `payload` splits backend problems onto a dedicated + `problem/update` topic, switch the `ToPipeline::Problem` arm in `pipeline.rs` + from `publish_message` to `publish_problem`. + ## Tests Unit tests in `pipeline/tests.rs` wire `pipeline::spawn` to a real `Broker` instance (no sockets required) and verify: -- Immediate forwarding of connections, protections, board messages, problems, - and order outcomes (`OrderSent` / `OrderFailed`). +- Immediate forwarding of board connections, protections, board messages, + problems, and order outcomes (`OrderSent` / `OrderFailed`). - 100 ms windowing for `Packet::Data` (cumulative `count`, mean `cycleTime`, window `average`, `last`, and flush-on-shutdown). +- Frontend reconnect grace period cancellation and `ProblemKind::Fatal` emission + on expiry. +- Per-session `connection/heartbeat` renewal, independent stale-session expiry, + and immediate `ProblemKind::Fatal` when the last live frontend times out. - UTC calendar conversion on epoch and leap-day timestamps. Run them with: From 799f13512e250a516293522a81872e15be2fd68f Mon Sep 17 00:00:00 2001 From: Gazi Al Saad Halawani Date: Sat, 5 Dec 2026 11:13:13 +0100 Subject: [PATCH 204/225] Feat(backend, pipeline): Fixed merging conflicts --- backend/crates/station/src/pipeline.rs | 70 ++++++++++++------- .../station/src/pipeline/accumulator.rs | 6 +- .../crates/station/src/pipeline/message.rs | 22 +++--- backend/crates/station/src/pipeline/tests.rs | 52 ++++++++------ .../crates/station/src/pipeline/timestamp.rs | 4 -- 5 files changed, 92 insertions(+), 62 deletions(-) diff --git a/backend/crates/station/src/pipeline.rs b/backend/crates/station/src/pipeline.rs index ab7931c4c..3d0deeb94 100644 --- a/backend/crates/station/src/pipeline.rs +++ b/backend/crates/station/src/pipeline.rs @@ -42,11 +42,11 @@ use std::sync::Arc; use std::time::Duration; use crate::event::{Problem, ProblemKind, ToPipeline}; -use crate::payload::{Connection, ProtectionUpdate}; +use crate::payload::{Connection, ProtectionUpdate, ConnectionUpdate, DataPacketUpdate, DataUpdate}; use crate::websocket::broker::BrokerClient; use accumulator::DataAccumulator; use frontend::FrontendWatchdog; -use software_core::model::{BoardId, Packet, PodData}; +use software_core::model::{BoardId, Packet, PodData, AdjId}; use software_core::net::{Event, Notification}; use software_core::protocol::Index; use tokio::sync::mpsc; @@ -133,16 +133,19 @@ async fn run_loop( pod_data.boards.keys().map(|&id| (id, false)).collect(); // Publish initial `false` states so the frontend immediately sees all boards. - for (&id, &is_connected) in &board_connections { - let update = Connection { - name: message::board_name(&pod_data, id), - is_connected, - }; - if !publish_or_log(broker.publish_connection(update).await) { - return; - } + if !board_connections.is_empty() + && !publish_or_log( + broker + .publish_connections(connection_snapshot(&board_connections, &pod_data)) + .await, + ) + { + return; } + // Holds the latest snapshot per packet ID because `Broker::publish_data` replaces the whole map. + let mut latest_data: HashMap = HashMap::new(); + loop { let frontend_deadline = watchdog.deadline(); @@ -178,7 +181,7 @@ async fn run_loop( } // 3. Periodic 100 ms telemetry flush. _ = tick.tick() => { - if !flush_data(&broker, &index, &mut accumulator).await { + if !flush_data(&broker, &index, &mut accumulator, &mut latest_data).await { return; } } @@ -193,7 +196,7 @@ async fn run_loop( None => { // Upstream (`event`) closed: perform a best-effort flush of any // buffered telemetry before exiting. - let _ = flush_data(&broker, &index, &mut accumulator).await; + let _ = flush_data(&broker, &index, &mut accumulator, &mut latest_data).await; return; } } @@ -255,22 +258,22 @@ async fn handle_notification( match ¬ification.event { Event::Connected | Event::Disconnected => { let is_connected = matches!(notification.event, Event::Connected); - // Only publish when a board's connection state actually changes. if board_connections.insert(notification.board, is_connected) == Some(is_connected) { return true; } - let update = Connection { - name: message::board_name(pod_data, notification.board), - is_connected, - }; - publish_or_log(broker.publish_connection(update).await) + let snapshot = connection_snapshot(board_connections, pod_data); + publish_or_log(broker.publish_connections(snapshot).await) } Event::Received(Packet::Data(data)) => { accumulator.record(data, notification.at, index); true } Event::Received(Packet::Protection(protection)) => { - let update = ProtectionUpdate::from(protection.clone()); + let update = ProtectionUpdate { + id: protection.id, + value: protection.value.clone(), + timestamp: timestamp::from_short(notification.at, protection.timestamp), + }; publish_or_log(broker.publish_protection(update).await) } Event::Received(Packet::Message(msg)) => { @@ -311,13 +314,16 @@ async fn flush_data( broker: &BrokerClient, index: &Index, accumulator: &mut DataAccumulator, + latest_data: &mut HashMap, ) -> bool { - for update in accumulator.drain_updates(index) { - if !publish_or_log(broker.publish_data(update).await) { - return false; - } + let updates = accumulator.drain_updates(index); + if updates.is_empty() { + return true; } - true + for update in updates { + latest_data.insert(update.id, update); + } + publish_or_log(broker.publish_data(DataUpdate(latest_data.clone())).await) } /// Converts a broker publish result into a loop-continuation flag (`true` to @@ -331,3 +337,19 @@ fn publish_or_log(result: Result<(), crate::websocket::broker::Error>) -> bool { } } } + +/// Builds the full `connection/update` snapshot from `board_connections`. +fn connection_snapshot( + board_connections: &HashMap, + pod_data: &PodData, +) -> ConnectionUpdate { + ConnectionUpdate( + board_connections + .iter() + .map(|(&id, &is_connected)| { + let name = message::board_name(pod_data, id); + (name.clone(), Connection { name, is_connected }) + }) + .collect(), + ) +} diff --git a/backend/crates/station/src/pipeline/accumulator.rs b/backend/crates/station/src/pipeline/accumulator.rs index 247d0d157..e977eef7e 100644 --- a/backend/crates/station/src/pipeline/accumulator.rs +++ b/backend/crates/station/src/pipeline/accumulator.rs @@ -188,17 +188,15 @@ impl DataAccumulator { // `slot.take()` moves the accumulator out and resets the slot to // `None` in one step, preparing it cleanly for the next 100 ms window. - let mut measurement_updates = HashMap::with_capacity(defs.len()); + let mut measurement_updates: HashMap = HashMap::with_capacity(defs.len()); for (measurement_def, slot) in defs.iter().zip(window.measurements.iter_mut()) { if let Some(acc) = slot.take() { - measurement_updates.insert(measurement_def.alias.clone(), acc.into_update()); + measurement_updates.insert(measurement_def.id.clone(), acc.into_update()); } } updates.push(DataPacketUpdate { id, - // Raw wire bytes are not carried by `Notification`; left empty. - hex_value: String::new(), count: window.count, cycle_time: window.last_cycle_time_ns, measurement_updates, diff --git a/backend/crates/station/src/pipeline/message.rs b/backend/crates/station/src/pipeline/message.rs index 52ca96dca..09e7f3676 100644 --- a/backend/crates/station/src/pipeline/message.rs +++ b/backend/crates/station/src/pipeline/message.rs @@ -2,8 +2,8 @@ use std::time::SystemTime; use super::timestamp; use crate::event::{Problem, ProblemKind}; -use crate::payload::{MessageKind, MessagePayload, MessageUpdate}; -use software_core::model::{AdjId, BoardId, MessagePacket, OrderPacket, PacketType, PodData}; +use crate::payload::{MessagePayload, MessageUpdate}; +use software_core::model::{MessageLevel, AdjId, BoardId, MessagePacket, OrderPacket, PacketType, PodData}; use software_core::protocol::Index; use tracing::warn; @@ -29,18 +29,18 @@ pub(super) fn from_board_message( ) -> MessageUpdate { let kind = match index.packet(message.id) { Some(def) => match def.packet_type { - PacketType::Message(level) => MessageKind::from(level), + PacketType::Message(level) => MessageLevel::from(level), _ => { warn!( id = message.id.0, "message packet id does not map to PacketType::Message" ); - MessageKind::Info + MessageLevel::Info } }, None => { warn!(id = message.id.0, "unknown message packet id in index"); - MessageKind::Info + MessageLevel::Info } }; @@ -54,6 +54,7 @@ pub(super) fn from_board_message( kind, payload: MessagePayload::Text(message.message.clone()), board: board_name(pod_data, board), + origin: String::new(), name, timestamp: timestamp::from_short(at, message.timestamp), } @@ -63,8 +64,8 @@ pub(super) fn from_board_message( /// for [`ProblemKind::Silent`] problems that should not be shown on the front. pub(super) fn from_problem(problem: Problem, pod_data: &PodData) -> Option { let kind = match problem.kind { - ProblemKind::Shown => MessageKind::Warning, - ProblemKind::Fatal => MessageKind::Fault, + ProblemKind::Shown => MessageLevel::Warning, + ProblemKind::Fatal => MessageLevel::Fault, ProblemKind::Silent => return None, }; @@ -76,6 +77,7 @@ pub(super) fn from_problem(problem: Problem, pod_data: &PodData) -> Option Result<(), Box> { let (pod_data, index) = sample_fixture(); let (broker, client) = Broker::new(); - let mut conn_sub = client.subscribe_connections(); - let mut msg_sub = client.subscribe_messages()?; - let mut prot_sub = client.subscribe_protections()?; + let sub = client.subscriber(); + let mut conn_sub = sub.subscribe_connections(); + let mut msg_sub = sub.subscribe_messages()?; + let mut prot_sub = sub.subscribe_protections()?; let broker_task = tokio::spawn(broker.run()); let (tx, rx) = mpsc::channel(32); @@ -124,7 +125,7 @@ async fn forwards_connections_protections_messages_problems_and_orders_immediate }))) .await?; timeout(Duration::from_secs(1), conn_sub.changed()).await??; - assert!(conn_sub.borrow_and_update()["PCU"].is_connected); + assert!(conn_sub.borrow_and_update().0["PCU"].is_connected); // 2. Protection event // Compound ADJv3 protection ID: high 3 bits = protection slot (1), low 13 bits = measurement ID (3001). @@ -138,6 +139,18 @@ async fn forwards_connections_protections_messages_problems_and_orders_immediate }, value: Value::Number(48.5), }; + let protection_update = ProtectionUpdate { + id: AdjId((1 << 13) | 3001), + timestamp: MessageTimestamp { + second: 56, + minute: 34, + hour: 12, + day: 14, + month: 11, + year: 2023, + }, + value: Value::Number(48.5), + }; tx.send(ToPipeline::Received(Arc::new(Notification { board: BoardId(5), at: UNIX_EPOCH + Duration::from_secs(1_700_000_001), @@ -145,7 +158,7 @@ async fn forwards_connections_protections_messages_problems_and_orders_immediate }))) .await?; let got_prot = timeout(Duration::from_secs(1), prot_sub.recv()).await??; - assert_eq!(got_prot, ProtectionUpdate::from(protection)); + assert_eq!(got_prot, protection_update); // 3. Board message tx.send(ToPipeline::Received(Arc::new(Notification { @@ -165,7 +178,7 @@ async fn forwards_connections_protections_messages_problems_and_orders_immediate }))) .await?; let got_msg = timeout(Duration::from_secs(1), msg_sub.recv()).await??; - assert_eq!(got_msg.kind, MessageKind::Warning); + assert_eq!(got_msg.kind, MessageLevel::Warning); assert_eq!(got_msg.board, "PCU"); assert_eq!(got_msg.name, "pcu.c"); assert_eq!( @@ -173,7 +186,6 @@ async fn forwards_connections_protections_messages_problems_and_orders_immediate MessagePayload::Text("temp high".to_string()) ); assert_eq!(got_msg.timestamp.hour, 1); - assert_eq!(got_msg.timestamp.counter, 4); // 4. Problem (Fatal -> Fault) tx.send(ToPipeline::Problem(Problem { @@ -184,7 +196,7 @@ async fn forwards_connections_protections_messages_problems_and_orders_immediate })) .await?; let got_problem = timeout(Duration::from_secs(1), msg_sub.recv()).await??; - assert_eq!(got_problem.kind, MessageKind::Fault); + assert_eq!(got_problem.kind, MessageLevel::Fault); assert_eq!(got_problem.board, "PCU"); assert_eq!( got_problem.payload, @@ -199,7 +211,7 @@ async fn forwards_connections_protections_messages_problems_and_orders_immediate }) .await?; let got_sent = timeout(Duration::from_secs(1), msg_sub.recv()).await??; - assert_eq!(got_sent.kind, MessageKind::Info); + assert_eq!(got_sent.kind, MessageLevel::Info); assert_eq!(got_sent.name, "1001"); assert_eq!(got_sent.board, "PCU"); @@ -210,7 +222,7 @@ async fn forwards_connections_protections_messages_problems_and_orders_immediate }) .await?; let got_failed = timeout(Duration::from_secs(1), msg_sub.recv()).await??; - assert_eq!(got_failed.kind, MessageKind::Warning); + assert_eq!(got_failed.kind, MessageLevel::Warning); assert_eq!(got_failed.name, "1001"); assert_eq!( got_failed.payload, @@ -233,7 +245,7 @@ async fn batches_data_every_100ms_with_window_average_last_and_cycle_time() -> Result<(), Box> { let (pod_data, index) = sample_fixture(); let (broker, client) = Broker::new(); - let mut data_sub = client.subscribe_data(); + let mut data_sub = client.subscriber().subscribe_data(); let broker_task = tokio::spawn(broker.run()); let (tx, rx) = mpsc::channel(32); @@ -283,23 +295,23 @@ async fn batches_data_every_100ms_with_window_average_last_and_cycle_time() advance(Duration::from_millis(100)).await; timeout(Duration::from_millis(10), data_sub.changed()).await??; - let first = data_sub.borrow_and_update()[&551].clone(); + let first = data_sub.borrow_and_update().0[&AdjId(551)].clone(); assert_eq!(first.count, 3); // Deltas were 20 ms and 30 ms -> average 25 ms = 25_000_000 ns. assert_eq!(first.cycle_time, 25_000_000); assert_eq!( - first.measurement_updates["voltage_battery_a"], + first.measurement_updates[&AdjId(3001)], MeasurementUpdate::Numeric { last: 30.0, average: 20.0, } ); assert_eq!( - first.measurement_updates["is_active"], + first.measurement_updates[&AdjId(3002)], MeasurementUpdate::Boolean(true) ); assert_eq!( - first.measurement_updates["state"], + first.measurement_updates[&AdjId(3003)], MeasurementUpdate::Enum("Fault".to_string()) ); @@ -323,11 +335,11 @@ async fn batches_data_every_100ms_with_window_average_last_and_cycle_time() timeout(Duration::from_secs(1), pipe_task).await??; timeout(Duration::from_secs(1), broker_task).await??; - let second = data_sub.borrow_and_update()[&551].clone(); + let second = data_sub.borrow_and_update().0[&AdjId(551)].clone(); assert_eq!(second.count, 4); assert_eq!(second.cycle_time, 100_000_000); assert_eq!( - second.measurement_updates["voltage_battery_a"], + second.measurement_updates[&AdjId(3001)], MeasurementUpdate::Numeric { last: 50.0, average: 50.0, @@ -458,7 +470,6 @@ fn utc_calendar_conversion_handles_epoch_and_leap_day() { assert_eq!( epoch, MessageTimestamp { - counter: 0, second: 0, minute: 0, hour: 0, @@ -475,7 +486,6 @@ fn utc_calendar_conversion_handles_epoch_and_leap_day() { assert_eq!( leap, MessageTimestamp { - counter: 250, second: 9, minute: 45, hour: 13, diff --git a/backend/crates/station/src/pipeline/timestamp.rs b/backend/crates/station/src/pipeline/timestamp.rs index 912f09226..3292dc35f 100644 --- a/backend/crates/station/src/pipeline/timestamp.rs +++ b/backend/crates/station/src/pipeline/timestamp.rs @@ -17,11 +17,8 @@ pub(super) fn from_system_time(at: SystemTime) -> MessageTimestamp { let hour = u8::try_from(secs_of_day / 3_600).unwrap_or(0); let minute = u8::try_from((secs_of_day % 3_600) / 60).unwrap_or(0); let second = u8::try_from(secs_of_day % 60).unwrap_or(0); - // Backend-originated messages use millisecond subsecond ticks (0–999) as the RTC counter. - let counter = u16::try_from(dur.subsec_millis()).unwrap_or(0); MessageTimestamp { - counter, second, minute, hour, @@ -36,7 +33,6 @@ pub(super) fn from_system_time(at: SystemTime) -> MessageTimestamp { pub(super) fn from_short(received_at: SystemTime, short: ShortTimestamp) -> MessageTimestamp { let date = from_system_time(received_at); MessageTimestamp { - counter: u16::from(short.subsecond), second: short.second, minute: short.minute, hour: short.hour, From 9e7e13aa18428d8f78bb50c83ca9c7a7d94e3b48 Mon Sep 17 00:00:00 2001 From: Gazi Al Saad Halawani Date: Sat, 5 Dec 2026 11:36:40 +0100 Subject: [PATCH 205/225] Feat(backend, pipeline): Upload of test used. --- .../station/src/examples/podDataTest.rs | 519 ++++++++++++++++++ 1 file changed, 519 insertions(+) create mode 100644 backend/crates/station/src/examples/podDataTest.rs diff --git a/backend/crates/station/src/examples/podDataTest.rs b/backend/crates/station/src/examples/podDataTest.rs new file mode 100644 index 000000000..2ab9d056c --- /dev/null +++ b/backend/crates/station/src/examples/podDataTest.rs @@ -0,0 +1,519 @@ +//! Temporary test harness: runs `UDP + synthetic board traffic -> event -> pipeline -> Broker`. +//! Remember to revert with `git checkout -- crates/station/src/main.rs` before committing. + +use std::collections::HashMap; +use std::net::SocketAddr; +use std::path::PathBuf; +use std::process::ExitCode; +use std::sync::Arc; +use std::time::{Duration, SystemTime}; + +use software_core::adj::{self, Adj, LoadError}; +use software_core::git::{self, GitError}; +use software_core::model::{ + AdjId, BoardId, DataPacket, MeasurementKind, OrderPacket, Packet, PacketType, PodData, + ProtectionPacket, ShortTimestamp, Value, +}; +use software_core::net::udp::{UdpConfig, UdpError, spawn_udp}; +use software_core::net::{Event, Notification}; +use software_core::protocol::Index; +use tokio::sync::{broadcast, mpsc}; +use tokio::task::JoinError; +use tokio::time::MissedTickBehavior; +use tracing::{debug, error, info, warn}; +use tracing_subscriber::EnvFilter; + +use station::event::{self, Problem, ProblemKind, Stop, ToLogging, ToPipeline}; +use station::pipeline::{self, Config as PipelineConfig, FrontendEvent}; +use station::websocket::broker::{Broker, Subscriber}; + +const ADJ_BRANCH: &str = "adjv3-software"; +const RECV_BUFFER: usize = 2 * 1024 * 1024; +const SUMMARY_EVERY: Duration = Duration::from_secs(1); +const SHUTDOWN_GRACE: Duration = Duration::from_secs(5); + +#[derive(Debug, thiserror::Error)] +enum StartError { + #[error("could not get the ADJ (branch {ADJ_BRANCH})")] + Download(#[source] GitError), + #[error("the downloaded ADJ has no working directory")] + NoWorkdir, + #[error("could not load the ADJ from {path}")] + Load { + path: PathBuf, + #[source] + source: LoadError, + }, + #[error("the ADJ's general_info.json has no `{0}`")] + MissingInAdj(&'static str), + #[error("could not start tokio")] + Runtime(#[source] std::io::Error), + #[error("could not listen for Ctrl+C")] + CtrlC(#[source] std::io::Error), + #[error("could not open the UDP port")] + Bind(#[source] UdpError), + #[error("the event task failed")] + Event(#[source] JoinError), +} + +fn main() -> ExitCode { + let filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info")); + tracing_subscriber::fmt().with_env_filter(filter).init(); + + match run() { + Ok(code) => code, + Err(error) => { + error!(error = %event::full_message(&error), "stopping"); + ExitCode::FAILURE + } + } +} + +fn run() -> Result { + let adj = download_adj()?; + let addr = udp_addr(&adj)?; + let index = Arc::new(Index::new(&adj.pod_data, Some(&adj.info.message_levels))); + let pod_data = Arc::new(adj.pod_data); + + let runtime = tokio::runtime::Runtime::new().map_err(StartError::Runtime)?; + runtime.block_on(serve(addr, index, pod_data)) +} + +fn download_adj() -> Result { + let commit = git::update_adj(None, ADJ_BRANCH).map_err(StartError::Download)?; + let repo = git::open_repo(None).map_err(StartError::Download)?; + let path = repo.workdir().ok_or(StartError::NoWorkdir)?.to_path_buf(); + + let adj = adj::load_from_dir(&path).map_err(|source| StartError::Load { + path: path.clone(), + source, + })?; + info!( + branch = ADJ_BRANCH, + %commit, + path = %path.display(), + boards = adj.pod_data.boards.len(), + "ADJ loaded" + ); + Ok(adj) +} + +fn udp_addr(adj: &Adj) -> Result { + let ip = adj + .info + .addresses + .get("backend") + .ok_or(StartError::MissingInAdj("addresses.backend"))?; + let port = adj + .info + .ports + .get("UDP") + .ok_or(StartError::MissingInAdj("ports.UDP"))?; + Ok(SocketAddr::new(*ip, port.0)) +} + +async fn serve( + addr: SocketAddr, + index: Arc, + pod_data: Arc, +) -> Result { + let config = event::EventConfig::default(); + let event::Channels { + udp, + tcp, + event: ends, + orders, + problems, + logging, + pipeline: event_pipeline_rx, + } = event::channels(&config); + + drop(tcp); + + let udp_task = spawn_udp( + UdpConfig { + addr, + recv_buffer: RECV_BUFFER, + boards: pod_data.boards_by_ip(), + }, + index.clone(), + udp, + ) + .map_err(StartError::Bind)?; + info!(%addr, "listening on UDP (Ctrl+C to stop)"); + + // Real websocket Broker + console monitor acting as the frontend subscriber. + let (broker, broker_client) = Broker::new(); + let subscriber = broker_client.subscriber(); + let broker_task = tokio::spawn(broker.run()); + let monitor_task = tokio::spawn(monitor_broker(subscriber)); + + // Merge real `event -> pipeline` output with our synthetic board events. + let (pipe_tx, pipe_rx) = mpsc::channel::(128); + let bridge_tx = pipe_tx.clone(); + let bridge_task = tokio::spawn(async move { + let mut rx = event_pipeline_rx; + while let Some(item) = rx.recv().await { + if bridge_tx.send(item).await.is_err() { + break; + } + } + }); + + let (frontend_tx, frontend_rx) = mpsc::channel::(16); + + let logging_task = tokio::spawn(stand_in_logging(logging, pod_data.clone())); + let pipeline_task = pipeline::spawn( + PipelineConfig::default(), + pipe_rx, + frontend_rx, + problems.clone(), + broker_client, + pod_data.clone(), + index.clone(), + ); + let mut event_task = event::spawn(config, ends, pod_data.clone(), index, None); + + // Inject synthetic events using the real ADJ definitions. + let sim_task = tokio::spawn(simulate_traffic( + pod_data, + pipe_tx, + orders, + problems, + frontend_tx, + )); + + let (stop, by_ctrl_c) = tokio::select! { + stop = &mut event_task => (stop, false), + signal = tokio::signal::ctrl_c() => { + signal.map_err(StartError::CtrlC)?; + info!("Ctrl+C, stopping"); + udp_task.abort(); + sim_task.abort(); + (event_task.await, true) + } + }; + udp_task.abort(); + sim_task.abort(); + + let finished = tokio::time::timeout(SHUTDOWN_GRACE, async { + let _ = bridge_task.await; + let _ = logging_task.await; + let _ = pipeline_task.await; + let _ = broker_task.await; + let _ = monitor_task.await; + }) + .await; + if finished.is_err() { + warn!(grace = ?SHUTDOWN_GRACE, "tasks did not finish in time"); + } + + match stop.map_err(StartError::Event)? { + Stop::Fatal(problem) => { + info!(reason = %problem.text, "stopped after a fatal error"); + Ok(ExitCode::FAILURE) + } + Stop::NetGone if by_ctrl_c => { + info!("stopped"); + Ok(ExitCode::SUCCESS) + } + Stop::NetGone => { + error!("UDP stopped on its own"); + Ok(ExitCode::FAILURE) + } + } +} + +/// Feeds a short sequence of realistic ADJ events through `event` and `pipeline`. +async fn simulate_traffic( + pod_data: Arc, + pipe_tx: mpsc::Sender, + orders: mpsc::Sender, + problems: mpsc::Sender, + frontend_tx: mpsc::Sender, +) { + // Pick the first board that declares at least one Data packet in the loaded ADJ. + let Some((board_id, data_id, first_meas_id)) = pod_data.boards.values().find_map(|board| { + board + .packets + .values() + .find_map(|def| match &def.packet_type { + PacketType::Data(defs) if !defs.is_empty() => { + Some((board.id, def.id, defs[0].id)) + } + _ => None, + }) + }) else { + warn!("no Data packets found in ADJ to simulate"); + return; + }; + + let order_id = pod_data + .boards + .values() + .find_map(|board| { + board + .packets + .values() + .find_map(|def| match &def.packet_type { + PacketType::Order(_) => Some(def.id), + _ => None, + }) + }) + .unwrap_or(AdjId(1001)); + + info!( + board = %name(&pod_data, board_id), + data_packet = data_id.0, + order_packet = order_id.0, + "starting synthetic scenario" + ); + + // 1. Frontend connects. + let _ = frontend_tx.send(FrontendEvent::Connected(1)).await; + tokio::time::sleep(Duration::from_millis(200)).await; + + // 2. Board connects -> `connection/update`. + let _ = pipe_tx + .send(ToPipeline::Received(Arc::new(Notification { + board: board_id, + at: SystemTime::now(), + event: Event::Connected, + }))) + .await; + + // 3. Burst of 16 Data packets (1 every 25 ms -> ~4 aggregated 100 ms `podData/update` flushes). + for step in 1_u32..=16 { + let values = match pod_data + .boards + .get(&board_id) + .and_then(|b| b.packets.get(&data_id)) + .map(|def| &def.packet_type) + { + Some(PacketType::Data(defs)) => defs + .iter() + .map(|m| match &m.kind { + MeasurementKind::Numeric { .. } => Value::Number(f64::from(step) * 10.0), + MeasurementKind::Boolean => Value::Bool(step % 2 == 0), + MeasurementKind::Enum { options } => { + let idx = (step as usize) % options.len().max(1); + Value::Enum(options.get(idx).cloned().unwrap_or_default()) + } + }) + .collect(), + _ => Vec::new(), + }; + + let _ = pipe_tx + .send(ToPipeline::Received(Arc::new(Notification { + board: board_id, + at: SystemTime::now(), + event: Event::Received(Packet::Data(DataPacket::new(data_id, values))), + }))) + .await; + + tokio::time::sleep(Duration::from_millis(25)).await; + } + + // 4. Protection packet -> `protection/update`. + let _ = pipe_tx + .send(ToPipeline::Received(Arc::new(Notification { + board: board_id, + at: SystemTime::now(), + event: Event::Received(Packet::Protection(ProtectionPacket { + id: AdjId((1 << 13) | (first_meas_id.0 & 0x1FFF)), + timestamp: ShortTimestamp { + hour: 12, + minute: 30, + second: 45, + subsecond: 0, + }, + value: Value::Number(99.5), + })), + }))) + .await; + tokio::time::sleep(Duration::from_millis(200)).await; + + // 5. Real `event` round-trip: Problem & OrderPacket go through `event -> pipeline -> Broker`. + let _ = problems + .send(Problem::now( + ProblemKind::Shown, + Some(board_id), + "simulated warning through event", + )) + .await; + let _ = orders.send(OrderPacket::new(order_id, vec![])).await; + tokio::time::sleep(Duration::from_millis(200)).await; + + // 6. Board disconnects -> `connection/update`. + let _ = pipe_tx + .send(ToPipeline::Received(Arc::new(Notification { + board: board_id, + at: SystemTime::now(), + event: Event::Disconnected, + }))) + .await; + + info!("synthetic scenario complete — keeping frontend heartbeat alive (press Ctrl+C to stop)"); + + // 7. Keep frontend alive. Comment out this loop to test the 3 s fatal watchdog! + let mut hb = tokio::time::interval(Duration::from_secs(1)); + loop { + hb.tick().await; + if frontend_tx.send(FrontendEvent::Heartbeat(1)).await.is_err() { + break; + } + } +} + +/// Logs every topic published through `websocket::Broker` by `pipeline`. +async fn monitor_broker(sub: Subscriber) { + let mut conn_sub = sub.subscribe_connections(); + let mut data_sub = sub.subscribe_data(); + let msg_sub = sub.subscribe_messages(); + let prot_sub = sub.subscribe_protections(); + let backend_sub = sub.subscribe_backend_messages(); + + let connections = async move { + while conn_sub.changed().await.is_ok() { + let snap = conn_sub.borrow_and_update(); + info!(boards = ?snap.0, "broker -> connection/update"); + } + }; + + let data = async move { + while data_sub.changed().await.is_ok() { + let snap = data_sub.borrow_and_update(); + for pkt in snap.0.values() { + info!( + id = pkt.id.0, + count = pkt.count, + cycle_time_ns = pkt.cycle_time, + measurements = ?pkt.measurement_updates, + "broker -> podData/update" + ); + } + } + }; + + let messages = async move { + let Ok(mut rx) = msg_sub else { return }; + loop { + match rx.recv().await { + Ok(msg) => info!(?msg, "broker -> message/update"), + Err(broadcast::error::RecvError::Lagged(n)) => { + warn!(skipped = n, "message/update lagged"); + } + Err(broadcast::error::RecvError::Closed) => break, + } + } + }; + + let protections = async move { + let Ok(mut rx) = prot_sub else { return }; + loop { + match rx.recv().await { + Ok(prot) => info!(?prot, "broker -> protection/update"), + Err(broadcast::error::RecvError::Lagged(n)) => { + warn!(skipped = n, "protection/update lagged"); + } + Err(broadcast::error::RecvError::Closed) => break, + } + } + }; + + let backend_messages = async move { + let Ok(mut rx) = backend_sub else { return }; + loop { + match rx.recv().await { + Ok(msg) => info!(?msg, "broker -> backend/message"), + Err(broadcast::error::RecvError::Lagged(n)) => { + warn!(skipped = n, "backend/message lagged"); + } + Err(broadcast::error::RecvError::Closed) => break, + } + } + }; + + tokio::join!(connections, data, messages, protections, backend_messages); +} + +async fn stand_in_logging(mut queue: mpsc::Receiver, pod_data: Arc) { + let mut summary = tokio::time::interval(SUMMARY_EVERY); + summary.set_missed_tick_behavior(MissedTickBehavior::Delay); + let mut counts: HashMap = HashMap::new(); + + loop { + tokio::select! { + biased; + _ = summary.tick() => log_summary(&mut counts, &pod_data), + message = queue.recv() => match message { + None => break, + Some(ToLogging::Received(notification)) => { + count_and_trace(¬ification, &mut counts, &pod_data); + } + Some(ToLogging::OrderSent { at, board, order }) => { + let to = order_target(board, &pod_data); + info!(to, id = ?order.id, at = %clock(at), "order sent"); + } + }, + } + } + log_summary(&mut counts, &pod_data); +} + +fn order_target(board: Option, pod_data: &PodData) -> String { + match board { + Some(board) => name(pod_data, board), + None => "every board".to_string(), + } +} + +fn name(pod_data: &PodData, board: BoardId) -> String { + pod_data + .board_name(board) + .map_or_else(|| format!("{board:?}"), str::to_owned) +} + +fn clock(at: SystemTime) -> String { + match at.duration_since(SystemTime::UNIX_EPOCH) { + Ok(since) => format!("{}.{:03}", since.as_secs(), since.subsec_millis()), + Err(_) => "before 1970".to_string(), + } +} + +fn count_and_trace( + notification: &Notification, + counts: &mut HashMap, + pod_data: &PodData, +) { + *counts.entry(notification.board).or_insert(0) += 1; + + match ¬ification.event { + Event::Received(Packet::Data(packet)) => debug!( + board = %name(pod_data, notification.board), + id = ?packet.id, + values = ?packet.values, + "packet" + ), + other => debug!( + board = %name(pod_data, notification.board), + event = ?other, + "notification" + ), + } +} + +fn log_summary(counts: &mut HashMap, pod_data: &PodData) { + let total: u64 = counts.values().sum(); + if total == 0 { + return; + } + let mut per_board: Vec = counts + .iter() + .map(|(&board, count)| format!("{}={count}", name(pod_data, board))) + .collect(); + per_board.sort(); + info!(total, boards = %per_board.join(" "), "packets in the last second"); + counts.clear(); +} \ No newline at end of file From c59a155d0758e2fdac012ad3d0e540fea21e7c26 Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Sat, 5 Dec 2026 12:05:48 +0100 Subject: [PATCH 206/225] refactor(backend, event): Problem becomes Notice, with an Info level for news that is not an error --- backend/crates/station/src/event.rs | 61 +++++++----- backend/crates/station/src/event/README.md | 86 +++++++++------- backend/crates/station/src/event/fault.rs | 6 +- .../crates/station/src/event/manual_tests.rs | 4 +- backend/crates/station/src/event/policy.rs | 21 ++-- backend/crates/station/src/event/router.rs | 99 +++++++++---------- backend/crates/station/src/event/tests.rs | 81 +++++++-------- backend/crates/station/src/main.rs | 33 ++++--- 8 files changed, 207 insertions(+), 184 deletions(-) diff --git a/backend/crates/station/src/event.rs b/backend/crates/station/src/event.rs index 5749e36b3..e8cdf82cf 100644 --- a/backend/crates/station/src/event.rs +++ b/backend/crates/station/src/event.rs @@ -70,8 +70,8 @@ pub trait TcpLink: Send + Sync { pub struct EventConfig { /// Slots in each of `net`'s error queues (①, one per transport). pub errors_queue: usize, - /// Slots in ② (problems from station modules). - pub problems_queue: usize, + /// Slots in ② (notices from station modules). + pub notices_queue: usize, /// Slots in ③ (TCP notifications). pub tcp_queue: usize, /// Slots in ④ (UDP notifications). The only stretch of queue between the @@ -94,7 +94,7 @@ impl Default for EventConfig { fn default() -> Self { Self { errors_queue: 16, - problems_queue: 16, + notices_queue: 16, tcp_queue: 1024, udp_queue: 8192, logging_queue: 8192, @@ -106,23 +106,25 @@ impl Default for EventConfig { } } -/// Something the operator has to see. +/// Something the operator is told: an error, or just news ("recording +/// started"). Its [`NoticeKind`] says which, and what the backend does about +/// it. #[derive(Debug, Clone, PartialEq, Eq)] -pub struct Problem { - /// When it was detected. +pub struct Notice { + /// When it happened. pub at: SystemTime, - /// The board, if known. + /// The board, if it concerns one. pub board: Option, - /// What it means for the backend. - pub kind: ProblemKind, - /// The message with all its causes: "could not X: because Y: because Z" - /// (see [`full_message`]). + /// How it is shown, and what it means for the backend. + pub kind: NoticeKind, + /// The text. For an error, the message with all its causes: "could not + /// X: because Y: because Z" (see [`full_message`]). pub text: String, } -impl Problem { - /// A problem detected now. - pub fn now(kind: ProblemKind, board: Option, text: impl Into) -> Self { +impl Notice { + /// A notice of something that happened now. + pub fn now(kind: NoticeKind, board: Option, text: impl Into) -> Self { Self { at: SystemTime::now(), board, @@ -132,11 +134,14 @@ impl Problem { } } -/// What a [`Problem`] means for the backend. +/// How a [`Notice`] is shown, and what it means for the backend. #[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum ProblemKind { - /// Shown on the front; the backend keeps running. - Shown, +pub enum NoticeKind { + /// News, not an error: shown on the front as information; the backend + /// keeps running. + Info, + /// Shown on the front as a warning; the backend keeps running. + Warning, /// The fault is sent, it is shown on the front and the backend stops. Fatal, /// Only written to the trace: not shown, the backend keeps running. @@ -167,8 +172,9 @@ pub enum ToPipeline { /// A notification, TCP or UDP, as soon as it arrives. `logging` gets the /// same copy. Received(Arc), - /// Something the operator has to see. - Problem(Problem), + /// Something the operator is told, shown on the front as a message from + /// the backend: as information, a warning or a fatal error, by its kind. + Notice(Notice), /// An order the front sent that went out: shown on the front as a message /// from the backend. OrderSent { @@ -195,8 +201,9 @@ pub enum ToPipeline { /// Why `event` ended. `main` reads it and shuts everything down in order. #[derive(Debug)] pub enum Stop { - /// A fatal error: shown on the front, fault sent (or attempted). - Fatal(Problem), + /// A fatal error, with the notice that told it: fault sent (or + /// attempted), shown on the front. + Fatal(Notice), /// `net`'s queues closed: UDP and TCP were stopped. NetGone, } @@ -220,8 +227,8 @@ pub struct Channels { pub event: EventEnds, /// ⑦, for websocket's order forwarder. pub orders: mpsc::Sender, - /// ②, cloned for every station module that reports problems. - pub problems: mpsc::Sender, + /// ②, cloned for every station module that reports notices. + pub notices: mpsc::Sender, /// ⑤, for `logging`. pub logging: mpsc::Receiver, /// ⑥, for `pipeline`. @@ -252,7 +259,7 @@ pub fn channels(config: &EventConfig) -> Channels { // Channel creation let (udp, udp_sinks) = Reporter::channels(udp_capacity, errors); let (tcp, tcp_sinks) = Reporter::channels(tcp_capacity, errors); - let (problems_tx, problems_rx) = mpsc::channel(config.problems_queue.max(1)); + let (notices_tx, notices_rx) = mpsc::channel(config.notices_queue.max(1)); let (orders_tx, orders_rx) = mpsc::channel(config.orders_queue.max(1)); let (logging_tx, logging_rx) = mpsc::channel(config.logging_queue.max(1)); let (pipeline_tx, pipeline_rx) = mpsc::channel(config.pipeline_queue.max(1)); @@ -264,7 +271,7 @@ pub fn channels(config: &EventConfig) -> Channels { router: RouterEnds { udp: udp_sinks, tcp: tcp_sinks, - problems: problems_rx, + notices: notices_rx, logging: logging_tx, pipeline: pipeline_tx, tcp_capacity, @@ -273,7 +280,7 @@ pub fn channels(config: &EventConfig) -> Channels { orders: orders_rx, }, orders: orders_tx, - problems: problems_tx, + notices: notices_tx, logging: logging_rx, pipeline: pipeline_rx, } diff --git a/backend/crates/station/src/event/README.md b/backend/crates/station/src/event/README.md index 2963c706a..c03d0e54d 100644 --- a/backend/crates/station/src/event/README.md +++ b/backend/crates/station/src/event/README.md @@ -41,7 +41,7 @@ the boards. ┌─ task ─────┐ ─① errors──────► │ reads in this order: │ │ net::tcp │ ─③ TCP notif.──► │ 1. ① ② errors │ ─⑥─► ┌─ task ───┐ └────────────┘ │ 2. ③ TCP notifications │ │ pipeline │ → websocket → front - any station ─② problems─────► │ 3. ④ UDP notifications │ └──────────┘ + any station ─② notices─────► │ 3. ④ UDP notifications │ └──────────┘ module └────────────┬─────────────┘ │ ⑧ (fatal error, board fault) ▼ @@ -127,7 +127,7 @@ event/ | # | Queue | From → to | Carries | |---|---|---|---| | ① | net errors (one queue per transport) | `net::udp`, `net::tcp` → routing loop | `ErrorReport` | -| ② | problems | any station module → routing loop | `Problem` | +| ② | notices | any station module → routing loop | `Notice` | | ③ | TCP notifications | `net::tcp` → routing loop | `Notification` (protections, messages, connected/disconnected) | | ④ | UDP notifications | `net::udp` → routing loop | `Notification` (data) | | ⑤ | to logging | routing loop, both workers → `logging` | `ToLogging` | @@ -162,7 +162,7 @@ let event = event::spawn(config, channels.event, pod_data, index, tcp); // Arc

, - /// ②, cloned for every station module that reports problems. - pub problems: mpsc::Sender, + /// ②, cloned for every station module that reports notices. + pub notices: mpsc::Sender, /// ⑤, for logging. pub logging: mpsc::Receiver, /// ⑥, for pipeline. @@ -396,28 +402,32 @@ pub enum ToLogging { pub enum ToPipeline { /// A notification, the same copy logging gets. Received(Arc), - Problem(Problem), + Notice(Notice), /// An order the front sent that went out, as in `ToLogging`. OrderSent { at: SystemTime, board: Option, order: OrderPacket }, /// An order the front sent that did not go out, and why. OrderFailed { at: SystemTime, order: OrderPacket, reason: String }, } -/// Something the operator has to see. `Problem::now(kind, board, text)` -/// builds one stamped with the current time. -pub struct Problem { +/// Something the operator is told: an error, or just news. Its kind says +/// which. `Notice::now(kind, board, text)` builds one stamped with the +/// current time. +pub struct Notice { pub at: SystemTime, - /// The board, if known. + /// The board, if it concerns one. pub board: Option, - pub kind: ProblemKind, - /// The message with all its causes: "could not X: because Y: because Z" - /// (`event::full_message` builds it from any error). + pub kind: NoticeKind, + /// The text. For an error, the message with all its causes: "could not + /// X: because Y: because Z" (`event::full_message` builds it from any + /// error). pub text: String, } -pub enum ProblemKind { - /// Procedure 2: shown, the backend keeps running. - Shown, +pub enum NoticeKind { + /// News, not an error: shown as information, the backend keeps running. + Info, + /// Procedure 2: shown as a warning, the backend keeps running. + Warning, /// Procedure 3: the fault is sent, it is shown and the backend stops. Fatal, /// Procedure 1: only traced, not shown; the backend keeps running. @@ -426,7 +436,7 @@ pub enum ProblemKind { /// Why event ended. `main` reads it and shuts down in order. pub enum Stop { - Fatal(Problem), + Fatal(Notice), /// `net`'s queues closed: UDP and TCP were stopped. NetGone, } @@ -435,7 +445,7 @@ pub enum Stop { /// clamped to at least 1. pub struct EventConfig { pub errors_queue: usize, // each of net's two error queues, ① (16) - pub problems_queue: usize, // ② (16) + pub notices_queue: usize, // ② (16) pub tcp_queue: usize, // ③ (1,024) pub udp_queue: usize, // ④ (8,192) pub logging_queue: usize, // ⑤ (8,192) @@ -454,11 +464,11 @@ these two calls only. `FaultRequest` (⑧) is private to `event`. ```text loop, select! in fixed order (closed queues are no longer watched): - 1. ① UDP errors, ① TCP errors, then ② problems -> policy: + 1. ① UDP errors, ① TCP errors, then ② notices -> policy: fatal -> stop (see "Stopping") board fault -> propagate_fault? request to ⑧ (every time) - first from that board? Problem to ⑥ - shown -> Problem to ⑥ + first from that board? Notice to ⑥ + shown -> Notice to ⑥ silent -> trace only 2. ③ TCP notifications.recv() -> fault protection or message? propagate_fault? request to ⑧ @@ -513,13 +523,15 @@ notifications a second through `event`, over 20 times the requirement. (`logger/enable`, variable selection) go straight to `logging`, not through `event`. - **`logging`** reads ⑤, picks which measurements to store following its own - selection, records the orders that went out, and reports its own failures - (e.g. the disk) on ②. + selection, records the orders that went out, and reports on ② its own + failures (e.g. the disk, as a `Fatal` notice) and its news (an `Info`, e.g. + recording started). - **`pipeline`** reads ⑥ and turns it into what the front shows: a notification into per-packet updates (counts, cycle time, averages) or protection and - message updates; a `Problem`, and an order that went out or failed + message updates; a `Notice`, and an order that went out or failed (`OrderSent`, `OrderFailed`), into a message from the backend - (`message/update`). It waits instead of dropping and does not decide anything + (`message/update`). A notice keeps its kind there: `Info` as info, `Warning` + as warning, `Fatal` as fault. It waits instead of dropping and does not decide anything about errors. ## Implementation notes diff --git a/backend/crates/station/src/event/fault.rs b/backend/crates/station/src/event/fault.rs index 8bd2ccc51..db948d41e 100644 --- a/backend/crates/station/src/event/fault.rs +++ b/backend/crates/station/src/event/fault.rs @@ -10,7 +10,7 @@ use tokio::sync::{mpsc, oneshot}; use tracing::{error, info, warn}; use super::orders::TCP_NOT_AVAILABLE; -use super::{Problem, ProblemKind, TcpLink, ToLogging, ToPipeline, board_name}; +use super::{Notice, NoticeKind, TcpLink, ToLogging, ToPipeline, board_name}; /// The fault's id on the wire: what a board sends when it detects an error, /// and what the backend sends to every board to put the pod in fault. @@ -82,8 +82,8 @@ pub(super) async fn run( error!(%text); // A fault that only half landed is exactly what the // operator has to know. - let problem = Problem::now(ProblemKind::Shown, None, text); - let _ = pipeline.send(ToPipeline::Problem(problem)).await; + let notice = Notice::now(NoticeKind::Warning, None, text); + let _ = pipeline.send(ToPipeline::Notice(notice)).await; } } if let Some(done) = done { diff --git a/backend/crates/station/src/event/manual_tests.rs b/backend/crates/station/src/event/manual_tests.rs index 3ca606239..9314ee5d1 100644 --- a/backend/crates/station/src/event/manual_tests.rs +++ b/backend/crates/station/src/event/manual_tests.rs @@ -28,11 +28,11 @@ async fn manual_event_throughput() -> Result<(), Box> { tcp, event, orders, - problems, + notices, mut logging, mut pipeline, } = channels(&config); - drop((tcp, orders, problems)); + drop((tcp, orders, notices)); let event = spawn(config, event, Arc::default(), Arc::default(), None); let logged = tokio::spawn(async move { diff --git a/backend/crates/station/src/event/policy.rs b/backend/crates/station/src/event/policy.rs index 074dd551d..69189d2b6 100644 --- a/backend/crates/station/src/event/policy.rs +++ b/backend/crates/station/src/event/policy.rs @@ -8,7 +8,7 @@ use software_core::model::{AdjId, BoardId, MessageLevel, Packet, PacketType, Sev use software_core::net::{self, Event, tcp, udp::UdpError}; use software_core::protocol::Index; -use super::ProblemKind; +use super::NoticeKind; /// What the routing loop does about an error. #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -50,13 +50,13 @@ pub(super) fn classify(error: &net::Error) -> Action { } } -/// Decides what a [`super::Problem`] from a station module means: whatever +/// Decides what a [`super::Notice`] from a station module means: whatever /// the module that sent it says. -pub(super) fn for_problem(kind: ProblemKind) -> Action { +pub(super) fn for_notice(kind: NoticeKind) -> Action { match kind { - ProblemKind::Fatal => Action::Fatal, - ProblemKind::Shown => Action::Show, - ProblemKind::Silent => Action::Silent, + NoticeKind::Fatal => Action::Fatal, + NoticeKind::Info | NoticeKind::Warning => Action::Show, + NoticeKind::Silent => Action::Silent, } } @@ -353,10 +353,11 @@ mod tests { } #[test] - fn a_problem_means_what_its_module_says() { - assert_eq!(for_problem(ProblemKind::Fatal), Action::Fatal); - assert_eq!(for_problem(ProblemKind::Shown), Action::Show); - assert_eq!(for_problem(ProblemKind::Silent), Action::Silent); + fn a_notice_means_what_its_module_says() { + assert_eq!(for_notice(NoticeKind::Fatal), Action::Fatal); + assert_eq!(for_notice(NoticeKind::Info), Action::Show); + assert_eq!(for_notice(NoticeKind::Warning), Action::Show); + assert_eq!(for_notice(NoticeKind::Silent), Action::Silent); } #[test] diff --git a/backend/crates/station/src/event/router.rs b/backend/crates/station/src/event/router.rs index 8a5e817de..76028cbd6 100644 --- a/backend/crates/station/src/event/router.rs +++ b/backend/crates/station/src/event/router.rs @@ -1,6 +1,6 @@ //! The routing loop: everything towards the front. //! -//! Reads ① ② ③ ④ in fixed order (errors, problems, TCP, UDP), hands every +//! Reads ① ② ③ ④ in fixed order (errors, notices, TCP, UDP), hands every //! notification to `logging` and `pipeline` (⑤ ⑥), decides what each error //! and each board fault means with [`super::policy`], and asks the fault //! worker (⑧) for the fault. It never writes to a socket itself, so it never @@ -20,7 +20,7 @@ use tracing::{debug, error, warn}; use super::fault::FaultRequest; use super::policy::{self, Action}; use super::{ - EventConfig, Problem, ProblemKind, Stop, ToLogging, ToPipeline, board_name, full_message, + EventConfig, Notice, NoticeKind, Stop, ToLogging, ToPipeline, board_name, full_message, }; /// The routing loop's ends of the queues: the reading side of ① ② ③ ④ and @@ -31,8 +31,8 @@ pub(super) struct RouterEnds { pub(super) udp: Sinks, /// ① and ③: TCP's errors and notifications. pub(super) tcp: Sinks, - /// ②: problems from station modules. - pub(super) problems: mpsc::Receiver, + /// ②: notices from station modules. + pub(super) notices: mpsc::Receiver, /// ⑤: to `logging`. The workers get clones. pub(super) logging: mpsc::Sender, /// ⑥: to `pipeline`. The workers get clones. @@ -60,14 +60,14 @@ enum Consumer { /// Why the routing loop has to stop, before it does it. #[derive(Debug)] enum Halt { - Fatal(Problem), + Fatal(Notice), Gone(Consumer), } /// What one round of the `select!` got. enum Step { NetError(Transport, Option), - Problem(Option), + Notice(Option), Notification(Transport, Option), } @@ -78,7 +78,7 @@ enum Step { struct Open { udp_errors: bool, tcp_errors: bool, - problems: bool, + notices: bool, tcp_notifications: bool, udp_notifications: bool, } @@ -88,7 +88,7 @@ impl Default for Open { Self { udp_errors: true, tcp_errors: true, - problems: true, + notices: true, tcp_notifications: true, udp_notifications: true, } @@ -111,7 +111,7 @@ pub(super) struct Router { index: Arc, udp: Sinks, tcp: Sinks, - problems: mpsc::Receiver, + notices: mpsc::Receiver, logging: mpsc::Sender, pipeline: mpsc::Sender, fault: mpsc::Sender, @@ -139,7 +139,7 @@ impl Router { index, udp: ends.udp, tcp: ends.tcp, - problems: ends.problems, + notices: ends.notices, logging: ends.logging, pipeline: ends.pipeline, fault, @@ -172,7 +172,7 @@ impl Router { report = self.tcp.errors.recv(), if open.tcp_errors => { Step::NetError(Transport::Tcp, report) } - problem = self.problems.recv(), if open.problems => Step::Problem(problem), + notice = self.notices.recv(), if open.notices => Step::Notice(notice), // Then notifications after errrors notification = self.tcp.notifications.recv(), if open.tcp_notifications => { @@ -196,11 +196,11 @@ impl Router { Ok(()) } Step::NetError(_, Some(report)) => self.on_net_error(report).await, - Step::Problem(None) => { - self.open.problems = false; + Step::Notice(None) => { + self.open.notices = false; Ok(()) } - Step::Problem(Some(problem)) => self.on_problem(problem).await, + Step::Notice(Some(notice)) => self.on_notice(notice).await, // Notifications empty Step::Notification(Transport::Tcp, None) => { @@ -226,7 +226,7 @@ impl Router { match handled { Ok(()) => {} - Err(Halt::Fatal(problem)) => return self.stop_fatal(problem).await, + Err(Halt::Fatal(notice)) => return self.stop_fatal(notice).await, Err(Halt::Gone(consumer)) => return self.stop_consumer_gone(consumer).await, } } @@ -264,13 +264,13 @@ impl Router { } let kind = match action { - Action::Fatal => ProblemKind::Fatal, - Action::Silent => ProblemKind::Silent, - Action::Show | Action::BoardFault => ProblemKind::Shown, + Action::Fatal => NoticeKind::Fatal, + Action::Silent => NoticeKind::Silent, + Action::Show | Action::BoardFault => NoticeKind::Warning, }; - // Defines the problem to show, or to send with the fault if it is fatal. - let problem = Problem { + // Defines the notice to show, or to send with the fault if it is fatal. + let notice = Notice { at: report.at, board, kind, @@ -279,31 +279,31 @@ impl Router { // What to do with it: show it, send the fault, or just trace it. match action { - Action::Fatal => Err(Halt::Fatal(problem)), - Action::BoardFault => self.on_board_fault(problem, source.ip).await, - Action::Show => self.show(problem).await.map_err(Halt::Gone), + Action::Fatal => Err(Halt::Fatal(notice)), + Action::BoardFault => self.on_board_fault(notice, source.ip).await, + Action::Show => self.show(notice).await.map_err(Halt::Gone), Action::Silent => { - self.trace_silent(&problem); + self.trace_silent(¬ice); Ok(()) } } } - async fn on_problem(&mut self, problem: Problem) -> Result<(), Halt> { - match policy::for_problem(problem.kind) { - Action::Fatal => Err(Halt::Fatal(problem)), + async fn on_notice(&mut self, notice: Notice) -> Result<(), Halt> { + match policy::for_notice(notice.kind) { + Action::Fatal => Err(Halt::Fatal(notice)), Action::Silent => { - self.trace_silent(&problem); + self.trace_silent(¬ice); Ok(()) } - Action::Show | Action::BoardFault => self.show(problem).await.map_err(Halt::Gone), + Action::Show | Action::BoardFault => self.show(notice).await.map_err(Halt::Gone), } } /// Procedure 1: written to the trace, and nothing else. - fn trace_silent(&self, problem: &Problem) { - let board = problem.board.map(|board| board_name(&self.pod_data, board)); - warn!(board = ?board, problem = %problem.text, "problem not shown on the front"); + fn trace_silent(&self, notice: &Notice) { + let board = notice.board.map(|board| board_name(&self.pod_data, board)); + warn!(board = ?board, notice = %notice.text, "notice not shown on the front"); } /// A fault (packet id 0) a board sent: sent to every board each time. @@ -311,8 +311,8 @@ impl Router { /// It arrives as an error, not as a notification, so the front only sees /// it if it is shown here: the first one from each address is, repeats /// are not (`net` already traces them, rate-limited). - async fn on_board_fault(&mut self, problem: Problem, ip: Option) -> Result<(), Halt> { - let board = problem.board.map_or_else( + async fn on_board_fault(&mut self, notice: Notice, ip: Option) -> Result<(), Halt> { + let board = notice.board.map_or_else( || "an unknown board".to_string(), |board| board_name(&self.pod_data, board), ); @@ -320,8 +320,8 @@ impl Router { let first = ip.is_none_or(|ip| self.faults_shown.insert(ip)); if first { - warn!(fault = %problem.text, "first fault from this board"); - self.show(problem).await.map_err(Halt::Gone)?; + warn!(fault = %notice.text, "first fault from this board"); + self.show(notice).await.map_err(Halt::Gone)?; } Ok(()) } @@ -340,28 +340,28 @@ impl Router { } } - // sends to pipelne a Problem - async fn show(&self, problem: Problem) -> Result<(), Consumer> { + // sends to pipelne a Notice + async fn show(&self, notice: Notice) -> Result<(), Consumer> { self.pipeline - .send(ToPipeline::Problem(problem)) + .send(ToPipeline::Notice(notice)) .await .map_err(|_| Consumer::Pipeline) } - /// Procedure 3: send the fault, show the problem, pass on what was + /// Procedure 3: send the fault, show the notice, pass on what was /// already queued, stop. /// /// The fault is asked for first, since it has to reach the boards as soon /// as possible; the rest happens while the fault worker writes it, and the /// loop only stops once it has gone out. - async fn stop_fatal(mut self, problem: Problem) -> Stop { - error!(problem = %problem.text, "fatal error, stopping"); + async fn stop_fatal(mut self, notice: Notice) -> Stop { + error!(notice = %notice.text, "fatal error, stopping"); let deadline = Instant::now() + self.config.fault_timeout; let fault_sent = self.ask_for_fault(deadline).await; let pipeline_alive = self .pipeline - .send(ToPipeline::Problem(problem.clone())) + .send(ToPipeline::Notice(notice.clone())) .await .is_ok(); if pipeline_alive { @@ -372,7 +372,7 @@ impl Router { } self.wait_for_fault(fault_sent, deadline).await; - Stop::Fatal(problem) + Stop::Fatal(notice) } /// `logging` or `pipeline` stopped: nothing is recorded, or nothing is @@ -382,20 +382,17 @@ impl Router { Consumer::Logging => "logging stopped: nothing is being recorded", Consumer::Pipeline => "pipeline stopped: nothing reaches the front", }; - let problem = Problem::now(ProblemKind::Fatal, None, text); - error!(problem = %problem.text, "fatal error, stopping"); + let notice = Notice::now(NoticeKind::Fatal, None, text); + error!(notice = %notice.text, "fatal error, stopping"); let deadline = Instant::now() + self.config.fault_timeout; let fault_sent = self.ask_for_fault(deadline).await; if consumer == Consumer::Logging { - let _ = self - .pipeline - .send(ToPipeline::Problem(problem.clone())) - .await; + let _ = self.pipeline.send(ToPipeline::Notice(notice.clone())).await; } self.wait_for_fault(fault_sent, deadline).await; - Stop::Fatal(problem) + Stop::Fatal(notice) } /// Passes on what is already in ③ and ④, at most their capacity each, so diff --git a/backend/crates/station/src/event/tests.rs b/backend/crates/station/src/event/tests.rs index 0fbfda463..5cec5a0cf 100644 --- a/backend/crates/station/src/event/tests.rs +++ b/backend/crates/station/src/event/tests.rs @@ -203,14 +203,10 @@ async fn errors_come_first_then_tcp_then_udp() -> TestResult { channels.udp.report(fault_from(hvscu_addr(), HVSCU)).await?; let _event = spawn(config, channels.event, pod_data(), index(), None); - let ToPipeline::Problem(problem) = next(&mut channels.pipeline).await? else { + let ToPipeline::Notice(notice) = next(&mut channels.pipeline).await? else { unreachable!("the error comes first"); }; - assert!( - problem.text.contains("signalled a fault"), - "{}", - problem.text - ); + assert!(notice.text.contains("signalled a fault"), "{}", notice.text); let ToPipeline::Received(tcp) = next(&mut channels.pipeline).await? else { unreachable!("then the TCP notification"); @@ -233,12 +229,12 @@ async fn a_fatal_error_passes_on_what_was_queued_and_stops() -> TestResult { channels.udp.report(decode_error()).await?; let event = spawn(config, channels.event, pod_data(), index(), None); - let ToPipeline::Problem(problem) = next(&mut channels.pipeline).await? else { + let ToPipeline::Notice(notice) = next(&mut channels.pipeline).await? else { unreachable!("the fatal error is shown first"); }; - assert_eq!(problem.kind, ProblemKind::Fatal); - assert_eq!(problem.board, Some(HVSCU), "the board the error carries"); - assert!(problem.text.starts_with("HVSCU: "), "{}", problem.text); + assert_eq!(notice.kind, NoticeKind::Fatal); + assert_eq!(notice.board, Some(HVSCU), "the board the error carries"); + assert!(notice.text.starts_with("HVSCU: "), "{}", notice.text); // The data that arrived before the error still gets through, to both. shown(&mut channels.pipeline, 2).await?; @@ -247,7 +243,7 @@ async fn a_fatal_error_passes_on_what_was_queued_and_stops() -> TestResult { let Stop::Fatal(stopped_by) = stops(event).await? else { unreachable!("a decode error is fatal"); }; - assert_eq!(stopped_by, problem); + assert_eq!(stopped_by, notice); Ok(()) } @@ -265,10 +261,10 @@ async fn a_board_fault_is_shown_once_per_board_and_sent_to_every_board_each_time // A marker: whatever comes before it on pipeline is all there is. channels.udp.notify(HVSCU, data()).await?; - let ToPipeline::Problem(first) = next(&mut channels.pipeline).await? else { + let ToPipeline::Notice(first) = next(&mut channels.pipeline).await? else { unreachable!("HVSCU's first fault is shown"); }; - let ToPipeline::Problem(second) = next(&mut channels.pipeline).await? else { + let ToPipeline::Notice(second) = next(&mut channels.pipeline).await? else { unreachable!("VCU's first fault is shown"); }; let ToPipeline::Received(_) = next(&mut channels.pipeline).await? else { @@ -276,7 +272,7 @@ async fn a_board_fault_is_shown_once_per_board_and_sent_to_every_board_each_time }; assert_eq!(first.board, Some(HVSCU)); assert_eq!(second.board, Some(VCU)); - assert_eq!(first.kind, ProblemKind::Shown); + assert_eq!(first.kind, NoticeKind::Warning); // Four faults arrived, so the fault goes out four times. eventually(|| fake.faults.load(Ordering::SeqCst) == 4).await?; @@ -301,7 +297,7 @@ async fn a_fault_protection_or_message_is_forwarded_and_sent_to_every_board() -> channels.tcp.notify(HVSCU, policy::message_sent(2)).await?; channels.tcp.notify(HVSCU, policy::message_sent(3)).await?; - // They still reach the front as what they are, not as extra problems. + // They still reach the front as what they are, not as extra notices. shown(&mut channels.pipeline, 3).await?; logged(&mut channels.logging, 3).await?; eventually(|| fake.faults.load(Ordering::SeqCst) == 3).await?; @@ -357,7 +353,7 @@ async fn propagating_a_board_fault_can_be_turned_off() -> TestResult { let _event = spawn(config, channels.event, pod_data(), index(), as_link(&fake)); channels.udp.report(fault_from(hvscu_addr(), HVSCU)).await?; - let ToPipeline::Problem(_) = next(&mut channels.pipeline).await? else { + let ToPipeline::Notice(_) = next(&mut channels.pipeline).await? else { unreachable!("the fault is still shown"); }; channels @@ -378,11 +374,11 @@ async fn closed_queues_do_not_hide_the_others() -> TestResult { tcp, event, orders, - problems, + notices, mut logging, pipeline: _pipeline, } = channels(&config); - drop((tcp, orders, problems)); + drop((tcp, orders, notices)); let _event = spawn(config, event, pod_data(), index(), None); udp.notify(HVSCU, data()).await?; @@ -486,7 +482,7 @@ async fn a_fault_from_the_front_goes_out_even_if_one_was_sent_already() -> TestR eventually(|| fake.faults.load(Ordering::SeqCst) == 1).await?; channels.orders.send(order(0)).await?; - let ToPipeline::Problem(_) = next(&mut channels.pipeline).await? else { + let ToPipeline::Notice(_) = next(&mut channels.pipeline).await? else { unreachable!("the board's fault is shown first"); }; let ToPipeline::OrderSent { .. } = next(&mut channels.pipeline).await? else { @@ -540,38 +536,45 @@ async fn a_fault_that_misses_boards_is_shown() -> TestResult { let _event = spawn(config, channels.event, pod_data(), index(), as_link(&fake)); channels.udp.report(fault_from(hvscu_addr(), HVSCU)).await?; - let ToPipeline::Problem(fault) = next(&mut channels.pipeline).await? else { + let ToPipeline::Notice(fault) = next(&mut channels.pipeline).await? else { unreachable!("the board's fault is shown"); }; - let ToPipeline::Problem(missed) = next(&mut channels.pipeline).await? else { + let ToPipeline::Notice(missed) = next(&mut channels.pipeline).await? else { unreachable!("then the boards the fault did not reach"); }; assert!(fault.text.contains("signalled a fault"), "{}", fault.text); - assert_eq!(missed.kind, ProblemKind::Shown); + assert_eq!(missed.kind, NoticeKind::Warning); assert!(missed.text.contains("VCU"), "{}", missed.text); Ok(()) } #[tokio::test] -async fn a_station_problem_is_traced_shown_or_stops_as_its_module_says() -> TestResult { +async fn a_station_notice_is_traced_shown_or_stops_as_its_module_says() -> TestResult { let config = EventConfig::default(); let mut channels = channels(&config); let event = spawn(config, channels.event, pod_data(), index(), None); - let silent = Problem::now(ProblemKind::Silent, None, "only for the trace"); - let shown = Problem::now(ProblemKind::Shown, None, "something to show"); - channels.problems.send(silent).await?; - channels.problems.send(shown.clone()).await?; - let ToPipeline::Problem(problem) = next(&mut channels.pipeline).await? else { - unreachable!("a shown problem reaches pipeline"); - }; + let silent = Notice::now(NoticeKind::Silent, None, "only for the trace"); + let info = Notice::now(NoticeKind::Info, None, "recording started"); + let warning = Notice::now(NoticeKind::Warning, None, "something to show"); + channels.notices.send(silent).await?; + channels.notices.send(info.clone()).await?; + channels.notices.send(warning.clone()).await?; // The silent one went first, but only to the trace. - assert_eq!(problem, shown); + let ToPipeline::Notice(first) = next(&mut channels.pipeline).await? else { + unreachable!("an info notice reaches pipeline"); + }; + let ToPipeline::Notice(second) = next(&mut channels.pipeline).await? else { + unreachable!("a warning reaches pipeline"); + }; + assert_eq!(first, info); + assert_eq!(second, warning); + assert!(!event.is_finished(), "neither stops the backend"); - let fatal = Problem::now(ProblemKind::Fatal, None, "the disk is full"); - channels.problems.send(fatal.clone()).await?; + let fatal = Notice::now(NoticeKind::Fatal, None, "the disk is full"); + channels.notices.send(fatal.clone()).await?; let Stop::Fatal(stopped_by) = stops(event).await? else { - unreachable!("a fatal problem stops event"); + unreachable!("a fatal notice stops event"); }; assert_eq!(stopped_by, fatal); Ok(()) @@ -585,7 +588,7 @@ async fn when_logging_stops_event_stops_and_tells_pipeline() -> TestResult { tcp: _tcp, event, orders: _orders, - problems: _problems, + notices: _notices, logging, mut pipeline, } = channels(&config); @@ -593,11 +596,11 @@ async fn when_logging_stops_event_stops_and_tells_pipeline() -> TestResult { let event = spawn(config, event, pod_data(), index(), None); udp.notify(HVSCU, data()).await?; - let ToPipeline::Problem(problem) = next(&mut pipeline).await? else { + let ToPipeline::Notice(notice) = next(&mut pipeline).await? else { unreachable!("pipeline is told that logging stopped"); }; - assert_eq!(problem.kind, ProblemKind::Fatal); - assert!(problem.text.contains("logging"), "{}", problem.text); + assert_eq!(notice.kind, NoticeKind::Fatal); + assert!(notice.text.contains("logging"), "{}", notice.text); let Stop::Fatal(_) = stops(event).await? else { unreachable!("losing logging is fatal"); @@ -613,7 +616,7 @@ async fn when_net_closes_what_was_left_is_passed_on_and_event_stops() -> TestRes tcp, event, orders: _orders, - problems: _problems, + notices: _notices, mut logging, pipeline: _pipeline, } = channels(&config); diff --git a/backend/crates/station/src/main.rs b/backend/crates/station/src/main.rs index bf39e02bd..ab048ae59 100644 --- a/backend/crates/station/src/main.rs +++ b/backend/crates/station/src/main.rs @@ -6,7 +6,7 @@ //! - the **logging stand-in** counts the packets it would record and writes a //! summary every second (and every packet, with `RUST_LOG=station=debug`); //! - the **pipeline stand-in** writes to the log what the front would show: -//! problems and failed orders. +//! notices and failed orders. //! //! There is no TCP and no websocket yet: their queues are closed at start. //! @@ -45,7 +45,7 @@ use tokio::time::MissedTickBehavior; use tracing::{debug, error, info, warn}; use tracing_subscriber::EnvFilter; -use station::event::{self, ProblemKind, Stop, ToLogging, ToPipeline}; +use station::event::{self, NoticeKind, Stop, ToLogging, ToPipeline}; /// Branch of the ADJ repository that is downloaded. const ADJ_BRANCH: &str = "adjv3-software"; @@ -160,14 +160,14 @@ async fn serve( tcp, event: ends, orders, - problems, + notices, logging, pipeline, } = event::channels(&config); - // Not built yet: TCP, websocket, and modules that report problems. + // Not built yet: TCP, websocket, and modules that report notices. // Dropping their ends closes those queues, and event stops watching them. - drop((tcp, orders, problems)); + drop((tcp, orders, notices)); let udp_task = spawn_udp( UdpConfig { @@ -210,8 +210,8 @@ async fn serve( } match stop.map_err(StartError::Event)? { - Stop::Fatal(problem) => { - info!(reason = %problem.text, "stopped after a fatal error"); + Stop::Fatal(notice) => { + info!(reason = %notice.text, "stopped after a fatal error"); Ok(ExitCode::FAILURE) } Stop::NetGone if by_ctrl_c => { @@ -268,17 +268,20 @@ async fn stand_in_pipeline(mut queue: mpsc::Receiver, pod_data: Arc< Event::Received(_) => {} } } - ToPipeline::Problem(problem) => { - let board = problem.board.map(|board| name(&pod_data, board)); - match problem.kind { - ProblemKind::Fatal => { - error!(board = ?board, text = %problem.text, "front: fatal error"); + ToPipeline::Notice(notice) => { + let board = notice.board.map(|board| name(&pod_data, board)); + match notice.kind { + NoticeKind::Fatal => { + error!(board = ?board, text = %notice.text, "front: fatal error"); } - ProblemKind::Shown => { - warn!(board = ?board, text = %problem.text, "front: problem") + NoticeKind::Warning => { + warn!(board = ?board, text = %notice.text, "front: warning") + } + NoticeKind::Info => { + info!(board = ?board, text = %notice.text, "front: info") } // event only traces these: they never reach pipeline. - ProblemKind::Silent => {} + NoticeKind::Silent => {} } } // The front shows both as a message from the backend. From b44b10a912fe1300cda71820058ac727c1c16d3b Mon Sep 17 00:00:00 2001 From: Jeremias Date: Thu, 3 Dec 2026 19:44:19 +0100 Subject: [PATCH 207/225] feat(testing-view): highlight measurements that trigger a protection Subscribe to protection/update and keep the last protection of each measurement, keyed by the low 13 bits of the compound protection id. The measurement row turns red with a shield icon until the messages are cleared, since the new protocol sends no recovery event. Measurements are matched by a new optional Variable.adjId (numeric ADJ id), which the new adj/DataPackets catalog has to fill. --- frontend/testing-view/src/App.tsx | 9 ++ .../rightSidebar/sections/MessagesSection.tsx | 2 + .../tabs/telemetry/VariableItem.tsx | 23 +++- .../slices/__tests__/messagesSlice.test.ts | 106 ++++++++++++++++++ .../src/store/slices/messagesSlice.ts | 21 +++- .../testing-view/src/types/data/protection.ts | 25 +++++ .../src/types/data/telemetryCatalogItem.ts | 5 + 7 files changed, 189 insertions(+), 2 deletions(-) create mode 100644 frontend/testing-view/src/store/slices/__tests__/messagesSlice.test.ts create mode 100644 frontend/testing-view/src/types/data/protection.ts diff --git a/frontend/testing-view/src/App.tsx b/frontend/testing-view/src/App.tsx index ebe5212d6..9785243cd 100644 --- a/frontend/testing-view/src/App.tsx +++ b/frontend/testing-view/src/App.tsx @@ -14,6 +14,7 @@ import { Testing } from "./pages/Testing"; import { useStore } from "./store/store"; import type { Connection } from "./types/common/connection"; import type { MessagePacket } from "./types/data/message"; +import type { ProtectionUpdate } from "./types/data/protection"; import type { TelemetryData } from "./types/telemetry/telemetry"; function App() { @@ -63,6 +64,14 @@ function App() { }); }); + // Callback executed when a protection triggers + const addProtection = useStore((s) => s.addProtection); + + // Subscribe to protections, to highlight the measurement that triggered them + useTopic("protection/update", (protection) => { + addProtection(protection); + }); + return ( diff --git a/frontend/testing-view/src/features/workspace/components/rightSidebar/sections/MessagesSection.tsx b/frontend/testing-view/src/features/workspace/components/rightSidebar/sections/MessagesSection.tsx index 533c592c8..f8c39c1a1 100644 --- a/frontend/testing-view/src/features/workspace/components/rightSidebar/sections/MessagesSection.tsx +++ b/frontend/testing-view/src/features/workspace/components/rightSidebar/sections/MessagesSection.tsx @@ -24,6 +24,8 @@ const MessagesSection = () => { variant="secondary" size="icon" className="text-muted-foreground hover:text-destructive h-6 w-6" + title="Clear messages and protections" + aria-label="Clear messages and protections" onClick={clearMessages} > diff --git a/frontend/testing-view/src/features/workspace/components/rightSidebar/tabs/telemetry/VariableItem.tsx b/frontend/testing-view/src/features/workspace/components/rightSidebar/tabs/telemetry/VariableItem.tsx index 6ea4396dc..08ea6c402 100644 --- a/frontend/testing-view/src/features/workspace/components/rightSidebar/tabs/telemetry/VariableItem.tsx +++ b/frontend/testing-view/src/features/workspace/components/rightSidebar/tabs/telemetry/VariableItem.tsx @@ -1,6 +1,7 @@ import { useDraggable } from "@dnd-kit/core"; import { Badge } from "@hyperloopupv/frontend-kit"; import { cn } from "@hyperloopupv/frontend-kit/lib"; +import { Shield } from "lucide-react"; import { useShallow } from "zustand/shallow"; import { canAddSeriesToChart, @@ -34,6 +35,13 @@ export const VariableItem = ({ packetId, variable }: VariableItemProps) => { })), ); + // A protection triggered on this measurement and the messages weren't cleared since + const isProtected = useStore( + (s) => + variable.adjId !== undefined && + s.activeProtections[variable.adjId] !== undefined, + ); + const { attributes, listeners, setNodeRef, transform, isDragging } = useDraggable({ id: `draggable-${packetId}-${variable.id}`, @@ -89,6 +97,7 @@ export const VariableItem = ({ packetId, variable }: VariableItemProps) => { {...listeners} className={cn( "hover:bg-accent/30 group flex items-center justify-between gap-3 border-t py-2 pl-6 pr-3", + isProtected && "bg-red-500/15 hover:bg-red-500/25", opacityStyle, cursorStyle, )} @@ -105,9 +114,21 @@ export const VariableItem = ({ packetId, variable }: VariableItemProps) => { {variable.type} + {/* Protection Icon */} + {isProtected && ( + + + + )} + {/* Variable Name */}

- + {variable.name} diff --git a/frontend/testing-view/src/store/slices/__tests__/messagesSlice.test.ts b/frontend/testing-view/src/store/slices/__tests__/messagesSlice.test.ts new file mode 100644 index 000000000..0c512a4be --- /dev/null +++ b/frontend/testing-view/src/store/slices/__tests__/messagesSlice.test.ts @@ -0,0 +1,106 @@ +import { beforeEach, describe, expect, it } from "vitest"; +import { create } from "zustand"; +import { createChartsSlice } from "../../../features/charts/store/chartsSlice"; +import { createFilteringSlice } from "../../../features/filtering/store/filteringSlice"; +import { createRightSidebarSlice } from "../../../features/workspace/store/rightSidebarSlice"; +import { createWorkspacesSlice } from "../../../features/workspace/store/workspacesSlice"; +import type { Message } from "../../../types/data/message"; +import type { ProtectionUpdate } from "../../../types/data/protection"; +import type { Store } from "../../store"; +import { createAppSlice } from "../appSlice"; +import { createCatalogSlice } from "../catalogSlice"; +import { createConnectionsSlice } from "../connectionsSlice"; +import { createMessagesSlice } from "../messagesSlice"; +import { createTelemetrySlice } from "../telemetrySlice"; + +const createTestStore = () => + create()((...a) => ({ + ...createAppSlice(...a), + ...createCatalogSlice(...a), + ...createWorkspacesSlice(...a), + ...createTelemetrySlice(...a), + ...createRightSidebarSlice(...a), + ...createConnectionsSlice(...a), + ...createMessagesSlice(...a), + ...createChartsSlice(...a), + ...createFilteringSlice(...a), + })); + +/** Protection number `position` (1-7) of the measurement `measurementId`. */ +const protection = ( + position: number, + measurementId: number, + value: ProtectionUpdate["value"] = 105.5, +): ProtectionUpdate => ({ + id: (position << 13) | measurementId, + value, + timestamp: { hour: 12, minute: 30, second: 6, subsecond: 0 }, +}); + +const MESSAGE: Message = { + id: "message-1", + kind: "info", + board: "LCU", + name: "Example", + payload: "Example message", + timestamp: { + counter: 0, + second: 0, + minute: 0, + hour: 12, + day: 1, + month: 1, + year: 2026, + }, +}; + +let store: ReturnType; + +beforeEach(() => { + store = createTestStore(); +}); + +describe("addProtection", () => { + it("activates the measurement in the low 13 bits of the protection id", () => { + store.getState().addProtection(protection(1, 3000)); + + expect(Object.keys(store.getState().activeProtections)).toEqual(["3000"]); + expect(store.getState().activeProtections[3000].id).toBe(11192); + }); + + it("keeps the last protection when several protections of one measurement trigger", () => { + store.getState().addProtection(protection(1, 3000, 105.5)); + store.getState().addProtection(protection(2, 3000, 5)); + + expect(Object.keys(store.getState().activeProtections)).toEqual(["3000"]); + expect(store.getState().activeProtections[3000].value).toBe(5); + }); + + it("keeps the protections of different measurements apart", () => { + store.getState().addProtection(protection(1, 3000)); + store.getState().addProtection(protection(1, 3001)); + + expect(Object.keys(store.getState().activeProtections)).toEqual([ + "3000", + "3001", + ]); + }); + + it("does not add messages", () => { + store.getState().addProtection(protection(1, 3000)); + + expect(store.getState().messages).toEqual([]); + }); +}); + +describe("clearMessages", () => { + it("clears the messages and the active protections", () => { + store.getState().addMessage(MESSAGE); + store.getState().addProtection(protection(1, 3000)); + + store.getState().clearMessages(); + + expect(store.getState().messages).toEqual([]); + expect(store.getState().activeProtections).toEqual({}); + }); +}); diff --git a/frontend/testing-view/src/store/slices/messagesSlice.ts b/frontend/testing-view/src/store/slices/messagesSlice.ts index 0a9b2d898..87278f7ee 100644 --- a/frontend/testing-view/src/store/slices/messagesSlice.ts +++ b/frontend/testing-view/src/store/slices/messagesSlice.ts @@ -1,11 +1,22 @@ import type { StateCreator } from "zustand"; import { config } from "../../../config"; import type { Message } from "../../types/data/message"; +import type { ProtectionUpdate } from "../../types/data/protection"; import type { Store } from "../store"; +/** The low 13 bits of a protection id are the id of the measurement it watches. */ +const MEASUREMENT_ID_MASK = 0x1fff; + export interface MessagesSlice { messages: Message[]; addMessage: (message: Message) => void; + /** + * Last protection received for each measurement, by the measurement's numeric ADJ id.\ + * Those measurements are highlighted until the messages are cleared. + */ + activeProtections: Record; + addProtection: (protection: ProtectionUpdate) => void; + /** Clears the messages and the active protections */ clearMessages: () => void; } @@ -20,5 +31,13 @@ export const createMessagesSlice: StateCreator = ( config.MAX_MESSAGES_COUNT, ), })), - clearMessages: () => set({ messages: [] }), + activeProtections: {}, + addProtection: (protection) => + set((state) => ({ + activeProtections: { + ...state.activeProtections, + [protection.id & MEASUREMENT_ID_MASK]: protection, + }, + })), + clearMessages: () => set({ messages: [], activeProtections: {} }), }); diff --git a/frontend/testing-view/src/types/data/protection.ts b/frontend/testing-view/src/types/data/protection.ts new file mode 100644 index 000000000..c7acd27d5 --- /dev/null +++ b/frontend/testing-view/src/types/data/protection.ts @@ -0,0 +1,25 @@ +/** + * Time of day at which the board detected the protection.\ + * It carries no date: it is the day the protection was received. + */ +export type ProtectionTimestamp = { + hour: number; + minute: number; + second: number; + /** Raw sub-second byte from the board (its unit is not settled yet) */ + subsecond: number; +}; + +/** + * Protection event as it arrives from the backend on `protection/update`. + */ +export type ProtectionUpdate = { + /** + * Compound id: `(position << 13) | measurementId`.\ + * The low 13 bits are the numeric ADJ id of the measurement that triggered it. + */ + id: number; + /** Value of the measurement that triggered the protection */ + value: number | boolean | string; + timestamp: ProtectionTimestamp; +}; diff --git a/frontend/testing-view/src/types/data/telemetryCatalogItem.ts b/frontend/testing-view/src/types/data/telemetryCatalogItem.ts index 3d8532a11..f0653db79 100644 --- a/frontend/testing-view/src/types/data/telemetryCatalogItem.ts +++ b/frontend/testing-view/src/types/data/telemetryCatalogItem.ts @@ -8,6 +8,11 @@ export type Variable = { name: string; type: string; units?: string; + /** + * Numeric id of the measurement in the ADJ.\ + * Protections point to the measurement they watch by this id. + */ + adjId?: number; }; export interface NumericVariable extends Variable { From 5a48533abb60f33b9b9d44411cc6ef4721972121 Mon Sep 17 00:00:00 2001 From: Jeremias Date: Fri, 4 Dec 2026 18:16:31 +0100 Subject: [PATCH 208/225] feat(testing-view): adapt catalogs to the new backend HTTP endpoints - Fetch packets, orders and protections from adj/DataPackets, adj/OrderPackets and adj/ProtectionPackets - Identify measurements by alias and command params by a measurements array with their protections instead of safe/warning ranges - Show triggered protections as messages and categorize messages by the topic they arrive on (message/update, backend/update) - Update mocks to the new shapes --- frontend/testing-view/src/App.tsx | 34 +- .../components/AddKeyBindingDialog.tsx | 20 +- .../keyBindings/hooks/useGlobalKeyBindings.ts | 31 +- .../tabs/commands/CommandItem.tsx | 29 +- .../tabs/commands/CommandParameters.tsx | 85 +- .../tabs/telemetry/VariableItem.tsx | 35 +- .../testing-view/src/hooks/useAppConfigs.ts | 11 +- frontend/testing-view/src/hooks/useLogger.ts | 2 +- frontend/testing-view/src/lib/commandUtils.ts | 38 +- frontend/testing-view/src/lib/utils.test.ts | 61 + frontend/testing-view/src/lib/utils.ts | 72 +- frontend/testing-view/src/mocks/commands.ts | 716 ++++++---- frontend/testing-view/src/mocks/telemetry.ts | 1254 ++++++++--------- .../src/types/data/commandCatalogItem.ts | 44 +- .../testing-view/src/types/data/protection.ts | 20 + .../src/types/data/telemetryCatalogItem.ts | 35 +- 16 files changed, 1355 insertions(+), 1132 deletions(-) diff --git a/frontend/testing-view/src/App.tsx b/frontend/testing-view/src/App.tsx index 9785243cd..c6b230c33 100644 --- a/frontend/testing-view/src/App.tsx +++ b/frontend/testing-view/src/App.tsx @@ -9,6 +9,7 @@ import { useAppMode } from "./hooks/useAppMode"; import { useErrorHandler } from "./hooks/useErrorHandler"; import { useTransformedBoards } from "./hooks/useTransformedBoards"; import { AppLayout } from "./layout/AppLayout"; +import { protectionToMessage } from "./lib/utils"; import { Logs } from "./pages/Logs"; import { Testing } from "./pages/Testing"; import { useStore } from "./store/store"; @@ -22,7 +23,8 @@ function App() { const { reportError } = useErrorHandler(); // Fetch app configs - const { packets, commands, isLoading } = useAppConfigs(isConnected); + const { packets, commands, protections, isLoading } = + useAppConfigs(isConnected); // Determine app mode useAppMode(packets, commands, isLoading); @@ -56,20 +58,34 @@ function App() { // Callback executed when messages are received const addMessage = useStore((s) => s.addMessage); - useTopic("message/update", (data) => { - console.log("Message received:", data); - addMessage({ - ...data, - id: crypto.randomUUID(), - }); - }); + // The backend doesn't send the category: it's the topic the message arrives on + const handleMessage = + (category: MessagePacket["category"]) => (data: MessagePacket) => { + console.log("Message received:", data); + addMessage({ + ...data, + category, + id: crypto.randomUUID(), + }); + }; + + // Each message category arrives on its own topic + useTopic("message/update", handleMessage("message")); + useTopic("backend/update", handleMessage("backend")); // Callback executed when a protection triggers const addProtection = useStore((s) => s.addProtection); - // Subscribe to protections, to highlight the measurement that triggered them + // Protections highlight the measurement that triggered them and are shown as messages useTopic("protection/update", (protection) => { addProtection(protection); + handleMessage("protection")( + protectionToMessage( + protection, + protections?.protections ?? [], + useStore.getState().telemetryCatalog, + ), + ); }); return ( diff --git a/frontend/testing-view/src/features/keyBindings/components/AddKeyBindingDialog.tsx b/frontend/testing-view/src/features/keyBindings/components/AddKeyBindingDialog.tsx index 77844d240..8529b833c 100644 --- a/frontend/testing-view/src/features/keyBindings/components/AddKeyBindingDialog.tsx +++ b/frontend/testing-view/src/features/keyBindings/components/AddKeyBindingDialog.tsx @@ -17,7 +17,10 @@ import { } from "@hyperloopupv/frontend-kit"; import { X } from "@hyperloopupv/frontend-kit/icons"; import { useEffect, useRef, useState } from "react"; -import { getDefaultParameterValues } from "../../../lib/commandUtils"; +import { + getDefaultParameterValues, + getParameterKind, +} from "../../../lib/commandUtils"; import { useStore } from "../../../store/store"; import type { CommandCatalogItem } from "../../../types/data/commandCatalogItem"; import { CommandParameters } from "../../workspace/components/rightSidebar/tabs/commands/CommandParameters"; @@ -56,7 +59,7 @@ export const AddKeyBindingDialog = ({ : null; const hasParameters = selectedCommand - ? Object.keys(selectedCommand.fields).length > 0 + ? selectedCommand.measurements.length > 0 : false; // Reset state when dialog closes @@ -73,7 +76,7 @@ export const AddKeyBindingDialog = ({ useEffect(() => { if (selectedCommand) { const defaults: Record = getDefaultParameterValues( - selectedCommand.fields, + selectedCommand.measurements, ); setParameterValues(defaults); } @@ -124,9 +127,10 @@ export const AddKeyBindingDialog = ({ const hasInvalidNumericParams = selectedCommand !== null && selectedCommand !== undefined && - Object.entries(selectedCommand.fields).some( - ([key, field]) => - field.kind === "numeric" && isNaN(parseFloat(parameterValues[key])), + selectedCommand.measurements.some( + (field) => + getParameterKind(field) === "numeric" && + isNaN(parseFloat(parameterValues[field.alias])), ); const canSubmit = @@ -199,12 +203,12 @@ export const AddKeyBindingDialog = ({
- {Object.keys(selectedCommand.fields).length} parameter(s) + {selectedCommand.measurements.length} parameter(s)
diff --git a/frontend/testing-view/src/features/keyBindings/hooks/useGlobalKeyBindings.ts b/frontend/testing-view/src/features/keyBindings/hooks/useGlobalKeyBindings.ts index 9a46c26e0..e9898b16b 100644 --- a/frontend/testing-view/src/features/keyBindings/hooks/useGlobalKeyBindings.ts +++ b/frontend/testing-view/src/features/keyBindings/hooks/useGlobalKeyBindings.ts @@ -1,7 +1,11 @@ import { logger, socketService } from "@hyperloopupv/frontend-kit/core"; import { useEffect } from "react"; import { useLogger } from "../../../hooks/useLogger"; -import { getDefaultParameterValues } from "../../../lib/commandUtils"; +import { + getDefaultParameterValues, + getFieldType, + getParameterKind, +} from "../../../lib/commandUtils"; import { useStore } from "../../../store/store"; import type { CommandCatalogItem } from "../../../types/data/commandCatalogItem"; import { @@ -76,22 +80,29 @@ export const useGlobalKeyBindings = () => { // Build payload with binding's configured parameters const payload = { id: commandToExecute.id, - fields: Object.entries(commandToExecute.fields).reduce( - (acc, [fieldKey, field]) => { + fields: commandToExecute.measurements.reduce( + (acc, field) => { + const fieldKey = field.alias; + // Use binding's parameter value or fall back to default let value = parameterValues[fieldKey]; // If no value in binding, use field defaults if (value === undefined) { - value = getDefaultParameterValues(commandToExecute.fields)[ - fieldKey - ]; + value = getDefaultParameterValues( + commandToExecute.measurements, + )[fieldKey]; } const numericValue = - field.kind === "numeric" ? parseFloat(value) : value; - - if (field.kind === "numeric" && isNaN(numericValue as number)) { + getParameterKind(field) === "numeric" + ? parseFloat(value) + : value; + + if ( + getParameterKind(field) === "numeric" && + isNaN(numericValue as number) + ) { logger.testingView.warn( `Skipping command: numeric field "${fieldKey}" has no valid value`, ); @@ -101,7 +112,7 @@ export const useGlobalKeyBindings = () => { acc[fieldKey] = { value: numericValue, isEnabled: true, - type: field.type, + type: getFieldType(field), }; return acc; }, diff --git a/frontend/testing-view/src/features/workspace/components/rightSidebar/tabs/commands/CommandItem.tsx b/frontend/testing-view/src/features/workspace/components/rightSidebar/tabs/commands/CommandItem.tsx index 70518b8bd..f1032e320 100644 --- a/frontend/testing-view/src/features/workspace/components/rightSidebar/tabs/commands/CommandItem.tsx +++ b/frontend/testing-view/src/features/workspace/components/rightSidebar/tabs/commands/CommandItem.tsx @@ -8,7 +8,11 @@ import { import { ChevronDown, Play, Send } from "@hyperloopupv/frontend-kit/icons"; import { cn } from "@hyperloopupv/frontend-kit/lib"; import { useState } from "react"; -import { getDefaultParameterValues } from "../../../../../../lib/commandUtils"; +import { + getDefaultParameterValues, + getFieldType, + getParameterKind, +} from "../../../../../../lib/commandUtils"; import { useStore } from "../../../../../../store/store"; import type { CommandCatalogItem } from "../../../../../../types/data/commandCatalogItem"; import { CommandParameters } from "./CommandParameters"; @@ -27,16 +31,16 @@ export const CommandItem = ({ item: commandCatalogItem }: CommandItemProps) => { ); const [parameterValues, setParameterValues] = useState>( - () => getDefaultParameterValues(commandCatalogItem.fields), + () => getDefaultParameterValues(commandCatalogItem.measurements), ); - const paramCount = Object.keys(commandCatalogItem.fields).length; + const paramCount = commandCatalogItem.measurements.length; const hasParameters = paramCount > 0; - const hasInvalidNumeric = Object.entries(commandCatalogItem.fields).some( - ([key, field]) => - field.kind === "numeric" && - !Number.isFinite(parseFloat(parameterValues[key])), + const hasInvalidNumeric = commandCatalogItem.measurements.some( + (field) => + getParameterKind(field) === "numeric" && + !Number.isFinite(parseFloat(parameterValues[field.alias])), ); const handleRun = (e: React.MouseEvent) => { @@ -45,15 +49,16 @@ export const CommandItem = ({ item: commandCatalogItem }: CommandItemProps) => { const payload = { id: commandCatalogItem.id, - fields: Object.entries(commandCatalogItem.fields).reduce( - (acc, [key, field]) => { + fields: commandCatalogItem.measurements.reduce( + (acc, field) => { + const key = field.alias; acc[key] = { value: - field.kind === "numeric" + getParameterKind(field) === "numeric" ? parseFloat(parameterValues[key]) : parameterValues[key], isEnabled: true, // Set to true by default, could be implemented in the future, but does not really make any sense for me - type: field.type, + type: getFieldType(field), }; return acc; }, @@ -133,7 +138,7 @@ export const CommandItem = ({ item: commandCatalogItem }: CommandItemProps) => {
diff --git a/frontend/testing-view/src/features/workspace/components/rightSidebar/tabs/commands/CommandParameters.tsx b/frontend/testing-view/src/features/workspace/components/rightSidebar/tabs/commands/CommandParameters.tsx index e7b8e32f4..8e5950306 100644 --- a/frontend/testing-view/src/features/workspace/components/rightSidebar/tabs/commands/CommandParameters.tsx +++ b/frontend/testing-view/src/features/workspace/components/rightSidebar/tabs/commands/CommandParameters.tsx @@ -8,14 +8,16 @@ import { SelectTrigger, SelectValue, } from "@hyperloopupv/frontend-kit"; -import type { - CommandParameter, - EnumCommandParameter, - NumericCommandParameter, -} from "../../../../../../types/data/commandCatalogItem"; +import { + getEnumOptions, + getFieldType, + getParameterKind, +} from "../../../../../../lib/commandUtils"; +import { describeCondition } from "../../../../../../lib/utils"; +import type { CommandParameter } from "../../../../../../types/data/commandCatalogItem"; interface CommandParametersProps { - fields: Record; + fields: CommandParameter[]; values: Record; onChange: (fieldId: string, value: any) => void; } @@ -26,63 +28,58 @@ export const CommandParameters = ({ onChange, }: CommandParametersProps) => { const renderParameterInput = (field: CommandParameter) => { - if (field.kind === "numeric") { - const numField = field as NumericCommandParameter; - const minSafeRange = numField.safeRange[0]; - const maxSafeRange = numField.safeRange[1]; - const minWarningRange = numField.warningRange[0]; - const maxWarningRange = numField.warningRange[1]; + const kind = getParameterKind(field); + if (kind === "numeric") { return ( -
+
onChange(field.id, e.target.value)} + placeholder={getFieldType(field)} + value={values[field.alias] ?? ""} + onChange={(e) => onChange(field.alias, e.target.value)} onWheel={(e) => e.currentTarget.blur()} className="h-8 text-xs" /> - {minSafeRange !== null && maxSafeRange !== null && ( -

- Range: {minSafeRange} to {maxSafeRange} -

- )} - {minWarningRange !== null && maxWarningRange !== null && ( -

- Warning range: {minWarningRange} to {maxWarningRange} + {field.protections.map((protection) => ( +

+ {protection.severity === "fault" ? "Fault" : "Warning"} if{" "} + {describeCondition(protection.type)} + {protection.time && ` for ${protection.time}`}

- )} + ))}
); } - if (field.kind === "enum") { - const enumField = field as EnumCommandParameter; + if (kind === "enum") { return ( -
+