diff --git a/CHANGELOG.en.md b/CHANGELOG.en.md index 999da76..163d07e 100644 --- a/CHANGELOG.en.md +++ b/CHANGELOG.en.md @@ -4,6 +4,10 @@ English · [简体中文](CHANGELOG.md) ## Unreleased +- Add shared runtime channel ownership, device rebind and coordinated recovery, owned-operation close permits, per-device pacing and failure limits, masked routes and bounded discovery observation. Keep legacy C++ defaults and use the existing Session writer. Add lifecycle, allocation rollback and installed-consumer regression coverage. + +- Add logical device handles with owned inboxes, generation-bound submission and retryable endpoint drain on the existing Session writer. Add shared admission domains and opt-in endpoint-local age checks; preserve legacy defaults. + - Add opt-in Session scheduling for SDK bindings: weighted FIFO and separate latest capacity, endpoint FIFO/fair selection, generation/age admission, start-only deadlines, native per-frame pacing and a consecutive-send-failure threshold. Preserve existing signatures and defaults. - Add atomic conditional latest replacement, endpoint admission/drain gates and value-returning terminal receipt waits. Existing cancellation and throwing waits retain their behavior. - Add coalesced state-change signals, route-key extraction with original frame preservation, shared claim/RX event ordering and queue/route diagnostics. Document the single-writer integration boundary and add offline regressions; no Python binding or hardware acceptance is included. diff --git a/CHANGELOG.md b/CHANGELOG.md index 945b39d..79532a3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,10 @@ ## 未发布 +- 补齐 Runtime 共享连接、设备 rebind 与协调恢复、已登记操作收尾、设备节拍与错误阈值、掩码路由及有界发现观察;复用 Session writer,保留旧 C++ 默认行为,增加生命周期、分配失败回滚及安装消费者回归。 + +- 新增逻辑设备句柄,拥有独立 inbox、绑定 generation 的发送入口及可重试排空,复用原 Session writer;新增共享准入额度域及可选 endpoint 局部队龄检查,保留旧默认行为。 + - 为 SDK 绑定新增可选 Session 调度:FIFO 容量计量与独立 latest 限制、同 endpoint FIFO 和公平选择、generation/年龄准入、开始前 deadline、原生逐帧周期及连续发送失败阈值。保留原有签名和默认值。 - 新增原子的条件 latest 替换、endpoint 准入/排空及返回终态值的回执等待;原取消和抛异常等待接口保持行为。 - 新增可合并状态通知、保留原帧的路由 key 提取、共享领取/RX 事件顺序和队列/路由诊断。说明唯一 writer 接入边界并增加离线回归;不包含 Python 绑定或实机验收。 diff --git a/CMakeLists.txt b/CMakeLists.txt index 4cc956a..39e1ff0 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -68,6 +68,7 @@ add_library(linkerbot-can STATIC src/vendor_canfd_transport.cpp src/vendor_canfd_loader.cpp src/session.cpp + src/runtime.cpp src/pcan_transport.cpp src/pcan_loader.cpp src/slcan_transport.cpp @@ -153,6 +154,7 @@ if(LINKERBOT_TRANSPORT_BUILD_TESTS) tests/test_session.cpp tests/test_session_receive_compat.cpp tests/test_session_tx_compat.cpp + tests/test_transport_runtime.cpp tests/test_session_tx_edges.cpp tests/test_session_physical_compat.cpp tests/test_session_review.cpp diff --git a/docs/en/device-sessions.md b/docs/en/device-sessions.md new file mode 100644 index 0000000..3d22a0c --- /dev/null +++ b/docs/en/device-sessions.md @@ -0,0 +1,55 @@ +# Logical device sessions + +`Session::attach_device(identity, DeviceOptions)` creates a logical device on the existing Session writer. Attach devices before legacy sends or route registration. Raw Session sends are rejected after the first device attaches. Existing Session constructors, default scheduling, receipt methods and deadline policies retain their behavior. + +A device binds its endpoint and physical generation to submissions. Callers cannot override these fields. A closed handle stays closed; attaching the same identity creates a new registration. Recovery invalidates previous handles. `channel_instance` distinguishes connections recreated with the same backend generation. + +## Shared physical ownership + +Include `` to use `TransportRuntime`. Runtime instances in the same linked library share a channel registry and `SharedCANBusPool`. Each channel owns one physical pool lease and one Session; logical devices hold counted leases on that owner. + +`open_device(ChannelSpec, DeviceSpec, factory)` requires an explicit configuration fingerprint for backend settings not represented by `CANBusKey`. Reusing a channel requires identical fingerprints and Session scheduling options. The pool also checks incompatible physical modes. Factories execute outside the registry lock; concurrent first opens share initialization, and cyclic initialization is rejected. + +Closing one device leaves its peers connected. The last device closes the Session and releases the physical lease. Explicit close failures retain the registration and connection owner for retry. Destructor cleanup is best effort and uses the existing physical lease cleanup mechanism; applications should explicitly close and handle errors. + +`recover_channel(key, observed_generation)` coordinates physical recovery. Concurrent callers join an in-progress attempt; successful recovery is reused for an older observed generation. Failed attempts may be retried. Existing handles remain invalid and unfinished work is not replayed. A device registered with `ChannelResetPolicy::kRequireDetach` prevents physical reset until it detaches. This supports SDKs whose recovery requires rebuilding their device state. + +`rebind_device(key, previous, replacement, deadline)` pins the connection, closes the old logical registration, and attaches a replacement without reopening the backend. SDK identity checks, cache invalidation and initialization remain the caller's responsibility. This operation does not replace the existing Python hand recovery behavior, which requests physical recovery. + +## Admission and scheduling + +An `AdmissionDomain` is immutable accounting identity, not another queue. Share a domain object among devices sharing a budget and set it in `DeviceOptions::admission_domain`. FIFO capacity counts batches or frames; latest capacity counts waiting slots. Claimed work does not consume waiting capacity. Both domain and Session limits apply. Failed replacement admission leaves the previous latest job intact. Reusing a domain on separate physical Sessions does not combine their accounting. + +`SessionOptions::domain_round_robin` selects an eligible domain by least recent service before ranking its jobs. It is opt-in for mixed deployments. FIFO work retains device ordering. `max_batch_frames` bounds a claimed atomic batch; zero retains the legacy unlimited batch size. Deployment configuration must choose aggregate budgets and batch limits explicitly. + +Device pending-age checks default to the device endpoint and include queued, writing and final-cooldown work. `PendingAgeScope::kAdmissionDomain` explicitly checks the shared domain. Legacy Session submissions retain the whole-Session default. + +Device `send_period` measures each successful frame from dispatch attempt entry. It disables native batch merging, retains the atomic boundary within a batch, and releases the writer during the final cooldown so another device can send. The same Job remains owned until completion; drain and pending-age accounting include it. Device and legacy Session periods cannot be combined. + +`max_consecutive_send_errors` faults only that device. A successful frame resets its streak; peer success does not. Reaching the threshold fails its waiting jobs and closes its inboxes with a fault reason. It does not directly fault the physical Session. + +The Python source baselines use a shared hand domain of 256 request batches and 64 latest slots with 50 ms aging, and an arm domain of 2000 frames per arm with a 300 microsecond period and error threshold 10. These values are not new C++ defaults. Applications must provide resolved deployment profiles and provenance before treating them as original-business configuration. + +## Deadlines and progress + +`DeadlinePolicy::kDispatchStart` records claim, then checks the deadline once at dispatch entry. Expiry produces zero transmitted frames with claim metadata. Once dispatch begins, that queue deadline does not truncate physical lock waiting or the batch suffix. Explicit cancellation and physical failure still apply. Existing `kExecution` and `kStartOnly` retain their previous boundaries. Caller receipt waits have independent deadlines and do not cancel work. + +`sent_frames` reports the known backend-accepted prefix. `dispatch_completed_frames` separately exposes the prefix whose pacing has completed. Pending final cooldown may therefore show full physical acceptance with incomplete dispatch progress. Ending final cooldown during close preserves a known dispatched result. + +## Device close and owned operations + +`begin_operation()` registers thread-bound SDK work before close begins. The move-only `DeviceOperation` permits that owner to submit restoration work after the public device gate closes. It creates no worker or payload queue. Other threads cannot submit through the operation, and its owning thread cannot synchronously close the device while still holding it. + +`close_until(deadline)` closes public admission, waits for registered operations, cancels waiting jobs, drains claimed work without truncating it, closes device inboxes, and releases the logical channel lease. Timeout retains the registration for retry. Backend close calls can exceed the waiting deadline. Close itself sends no motion, disable, calibration or brake commands; model-specific restoration remains in the SDK. + +## Routes and diagnostics + +`subscribe_routes()` owns exact ID/format pairs. `subscribe_rules()` owns masked ID/format ranges, including extended A7 Lite routing. Rules preserve the original frame and record their logical key separately. Overlap is rejected using actual wire ranges, including exact-versus-masked conflicts. Group registration rolls back after allocation failure. Masked routes cannot use the legacy global extractor. + +`observe_rules(rules, capacity)` provides bounded read-only discovery observation. It does not take route ownership or ordinary receive-budget slots; a full observer drops its own copy. Normal owners receive their frame first. Discovery requests still use the same device writer. Observation inbox health records its own backlog and drops. + +`max_route_keys` bounds registered rules including observations; `max_pending_rx` bounds the ordinary receive backlog. Zero preserves legacy unlimited behavior. Inbox overflow drops the new frame. `compatibility_sequence` increments after matching and before queue offer, so overflow leaves gaps; it resets on physical invalidation. The existing C++ sequence remains unchanged. Device fault reasons are retained by inboxes; legacy inbox close exceptions retain their existing contract. + +Channel health includes route count, receive backlog/high-water mark, routed frames, stale frames, registration quota rejections and close drops. Device health reports admission state, generation, instance, registered operations, send-error streak, queued FIFO frames/latest slots, in-flight jobs and oldest owned work. + +This transport implementation does not provide Python bindings, Python Future execution, protocol transactions, SDK migration or motor safety policy. Hardware timestamps and arbitrary Python backend plugins are not provided by these APIs. Software tests do not establish hardware or firmware compatibility; deployments need the device/driver/topology acceptance checks described in the migration plan. diff --git a/docs/zh/device-sessions.md b/docs/zh/device-sessions.md new file mode 100644 index 0000000..dabbd94 --- /dev/null +++ b/docs/zh/device-sessions.md @@ -0,0 +1,53 @@ +# 逻辑设备会话 + +`Session::attach_device(identity, DeviceOptions)` 在既有 Session writer 上注册设备。必须在旧式发送和路由注册前接入;进入设备模式后,原始 Session 发送被拒绝。现有 C++ 构造入口、默认调度、回执等待和截止时间策略保持兼容。 + +设备句柄为提交绑定独立 endpoint 和物理 generation,调用方不能覆盖。关闭后重新注册同名设备会获得新 endpoint,旧句柄始终关闭。物理恢复使旧句柄失效;`channel_instance` 区分底层 generation 相同但已经重新创建的连接。 + +## 共享连接与恢复 + +`` 提供 `TransportRuntime`。同一链接库内的 Runtime 实例共享通道注册表和 `SharedCANBusPool`,每个通道持有一个物理租约和一个 Session,设备持有逻辑租约。 + +`open_device(ChannelSpec, DeviceSpec, factory)` 要求明确提供配置 fingerprint,覆盖 `CANBusKey` 之外的后端参数。共享连接必须使用一致的 fingerprint 和 Session 调度配置。池同时检查物理模式冲突。factory 在注册表锁外执行;并发首次打开合并初始化,循环等待被拒绝。 + +关闭一个设备保留其他设备通信;最后一个设备关闭 Session 并释放物理租约。显式关闭失败保留注册和连接所有者,允许重试。析构只尽力清理,底层失败资源沿用物理租约的保留机制。应用应显式关闭并处理异常。 + +`recover_channel(key, observed_generation)` 协调物理恢复:并发请求复用在途尝试,成功结果按旧 generation 复用,失败后允许再次尝试。旧句柄失效,未完成工作不重放。`ChannelResetPolicy::kRequireDetach` 阻止活跃设备期间的通道重置,适用于需要重建 SDK 状态的设备。 + +`rebind_device(key, previous, replacement, deadline)` 先保留连接租约,再关闭旧注册并接入替代设备,不重开后端。SDK 仍负责身份核对、缓存失效和初始化。它不替代 Python hand 既有的物理 recover 行为。 + +## 同一队列内的设备政策 + +`AdmissionDomain` 是不可变额度身份,不是额外队列。共享预算的设备使用同一个对象,并通过 `DeviceOptions::admission_domain` 绑定。FIFO 可按批次或帧计费,latest 按等待槽计费,claimed 工作不占等待额度。domain 与 Session 限制同时生效。latest 替换准入失败不影响旧任务。跨物理 Session 使用同一 domain 不合并额度。 + +`domain_round_robin` 为混合通道提供显式跨 domain 轮转,再执行域内排序。设备 FIFO 保持顺序。`max_batch_frames` 限制单个原子批次,零保留旧式不限制行为。部署必须明确给出总容量、批次上限和拓扑。 + +设备默认队龄检查只包含自身 queued、writing 和最终 cooldown;显式 `kAdmissionDomain` 检查共享额度域。旧 Session 提交保留全 Session 默认作用域。 + +设备 `send_period` 从每帧 dispatch attempt 入口计时,禁用原生批次合并,批次内部保持原子边界。最终帧 cooldown 释放 writer,使其他设备可发送;同一个 Job 仍由原生层保留,排空和队龄统计继续计入。设备周期不能与旧 Session 周期同时配置。 + +`max_consecutive_send_errors` 只使相应设备 fault。成功帧清除本设备错误连续计数,邻居发送成功不清除它。达到阈值时终结其等待任务并以 fault 原因关闭 inbox,不直接终止物理 Session。 + +已核对的 Python 源码基准为:hand 共享 FIFO 256 个请求批次、latest 64 槽、aging 50 ms;arm 每臂 FIFO 2000 帧、成功帧周期 300 μs、错误阈值 10。这些不是新的 C++ 默认值。部署需提供展开配置及来源,才能标记为原始业务配置。 + +## 时间、进度与关闭 + +新增 `DeadlinePolicy::kDispatchStart` 先记录 claim,再在 dispatch 入口检查一次截止时间。过期时零帧发送并保留 claim 元数据;开始后不再用该期限截断物理锁等待或发送后缀。取消和物理故障仍生效。旧 `kExecution`、`kStartOnly` 边界不变。调用方等待期限独立,等待超时不取消任务。 + +`sent_frames` 为已知后端接受前缀,`dispatch_completed_frames` 为完成节拍的前缀。最终 cooldown 中可能已经全部物理发送,但 dispatch 尚未完成。关闭唤醒最终等待时保留已知 dispatched 结果。 + +SDK 在关闭前用 `begin_operation()` 登记已有工作。可移动的 `DeviceOperation` 绑定创建线程,允许所属工作在公开准入关闭后发送恢复命令,不创建 worker 或载荷队列。其他线程不能借用它发送;持有操作的线程不能同步等待自身关闭。 + +`close_until(deadline)` 依次关闭公开准入、等待已登记操作、取消等待任务、排空 claimed 批次、关闭设备 inbox、释放逻辑租约。超时保留注册以便重试。底层关闭调用可能超过等待期限。transport 不自动发送运动、失能、标定或抱闸命令;不同型号的收尾规则仍由 SDK 执行。 + +## 路由、发现与诊断 + +`subscribe_routes()` 注册精确 ID 和帧格式,`subscribe_rules()` 注册掩码范围,支持 A7 Lite 扩展 ID。始终交付原始帧,逻辑 key 单独记录。按实际 wire 范围拒绝精确与掩码的重叠,整组注册在分配失败后回滚。掩码规则不能与旧全局 extractor 混用。 + +`observe_rules(rules, capacity)` 提供显式、有界、只读的发现观察。它不占用普通路由所有权或普通接收总容量,原始 owner 优先收到自己的帧;观察流满时仅丢弃其观察副本。发现请求发送仍使用设备的同一 writer。观察 inbox 的容量与丢弃情况通过自身 health 查看。 + +`max_route_keys` 限制注册规则总数,包含观察规则;`max_pending_rx` 限制普通路由总积压。零保留旧无限制行为。溢出丢弃新帧。`compatibility_sequence` 在匹配后、offer 前递增,因此溢出保留间隙;物理失效后重置。原 C++ sequence 不改变。相同报文的普通交付和观察副本共用原生事件顺序。 + +通道 health 包含路由数、普通接收积压与高水位、已路由帧、过期帧、额度拒绝和关闭丢弃。设备 health 包含准入、generation、instance、已登记操作、错误连续计数、等待 FIFO 帧/latest 槽、in-flight Job 和最老工作。设备故障原因由 inbox 保留,旧式 inbox 的关闭异常约定不变。 + +本次不交付 Python 绑定、Future 执行、协议事务、hand/arm SDK 接入或电机安全政策。硬件时间戳和任意 Python 插件后端仍需各自兼容实现。软件 fake 测试不代表实机、固件与驱动已验收;部署继续遵循迁移方案的型号、驱动和拓扑验收要求。 diff --git a/include/linkerbot/can/dispatcher.hpp b/include/linkerbot/can/dispatcher.hpp index a0dcafb..ef2cc1c 100644 --- a/include/linkerbot/can/dispatcher.hpp +++ b/include/linkerbot/can/dispatcher.hpp @@ -24,6 +24,14 @@ #include namespace linkerbot::can { + // Native endpoint pacing. Output pointers must outlive the synchronous call. + struct LocalBatchPacing { + bool enabled = false; + bool defer_final_cooldown = false; + std::chrono::steady_clock::time_point attempt_started{}; + std::chrono::steady_clock::time_point *cooldown_until = nullptr; + std::atomic *dispatch_progress = nullptr; + }; using SubscriptionId = uint64_t; @@ -478,7 +486,22 @@ namespace linkerbot::can { bool &uncertain, bool start_only, std::chrono::microseconds send_period, std::atomic *progress = nullptr) -> void { + send_batch_until(frames, deadline, gap, initial_delay, cancelled, sent, uncertain, + start_only, send_period, progress, LocalBatchPacing{}); + } + + auto send_batch_until(const std::vector &frames, + std::chrono::steady_clock::time_point deadline, + std::chrono::microseconds gap, + std::chrono::microseconds initial_delay, + const std::function &cancelled, + size_t &sent, // NOLINT(bugprone-easily-swappable-parameters) + bool &uncertain, bool start_only, + std::chrono::microseconds send_period, std::atomic *progress, + const LocalBatchPacing &local) -> void { sent = 0; + auto local_next = std::chrono::steady_clock::time_point{}; + auto &next_write = local.enabled ? local_next : next_write_at_; if (progress != nullptr) { progress->store(0, std::memory_order_relaxed); } @@ -521,9 +544,9 @@ namespace linkerbot::can { pace(initial_delay); if (gap.count() == 0 && send_period.count() == 0 && transport_->prefers_write_batch() && !frames.empty()) { - while (std::chrono::steady_clock::now() < next_write_at_) { + while (std::chrono::steady_clock::now() < next_write) { pace(std::chrono::duration_cast( - next_write_at_ - std::chrono::steady_clock::now())); + next_write - std::chrono::steady_clock::now())); } begun = true; uncertain = true; @@ -538,12 +561,14 @@ namespace linkerbot::can { if (sent != 0u) { pace(gap); } - while (std::chrono::steady_clock::now() < next_write_at_) { + while (std::chrono::steady_clock::now() < next_write) { pace(std::chrono::duration_cast( - next_write_at_ - std::chrono::steady_clock::now())); + next_write - std::chrono::steady_clock::now())); } check(); - const auto write_started = std::chrono::steady_clock::now(); + const auto write_started = local.enabled && sent == 0u + ? local.attempt_started + : std::chrono::steady_clock::now(); begun = true; uncertain = true; transport_->write(frame); @@ -556,12 +581,18 @@ namespace linkerbot::can { const auto remaining = std::chrono::duration_cast( std::chrono::steady_clock::time_point::max() - write_started); - next_write_at_ = send_period >= remaining - ? std::chrono::steady_clock::time_point::max() - : write_started + send_period; + next_write = send_period >= remaining + ? std::chrono::steady_clock::time_point::max() + : write_started + send_period; // Once every frame was accepted, cancellation or expiry // may shorten cooldown but cannot deny known delivery. - while (std::chrono::steady_clock::now() < next_write_at_) { + if (local.cooldown_until != nullptr) { + *local.cooldown_until = next_write; + } + if (local.defer_final_cooldown && sent == frames.size()) { + break; + } + while (std::chrono::steady_clock::now() < next_write) { if (sent == frames.size()) { if (!running_.load(std::memory_order_acquire) || (cancelled && cancelled()) || @@ -572,11 +603,14 @@ namespace linkerbot::can { check(); } std::this_thread::sleep_until( - std::min({next_write_at_, effective_deadline(), + std::min({next_write, effective_deadline(), std::chrono::steady_clock::now() + std::chrono::microseconds(250)})); } } + if (local.dispatch_progress != nullptr) { + local.dispatch_progress->store(sent, std::memory_order_relaxed); + } } } const std::scoped_lock health_lock(health_mutex_); diff --git a/include/linkerbot/can/managed_bus.hpp b/include/linkerbot/can/managed_bus.hpp index de858ca..479958c 100644 --- a/include/linkerbot/can/managed_bus.hpp +++ b/include/linkerbot/can/managed_bus.hpp @@ -178,6 +178,19 @@ namespace linkerbot::can { uncertain, start_only, send_period, progress); } + auto send_batch_until(const std::vector &frames, + std::chrono::steady_clock::time_point deadline, + std::chrono::microseconds gap, + std::chrono::microseconds initial_delay, + const std::function &cancelled, size_t &sent, bool &uncertain, + bool start_only, std::chrono::microseconds send_period, + std::atomic *progress, + const LocalBatchPacing &local) -> void { + const auto dispatcher = require_dispatcher(); + dispatcher->send_batch_until(frames, deadline, gap, initial_delay, cancelled, sent, + uncertain, start_only, send_period, progress, local); + } + auto queue_send(const Message &message) -> SendReceipt { auto state = std::make_shared(); { diff --git a/include/linkerbot/transport/runtime.hpp b/include/linkerbot/transport/runtime.hpp new file mode 100644 index 0000000..feaabf5 --- /dev/null +++ b/include/linkerbot/transport/runtime.hpp @@ -0,0 +1,39 @@ +#pragma once + +#include +#include + +namespace linkerbot::transport { + enum class ChannelResetPolicy { kAllowCoordinatedReset, kRequireDetach }; + struct ChannelSpec { + can::CANBusKey key; + // Canonical identity for all backend settings not represented in key. + std::string configuration_fingerprint; + SessionOptions scheduling; + }; + struct DeviceSpec { + std::string identity; + DeviceOptions scheduling; + ChannelResetPolicy channel_reset = ChannelResetPolicy::kAllowCoordinatedReset; + }; + + // All instances in this linked runtime share one channel registry and pool. + // Last-device close releases the physical lease; failed closes are retryable. + class TransportRuntime { + public: + TransportRuntime(); + std::shared_ptr open_device(ChannelSpec channel, DeviceSpec device, + Session::Factory factory); + // Replace only this logical registration. SDK revalidation runs separately. + std::shared_ptr rebind_device(const can::CANBusKey &key, + const std::shared_ptr &previous, + DeviceSpec device, Deadline deadline); + [[nodiscard]] size_t active_devices(const can::CANBusKey &key) const; + [[nodiscard]] SessionHealth channel_health(const can::CANBusKey &key) const; + uint64_t recover_channel(const can::CANBusKey &key, uint64_t observed_generation); + + private: + struct Impl; + std::shared_ptr impl_; + }; +} // namespace linkerbot::transport diff --git a/include/linkerbot/transport/session.hpp b/include/linkerbot/transport/session.hpp index 24243ea..01fa292 100644 --- a/include/linkerbot/transport/session.hpp +++ b/include/linkerbot/transport/session.hpp @@ -12,6 +12,7 @@ #include #include #include +#include #include namespace linkerbot::can { @@ -22,6 +23,9 @@ namespace linkerbot::can { } // namespace linkerbot::can namespace linkerbot::transport { + class DeviceSession; + class DeviceOperation; + class TransportRuntime; // Coalesced state-change notification for a language/runtime bridge. Read the // revision before inspecting state, then wait on that revision. No application @@ -52,6 +56,15 @@ namespace linkerbot::transport { } }; + struct RouteRule { + uint32_t value = 0; + uint32_t mask = 0x7ff; + bool extended = false; + friend bool operator<(const RouteRule &a, const RouteRule &b) noexcept { + return std::tie(a.extended, a.mask, a.value) < std::tie(b.extended, b.mask, b.value); + } + }; + struct RoutedMessage { can::Message message; uint64_t generation = 0; @@ -59,6 +72,8 @@ namespace linkerbot::transport { Deadline received_at{}; RouteKey route_key{}; uint64_t received_order = 0; // Same Session event domain as SendResult::claimed_order. + uint64_t compatibility_sequence = 0; + uint64_t channel_instance = 0; }; struct RouteHealth { @@ -106,7 +121,34 @@ namespace linkerbot::transport { }; enum class CapacityUnit { kBatches, kFrames }; - enum class DeadlinePolicy { kExecution, kStartOnly }; + enum class DeadlinePolicy { kExecution, kStartOnly, kDispatchStart }; + enum class PendingAgeScope { kSession, kEndpoint, kAdmissionDomain }; + + struct AdmissionLimits { + size_t fifo_capacity = 2000; + size_t latest_capacity = 64; + CapacityUnit fifo_unit = CapacityUnit::kBatches; + }; + + // Shared accounting identity, not another queue or writer. Limits are immutable. + class AdmissionDomain { + public: + explicit AdmissionDomain(AdmissionLimits limits); + AdmissionDomain(const AdmissionDomain &) = delete; + AdmissionDomain &operator=(const AdmissionDomain &) = delete; + [[nodiscard]] AdmissionLimits limits() const noexcept { + return limits_; + } + + private: + AdmissionLimits limits_; + }; + + struct DeviceOptions { + std::shared_ptr admission_domain = nullptr; + std::chrono::microseconds send_period{0}; + uint32_t max_consecutive_send_errors = 0; + }; // Opt-in SDK scheduling. Defaults retain the existing Session behavior. struct SessionOptions { @@ -119,6 +161,10 @@ namespace linkerbot::transport { std::chrono::milliseconds aging_quantum{10}; std::chrono::microseconds send_period{0}; uint32_t max_consecutive_send_errors = 0; // zero disables terminal TX faulting + bool domain_round_robin = false; + size_t max_route_keys = 0; // zero preserves the legacy unlimited registry + size_t max_pending_rx = 0; + size_t max_batch_frames = 0; // zero preserves legacy unbounded batch size }; struct SendOptions { @@ -131,6 +177,8 @@ namespace linkerbot::transport { std::optional expected_generation = std::nullopt; std::optional max_pending_age = std::nullopt; DeadlinePolicy deadline_policy = DeadlinePolicy::kExecution; + PendingAgeScope pending_age_scope = PendingAgeScope::kSession; + std::shared_ptr admission_domain = nullptr; }; struct SendResult { @@ -146,6 +194,8 @@ namespace linkerbot::transport { bool current_frame_uncertain = false; std::exception_ptr error; std::optional claimed_order = std::nullopt; + size_t dispatch_completed_frames = 0; + uint64_t channel_instance = 0; }; class SendReceipt { @@ -207,6 +257,14 @@ namespace linkerbot::transport { uint64_t rejected_stale = 0; uint32_t consecutive_send_errors = 0; uint64_t route_key_errors = 0; + size_t route_count = 0; + size_t pending_rx = 0; + size_t max_pending_rx = 0; + uint64_t routed_rx_frames = 0; + uint64_t stale_rx_frames = 0; + uint64_t route_registration_rejections = 0; + uint64_t dropped_rx_on_close = 0; + uint64_t channel_instance = 0; }; // One Session per physical ManagedCANBus/borrowed Dispatcher. All Session @@ -222,6 +280,9 @@ namespace linkerbot::transport { // Caller must keep Dispatcher alive until all runtimes/Session references // are destroyed. Physical recover is unavailable for this borrowed adapter. static std::shared_ptr borrow(can::CANDispatcher &dispatcher); + // Logical device ownership; all devices still submit to this Session's writer. + std::shared_ptr attach_device(std::string identity); + std::shared_ptr attach_device(std::string identity, DeviceOptions options); ~Session(); // Final release inside RX/backend callbacks defers destruction to an // external cleanup worker. A borrowed dispatcher must outlive this drain. @@ -271,12 +332,88 @@ namespace linkerbot::transport { void close(); private: + friend class DeviceSession; struct Impl; class Cleanup; explicit Session(std::unique_ptr impl); void start(); std::optional submit_impl(MessageBatch batch, SendOptions options, - bool replace_only); + bool replace_only, + std::shared_ptr owner = nullptr); + std::shared_ptr subscribe_routes_impl(const std::vector &keys, + size_t capacity, const void *device); + std::shared_ptr subscribe_rules_impl(const std::vector &rules, + size_t capacity, const void *device, + bool observation = false); std::unique_ptr impl_; }; + + // A device owns its admission gate and inboxes, not the physical connection. + // Explicit close is retryable after a drain timeout. Destruction attempts close. + struct DeviceHealth { + bool accepting = false; + bool closed = false; + uint64_t generation = 0; + size_t owned_operations = 0; + bool faulted = false; + uint32_t consecutive_send_errors = 0; + uint64_t channel_instance = 0; + size_t pending_fifo = 0; + size_t pending_latest = 0; + size_t in_flight = 0; + std::optional oldest_pending = std::nullopt; + }; + + class DeviceSession : public std::enable_shared_from_this { + public: + ~DeviceSession(); + DeviceSession(const DeviceSession &) = delete; + DeviceSession &operator=(const DeviceSession &) = delete; + SendReceipt submit(MessageBatch batch, SendOptions options = {}); + std::optional replace_latest_if_pending(MessageBatch batch, + SendOptions options); + std::shared_ptr subscribe_routes(const std::vector &keys, + size_t capacity = 256); + std::shared_ptr subscribe_rules(const std::vector &rules, + size_t capacity = 256); + // Bounded read-only discovery observation; never takes route ownership. + std::shared_ptr observe_rules(const std::vector &rules, + size_t capacity); + void close_until(Deadline deadline); + // Register before close begins. Already-owned work may finish while closing. + DeviceOperation begin_operation(); + [[nodiscard]] DeviceHealth health() const; + [[nodiscard]] std::shared_ptr notification() const; + [[nodiscard]] bool closed() const; + [[nodiscard]] uint64_t generation() const; + + private: + friend class Session; + friend class DeviceOperation; + friend class TransportRuntime; + struct State; + explicit DeviceSession(std::shared_ptr state); + std::optional submit_impl(MessageBatch batch, SendOptions options, + bool replace_only, bool owned = false); + std::shared_ptr state_; + void set_channel_release(std::function release); + }; + + // Thread-bound SDK work lease. No worker, payload queue or physical ownership. + class DeviceOperation { + public: + DeviceOperation(); + ~DeviceOperation(); + DeviceOperation(DeviceOperation &&) noexcept; + DeviceOperation &operator=(DeviceOperation &&) noexcept; + DeviceOperation(const DeviceOperation &) = delete; + DeviceOperation &operator=(const DeviceOperation &) = delete; + SendReceipt submit(MessageBatch batch, SendOptions options = {}); + + private: + friend class DeviceSession; + struct State; + explicit DeviceOperation(std::unique_ptr state); + std::unique_ptr state_; + }; } // namespace linkerbot::transport diff --git a/src/runtime.cpp b/src/runtime.cpp new file mode 100644 index 0000000..77f7524 --- /dev/null +++ b/src/runtime.cpp @@ -0,0 +1,312 @@ +#include + +#include +#include +#include +#include +#include +#include + +namespace linkerbot::transport { + namespace { + bool same_scheduling(const SessionOptions &a, const SessionOptions &b) { + return std::tie(a.tx_capacity, a.separate_policy_capacity, a.fifo_capacity, + a.latest_capacity, a.fifo_unit, a.endpoint_fifo, a.aging_quantum, + a.send_period, a.max_consecutive_send_errors, a.domain_round_robin, + a.max_route_keys, a.max_pending_rx, a.max_batch_frames) == + std::tie(b.tx_capacity, b.separate_policy_capacity, b.fifo_capacity, + b.latest_capacity, b.fifo_unit, b.endpoint_fifo, b.aging_quantum, + b.send_period, b.max_consecutive_send_errors, b.domain_round_robin, + b.max_route_keys, b.max_pending_rx, b.max_batch_frames); + } + + struct RecoveryAttempt { + std::mutex mutex; + std::condition_variable changed; + bool completed = false; + uint64_t generation = 0; + std::exception_ptr error; + }; + struct Channel { + can::CANBusLease lease; + std::shared_ptr session; + ChannelSpec spec; + mutable std::mutex mutex; + size_t devices = 0; + size_t reset_blockers = 0; + bool closing = false; + bool closed = false; + std::exception_ptr close_error; + std::shared_ptr recovery; + + Channel(can::CANBusLease connection, std::shared_ptr parent, + ChannelSpec specification) + : lease(std::move(connection)), session(std::move(parent)), + spec(std::move(specification)) {} + + void acquire(ChannelResetPolicy policy) { + std::lock_guard lock(mutex); + if (closing || closed || (recovery && !recovery->completed)) { + throw can::FaultedError("channel release is incomplete or already closed"); + } + ++devices; + if (policy == ChannelResetPolicy::kRequireDetach) { + ++reset_blockers; + } + } + void release(ChannelResetPolicy policy) { + { + std::lock_guard lock(mutex); + if (devices > 1) { + --devices; + if (policy == ChannelResetPolicy::kRequireDetach) { + --reset_blockers; + } + return; + } + closing = true; + } + try { + session->close(); + lease.close(); + } catch (...) { + std::lock_guard lock(mutex); + close_error = std::current_exception(); + throw; + } + std::lock_guard lock(mutex); + devices = 0; + reset_blockers = 0; + closed = true; + closing = false; + close_error = {}; + } + }; + + struct LogicalLease { + std::shared_ptr channel; + bool active = false; + ChannelResetPolicy policy; + LogicalLease(std::shared_ptr owner, ChannelResetPolicy reset_policy) + : channel(std::move(owner)), active(true), policy(reset_policy) { + channel->acquire(policy); + } + ~LogicalLease() { + if (active) { + try { + release(); + } catch (...) { + // The physical lease destructor retains failed cleanup ownership. + std::lock_guard lock(channel->mutex); + channel->close_error = std::current_exception(); + } + } + } + void release() { + if (active) { + channel->release(policy); + active = false; + } + } + }; + } // namespace + + struct TransportRuntime::Impl { + struct Entry { + std::weak_ptr channel; + std::condition_variable changed; + bool opening = false; + std::thread::id initializer; + uint64_t attempt = 0; + }; + struct WaitEdge { + Entry *entry; + std::thread::id initializer; + uint64_t attempt; + }; + can::SharedCANBusPool pool; + mutable std::mutex mutex; + std::map> channels; + std::map waiters; + + std::shared_ptr find(const can::CANBusKey &key) const { + std::lock_guard lock(mutex); + const auto it = channels.find(key); + if (it == channels.end()) { + return {}; + } + return it->second->channel.lock(); + } + }; + TransportRuntime::TransportRuntime() + : impl_([] { + static const auto core = std::make_shared(); + return core; + }()) {} + std::shared_ptr TransportRuntime::open_device(ChannelSpec channel, + DeviceSpec device, + Session::Factory factory) { + if (channel.configuration_fingerprint.empty() || !factory || device.identity.empty() || + device.scheduling.send_period.count() < 0 || + (device.channel_reset != ChannelResetPolicy::kAllowCoordinatedReset && + device.channel_reset != ChannelResetPolicy::kRequireDetach)) { + throw can::ValidationError("channel fingerprint and factory must be explicit"); + } + std::shared_ptr context; + std::shared_ptr entry; + { + std::unique_lock lock(impl_->mutex); + auto &slot = impl_->channels[channel.key]; + if (!slot) { + slot = std::make_shared(); + } + entry = slot; + while (entry->opening) { + const auto caller = std::this_thread::get_id(); + auto owner = entry->initializer; + for (;;) { + if (owner == caller) { + throw can::ValidationError("cyclic channel initialization"); + } + const auto waiting = impl_->waiters.find(owner); + if (waiting == impl_->waiters.end()) { + break; + } + const auto &edge = waiting->second; + if (!edge.entry->opening || edge.entry->attempt != edge.attempt || + edge.entry->initializer != edge.initializer) { + break; + } + owner = edge.initializer; + } + if (!impl_->waiters + .emplace(caller, + Impl::WaitEdge{entry.get(), entry->initializer, entry->attempt}) + .second) { + throw can::ValidationError("reentrant initialization of the same channel"); + } + struct ClearWait { + Impl *core; + std::thread::id thread; + ~ClearWait() { + core->waiters.erase(thread); + } + } waiting{impl_.get(), caller}; + entry->changed.wait(lock); + } + context = entry->channel.lock(); + if (!context) { + entry->opening = true; + entry->initializer = std::this_thread::get_id(); + ++entry->attempt; + } + } + if (!context) { + try { + auto lease = impl_->pool.acquire(channel.key, std::move(factory)); + auto session = Session::share(lease.shared_bus()); + session->configure(channel.scheduling); + context = std::make_shared(std::move(lease), session, channel); + std::lock_guard lock(impl_->mutex); + entry->channel = context; + entry->opening = false; + entry->changed.notify_all(); + } catch (...) { + std::lock_guard lock(impl_->mutex); + entry->opening = false; + entry->changed.notify_all(); + throw; + } + } + if (context->spec.configuration_fingerprint != channel.configuration_fingerprint || + !same_scheduling(context->spec.scheduling, channel.scheduling)) { + throw can::ValidationError("shared channel configurations differ"); + } + auto lease = std::make_shared(context, device.channel_reset); + std::function release = [lease] { lease->release(); }; + auto handle = context->session->attach_device(std::move(device.identity), + std::move(device.scheduling)); + handle->set_channel_release(std::move(release)); + return handle; + } + size_t TransportRuntime::active_devices(const can::CANBusKey &key) const { + const auto context = impl_->find(key); + if (!context) { + return 0; + } + std::lock_guard lock(context->mutex); + return context->devices; + } + std::shared_ptr + TransportRuntime::rebind_device(const can::CANBusKey &key, + const std::shared_ptr &previous, + DeviceSpec device, Deadline deadline) { + const auto context = impl_->find(key); + if (!context || !previous || previous->closed() || + previous->health().channel_instance != context->session->health().channel_instance) { + throw can::ValidationError("rebind requires an active handle on this channel"); + } + if (device.identity.empty() || device.scheduling.send_period.count() < 0 || + (device.channel_reset != ChannelResetPolicy::kAllowCoordinatedReset && + device.channel_reset != ChannelResetPolicy::kRequireDetach)) { + throw can::ValidationError("invalid replacement device profile"); + } + // Pin the connection before releasing the previous device's logical lease. + auto lease = std::make_shared(context, device.channel_reset); + std::function release = [lease] { lease->release(); }; + previous->close_until(deadline); + auto handle = context->session->attach_device(std::move(device.identity), + std::move(device.scheduling)); + handle->set_channel_release(std::move(release)); + return handle; + } + SessionHealth TransportRuntime::channel_health(const can::CANBusKey &key) const { + const auto context = impl_->find(key); + if (!context) { + throw can::ClosedError("channel has no active owner"); + } + return context->session->health(); + } + uint64_t TransportRuntime::recover_channel(const can::CANBusKey &key, + uint64_t observed_generation) { + const auto context = impl_->find(key); + if (!context) { + throw can::ClosedError("channel has no active owner"); + } + std::shared_ptr attempt; + bool owner = false; + { + std::lock_guard lock(context->mutex); + if (context->closing || context->closed || context->reset_blockers != 0) { + throw can::ValidationError("channel reset requires all devices to permit it"); + } + attempt = context->recovery; + if (!attempt || attempt->completed) { + attempt = std::make_shared(); + context->recovery = attempt; + owner = true; + } + } + if (owner) { + std::exception_ptr error; + uint64_t generation = 0; + try { + generation = context->session->recover(observed_generation); + } catch (...) { + error = std::current_exception(); + } + std::lock_guard lock(context->mutex); + std::lock_guard result_lock(attempt->mutex); + attempt->generation = generation; + attempt->error = std::move(error); + attempt->completed = true; + attempt->changed.notify_all(); + } + std::unique_lock lock(attempt->mutex); + attempt->changed.wait(lock, [&] { return attempt->completed; }); + if (attempt->error) { + std::rethrow_exception(attempt->error); + } + return attempt->generation; + } +} // namespace linkerbot::transport diff --git a/src/session.cpp b/src/session.cpp index 7f49da7..d2a238c 100644 --- a/src/session.cpp +++ b/src/session.cpp @@ -15,7 +15,57 @@ #include namespace linkerbot::transport { + struct DeviceSession::State { + std::shared_ptr session; + std::string endpoint; + uint64_t generation = 0; + uint64_t channel_instance = 0; + mutable std::mutex gate; + std::mutex closer; + std::condition_variable close_changed; + bool close_active = false; + bool closing = false; + std::atomic closed{true}; + std::vector> inboxes; + std::condition_variable work_changed; + std::map operations; + std::shared_ptr signal; + DeviceOptions options; + std::atomic faulted{false}; + std::atomic consecutive_send_errors{0}; + Deadline next_eligible{}; + std::function channel_release; + }; + + struct DeviceOperation::State { + std::shared_ptr device; + std::thread::id thread; + bool active = false; + ~State() { + if (active) { + auto ®istration = *device->state_; + std::lock_guard lock(registration.gate); + auto &count = registration.operations.at(thread); + if (--count == 0) { + registration.operations.erase(thread); + } + registration.work_changed.notify_all(); + registration.signal->notify(); + } + } + }; + AdmissionDomain::AdmissionDomain(AdmissionLimits limits) : limits_(limits) { + if (limits.fifo_capacity == 0 || limits.latest_capacity == 0 || + (limits.fifo_unit != CapacityUnit::kBatches && + limits.fifo_unit != CapacityUnit::kFrames)) { + throw can::ValidationError("invalid admission domain limits"); + } + } namespace { + uint64_t next_channel_instance() { + static std::atomic next{0}; + return ++next; + } auto current_writer() -> const void *& { static thread_local const void *writer = nullptr; return writer; @@ -71,6 +121,17 @@ namespace linkerbot::transport { ++state_->revision; state_->cv.notify_all(); } + struct ReceiveCounters { + std::atomic pending{0}; + std::atomic high_water{0}; + std::atomic dropped{0}; + void enqueue() { + const auto depth = pending.fetch_add(1) + 1; + auto high = high_water.load(); + while (high < depth && !high_water.compare_exchange_weak(high, depth)) { + } + } + }; struct RouteInbox::State { mutable std::mutex mutex; std::condition_variable cv; @@ -78,7 +139,24 @@ namespace linkerbot::transport { RouteHealth health; size_t capacity = 512; const void *owner = nullptr; + const void *device = nullptr; + std::exception_ptr terminal_reason; + std::shared_ptr counters; + bool masked = false; + std::vector observed_rules; std::shared_ptr signal; + void close_locked(std::exception_ptr reason = {}) { + if (!health.closed && reason) { + terminal_reason = std::move(reason); + } + health.closed = true; + health.dropped_on_close += queue.size(); + counters->pending.fetch_sub(queue.size()); + counters->dropped.fetch_add(queue.size()); + queue.clear(); + cv.notify_all(); + signal->notify(); + } }; RouteInbox::RouteInbox(std::shared_ptr state) : state_(std::move(state)) {} RouteInbox::~RouteInbox() { @@ -86,11 +164,7 @@ namespace linkerbot::transport { } void RouteInbox::close() noexcept { std::lock_guard lock(state_->mutex); - state_->health.closed = true; - state_->health.dropped_on_close += state_->queue.size(); - state_->queue.clear(); - state_->cv.notify_all(); - state_->signal->notify(); + state_->close_locked(); } RouteHealth RouteInbox::health() const { std::lock_guard lock(state_->mutex); @@ -109,6 +183,9 @@ namespace linkerbot::transport { state_->cv.wait_until(lock, deadline, [&] { return state_->health.closed || !state_->queue.empty(); }); if (state_->health.closed) { + if (state_->terminal_reason) { + std::rethrow_exception(state_->terminal_reason); + } throw can::ClosedError("route generation is closed"); } if (state_->queue.empty()) { @@ -116,6 +193,7 @@ namespace linkerbot::transport { } auto message = std::move(state_->queue.front()); state_->queue.pop_front(); + state_->counters->pending.fetch_sub(1); return message; } @@ -124,6 +202,7 @@ namespace linkerbot::transport { std::condition_variable cv; SendResult result; std::atomic progress{0}; + std::atomic dispatch_progress{0}; std::shared_ptr signal; }; SendReceipt::SendReceipt(std::shared_ptr state) : state_(std::move(state)) {} @@ -135,6 +214,8 @@ namespace linkerbot::transport { auto result = state_->result; if (result.outcome == SendOutcome::pending) { result.sent_frames = state_->progress.load(std::memory_order_relaxed); + result.dispatch_completed_frames = + state_->dispatch_progress.load(std::memory_order_relaxed); } return result; } @@ -182,10 +263,12 @@ namespace linkerbot::transport { Impl *cleanup_next = nullptr; void close(); struct Job { + std::shared_ptr owner; MessageBatch batch; SendOptions options; CancellationSource abort; std::shared_ptr receipt; + Deadline complete_at{}; }; std::shared_ptr bus; std::unique_ptr owned_dispatcher; @@ -197,8 +280,16 @@ namespace linkerbot::transport { std::mutex lifecycle; std::condition_variable cv; std::map> routes; + std::map> patterns; + std::vector> observers; + std::shared_ptr receive_counters = std::make_shared(); + uint64_t compatibility_sequence = 0; + std::map> devices; + uint64_t next_device = 0; + bool device_mode = false; std::deque> jobs; std::shared_ptr claimed; + std::vector> cooling; std::thread writer; bool stopping = false; bool recovering = false; @@ -211,10 +302,42 @@ namespace linkerbot::transport { uint64_t lifecycle_revision = 0; uint64_t service_order = 0; std::map last_served; + std::map, uint64_t, + std::owner_less>> + last_domain; uint64_t sequence = 0; std::shared_ptr signal = std::make_shared(); std::function route_key_of; SessionHealth health; + uint64_t instance = next_channel_instance(); + + static bool overlaps(const RouteRule &a, const RouteRule &b) { + return a.extended == b.extended && ((a.value ^ b.value) & a.mask & b.mask) == 0; + } + size_t route_count(const RouteInbox::State *exclude = nullptr) const { + size_t count = 0; + const auto add = [&](const auto &entries) { + for (const auto &entry : entries) { + if (auto route = entry.second.lock(); route && route.get() != exclude) { + std::lock_guard lock(route->mutex); + if (!route->health.closed) { + ++count; + } + } + } + }; + add(routes); + add(patterns); + for (const auto &entry : observers) { + if (auto route = entry.lock(); route && route.get() != exclude) { + std::lock_guard lock(route->mutex); + if (!route->health.closed) { + count += route->observed_rules.size(); + } + } + } + return count; + } void finish(const std::shared_ptr &job, SendOutcome outcome, std::exception_ptr error = {}, size_t sent = 0, bool uncertain = false) { @@ -226,6 +349,12 @@ namespace linkerbot::transport { r.outcome = outcome; r.error = std::move(error); r.sent_frames = sent; + const auto *device = static_cast(job->owner.get()); + r.dispatch_completed_frames = + device != nullptr && device->options.send_period.count() != 0 && + outcome != SendOutcome::dispatched + ? job->receipt->dispatch_progress.load(std::memory_order_relaxed) + : sent; r.current_frame_uncertain = uncertain; r.completed_at = Clock::now(); switch (outcome) { @@ -265,27 +394,62 @@ namespace linkerbot::transport { } return {fifo, latest}; } - Deadline oldest_accepted() const { - auto oldest = claimed ? claimed->receipt->result.accepted_at : Deadline::max(); + Deadline oldest_accepted(const std::string *endpoint = nullptr, + const AdmissionDomain *domain = nullptr) const { + const auto matches = [&](const auto &job) { + return (endpoint == nullptr || job->options.endpoint == *endpoint) && + (domain == nullptr || job->options.admission_domain.get() == domain); + }; + auto oldest = claimed && matches(claimed) ? claimed->receipt->result.accepted_at + : Deadline::max(); for (const auto &job : jobs) { - oldest = std::min(oldest, job->receipt->result.accepted_at); + if (matches(job)) { + oldest = std::min(oldest, job->receipt->result.accepted_at); + } + } + for (const auto &job : cooling) { + if (matches(job)) { + oldest = std::min(oldest, job->receipt->result.accepted_at); + } } return oldest; } + void complete_cooling(bool all = false) { + for (auto it = cooling.begin(); it != cooling.end();) { + auto &job = *it; + if (all || Clock::now() >= job->complete_at || job->abort.token().cancelled() || + job->options.cancellation.cancelled()) { + finish(job, SendOutcome::dispatched, {}, job->batch.frames.size()); + it = cooling.erase(it); + cv.notify_all(); + } else { + ++it; + } + } + } void invalidate_locked(std::exception_ptr reason) { ++lifecycle_revision; - for (auto &[key, weak] : routes) { - (void)key; - if (auto route = weak.lock()) { + compatibility_sequence = 0; + complete_cooling(true); + const auto close_routes = [&](auto &entries) { + for (auto &entry : entries) { + if (auto route = entry.second.lock()) { + std::lock_guard lock(route->mutex); + route->close_locked(route->device != nullptr ? reason + : std::exception_ptr{}); + } + } + entries.clear(); + }; + close_routes(routes); + close_routes(patterns); + for (const auto &entry : observers) { + if (auto route = entry.lock()) { std::lock_guard lock(route->mutex); - route->health.closed = true; - route->health.dropped_on_close += route->queue.size(); - route->queue.clear(); - route->cv.notify_all(); - route->signal->notify(); + route->close_locked(reason); } } - routes.clear(); + observers.clear(); for (auto &job : jobs) { job->abort.cancel(); finish(job, SendOutcome::cancelled, reason); @@ -330,6 +494,7 @@ namespace linkerbot::transport { refresh(); std::lock_guard lock(mutex); if (stopping || !health.open) { + ++health.stale_rx_frames; return; } try { @@ -358,28 +523,85 @@ namespace linkerbot::transport { } const auto it = routes.find(key); auto route = it == routes.end() ? nullptr : it->second.lock(); + if (route) { + bool closed = false; + { + std::lock_guard route_lock(route->mutex); + closed = route->health.closed; + } + if (closed) { + route.reset(); + } + } if (!route) { - ++health.route_misses; - return; + for (const auto &entry : patterns) { + if (entry.first.extended == message.is_extended && + (message.id & entry.first.mask) == entry.first.value) { + auto candidate = entry.second.lock(); + if (candidate) { + std::lock_guard route_lock(candidate->mutex); + if (!candidate->health.closed) { + route = std::move(candidate); + key = {entry.first.value, entry.first.extended}; + break; + } + } + } + } } - std::lock_guard route_lock(route->mutex); - if (route->health.closed || route->health.generation != health.generation) { - ++health.route_misses; - return; + bool matched = false; + uint64_t compat_sequence = 0; + uint64_t order = 0; + const auto received = Clock::now(); + const auto offer = [&](const std::shared_ptr &target, + RouteKey logical_key, bool observer) { + std::lock_guard route_lock(target->mutex); + if (target->health.closed || target->health.generation != health.generation) { + return; + } + if (!matched) { + compat_sequence = ++compatibility_sequence; + order = ++event_order; + matched = true; + } + if (target->queue.size() >= target->capacity || + (!observer && options.max_pending_rx != 0 && + receive_counters->pending.load() >= options.max_pending_rx)) { + ++target->health.overflow; + ++health.overflows; + target->cv.notify_all(); + target->signal->notify(); + return; + } + target->queue.push_back({message, health.generation, ++sequence, received, + logical_key, order, compat_sequence, instance}); + target->counters->enqueue(); + if (!observer) { + ++health.routed_rx_frames; + } + ++target->health.delivered; + target->health.high_water = + std::max(target->health.high_water, target->queue.size()); + target->cv.notify_one(); + target->signal->notify(); + }; + if (route) { + offer(route, key, false); } - if (route->queue.size() >= route->capacity) { - ++route->health.overflow; - ++health.overflows; - route->cv.notify_all(); - route->signal->notify(); - return; + for (const auto &entry : observers) { + if (auto observer = entry.lock()) { + for (const auto &rule : observer->observed_rules) { + if (rule.extended == message.is_extended && + (message.id & rule.mask) == rule.value) { + offer(observer, {rule.value, rule.extended}, true); + break; + } + } + } + } + if (!matched) { + ++health.route_misses; } - route->queue.push_back( - {message, health.generation, ++sequence, Clock::now(), key, ++event_order}); - ++route->health.delivered; - route->health.high_water = std::max(route->health.high_water, route->queue.size()); - route->cv.notify_one(); - route->signal->notify(); } catch (const std::exception &error) { std::lock_guard lock(mutex); health.last_error = error.what(); @@ -407,12 +629,22 @@ namespace linkerbot::transport { std::shared_ptr job; { std::unique_lock lock(mutex); - cv.wait_for(lock, std::chrono::milliseconds(2), - [&] { return stopping || !jobs.empty(); }); + complete_cooling(); + if (jobs.empty() && cooling.empty()) { + cv.wait_for(lock, std::chrono::milliseconds(2), + [&] { return stopping || !jobs.empty(); }); + } if (stopping && jobs.empty()) { break; } if (jobs.empty()) { + if (!cooling.empty()) { + auto wake = cooling.front()->complete_at; + for (const auto &pending : cooling) { + wake = std::min(wake, pending->complete_at); + } + cv.wait_until(lock, wake); + } continue; } // Priority includes bounded aging; equal ranks retain FIFO. @@ -424,9 +656,17 @@ namespace linkerbot::transport { .count() / options.aging_quantum.count(); }; - auto best = jobs.begin(); + auto best = jobs.end(); + auto wake = now + std::chrono::milliseconds(2); for (auto it = jobs.begin(); it != jobs.end(); ++it) { - if (options.endpoint_fifo && + auto *device = static_cast((*it)->owner.get()); + if (device != nullptr && device->next_eligible > now && + (*it)->options.deadline > now) { + wake = std::min(wake, device->next_eligible); + wake = std::min(wake, (*it)->options.deadline); + continue; + } + if ((options.endpoint_fifo || device != nullptr) && (*it)->options.policy == SendPolicy::fifo && std::any_of(jobs.begin(), it, [&](const auto &prior) { return prior->options.policy == SendPolicy::fifo && @@ -434,6 +674,19 @@ namespace linkerbot::transport { })) { continue; } + if (best == jobs.end()) { + best = it; + continue; + } + if (options.domain_round_robin && + (*it)->options.admission_domain != + (*best)->options.admission_domain) { + if (last_domain.at((*it)->options.admission_domain) < + last_domain.at((*best)->options.admission_domain)) { + best = it; + } + continue; + } const auto served = [&](const auto &candidate) { return last_served.at(candidate->options.endpoint); }; @@ -448,6 +701,10 @@ namespace linkerbot::transport { best = it; } } + if (best == jobs.end()) { + cv.wait_until(lock, wake); + continue; + } job = *best; jobs.erase(best); if (job->options.cancellation.cancelled() || @@ -457,7 +714,8 @@ namespace linkerbot::transport { std::make_exception_ptr(CancelledError("queued send cancelled"))); continue; } - if (Clock::now() >= job->options.deadline) { + if (job->options.deadline_policy != DeadlinePolicy::kDispatchStart && + Clock::now() >= job->options.deadline) { finish(job, SendOutcome::expired, std::make_exception_ptr(can::TimeoutError( "queued send expired before backend I/O"))); @@ -470,7 +728,14 @@ namespace linkerbot::transport { continue; } claimed = job; + if (auto *owner = static_cast(job->owner.get()); + owner != nullptr && owner->options.send_period.count() != 0) { + cooling.reserve(cooling.size() + 1); + } last_served.at(job->options.endpoint) = ++service_order; + if (options.domain_round_robin) { + last_domain.at(job->options.admission_domain) = service_order; + } std::lock_guard receipt_lock(job->receipt->mutex); job->receipt->result.claimed_at = Clock::now(); job->receipt->result.claimed_order = ++event_order; @@ -480,7 +745,25 @@ namespace linkerbot::transport { bool uncertain = false; auto outcome = SendOutcome::dispatched; std::exception_ptr error; + auto *device = static_cast(job->owner.get()); + can::LocalBatchPacing local; + local.dispatch_progress = &job->receipt->dispatch_progress; + auto period = options.send_period; + if (device != nullptr && device->options.send_period.count() != 0) { + period = device->options.send_period; + local.enabled = true; + local.defer_final_cooldown = true; + local.attempt_started = Clock::now(); + local.cooldown_until = &job->complete_at; + } try { + const bool dispatch_start = + job->options.deadline_policy == DeadlinePolicy::kDispatchStart; + if (dispatch_start && Clock::now() >= job->options.deadline) { + throw can::TimeoutError("send expired at dispatch entry"); + } + const auto backend_deadline = + dispatch_start ? Deadline::max() : job->options.deadline; auto cancelled = [&] { return job->abort.token().cancelled() || job->options.cancellation.cancelled(); @@ -489,16 +772,16 @@ namespace linkerbot::transport { // legacy synchronous and queued sends across all pacing. if (bus) { bus->send_batch_until( - job->batch.frames, job->options.deadline, job->batch.gap, + job->batch.frames, backend_deadline, job->batch.gap, job->batch.initial_delay, cancelled, sent, uncertain, - job->options.deadline_policy == DeadlinePolicy::kStartOnly, - options.send_period, &job->receipt->progress); + job->options.deadline_policy == DeadlinePolicy::kStartOnly, period, + &job->receipt->progress, local); } else { borrowed->send_batch_until( - job->batch.frames, job->options.deadline, job->batch.gap, + job->batch.frames, backend_deadline, job->batch.gap, job->batch.initial_delay, cancelled, sent, uncertain, - job->options.deadline_policy == DeadlinePolicy::kStartOnly, - options.send_period, &job->receipt->progress); + job->options.deadline_policy == DeadlinePolicy::kStartOnly, period, + &job->receipt->progress, local); } // A normal return means the backend accepted every frame. // A cancel seen only now lost the race, and reporting it @@ -555,8 +838,57 @@ namespace linkerbot::transport { // backend failure; queue/pacing expiry is not. ++health.consecutive_send_errors; } - finish(job, outcome, std::move(error), sent, uncertain); + if (device != nullptr) { + if (sent != 0u || outcome == SendOutcome::dispatched) { + device->consecutive_send_errors.store(0); + } + if (uncertain) { + ++device->consecutive_send_errors; + } + } + if (outcome == SendOutcome::dispatched && local.enabled && + job->complete_at > Clock::now() && !stopping && health.open && + stopped_endpoints.count(job->options.endpoint) == 0u) { + cooling.push_back(job); + device->next_eligible = job->complete_at; + signal->notify(); + } else { + finish(job, outcome, std::move(error), sent, uncertain); + } claimed.reset(); + if (device != nullptr && device->options.max_consecutive_send_errors != 0 && + device->consecutive_send_errors.load() >= + device->options.max_consecutive_send_errors) { + device->faulted.store(true); + const auto failure = std::make_exception_ptr( + can::FaultedError("consecutive device send failures")); + for (auto it = jobs.begin(); it != jobs.end();) { + if ((*it)->owner.get() == device) { + finish(*it, SendOutcome::failed, failure); + it = jobs.erase(it); + } else { + ++it; + } + } + const auto close_routes = [&](const auto &entries) { + for (const auto &entry : entries) { + if (auto route = entry.second.lock(); + route && route->device == device) { + std::lock_guard route_lock(route->mutex); + route->close_locked(failure); + } + } + }; + close_routes(routes); + close_routes(patterns); + for (const auto &entry : observers) { + if (auto route = entry.lock(); route && route->device == device) { + std::lock_guard route_lock(route->mutex); + route->close_locked(failure); + } + } + signal->notify(); + } if (options.max_consecutive_send_errors != 0 && health.consecutive_send_errors >= options.max_consecutive_send_errors) { health.open = false; @@ -1010,18 +1342,138 @@ namespace linkerbot::transport { } std::shared_ptr Session::subscribe_routes(const std::vector &keys, size_t capacity) { + return subscribe_routes_impl(keys, capacity, nullptr); + } + std::shared_ptr Session::subscribe_routes_impl(const std::vector &keys, + size_t capacity, + const void *device) { if (capacity == 0u) { throw can::ValidationError("route capacity must be positive"); } auto state = std::make_shared(); state->capacity = capacity; state->owner = impl_.get(); + state->device = device; + state->counters = impl_->receive_counters; state->signal = impl_->signal; state->health.capacity = capacity; auto inbox = std::shared_ptr(new RouteInbox(state)); update_routes(inbox, keys); return inbox; } + std::shared_ptr Session::subscribe_rules_impl(const std::vector &rules, + size_t capacity, const void *device, + bool observation) { + if (capacity == 0 || rules.empty()) { + throw can::ValidationError("masked routes require positive capacity and rules"); + } + std::set unique; + for (const auto &rule : rules) { + const auto maximum = rule.extended ? can::kExtendedIdMask : can::kStandardIdMask; + if ((rule.mask & ~maximum) != 0 || (rule.value & ~rule.mask) != 0) { + throw can::ValidationError("invalid route mask or value"); + } + for (const auto &other : unique) { + if (Impl::overlaps(rule, other)) { + throw can::ValidationError("overlapping rules within a route group"); + } + } + unique.insert(rule); + } + auto state = std::make_shared(); + state->capacity = capacity; + state->owner = impl_.get(); + state->device = device; + state->masked = true; + state->signal = impl_->signal; + state->counters = + observation ? std::make_shared() : impl_->receive_counters; + state->health.capacity = capacity; + if (observation) { + state->observed_rules = rules; + } + auto inbox = std::shared_ptr(new RouteInbox(state)); + auto &p = *impl_; + p.refresh(); + std::lock_guard lock(p.mutex); + if (!p.health.open || p.stopping) { + throw can::ClosedError("session is closed"); + } + if (p.route_key_of) { + throw can::ValidationError("masked routes cannot use a global route extractor"); + } + const auto occupied = p.route_count(); + if (p.options.max_route_keys != 0 && + (occupied > p.options.max_route_keys || + unique.size() > p.options.max_route_keys - occupied)) { + ++p.health.route_registration_rejections; + throw can::QueueFullError("route registry is full"); + } + if (observation) { + p.observers.erase(std::remove_if(p.observers.begin(), p.observers.end(), + [](const auto &entry) { + const auto route = entry.lock(); + if (!route) { + return true; + } + std::lock_guard lock(route->mutex); + return route->health.closed; + }), + p.observers.end()); + p.observers.push_back(state); + state->health.generation = p.health.generation; + p.routing_started = true; + return inbox; + } + for (const auto &rule : unique) { + for (const auto &entry : p.routes) { + const auto &key = entry.first; + const RouteRule exact{key.id, + key.extended ? can::kExtendedIdMask : can::kStandardIdMask, + key.extended}; + if (Impl::overlaps(rule, exact)) { + if (auto existing = entry.second.lock()) { + std::lock_guard route_lock(existing->mutex); + if (!existing->health.closed) { + throw can::ValidationError( + "masked route overlaps an exact registration"); + } + } + } + } + for (const auto &entry : p.patterns) { + if (Impl::overlaps(rule, entry.first)) { + if (auto existing = entry.second.lock()) { + std::lock_guard route_lock(existing->mutex); + if (!existing->health.closed) { + throw can::ValidationError("masked route already owned"); + } + } + } + } + } + std::vector inserted; + inserted.reserve(unique.size()); + try { + for (const auto &rule : unique) { + const auto result = p.patterns.emplace(rule, state); + if (result.second) { + inserted.push_back(rule); + } + } + } catch (...) { + for (const auto &rule : inserted) { + p.patterns.erase(rule); + } + throw; + } + for (const auto &rule : unique) { + p.patterns.at(rule) = state; + } + state->health.generation = p.health.generation; + p.routing_started = true; + return inbox; + } void Session::set_route_key_extractor(std::function extractor) { auto &p = *impl_; std::lock_guard lock(p.mutex); @@ -1038,7 +1490,8 @@ namespace linkerbot::transport { } void Session::update_routes(const std::shared_ptr &inbox, const std::vector &keys) { - if (!inbox || inbox->state_->owner != impl_.get() || keys.empty()) { + if (!inbox || inbox->state_->owner != impl_.get() || keys.empty() || + inbox->state_->masked) { throw can::ValidationError("route group must belong to this session and contain keys"); } std::set unique; @@ -1058,6 +1511,27 @@ namespace linkerbot::transport { if (inbox->state_->health.closed) { throw can::ClosedError("route is closed"); } + const auto occupied = p.route_count(inbox->state_.get()); + if (p.options.max_route_keys != 0 && + (occupied > p.options.max_route_keys || + unique.size() > p.options.max_route_keys - occupied)) { + ++p.health.route_registration_rejections; + throw can::QueueFullError("route registry is full"); + } + for (const auto &key : unique) { + const RouteRule exact{ + key.id, key.extended ? can::kExtendedIdMask : can::kStandardIdMask, key.extended}; + for (const auto &entry : p.patterns) { + if (Impl::overlaps(exact, entry.first)) { + if (auto route = entry.second.lock()) { + std::lock_guard route_lock(route->mutex); + if (!route->health.closed) { + throw can::ValidationError("CAN route overlaps a masked registration"); + } + } + } + } + } for (const auto &key : unique) { auto it = p.routes.find(key); if (it == p.routes.end()) { @@ -1114,7 +1588,8 @@ namespace linkerbot::transport { return submit_impl(std::move(batch), std::move(options), true); } std::optional Session::submit_impl(MessageBatch batch, SendOptions options, - bool replace_only) { + bool replace_only, + std::shared_ptr owner) { if (batch.frames.empty()) { throw can::ValidationError("empty send batch"); } @@ -1130,11 +1605,21 @@ namespace linkerbot::transport { if (options.max_pending_age && options.max_pending_age->count() <= 0) { throw can::ValidationError("pending age must be positive"); } + if (options.pending_age_scope != PendingAgeScope::kSession && + options.pending_age_scope != PendingAgeScope::kEndpoint && + options.pending_age_scope != PendingAgeScope::kAdmissionDomain) { + throw can::ValidationError("invalid pending age scope"); + } + if (options.pending_age_scope == PendingAgeScope::kAdmissionDomain && + !options.admission_domain) { + throw can::ValidationError("domain pending age requires an admission domain"); + } if (options.policy == SendPolicy::latest && (options.endpoint.empty() || options.family.empty())) { throw can::ValidationError("latest requires explicit endpoint and family"); } auto job = std::make_shared(); + job->owner = std::move(owner); job->batch = std::move(batch); job->options = std::move(options); job->receipt = std::make_shared(); @@ -1145,6 +1630,17 @@ namespace linkerbot::transport { throw can::ClosedError("session is closed"); } job->receipt->signal = p.signal; + if (p.device_mode && !job->owner) { + throw can::ValidationError("use DeviceSession for managed device submission"); + } + if (p.options.max_batch_frames != 0 && + job->batch.frames.size() > p.options.max_batch_frames) { + throw can::ValidationError("batch exceeds the configured frame limit"); + } + if (auto *device = static_cast(job->owner.get()); + device != nullptr && device->faulted.load()) { + throw can::FaultedError("device send policy is faulted"); + } if (p.stopped_endpoints.count(job->options.endpoint) != 0u) { throw can::ClosedError("endpoint admission is stopped"); } @@ -1158,8 +1654,18 @@ namespace linkerbot::transport { } const auto now = Clock::now(); const auto max_pending_age = job->options.max_pending_age; - if (max_pending_age.has_value() && p.oldest_accepted() != Deadline::max() && - std::chrono::duration_cast(now - p.oldest_accepted()) >= + const auto oldest = + max_pending_age + ? p.oldest_accepted(job->options.pending_age_scope == PendingAgeScope::kEndpoint + ? &job->options.endpoint + : nullptr, + job->options.pending_age_scope == + PendingAgeScope::kAdmissionDomain + ? job->options.admission_domain.get() + : nullptr) + : Deadline::max(); + if (max_pending_age.has_value() && oldest != Deadline::max() && + std::chrono::duration_cast(now - oldest) >= max_pending_age.value()) { ++p.health.rejected_stale; throw can::TimeoutError("pending work exceeded age budget"); @@ -1176,6 +1682,32 @@ namespace linkerbot::transport { return std::nullopt; } const auto units = p.pending_units(); + const auto domain = job->options.admission_domain; + if (domain) { + const auto limits = domain->limits(); + size_t fifo = 0; + size_t latest = 0; + for (const auto &pending : p.jobs) { + if (pending->options.admission_domain != domain || + pending == (previous == p.jobs.end() ? nullptr : *previous)) { + continue; + } + if (pending->options.policy == SendPolicy::latest) { + ++latest; + } else { + fifo += limits.fifo_unit == CapacityUnit::kFrames ? pending->batch.frames.size() + : 1; + } + } + const auto cost = + limits.fifo_unit == CapacityUnit::kFrames ? job->batch.frames.size() : 1; + if ((job->options.policy == SendPolicy::latest && latest >= limits.latest_capacity) || + (job->options.policy == SendPolicy::fifo && + (fifo > limits.fifo_capacity || cost > limits.fifo_capacity - fifo))) { + ++p.health.rejected_full; + throw can::QueueFullError("admission domain is full"); + } + } bool full = previous == p.jobs.end() && p.jobs.size() >= p.tx_capacity; if (p.options.separate_policy_capacity) { if (job->options.policy == SendPolicy::latest) { @@ -1190,12 +1722,16 @@ namespace linkerbot::transport { } auto &result = job->receipt->result; result.generation = p.health.generation; + result.channel_instance = p.instance; result.accepted_at = Clock::now(); result.total_frames = job->batch.frames.size(); // Allocate before changing an old receipt: failed admission must not // supersede accepted work. deque insertion may invalidate iterators. auto old = previous == p.jobs.end() ? nullptr : *previous; p.last_served.try_emplace(job->options.endpoint, 0); + if (p.options.domain_round_robin) { + p.last_domain.try_emplace(job->options.admission_domain, 0); + } auto replacement_error = old ? std::make_exception_ptr(CancelledError("pending latest send superseded")) : std::exception_ptr{}; @@ -1214,6 +1750,291 @@ namespace linkerbot::transport { auto receipt = submit(std::move(batch), std::move(options)); (void)receipt.wait_until(deadline); } + std::shared_ptr Session::attach_device(std::string identity) { + return attach_device(std::move(identity), DeviceOptions{}); + } + std::shared_ptr Session::attach_device(std::string identity, + DeviceOptions options) { + if (identity.empty()) { + throw can::ValidationError("device identity must not be empty"); + } + if (options.send_period.count() < 0) { + throw can::ValidationError("negative device send period"); + } + auto state = std::make_shared(); + state->session = shared_from_this(); + state->signal = impl_->signal; + state->options = std::move(options); + auto device = std::shared_ptr(new DeviceSession(state)); + impl_->refresh(); + std::lock_guard lock(impl_->mutex); + if (impl_->stopping || !impl_->health.open) { + throw can::ClosedError("session is closed"); + } + if (state->options.send_period.count() != 0 && impl_->options.send_period.count() != 0) { + throw can::ValidationError("device and legacy dispatcher periods cannot be combined"); + } + if (!impl_->device_mode && (impl_->health.accepted != 0 || !impl_->routes.empty())) { + throw can::ValidationError("attach devices before legacy Session use"); + } + if (auto previous = impl_->devices[identity].lock(); previous && !previous->closed.load()) { + // Do not take a device gate while holding the Session mutex. + throw can::ValidationError("device identity is still registered"); + } + state->generation = impl_->health.generation; + state->channel_instance = impl_->instance; + state->endpoint = "device/" + std::to_string(++impl_->next_device); + impl_->devices[std::move(identity)] = state; + state->closed.store(false); + impl_->device_mode = true; + return device; + } + + DeviceSession::DeviceSession(std::shared_ptr state) : state_(std::move(state)) {} + DeviceSession::~DeviceSession() { + try { + close_until(Deadline::max()); + } catch (...) { + // A claimed Job retains State until backend I/O has left the writer. + std::lock_guard gate(state_->gate); + state_->closing = true; + } + } + std::optional DeviceSession::submit_impl(MessageBatch batch, SendOptions options, + bool replace_only, bool owned) { + std::lock_guard lock(state_->gate); + if ((!owned && state_->closing) || state_->closed) { + throw can::ClosedError("device admission is closed"); + } + options.endpoint = state_->endpoint; + options.expected_generation = state_->generation; + if (options.pending_age_scope == PendingAgeScope::kSession) { + options.pending_age_scope = PendingAgeScope::kEndpoint; + } + if (state_->options.admission_domain) { + options.admission_domain = state_->options.admission_domain; + } + return state_->session->submit_impl(std::move(batch), std::move(options), replace_only, + state_); + } + SendReceipt DeviceSession::submit(MessageBatch batch, SendOptions options) { + auto receipt = submit_impl(std::move(batch), std::move(options), false); + if (!receipt.has_value()) { + throw can::InternalError("device submission returned no receipt"); + } + return receipt.value(); + } + std::optional DeviceSession::replace_latest_if_pending(MessageBatch batch, + SendOptions options) { + if (options.policy != SendPolicy::latest) { + throw can::ValidationError("conditional replacement requires latest policy"); + } + return submit_impl(std::move(batch), std::move(options), true); + } + std::shared_ptr DeviceSession::subscribe_routes(const std::vector &keys, + size_t capacity) { + std::lock_guard lock(state_->gate); + if (state_->closing || state_->closed) { + throw can::ClosedError("device admission is closed"); + } + if (state_->faulted.load()) { + throw can::FaultedError("device send policy is faulted"); + } + auto inbox = state_->session->subscribe_routes_impl(keys, capacity, state_.get()); + if (inbox->health().generation != state_->generation) { + inbox->close(); + throw can::ClosedError("device generation is stale"); + } + state_->inboxes.push_back(inbox); + return inbox; + } + std::shared_ptr DeviceSession::subscribe_rules(const std::vector &rules, + size_t capacity) { + std::lock_guard gate(state_->gate); + if (state_->closed || state_->closing) { + throw can::ClosedError("device admission is closed"); + } + if (state_->faulted.load()) { + throw can::FaultedError("device send policy is faulted"); + } + auto inbox = state_->session->subscribe_rules_impl(rules, capacity, state_.get()); + if (inbox->health().generation != state_->generation) { + inbox->close(); + throw can::ClosedError("device generation is stale"); + } + state_->inboxes.push_back(inbox); + return inbox; + } + std::shared_ptr DeviceSession::observe_rules(const std::vector &rules, + size_t capacity) { + std::lock_guard gate(state_->gate); + if (state_->closed || state_->closing) { + throw can::ClosedError("device admission is closed"); + } + if (state_->faulted.load()) { + throw can::FaultedError("device send policy is faulted"); + } + auto inbox = state_->session->subscribe_rules_impl(rules, capacity, state_.get(), true); + if (inbox->health().generation != state_->generation) { + inbox->close(); + throw can::ClosedError("device generation is stale"); + } + state_->inboxes.push_back(inbox); + return inbox; + } + void DeviceSession::close_until(Deadline deadline) { + if (current_writer() != nullptr || can::CANDispatcher::is_any_receive_thread()) { + throw can::ValidationError("device close requires an external caller"); + } + { + std::lock_guard gate(state_->gate); + if (state_->operations.count(std::this_thread::get_id()) != 0) { + throw can::ValidationError("cannot close from an owned device operation"); + } + } + std::unique_lock closer(state_->closer); + const auto available = [&] { return !state_->close_active; }; + if (deadline == Deadline::max()) { + state_->close_changed.wait(closer, available); + } else if (!state_->close_changed.wait_until(closer, deadline, available)) { + throw can::TimeoutError("another device close is still running"); + } + state_->close_active = true; + closer.unlock(); + struct ReleaseClose { + State *state; + ~ReleaseClose() { + std::lock_guard lock(state->closer); + state->close_active = false; + state->close_changed.notify_all(); + } + } release{state_.get()}; + std::shared_ptr session; + { + std::unique_lock gate(state_->gate); + if (state_->closed) { + return; + } + state_->closing = true; + state_->signal->notify(); + const auto finished = [&] { return state_->operations.empty(); }; + if (deadline == Deadline::max()) { + state_->work_changed.wait(gate, finished); + } else if (!state_->work_changed.wait_until(gate, deadline, finished)) { + throw can::TimeoutError("owned device operations did not finish"); + } + session = state_->session; + } + // No device gate is held across driver drain or route destruction. + session->stop_endpoint(state_->endpoint, deadline); + { + std::lock_guard gate(state_->gate); + for (const auto &inbox : state_->inboxes) { + inbox->close(); + } + state_->inboxes.clear(); + } + if (state_->channel_release) { + state_->channel_release(); + } + std::lock_guard gate(state_->gate); + state_->closed = true; + state_->session.reset(); + state_->channel_release = {}; + } + void DeviceSession::set_channel_release(std::function release) { + std::lock_guard gate(state_->gate); + state_->channel_release = std::move(release); + } + bool DeviceSession::closed() const { + std::lock_guard lock(state_->gate); + return state_->closed; + } + uint64_t DeviceSession::generation() const { + return state_->generation; + } + DeviceHealth DeviceSession::health() const { + std::lock_guard gate(state_->gate); + std::unique_lock native; + if (state_->session) { + native = std::unique_lock(state_->session->impl_->mutex); + } + DeviceHealth result; + result.closed = state_->closed.load(); + result.accepting = !state_->closing && !result.closed; + result.generation = state_->generation; + result.channel_instance = state_->channel_instance; + result.faulted = state_->faulted.load(); + result.accepting = result.accepting && !result.faulted; + if (state_->session && (!state_->session->impl_->health.open || + state_->session->impl_->health.generation != state_->generation)) { + result.accepting = false; + } + result.consecutive_send_errors = state_->consecutive_send_errors.load(); + if (state_->session) { + const auto &p = *state_->session->impl_; + for (const auto &job : p.jobs) { + if (job->owner.get() == state_.get()) { + if (job->options.policy == SendPolicy::fifo) { + result.pending_fifo += job->batch.frames.size(); + } else { + ++result.pending_latest; + } + } + } + result.in_flight = p.claimed && p.claimed->owner.get() == state_.get() ? 1 : 0; + for (const auto &job : p.cooling) { + result.in_flight += job->owner.get() == state_.get() ? 1 : 0; + } + const auto oldest = p.oldest_accepted(&state_->endpoint); + if (oldest != Deadline::max()) { + result.oldest_pending = oldest; + } + } + for (const auto &entry : state_->operations) { + result.owned_operations += entry.second; + } + return result; + } + std::shared_ptr DeviceSession::notification() const { + return state_->signal; + } + DeviceOperation DeviceSession::begin_operation() { + auto operation = std::make_unique(); + operation->device = shared_from_this(); + operation->thread = std::this_thread::get_id(); + std::lock_guard gate(state_->gate); + if (state_->closing || state_->closed) { + throw can::ClosedError("device admission is closed"); + } + if (state_->faulted.load()) { + throw can::FaultedError("device send policy is faulted"); + } + const auto channel = state_->session->health(); + if (!channel.open || channel.generation != state_->generation) { + throw can::ClosedError("device generation is stale"); + } + ++state_->operations[operation->thread]; + operation->active = true; + return DeviceOperation(std::move(operation)); + } + DeviceOperation::DeviceOperation() = default; + DeviceOperation::DeviceOperation(std::unique_ptr state) : state_(std::move(state)) {} + DeviceOperation::~DeviceOperation() = default; + DeviceOperation::DeviceOperation(DeviceOperation &&) noexcept = default; + DeviceOperation &DeviceOperation::operator=(DeviceOperation &&) noexcept = default; + SendReceipt DeviceOperation::submit(MessageBatch batch, SendOptions options) { + if (!state_ || state_->thread != std::this_thread::get_id()) { + throw can::ValidationError("device operation is empty or belongs to another thread"); + } + auto receipt = + state_->device->submit_impl(std::move(batch), std::move(options), false, true); + if (!receipt.has_value()) { + throw can::InternalError("owned submission returned no receipt"); + } + return receipt.value(); + } + void Session::cancel_endpoint(const std::string &endpoint) { auto &p = *impl_; std::lock_guard lock(p.mutex); @@ -1230,6 +2051,11 @@ namespace linkerbot::transport { if (p.claimed && p.claimed->options.endpoint == endpoint) { p.claimed->abort.cancel(); } + for (const auto &job : p.cooling) { + if (job->options.endpoint == endpoint) { + job->abort.cancel(); + } + } p.cv.notify_all(); } void Session::configure(SessionOptions options) { @@ -1239,8 +2065,9 @@ namespace linkerbot::transport { throw can::ValidationError("invalid Session scheduling options"); } std::lock_guard lock(impl_->mutex); - if (impl_->stopping || impl_->health.accepted != 0) { - throw can::ValidationError("configure requires a session with no accepted sends"); + if (impl_->stopping || impl_->health.accepted != 0 || impl_->device_mode) { + throw can::ValidationError( + "configure requires a session with no accepted sends or devices"); } impl_->options = options; impl_->tx_capacity = options.tx_capacity; @@ -1268,7 +2095,17 @@ namespace linkerbot::transport { } } p.cv.notify_all(); - const auto drained = [&] { return !p.claimed || p.claimed->options.endpoint != endpoint; }; + for (const auto &job : p.cooling) { + if (job->options.endpoint == endpoint) { + job->abort.cancel(); + } + } + p.complete_cooling(); + const auto drained = [&] { + return (!p.claimed || p.claimed->options.endpoint != endpoint) && + std::none_of(p.cooling.begin(), p.cooling.end(), + [&](const auto &job) { return job->options.endpoint == endpoint; }); + }; if (deadline == Deadline::max()) { p.cv.wait(lock, drained); } else if (!p.cv.wait_until(lock, deadline, drained)) { @@ -1281,7 +2118,9 @@ namespace linkerbot::transport { if (impl_->stopping || !impl_->health.open) { throw can::ClosedError("session closed"); } - if (impl_->claimed && impl_->claimed->options.endpoint == endpoint) { + if ((impl_->claimed && impl_->claimed->options.endpoint == endpoint) || + std::any_of(impl_->cooling.begin(), impl_->cooling.end(), + [&](const auto &job) { return job->options.endpoint == endpoint; })) { throw can::ValidationError("endpoint still has a claimed send"); } impl_->stopped_endpoints.erase(endpoint); @@ -1290,12 +2129,20 @@ namespace linkerbot::transport { impl_->refresh(); std::lock_guard lock(impl_->mutex); auto h = impl_->health; - h.pending_tx = impl_->jobs.size() + (impl_->claimed ? 1 : 0); + h.channel_instance = impl_->instance; + h.route_count = impl_->route_count(); + h.pending_rx = impl_->receive_counters->pending.load(); + h.max_pending_rx = impl_->receive_counters->high_water.load(); + h.dropped_rx_on_close = impl_->receive_counters->dropped.load(); + h.pending_tx = impl_->jobs.size() + impl_->cooling.size() + (impl_->claimed ? 1 : 0); const auto units = impl_->pending_units(); h.pending_fifo = units.first; h.pending_latest = units.second; - h.in_flight = bool(impl_->claimed); + h.in_flight = bool(impl_->claimed) || !impl_->cooling.empty(); h.in_flight_frames = impl_->claimed ? impl_->claimed->batch.frames.size() : 0; + for (const auto &job : impl_->cooling) { + h.in_flight_frames += job->batch.frames.size(); + } const auto oldest = impl_->oldest_accepted(); if (oldest != Deadline::max()) { h.oldest_pending_age = diff --git a/tests/lifecycle_allocation_failure.cpp b/tests/lifecycle_allocation_failure.cpp index d7401f6..f497d58 100644 --- a/tests/lifecycle_allocation_failure.cpp +++ b/tests/lifecycle_allocation_failure.cpp @@ -174,6 +174,32 @@ namespace { auto factory = [] { return std::make_unique(); }; // Initialize singleton cleanup before arming allocation faults. transport::Session::drain_deferred_cleanup(); + for (const bool observation : {false, true}) { + sweep("masked route registration", [&](int index) { + auto session = transport::Session::create(factory); + auto device = session->attach_device("masked"); + const std::vector rules{ + {0x100, 0x700, false}, {0x200, 0x700, false}, {0x300, 0x700, false}}; + std::shared_ptr inbox; + countdown = index; + try { + inbox = observation ? device->observe_rules(rules, 256) + : device->subscribe_rules(rules); + } catch (const std::bad_alloc &) { + require(countdown == -1); + } + countdown = -1; + const bool success = inbox != nullptr; + if (!success) { + require(session->health().route_count == 0); + inbox = observation ? device->observe_rules(rules, 256) + : device->subscribe_rules(rules); + } + require(session->health().route_count == rules.size()); + device->close_until(transport::Deadline::max()); + return success; + }); + } sweep("route update", [&](int index) { auto session = transport::Session::create(factory); const std::vector old_keys{{0x20, false}}; diff --git a/tests/test_session_receive_compat.cpp b/tests/test_session_receive_compat.cpp index a954c9d..a816f6d 100644 --- a/tests/test_session_receive_compat.cpp +++ b/tests/test_session_receive_compat.cpp @@ -50,6 +50,117 @@ namespace { } } // namespace +TEST_CASE("Discovery observation cannot consume an owner's route or receive budget", "[session]") { + ReceiveRig rig; + auto config = rig.session->options(); + config.max_route_keys = 4; + config.max_pending_rx = 1; + rig.session->configure(config); + auto device = rig.session->attach_device("hand"); + auto discovery = rig.session->attach_device("discovery"); + auto owner = device->subscribe_routes({{0x28, false}}, 2); + auto tap = discovery->observe_rules({{0x20, 0x7f0, false}}, 1); + REQUIRE(rig.session->health().route_count == 2); + rig.fake->inject(received_frame(0x28)); + const auto normal = require_value(owner->receive_until(transport::Clock::now() + 2s)); + REQUIRE(await_state(tap->notification(), [&] { return tap->health().pending == 1; })); + REQUIRE(rig.session->health().pending_rx == 0); + rig.fake->inject(received_frame(0x28)); + const auto second = require_value(owner->receive_until(transport::Clock::now() + 2s)); + REQUIRE(await_state(tap->notification(), [&] { return tap->health().overflow == 1; })); + const auto observed = require_value(tap->try_receive()); + REQUIRE(observed.compatibility_sequence == normal.compatibility_sequence); + REQUIRE(observed.received_order == normal.received_order); + REQUIRE(second.received_order > normal.received_order); + tap->close(); + rig.fake->inject(received_frame(0x28)); + REQUIRE(require_value(owner->receive_until(transport::Clock::now() + 2s)).message.id == 0x28); + auto replacement = discovery->observe_rules({{0x20, 0x7f0, false}}, 1); + rig.fake->inject(received_frame(0x21)); + REQUIRE(require_value(replacement->receive_until(transport::Clock::now() + 2s)).message.id == + 0x21); + discovery->close_until(transport::Deadline::max()); + REQUIRE_FALSE(owner->health().closed); + REQUIRE_THROWS_AS(discovery->observe_rules({{0, 0, false}}, 1), can::ClosedError); + auto terminal = device->observe_rules({{0, 0, false}}, 1); + rig.session->close(); + REQUIRE_THROWS_AS(terminal->try_receive(), can::ClosedError); +} + +TEST_CASE("Masked device routes reject legacy extractors and physical closure", "[session]") { + ReceiveRig rig; + rig.session->set_route_key_extractor([](const can::Message &message) { + return transport::RouteKey{message.id, message.is_extended}; + }); + auto device = rig.session->attach_device("masked"); + REQUIRE_THROWS_AS(device->subscribe_rules({{0, 0x7ff, false}}), can::ValidationError); + rig.session->close(); + REQUIRE_THROWS_AS(device->subscribe_rules({{0, 0x7ff, false}}), can::ClosedError); +} + +TEST_CASE("Device masked routes compose with exact routes and reject wire overlap", "[session]") { + ReceiveRig rig; + auto arm = rig.session->attach_device("arm"); + auto hand = rig.session->attach_device("hand"); + auto masked = arm->subscribe_rules({{0x3d00, 0xff00, true}}, 2); + auto exact = hand->subscribe_routes({{0x28, false}}, 2); + REQUIRE(rig.session->health().route_count == 2); + REQUIRE_THROWS_AS(hand->subscribe_routes({{0x123d01, true}}), can::ValidationError); + REQUIRE_THROWS_AS(hand->subscribe_rules({{0x3d00, 0xff00, true}}), can::ValidationError); + REQUIRE_THROWS_AS(hand->subscribe_rules({{0x28, 0x7ff, false}}), can::ValidationError); + REQUIRE_THROWS_AS(hand->subscribe_rules({}), can::ValidationError); + REQUIRE_THROWS_AS(hand->subscribe_rules({{0, 0x800, false}}), can::ValidationError); + REQUIRE_THROWS_AS(hand->subscribe_rules({{1, 0, false}}), can::ValidationError); + REQUIRE_THROWS_AS(hand->subscribe_rules({{0, 0, false}, {1, 0x7ff, false}}), + can::ValidationError); + rig.fake->inject(received_frame(0x123d01, true)); + const auto routed = require_value(masked->receive_until(transport::Clock::now() + 2s)); + REQUIRE(routed.message.id == 0x123d01); + REQUIRE(routed.route_key == transport::RouteKey{0x3d00, true}); + REQUIRE(routed.channel_instance == arm->health().channel_instance); + rig.fake->inject(received_frame(0x28)); + const auto other = require_value(exact->receive_until(transport::Clock::now() + 2s)); + REQUIRE(other.compatibility_sequence > routed.compatibility_sequence); + arm->close_until(transport::Deadline::max()); + REQUIRE(rig.session->health().route_count == 1); + auto replacement = hand->subscribe_rules({{0x3d00, 0xff00, true}}); + REQUIRE(rig.session->health().route_count == 2); + replacement->close(); + REQUIRE(rig.session->health().route_count == 1); +} + +TEST_CASE("Channel receive budget spans device inboxes and overflow leaves sequence gaps", + "[session]") { + ReceiveRig rig; + auto options = rig.session->options(); + options.max_route_keys = 2; + options.max_pending_rx = 1; + rig.session->configure(options); + auto first = rig.session->attach_device("first"); + auto second = rig.session->attach_device("second"); + auto a = first->subscribe_routes({{1, false}}, 4); + auto b = second->subscribe_rules({{2, 0x7ff, false}}, 4); + REQUIRE_THROWS_AS(first->subscribe_routes({{3, false}}), can::QueueFullError); + REQUIRE_THROWS_AS(second->subscribe_rules({{3, 0x7ff, false}}), can::QueueFullError); + REQUIRE(rig.session->health().route_registration_rejections == 2); + rig.fake->inject(received_frame(1)); + REQUIRE(await_state(a->notification(), [&] { return a->health().pending == 1; })); + rig.fake->inject(received_frame(2)); + REQUIRE(await_state(b->notification(), [&] { return b->health().overflow == 1; })); + const auto initial = require_value(a->try_receive()); + REQUIRE(rig.session->health().pending_rx == 0); + REQUIRE(rig.session->health().max_pending_rx == 1); + rig.fake->inject(received_frame(2)); + const auto following = require_value(b->receive_until(transport::Clock::now() + 2s)); + REQUIRE(following.compatibility_sequence == initial.compatibility_sequence + 2); + rig.fake->inject(received_frame(2)); + REQUIRE(await_state(b->notification(), [&] { return b->health().pending == 1; })); + b->close(); + REQUIRE(rig.session->health().pending_rx == 0); + REQUIRE(rig.session->health().dropped_rx_on_close == 1); + REQUIRE(rig.session->health().routed_rx_frames == 3); +} + TEST_CASE("Session change signals coalesce without losing a pre-wait notification", "[session]") { transport::ChangeSignal signal; const auto initial = signal.revision(); diff --git a/tests/test_session_tx_compat.cpp b/tests/test_session_tx_compat.cpp index 6b10af3..e27b17b 100644 --- a/tests/test_session_tx_compat.cpp +++ b/tests/test_session_tx_compat.cpp @@ -62,6 +62,68 @@ namespace { } } // namespace +TEST_CASE("Device pacing delays only its next batch and cancellation ends final cooldown", + "[session]") { + TxRig rig; + transport::DeviceOptions profile; + profile.send_period = 40ms; + auto device = rig.session->attach_device("paced", profile); + auto first = device->submit(batch(1)); + auto second = device->submit(batch(1)); + REQUIRE_THROWS_AS(second.wait_result_until(transport::Clock::now() + 5ms), can::TimeoutError); + first.wait(); + second.wait(); + REQUIRE(rig.fake->sent().size() == 2); +} + +TEST_CASE("Dispatch-start deadlines record claim and stop applying after dispatch entry", + "[session]") { + TxRig rig; + auto blocker = rig.block_writer(); + auto options = endpoint("expired"); + options.deadline_policy = transport::DeadlinePolicy::kDispatchStart; + options.deadline = transport::Clock::now() + 5ms; + auto expired = rig.session->submit(batch(1), options); + std::this_thread::sleep_for(10ms); + rig.fake->release_tx_gate(); + blocker.wait(); + auto result = expired.wait_result_until(transport::Clock::now() + 2s); + REQUIRE(result.outcome == transport::SendOutcome::expired); + REQUIRE(result.claimed_order.has_value()); + REQUIRE(test_support::require_value(result.claimed_order) > 0); + REQUIRE(result.sent_frames == 0); + options.deadline = transport::Clock::now() + 5ms; + auto delayed = batch(2); + delayed.initial_delay = 10ms; + auto accepted = rig.session->submit(delayed, options); + accepted.wait(); + REQUIRE(accepted.result().sent_frames == 2); +} + +TEST_CASE("Owned operation moves retain registration and reject foreign-thread submission", + "[session]") { + TxRig rig; + auto device = rig.session->attach_device("owned"); + transport::DeviceOperation empty; + REQUIRE_THROWS_AS(empty.submit(batch(1)), can::ValidationError); + auto operation = device->begin_operation(); + auto moved = std::move(operation); + // A moved-from operation is specified to be empty and reject submission. + // NOLINTNEXTLINE(bugprone-use-after-move,clang-analyzer-cplusplus.Move) + REQUIRE_THROWS_AS(operation.submit(batch(1)), can::ValidationError); + auto foreign = std::async(std::launch::async, [&] { + REQUIRE_THROWS_AS(moved.submit(batch(1)), can::ValidationError); + }); + foreign.get(); + empty = std::move(moved); + empty.submit(batch(1)).wait(); + REQUIRE(device->health().owned_operations == 1); + REQUIRE_THROWS_AS(device->close_until(transport::Clock::now()), can::ValidationError); + empty = transport::DeviceOperation{}; + REQUIRE(device->health().owned_operations == 0); + device->close_until(transport::Deadline::max()); +} + TEST_CASE("Session SDK capacity atomically admits frame groups separately from latest slots", "[session]") { TxRig rig; @@ -213,6 +275,458 @@ TEST_CASE("Session generation and oldest in-flight age are checked during admiss rig.session->submit(batch(1), stale).wait(); } +TEST_CASE("Session endpoint age excludes unrelated claimed and queued work", "[session]") { + TxRig rig; + auto active = rig.block_writer("hand"); + auto waiting = rig.session->submit(batch(1), endpoint("hand")); + auto arm = endpoint("arm"); + arm.max_pending_age = 1us; + std::this_thread::sleep_for(1ms); + REQUIRE_THROWS_AS(rig.session->submit(batch(1), arm), can::TimeoutError); + arm.pending_age_scope = transport::PendingAgeScope::kEndpoint; + auto accepted = rig.session->submit(batch(7), arm); + std::this_thread::sleep_for(1ms); + REQUIRE_THROWS_AS(rig.session->submit(batch(1), arm), can::TimeoutError); + REQUIRE(rig.session->health().rejected_stale == 2); + rig.fake->release_tx_gate(); + active.wait(); + waiting.wait(); + accepted.wait(); +} + +TEST_CASE("Session endpoint age includes its own claimed work", "[session]") { + TxRig rig; + auto active = rig.block_writer("arm"); + auto arm = endpoint("arm"); + arm.max_pending_age = 1us; + arm.pending_age_scope = transport::PendingAgeScope::kEndpoint; + std::this_thread::sleep_for(1ms); + REQUIRE_THROWS_AS(rig.session->submit(batch(1), arm), can::TimeoutError); + auto hand = arm; + hand.endpoint = "hand"; + auto accepted = rig.session->submit(batch(1), hand); + rig.fake->release_tx_gate(); + active.wait(); + accepted.wait(); +} + +TEST_CASE("Session admission domains share request limits and isolate frame budgets", "[session]") { + TxRig rig; + auto blocker = rig.block_writer(); + auto hands = std::make_shared( + transport::AdmissionLimits{1, 1, transport::CapacityUnit::kBatches}); + auto arms = std::make_shared( + transport::AdmissionLimits{7, 1, transport::CapacityUnit::kFrames}); + auto left = endpoint("left"); + left.admission_domain = hands; + auto right = endpoint("right"); + right.admission_domain = hands; + auto arm = endpoint("arm"); + arm.admission_domain = arms; + auto hand_request = rig.session->submit(batch(3), left); + REQUIRE_THROWS_AS(rig.session->submit(batch(1), right), can::QueueFullError); + auto targets = rig.session->submit(batch(7), arm); + REQUIRE_THROWS_AS(rig.session->submit(batch(1), arm), can::QueueFullError); + auto replaceable = latest("left"); + replaceable.admission_domain = hands; + auto old = rig.session->submit(batch(1), replaceable); + auto replacement = rig.session->replace_latest_if_pending(batch(2), replaceable); + REQUIRE(replacement.has_value()); + REQUIRE(old.wait_result_until(transport::Clock::now()).outcome == + transport::SendOutcome::superseded); + replaceable.endpoint = "right"; + REQUIRE_THROWS_AS(rig.session->submit(batch(1), replaceable), can::QueueFullError); + rig.session->cancel_endpoint("left"); + auto released = rig.session->submit(batch(1), right); + rig.fake->release_tx_gate(); + blocker.wait(); + targets.wait(); + released.wait(); + REQUIRE(hand_request.completed()); + REQUIRE(rig.session->health().rejected_full == 3); +} + +TEST_CASE("Session global capacity still limits independent admission domains", "[session]") { + TxRig rig; + transport::SessionOptions settings; + settings.tx_capacity = 1; + rig.session->configure(settings); + auto blocker = rig.block_writer(); + auto first = endpoint("first"); + first.admission_domain = + std::make_shared(transport::AdmissionLimits{}); + auto second = endpoint("second"); + second.admission_domain = + std::make_shared(transport::AdmissionLimits{}); + auto queued = rig.session->submit(batch(1), first); + REQUIRE_THROWS_AS(rig.session->submit(batch(1), second), can::QueueFullError); + rig.fake->release_tx_gate(); + blocker.wait(); + queued.wait(); +} + +TEST_CASE("Admission domains validate immutable limits", "[session]") { + // Model an enum received from a runtime configuration boundary. + volatile int invalid_enum = 99; + // Intentionally exercise validation of an unrecognized configuration value. + // NOLINTNEXTLINE(clang-analyzer-optin.core.EnumCastOutOfRange) + const auto invalid_unit = static_cast(invalid_enum); + REQUIRE_THROWS_AS(transport::AdmissionDomain(transport::AdmissionLimits{0, 1}), + can::ValidationError); + REQUIRE_THROWS_AS(transport::AdmissionDomain(transport::AdmissionLimits{1, 0}), + can::ValidationError); + REQUIRE_THROWS_AS(transport::AdmissionDomain(transport::AdmissionLimits{1, 1, invalid_unit}), + can::ValidationError); + const transport::AdmissionDomain domain({7, 2, transport::CapacityUnit::kFrames}); + REQUIRE(domain.limits().fifo_capacity == 7); + REQUIRE(domain.limits().latest_capacity == 2); + REQUIRE(domain.limits().fifo_unit == transport::CapacityUnit::kFrames); + TxRig rig; + auto invalid = endpoint("arm"); + // NOLINTNEXTLINE(clang-analyzer-optin.core.EnumCastOutOfRange) + invalid.pending_age_scope = static_cast(invalid_enum); + REQUIRE_THROWS_AS(rig.session->submit(batch(1), invalid), can::ValidationError); +} + +TEST_CASE("Device sessions isolate admission routes and retryable drain", "[session]") { + TxRig rig; + REQUIRE_THROWS_AS(rig.session->attach_device(""), can::ValidationError); + auto left = rig.session->attach_device("left"); + auto right = rig.session->attach_device("right"); + REQUIRE_THROWS_AS(rig.session->submit(batch(1)), can::ValidationError); + REQUIRE(left->generation() == rig.session->health().generation); + REQUIRE_FALSE(left->closed()); + REQUIRE_THROWS_AS(rig.session->attach_device("left"), can::ValidationError); + auto left_inbox = left->subscribe_routes({{0x28, false}}); + auto right_inbox = right->subscribe_routes({{0x29, false}}); + rig.fake->arm_tx_gate(); + auto active = left->submit(batch(3)); + REQUIRE(rig.fake->wait_until_tx_entered(2s)); + auto pending = left->submit(batch(1)); + auto retained = right->submit(batch(1)); + REQUIRE_THROWS_AS(left->close_until(transport::Clock::now()), can::TimeoutError); + REQUIRE_FALSE(left->closed()); + REQUIRE_THROWS_AS(left->submit(batch(1)), can::ClosedError); + REQUIRE_THROWS_AS(left->subscribe_routes({{0x30, false}}), can::ClosedError); + REQUIRE_THROWS_AS(rig.session->attach_device("left"), can::ValidationError); + REQUIRE(pending.completed()); + rig.fake->release_tx_gate(); + active.wait(); + retained.wait(); + left->close_until(transport::Deadline::max()); + left->close_until(transport::Clock::now()); + REQUIRE(left->closed()); + REQUIRE(left_inbox->health().closed); + REQUIRE_FALSE(right_inbox->health().closed); + REQUIRE(rig.session->health().open); + auto replacement = rig.session->attach_device("left"); + replacement->subscribe_routes({{0x28, false}}); + replacement->submit(batch(1)).wait(); + right->submit(batch(1)).wait(); +} + +TEST_CASE("Device sessions retain native latest and generation checks", "[session]") { + can::FakeTransport *backend = nullptr; + auto session = transport::Session::create([&] { + auto fresh = std::make_unique(); + backend = fresh.get(); + return fresh; + }); + auto device = session->attach_device("arm"); + auto options = latest("ignored"); + REQUIRE_FALSE(device->replace_latest_if_pending(batch(1), options)); + REQUIRE_THROWS_AS(device->replace_latest_if_pending(batch(1), {}), can::ValidationError); + backend->arm_tx_gate(); + auto active = device->submit(batch(1)); + REQUIRE(backend->wait_until_tx_entered(2s)); + auto old = device->submit(batch(1), options); + auto replacement = device->replace_latest_if_pending(batch(2), options); + REQUIRE(replacement.has_value()); + REQUIRE(old.wait_result_until(transport::Clock::now()).outcome == + transport::SendOutcome::superseded); + backend->release_tx_gate(); + active.wait(); + test_support::require_value(replacement).wait(); + const auto generation = session->health().generation; + REQUIRE(session->recover(generation) != generation); + REQUIRE_THROWS_AS(device->submit(batch(1)), can::ClosedError); + REQUIRE_THROWS_AS(device->subscribe_routes({{0x28, false}}), can::ClosedError); + device->close_until(transport::Deadline::max()); + session->close(); + REQUIRE_THROWS_AS(session->attach_device("closed"), can::ClosedError); +} + +TEST_CASE("Device attachment cannot reinterpret an active legacy Session", "[session]") { + TxRig rig; + rig.session->submit(batch(1)).wait(); + REQUIRE_THROWS_AS(rig.session->attach_device("arm"), can::ValidationError); + rig.session->submit(batch(1)).wait(); +} + +TEST_CASE("Device close rejects writer callbacks before changing admission", "[session]") { + TxRig rig; + auto device = rig.session->attach_device("arm"); + bool rejected = false; + rig.fake->on_request(0x28, [&](const can::Message &) { + try { + device->close_until(transport::Clock::now()); + } catch (const can::ValidationError &) { + rejected = true; + } + return std::vector{}; + }); + device->submit(batch(1)).wait(); + REQUIRE(rejected); + REQUIRE_FALSE(device->closed()); + device->submit(batch(1)).wait(); +} + +TEST_CASE("Concurrent device close observes its own waiting deadline", "[session]") { + TxRig rig; + auto device = rig.session->attach_device("arm"); + rig.fake->arm_tx_gate(); + auto active = device->submit(batch(1)); + REQUIRE(rig.fake->wait_until_tx_entered(2s)); + auto queued = device->submit(batch(1)); + auto closer = + std::async(std::launch::async, [&] { device->close_until(transport::Deadline::max()); }); + struct ReleaseGate { + can::FakeTransport *backend; + ~ReleaseGate() { + backend->release_tx_gate(); + } + } release{rig.fake}; + REQUIRE(queued.wait_result_until(transport::Clock::now() + 2s).outcome == + transport::SendOutcome::cancelled); + REQUIRE_THROWS_AS(device->close_until(transport::Clock::now()), can::TimeoutError); + rig.fake->release_tx_gate(); + closer.get(); + active.wait(); + REQUIRE(device->closed()); +} + +TEST_CASE("Owned device work completes restoration after public close begins", "[session]") { + TxRig rig; + auto device = rig.session->attach_device("arm"); + auto peer = rig.session->attach_device("hand"); + auto operation = device->begin_operation(); + auto nested = device->begin_operation(); + REQUIRE(device->health().owned_operations == 2); + REQUIRE_THROWS_AS(device->close_until(transport::Clock::now()), can::ValidationError); + auto timed = std::async(std::launch::async, [&] { + REQUIRE_THROWS_AS(device->close_until(transport::Clock::now()), can::TimeoutError); + }); + timed.get(); + REQUIRE_FALSE(device->health().accepting); + REQUIRE_THROWS_AS(device->begin_operation(), can::ClosedError); + REQUIRE_THROWS_AS(device->submit(batch(1)), can::ClosedError); + operation.submit(batch(1)).wait(); + nested.submit(batch(1)).wait(); + peer->submit(batch(1)).wait(); + auto foreign = std::async(std::launch::async, [&] { + REQUIRE_THROWS_AS(operation.submit(batch(1)), can::ValidationError); + }); + foreign.get(); + nested = {}; + operation = {}; + REQUIRE(device->health().owned_operations == 0); + auto signal = device->notification(); + const auto revision = signal->revision(); + device->close_until(transport::Deadline::max()); + REQUIRE(signal->wait_until(revision, transport::Clock::now())); + REQUIRE(device->health().closed); + transport::DeviceOperation empty; + REQUIRE_THROWS_AS(empty.submit(batch(1)), can::ValidationError); +} + +TEST_CASE("Device final cooldown releases the writer and remains drain owned", "[session]") { + TxRig rig; + transport::DeviceOptions options; + options.send_period = 200ms; + auto arm = rig.session->attach_device("arm", options); + auto hand = rig.session->attach_device("hand"); + auto sent = arm->submit(batch(1)); + const auto signal = arm->notification(); + const auto deadline = transport::Clock::now() + 2s; + while (sent.result().sent_frames == 0) { + const auto revision = signal->revision(); + if (sent.result().sent_frames != 0) { + break; + } + REQUIRE(signal->wait_until(revision, deadline)); + } + REQUIRE_FALSE(sent.completed()); + REQUIRE(sent.result().dispatch_completed_frames == 0); + (void)hand->submit(batch(1)).wait_until(transport::Clock::now() + 100ms); + REQUIRE(rig.session->health().in_flight_frames == 1); + REQUIRE(arm->health().oldest_pending.has_value()); + REQUIRE(arm->health().in_flight == 1); + rig.session->resume_endpoint("unrelated"); + rig.session->cancel_endpoint("unrelated"); + REQUIRE_FALSE(sent.completed()); + REQUIRE_FALSE(sent.completed()); + arm->close_until(transport::Clock::now() + 1s); + REQUIRE(sent.completed()); + REQUIRE(sent.result().outcome == transport::SendOutcome::dispatched); + REQUIRE(sent.result().dispatch_completed_frames == 1); + REQUIRE(rig.session->health().open); +} + +TEST_CASE("Device pacing applies inside batches without native merge", "[session]") { + TxRig rig; + rig.fake->set_prefer_batch(true); + transport::DeviceOptions options; + options.send_period = 5ms; + auto arm = rig.session->attach_device("arm", options); + auto receipt = arm->submit(batch(3)); + const auto result = receipt.wait_until(transport::Clock::now() + 2s); + REQUIRE(result.completed_at.has_value()); + REQUIRE(result.claimed_at.has_value()); + REQUIRE(test_support::require_value(result.completed_at) - + test_support::require_value(result.claimed_at) >= + 15ms); + REQUIRE(result.dispatch_completed_frames == 3); + REQUIRE(rig.fake->batch_writes().empty()); + REQUIRE(rig.fake->sent().size() == 3); +} + +TEST_CASE("Device send failure thresholds do not reset or fault peers", "[session]") { + TxRig rig; + transport::DeviceOptions options; + options.max_consecutive_send_errors = 2; + auto arm = rig.session->attach_device("arm", options); + auto peer = rig.session->attach_device("hand"); + auto inbox = arm->subscribe_routes({{0x28, false}}); + auto peer_inbox = peer->subscribe_routes({{0x29, false}}); + rig.fake->on_request(0x28, [](const can::Message &) -> std::vector { + throw can::TransportIOError("scripted arm failure"); + }); + REQUIRE_THROWS_AS(arm->submit(batch(1)).wait(), can::TransportIOError); + peer->submit(with_id(batch(1), 0x29)).wait(); + REQUIRE(arm->health().consecutive_send_errors == 1); + REQUIRE_THROWS_AS(arm->submit(batch(1)).wait(), can::TransportIOError); + REQUIRE(arm->health().faulted); + REQUIRE_FALSE(arm->health().accepting); + REQUIRE_THROWS_AS(arm->submit(batch(1)), can::FaultedError); + REQUIRE_THROWS_AS(arm->begin_operation(), can::FaultedError); + REQUIRE_THROWS_AS(arm->subscribe_routes({{0x30, false}}), can::FaultedError); + REQUIRE_THROWS_AS(arm->subscribe_rules({{0x30, 0x7ff, false}}), can::FaultedError); + REQUIRE_THROWS_AS(inbox->try_receive(), can::FaultedError); + REQUIRE_FALSE(peer_inbox->health().closed); + peer->submit(with_id(batch(1), 0x29)).wait(); + REQUIRE(rig.session->health().open); +} + +TEST_CASE("Device failure atomically fails queued work and masked inboxes", "[session]") { + TxRig rig; + transport::DeviceOptions profile; + profile.max_consecutive_send_errors = 1; + auto device = rig.session->attach_device("faulted", profile); + auto inbox = device->subscribe_rules({{0x28, 0x7ff, false}}); + auto tap = device->observe_rules({{0x20, 0x7f0, false}}, 1); + rig.fake->on_request(0x28, [](const can::Message &) -> std::vector { + throw can::TransportIOError("injected write failure"); + }); + rig.fake->arm_tx_gate(); + auto active = device->submit(batch(1)); + REQUIRE(rig.fake->wait_until_tx_entered(2s)); + auto queued = device->submit(batch(1)); + rig.fake->release_tx_gate(); + REQUIRE_THROWS_AS(active.wait(), can::TransportIOError); + REQUIRE_THROWS_AS(queued.wait(), can::FaultedError); + REQUIRE_THROWS_AS(inbox->try_receive(), can::FaultedError); + REQUIRE_THROWS_AS(tap->try_receive(), can::FaultedError); + REQUIRE_THROWS_AS(device->observe_rules({{0, 0, false}}, 1), can::FaultedError); + REQUIRE(rig.session->health().pending_tx == 0); +} + +TEST_CASE("Domain age and device diagnostics include native owned work", "[session]") { + TxRig rig; + auto config = rig.session->options(); + config.max_batch_frames = 2; + rig.session->configure(config); + auto domain = std::make_shared(transport::AdmissionLimits{}); + transport::DeviceOptions profile; + profile.admission_domain = domain; + auto first = rig.session->attach_device("first", profile); + auto second = rig.session->attach_device("second", profile); + REQUIRE_THROWS_AS(rig.session->configure(config), can::ValidationError); + REQUIRE_THROWS_AS(first->submit(batch(3)), can::ValidationError); + rig.fake->arm_tx_gate(); + auto active = first->submit(batch(1)); + REQUIRE(rig.fake->wait_until_tx_entered(2s)); + auto queued = first->submit(batch(2)); + auto fresh = latest("ignored"); + auto replaceable = first->submit(batch(1), fresh); + const auto health = first->health(); + REQUIRE(health.pending_fifo == 2); + REQUIRE(health.pending_latest == 1); + REQUIRE(health.in_flight == 1); + REQUIRE(health.oldest_pending.has_value()); + std::this_thread::sleep_for(2ms); + transport::SendOptions aged; + aged.pending_age_scope = transport::PendingAgeScope::kAdmissionDomain; + aged.max_pending_age = 1ms; + REQUIRE_THROWS_AS(second->submit(batch(1), aged), can::TimeoutError); + rig.fake->release_tx_gate(); + active.wait(); + queued.wait(); + replaceable.wait(); + REQUIRE_FALSE(first->health().oldest_pending.has_value()); + REQUIRE(first->health().in_flight == 0); +} + +TEST_CASE("Device profile validation preserves the legacy pacing boundary", "[session]") { + TxRig rig; + transport::DeviceOptions invalid; + invalid.send_period = -1us; + REQUIRE_THROWS_AS(rig.session->attach_device("bad", invalid), can::ValidationError); + auto config = rig.session->options(); + config.send_period = 1us; + rig.session->configure(config); + invalid.send_period = 1us; + REQUIRE_THROWS_AS(rig.session->attach_device("conflict", invalid), can::ValidationError); + transport::SendOptions age; + age.pending_age_scope = transport::PendingAgeScope::kAdmissionDomain; + REQUIRE_THROWS_AS(rig.session->submit(batch(1), age), can::ValidationError); +} + +TEST_CASE("Admission domains receive turns independently of their priorities", "[session]") { + TxRig rig; + transport::SessionOptions config; + config.domain_round_robin = true; + rig.session->configure(config); + transport::DeviceOptions left_config; + left_config.admission_domain = + std::make_shared(transport::AdmissionLimits{}); + transport::DeviceOptions right_config; + right_config.admission_domain = + std::make_shared(transport::AdmissionLimits{}); + auto left = rig.session->attach_device("left", left_config); + auto right = rig.session->attach_device("right", right_config); + rig.fake->arm_tx_gate(); + auto blocked = left->submit(with_id(batch(1), 1)); + REQUIRE(rig.fake->wait_until_tx_entered(2s)); + auto high = endpoint("ignored"); + high.priority = 100; + auto a = left->submit(batch(1), high); + auto b = left->submit(batch(1), high); + auto c = right->submit(with_id(batch(1), 0x29)); + auto d = right->submit(with_id(batch(1), 0x29)); + rig.fake->release_tx_gate(); + blocked.wait(); + a.wait(); + b.wait(); + c.wait(); + d.wait(); + const auto frames = rig.fake->sent(); + REQUIRE(frames.size() == 5); + REQUIRE(frames[1].id == 0x29); + REQUIRE(frames[2].id == 0x28); + REQUIRE(frames[3].id == 0x29); + REQUIRE(frames[4].id == 0x28); +} + TEST_CASE("Session optional endpoint FIFO prevents priority from overtaking an earlier request", "[session]") { TxRig rig; diff --git a/tests/test_transport_runtime.cpp b/tests/test_transport_runtime.cpp new file mode 100644 index 0000000..8e30bac --- /dev/null +++ b/tests/test_transport_runtime.cpp @@ -0,0 +1,304 @@ +#include +#include +#include + +#include +#include + +using namespace std::chrono_literals; +using namespace linkerbot; + +namespace { + transport::ChannelSpec channel(const std::string &name) { + transport::ChannelSpec spec; + spec.key.backend = "fake"; + spec.key.endpoint = name; + spec.configuration_fingerprint = "fake/default"; + return spec; + } + struct CountedFake : can::FakeTransport { + std::shared_ptr> closes; + explicit CountedFake(std::shared_ptr> counter) + : closes(std::move(counter)) {} + void close() override { + ++*closes; + can::FakeTransport::close(); + } + }; +} // namespace + +TEST_CASE("Runtime instances share a connection until the final logical lease", "[runtime]") { + transport::TransportRuntime first; + transport::TransportRuntime second; + const auto spec = channel("runtime/shared"); + auto closes = std::make_shared>(0); + int opens = 0; + const auto factory = [&] { + ++opens; + return std::make_unique(closes); + }; + REQUIRE(first.active_devices(spec.key) == 0); + REQUIRE_THROWS_AS(first.channel_health(spec.key), can::ClosedError); + REQUIRE_THROWS_AS(first.recover_channel(spec.key, 0), can::ClosedError); + auto left = first.open_device(spec, {"left", {}}, factory); + auto right = second.open_device(spec, {"right", {}}, factory); + REQUIRE(opens == 1); + REQUIRE(first.active_devices(spec.key) == 2); + const auto instance = left->health().channel_instance; + left->close_until(transport::Deadline::max()); + REQUIRE(closes->load() == 0); + right->submit({{{}}}).wait(); + REQUIRE(second.active_devices(spec.key) == 1); + right->close_until(transport::Deadline::max()); + REQUIRE(closes->load() == 1); + REQUIRE(first.active_devices(spec.key) == 0); + auto replacement = first.open_device(spec, {"left", {}}, factory); + REQUIRE(opens == 2); + REQUIRE(replacement->health().channel_instance != instance); + REQUIRE_THROWS_AS(left->submit({{{}}}), can::ClosedError); +} + +TEST_CASE("Device rebind keeps the physical connection and invalidates the old handle", + "[runtime]") { + transport::TransportRuntime runtime; + const auto spec = channel("runtime/rebind"); + int opens = 0; + auto device = runtime.open_device(spec, {"hand", {}}, [&] { + ++opens; + return std::make_unique(); + }); + const auto initial = device->health(); + transport::DeviceSpec invalid_reset{"hand", {}}; + volatile int invalid_policy = 99; + // Deliberately pass an unrecognized external configuration value. + // NOLINTNEXTLINE(clang-analyzer-optin.core.EnumCastOutOfRange) + invalid_reset.channel_reset = static_cast(invalid_policy); + REQUIRE_THROWS_AS( + runtime.rebind_device(spec.key, device, invalid_reset, transport::Deadline::max()), + can::ValidationError); + REQUIRE_THROWS_AS(runtime.rebind_device(spec.key, {}, {"hand", {}}, transport::Deadline::max()), + can::ValidationError); + REQUIRE_THROWS_AS(runtime.rebind_device(spec.key, device, {"", {}}, transport::Deadline::max()), + can::ValidationError); + auto rebound = + runtime.rebind_device(spec.key, device, {"hand", {}}, transport::Deadline::max()); + REQUIRE(opens == 1); + REQUIRE(runtime.active_devices(spec.key) == 1); + REQUIRE(rebound->health().generation == initial.generation); + REQUIRE(rebound->health().channel_instance == initial.channel_instance); + REQUIRE(device->closed()); + REQUIRE_THROWS_AS(device->begin_operation(), can::ClosedError); + REQUIRE_THROWS_AS(device->subscribe_rules({{0, 0x7ff, false}}), can::ClosedError); + REQUIRE(rebound->submit({{{}}}).wait_result_until(transport::Deadline::max()).outcome == + transport::SendOutcome::dispatched); + const auto before = rebound->generation(); + runtime.recover_channel(spec.key, before); + REQUIRE_THROWS_AS(rebound->begin_operation(), can::ClosedError); + REQUIRE_THROWS_AS(rebound->observe_rules({{0, 0, false}}, 1), can::ClosedError); + REQUIRE_THROWS_AS(rebound->subscribe_rules({{0, 0x7ff, false}}), can::ClosedError); + auto restored = + runtime.rebind_device(spec.key, rebound, {"hand", {}}, transport::Deadline::max()); + REQUIRE(opens == 2); + REQUIRE(restored->generation() != before); +} + +TEST_CASE("Runtime rejects conflicting profiles without opening a second backend", "[runtime]") { + transport::TransportRuntime runtime; + const auto spec = channel("runtime/config"); + int opens = 0; + const auto factory = [&] { + ++opens; + return std::make_unique(); + }; + auto device = runtime.open_device(spec, {"one", {}}, factory); + auto conflict = spec; + conflict.configuration_fingerprint = "other driver options"; + REQUIRE_THROWS_AS(runtime.open_device(conflict, {"two", {}}, factory), can::ValidationError); + conflict = spec; + ++conflict.scheduling.fifo_capacity; + REQUIRE_THROWS_AS(runtime.open_device(conflict, {"two", {}}, factory), can::ValidationError); + conflict = spec; + conflict.key.fd_mode = true; + REQUIRE_THROWS_AS(runtime.open_device(conflict, {"two", {}}, factory), can::ValidationError); + REQUIRE_THROWS_AS(runtime.open_device(spec, {"one", {}}, factory), can::ValidationError); + REQUIRE(opens == 1); + REQUIRE(runtime.active_devices(spec.key) == 1); +} + +TEST_CASE("Runtime keeps failed final shutdown reserved for retry", "[runtime]") { + transport::TransportRuntime runtime; + const auto spec = channel("runtime/retry-close"); + can::FakeTransport *backend = nullptr; + int opens = 0; + const auto factory = [&] { + ++opens; + auto fresh = std::make_unique(); + backend = fresh.get(); + return fresh; + }; + auto device = runtime.open_device(spec, {"one", {}}, factory); + backend->fail_next_closes(1); + REQUIRE_THROWS_AS(device->close_until(transport::Deadline::max()), can::CANError); + REQUIRE_FALSE(device->closed()); + REQUIRE(runtime.active_devices(spec.key) == 1); + REQUIRE_THROWS_AS(runtime.open_device(spec, {"two", {}}, factory), can::FaultedError); + REQUIRE(opens == 1); + device->close_until(transport::Deadline::max()); + REQUIRE(device->closed()); + auto replacement = runtime.open_device(spec, {"one", {}}, factory); + REQUIRE(opens == 2); +} + +TEST_CASE("Runtime initialization failure and same-key reentry are retryable", "[runtime]") { + transport::TransportRuntime runtime; + const auto spec = channel("runtime/init-failure"); + auto factory = [] { return std::make_unique(); }; + auto invalid = spec; + invalid.configuration_fingerprint.clear(); + REQUIRE_THROWS_AS(runtime.open_device(invalid, {"one", {}}, factory), can::ValidationError); + REQUIRE_THROWS_AS(runtime.open_device(spec, {"", {}}, factory), can::ValidationError); + REQUIRE_THROWS_AS(runtime.open_device(spec, {"one", {}}, {}), can::ValidationError); + REQUIRE_THROWS_AS(runtime.open_device(spec, {"one", {}}, + [&]() -> std::unique_ptr { + (void)runtime.open_device(spec, {"nested", {}}, + factory); + return factory(); + }), + can::ValidationError); + auto device = runtime.open_device(spec, {"one", {}}, factory); + REQUIRE(runtime.active_devices(spec.key) == 1); +} + +TEST_CASE("Runtime concurrent opens publish one configured Session", "[runtime]") { + transport::TransportRuntime runtime; + const auto spec = channel("runtime/concurrent"); + std::promise entered; + std::promise release; + auto ready = entered.get_future(); + auto resume = release.get_future().share(); + std::atomic opens{0}; + const auto factory = [&] { + ++opens; + entered.set_value(); + resume.wait(); + return std::make_unique(); + }; + auto one = std::async(std::launch::async, + [&] { return runtime.open_device(spec, {"one", {}}, factory); }); + const auto started = ready.wait_for(2s); + auto two = std::async(std::launch::async, + [&] { return runtime.open_device(spec, {"two", {}}, factory); }); + const auto waiting = two.wait_for(10ms); + release.set_value(); + REQUIRE(started == std::future_status::ready); + REQUIRE(waiting == std::future_status::timeout); + auto first = one.get(); + auto second = two.get(); + REQUIRE(opens.load() == 1); + REQUIRE(runtime.active_devices(spec.key) == 2); + first->submit({{{}}}).wait(); + second->submit({{{}}}).wait(); +} + +TEST_CASE("Runtime reset policy protects reconstruction-only devices", "[runtime]") { + transport::TransportRuntime runtime; + const auto spec = channel("runtime/recovery-policy"); + int opens = 0; + const auto factory = [&] { + ++opens; + return std::make_unique(); + }; + transport::DeviceSpec arm_spec{"arm", {}}; + arm_spec.channel_reset = transport::ChannelResetPolicy::kRequireDetach; + auto arm = runtime.open_device(spec, arm_spec, factory); + auto hand = runtime.open_device(spec, {"hand", {}}, factory); + const auto generation = runtime.channel_health(spec.key).generation; + REQUIRE_THROWS_AS(runtime.recover_channel(spec.key, generation), can::ValidationError); + REQUIRE(opens == 1); + arm->close_until(transport::Deadline::max()); + const auto recovered = runtime.recover_channel(spec.key, generation); + REQUIRE(recovered != generation); + REQUIRE(opens == 2); + REQUIRE_FALSE(hand->health().accepting); + REQUIRE_THROWS_AS(hand->submit({{{}}}), can::ClosedError); + REQUIRE(runtime.recover_channel(spec.key, generation) == recovered); + REQUIRE(opens == 2); +} + +TEST_CASE("Runtime permits a new attempt after failed recovery", "[runtime]") { + transport::TransportRuntime runtime; + const auto spec = channel("runtime/recovery-retry"); + int opens = 0; + const auto factory = [&] { + if (++opens == 2) { + throw can::TransportIOError("reopen failed"); + } + return std::make_unique(); + }; + auto device = runtime.open_device(spec, {"hand", {}}, factory); + const auto generation = runtime.channel_health(spec.key).generation; + REQUIRE_THROWS_AS(runtime.recover_channel(spec.key, generation), can::CANError); + REQUIRE_FALSE(runtime.channel_health(spec.key).open); + REQUIRE(runtime.recover_channel(spec.key, generation) != generation); + REQUIRE(opens == 3); + REQUIRE_FALSE(device->health().accepting); +} + +TEST_CASE("Runtime destruction retries failed physical cleanup", "[runtime]") { + transport::TransportRuntime runtime; + const auto spec = channel("runtime/destructor-retry"); + auto closes = std::make_shared>(0); + auto device = runtime.open_device(spec, {"hand", {}}, [&] { + auto backend = std::make_unique(closes); + backend->fail_next_closes(2); + return backend; + }); + device.reset(); + can::CANBusLease::drain_deferred_cleanup(); + REQUIRE(closes->load() >= 3); + REQUIRE(runtime.active_devices(spec.key) == 0); +} + +TEST_CASE("Runtime rejects a cycle between channel factories", "[runtime]") { + transport::TransportRuntime runtime; + const auto left = channel("runtime/cycle-left"); + const auto right = channel("runtime/cycle-right"); + std::promise left_entered; + std::promise right_entered; + auto left_ready = left_entered.get_future().share(); + auto right_ready = right_entered.get_future().share(); + const auto basic = [] { return std::make_unique(); }; + auto first = std::async(std::launch::async, [&] { + try { + auto device = runtime.open_device(left, {"outer", {}}, [&] { + left_entered.set_value(); + right_ready.wait(); + auto nested = runtime.open_device(right, {"nested", {}}, basic); + return basic(); + }); + return true; + } catch (const can::ValidationError &) { + return false; + } + }); + auto second = std::async(std::launch::async, [&] { + try { + auto device = runtime.open_device(right, {"outer", {}}, [&] { + right_entered.set_value(); + left_ready.wait(); + auto nested = runtime.open_device(left, {"nested", {}}, basic); + return basic(); + }); + return true; + } catch (const can::ValidationError &) { + return false; + } + }); + REQUIRE(first.wait_for(2s) == std::future_status::ready); + REQUIRE(second.wait_for(2s) == std::future_status::ready); + const bool first_opened = first.get(); + const bool second_opened = second.get(); + REQUIRE(first_opened != second_opened); + REQUIRE(runtime.active_devices(left.key) == 0); + REQUIRE(runtime.active_devices(right.key) == 0); +} diff --git a/validation/installed-consumer/main.cpp b/validation/installed-consumer/main.cpp index 502c9ba..961ddb1 100644 --- a/validation/installed-consumer/main.cpp +++ b/validation/installed-consumer/main.cpp @@ -29,6 +29,7 @@ #include #include #include +#include #include #include #include @@ -60,6 +61,25 @@ namespace { return 6; } // Exercise installed SLCAN symbols without opening any COM port. + linkerbot::transport::TransportRuntime runtime; + linkerbot::transport::ChannelSpec channel; + channel.key.backend = "fake"; + channel.key.endpoint = "installed-consumer"; + channel.configuration_fingerprint = "fake/default"; + auto device = runtime.open_device(channel, {"hand", {}}, [] { + return std::make_unique(); + }); + auto observed = device->subscribe_rules({{message.id, 0x7ff, false}}); + auto operation = device->begin_operation(); + operation.submit({{message}}).wait(); + operation = linkerbot::transport::DeviceOperation{}; + auto rebound = runtime.rebind_device(channel.key, device, {"hand", {}}, + linkerbot::transport::Deadline::max()); + rebound->close_until(linkerbot::transport::Deadline::max()); + if (!observed->health().closed || runtime.active_devices(channel.key) != 0) { + return 7; + } + // Exercise installed SLCAN symbols without opening any COM port. linkerbot::can::SlcanConfig serial; serial.port = "COM10"; linkerbot::can::validate_slcan_config(serial);