1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
//! Helpers for exercising private connection actor paths in integration tests.
// These helpers compile only for crate tests or the `test-support` feature so
// integration tests can exercise private connection actor paths.
use tokio::sync::mpsc;
use tokio_util::sync::CancellationToken;
use super::{
ConnectionActor,
ConnectionChannels,
drain::ActorStep,
multi_packet::MultiPacketTerminationReason,
state::ActorState,
};
use crate::{
NoProtocolError,
app::{Packet, PacketParts},
hooks::ProtocolHooks,
push::{PushConfigError, PushQueues},
};
// CorrelatableFrame for u8 and Vec<u8> is implemented in correlation.rs.
impl Packet for u8 {
fn id(&self) -> u32 { 0 }
fn into_parts(self) -> PacketParts { PacketParts::new(0, None, vec![self]) }
fn from_parts(parts: PacketParts) -> Self {
parts.into_payload().first().copied().unwrap_or_default()
}
}
impl Packet for Vec<u8> {
fn id(&self) -> u32 { 0 }
fn into_parts(self) -> PacketParts { PacketParts::new(0, None, self) }
fn from_parts(parts: PacketParts) -> Self { parts.into_payload() }
}
/// Build a connection actor configured with the supplied protocol hooks.
///
/// # Errors
///
/// Returns an error if the push queues cannot be constructed.
pub fn create_test_actor_with_hooks(
hooks: ProtocolHooks<u8, NoProtocolError>,
) -> Result<ConnectionActor<u8>, PushConfigError> {
let (queues, handle) = PushQueues::<u8>::builder()
.high_capacity(4)
.low_capacity(4)
.build()?;
Ok(ConnectionActor::with_hooks(
ConnectionChannels::new(queues, handle),
None,
CancellationToken::new(),
hooks,
))
}
/// Convenience harness wrapping an actor, its state, and buffered output.
pub struct ActorHarness {
/// Actor under test, retaining the real queue and lifecycle logic.
actor: ConnectionActor<u8>,
/// Mutable lifecycle state supplied to direct drain helpers.
state: ActorState,
/// Frames emitted by the actor during tests, preserved for assertions.
pub out: Vec<u8>,
}
impl ActorHarness {
/// Create a harness with custom hooks and state flags.
///
/// # Errors
///
/// Returns an error if the push queues cannot be constructed.
pub fn new_with_state(
hooks: ProtocolHooks<u8, NoProtocolError>,
has_response: bool,
has_multi_packet: bool,
) -> Result<Self, PushConfigError> {
let actor = create_test_actor_with_hooks(hooks)?;
Ok(Self {
actor,
state: ActorState::new(has_response, has_multi_packet),
out: Vec::new(),
})
}
/// Create a harness using default hooks and no active streams.
///
/// # Errors
///
/// Returns an error if the push queues cannot be constructed.
pub fn new() -> Result<Self, PushConfigError> {
Self::new_with_state(
ProtocolHooks::<u8, NoProtocolError>::default(),
false,
false,
)
}
/// Snapshot the internal actor state.
#[must_use]
pub const fn snapshot(&self) -> ActorStateSnapshot {
ActorStateSnapshot {
is_active: self.state.is_active(),
is_shutting_down: self.state.is_shutting_down(),
is_done: self.state.is_done(),
total_sources: self.state.total_sources(),
closed_sources: self.state.closed_sources(),
}
}
/// Replace the low-priority receiver.
pub fn set_low_queue(&mut self, queue: Option<mpsc::Receiver<u8>>) {
self.actor.set_low_queue(queue);
}
/// Replace the multi-packet receiver.
///
/// # Errors
///
/// Returns [`crate::connection::ConnectionStateError`] if a response stream
/// is currently active.
pub fn set_multi_queue(
&mut self,
queue: Option<mpsc::Receiver<u8>>,
) -> Result<(), crate::connection::ConnectionStateError> {
self.actor.set_multi_packet(queue)
}
/// Returns `true` when the low-priority queue is still available.
#[must_use]
pub const fn has_low_queue(&self) -> bool { self.actor.low_rx.is_some() }
/// Returns `true` when the multi-packet queue is still available.
#[must_use]
pub const fn has_multi_queue(&self) -> bool { self.actor.active_output.is_multi_packet() }
/// Process a multi-packet poll result.
pub fn process_multi_packet(&mut self, res: Option<u8>) {
// The harness has no queued pushes, so the push buffer is scratch.
let mut pushes = Vec::new();
let mut step = ActorStep {
state: &mut self.state,
out: &mut self.out,
pushes: &mut pushes,
};
self.actor.process_multi_packet(res, &mut step);
self.run_deferred_command_end();
}
/// Handle closure of the multi-packet receiver.
pub fn handle_multi_packet_closed(&mut self) {
self.actor.handle_multi_packet_closed(
MultiPacketTerminationReason::Drained,
&mut self.state,
&mut self.out,
);
self.run_deferred_command_end();
}
/// Run the completion hook deferred until the buffered frames are written.
///
/// Production runs this immediately after the sink accepts a batch. The
/// harness writes into `out` synchronously, so it applies the same boundary
/// here; hook-count assertions then match the real driver.
fn run_deferred_command_end(&mut self) { self.actor.run_deferred_command_end(); }
/// Trigger shutdown handling on the underlying actor.
pub fn start_shutdown(&mut self) {
self.actor.start_shutdown(&mut self.state);
self.run_deferred_command_end();
}
/// Attempt a low-priority opportunistic drain.
pub fn try_drain_low(&mut self) -> bool {
let state = &mut self.state;
let out = &mut self.out;
let drained = self.actor.try_opportunistic_low_drain(state, out);
self.run_deferred_command_end();
drained
}
/// Attempt a multi-packet opportunistic drain.
pub fn try_drain_multi(&mut self) -> bool {
let state = &mut self.state;
let out = &mut self.out;
let drained = self.actor.try_opportunistic_multi_drain(state, out);
self.run_deferred_command_end();
drained
}
/// Access the underlying actor mutably.
pub const fn actor_mut(&mut self) -> &mut ConnectionActor<u8> { &mut self.actor }
}
/// Snapshot of the actor lifecycle flags and counters.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ActorStateSnapshot {
/// `true` while the actor is still polling its sources.
pub is_active: bool,
/// `true` after shutdown has begun but before sources finish.
pub is_shutting_down: bool,
/// `true` once all sources have closed and the actor can exit.
pub is_done: bool,
/// Total number of sources being tracked for completion.
pub total_sources: usize,
/// Number of sources observed as closed so far.
pub closed_sources: usize,
}
/// Harness around `ActorState` for integration tests.
pub struct ActorStateHarness {
/// Lifecycle state exercised by verification helpers.
state: ActorState,
}
impl ActorStateHarness {
/// Construct a harness with the provided active sources.
#[must_use]
pub fn new(has_response: bool, has_multi_packet: bool) -> Self {
Self {
state: ActorState::new(has_response, has_multi_packet),
}
}
/// Mark a source as closed.
pub const fn mark_closed(&mut self) { self.state.mark_closed(); }
/// Begin shutdown, transitioning an active state to shutting-down.
pub const fn start_shutdown(&mut self) { self.state.start_shutdown(); }
/// Observe the current state snapshot.
#[must_use]
pub const fn snapshot(&self) -> ActorStateSnapshot {
ActorStateSnapshot {
is_active: self.state.is_active(),
is_shutting_down: self.state.is_shutting_down(),
is_done: self.state.is_done(),
total_sources: self.state.total_sources(),
closed_sources: self.state.closed_sources(),
}
}
}
/// Await a frame from the provided queue, returning `None` when absent.
pub async fn poll_queue_next(rx: Option<&mut mpsc::Receiver<u8>>) -> Option<u8> {
ConnectionActor::<u8, ()>::poll_queue(rx).await
}
#[cfg(test)]
mod tests {
//! Unit tests for the `ActorHarness` fixture using parameterized `rstest` cases.
use rstest::{fixture, rstest};
use tokio::sync::mpsc;
use super::*;
type TestResult<T> = Result<T, Box<dyn std::error::Error>>;
#[fixture]
fn harness() -> TestResult<ActorHarness> {
// Provides an ActorHarness for parameterized multi-queue state tests.
ActorHarness::new().map_err(Into::into)
}
#[rstest]
#[case::default(false, false, false)]
#[case::install(true, false, true)]
#[case::clear(true, true, false)]
fn has_multi_queue_states(
#[case] install: bool,
#[case] clear: bool,
#[case] expected: bool,
harness: TestResult<ActorHarness>,
) -> TestResult<()> {
let mut actor_harness = harness?;
if install {
let (_tx, rx) = mpsc::channel(1);
actor_harness.set_multi_queue(Some(rx))?;
}
if clear {
actor_harness.set_multi_queue(None)?;
}
if actor_harness.has_multi_queue() != expected {
return Err("multi-packet queue state mismatch".into());
}
Ok(())
}
}