shep-client 0.25.2

Async client for the shep daemon: typed requests, event subscriptions, and starting a shepherd that is not running yet
Documentation
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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
use super::*;
use crate::{Client, ReconnectingClient};
use futures_util::StreamExt;
use shep_core::protocol::{
    BusEvent, Envelope, HelloAck, Request, Response, RpcError, RpcErrorCode, codec, decode_frame,
};
use std::collections::VecDeque;
use std::path::Path;
use std::sync::atomic::{AtomicBool, AtomicU64};
use std::sync::{Arc, Mutex};
use std::time::Duration;
use tokio::sync::mpsc;
use tokio::task::JoinHandle;
use tokio_util::codec::Framed;

/// Binds `path`, handshakes with [`sample_ack`], and hands back a connected
/// [`Client`] alongside the still-live [`FakeDaemon`] script, for a test
/// that needs nothing daemon-specific.
pub async fn fake_client_on(path: &Path) -> (Client, FakeDaemon) {
    fake_client_with_ack(path, sample_ack()).await
}

/// As [`fake_client_on`], but with a caller-chosen [`HelloAck`], for a
/// test asserting on the ack a `Client` receives.
pub async fn fake_client_with_ack(path: &Path, ack: HelloAck) -> (Client, FakeDaemon) {
    let daemon = fake_daemon_scripted_on(path, ack);
    let client = Client::connect(path).await.unwrap();
    (client, daemon)
}

/// As [`fake_client_on`], but hands back a [`ReconnectingClient`], the
/// supervised wrapper a dog uses, instead of a bare [`Client`].
///
/// The [`FakeDaemon`] behind it still serves exactly one connection, so a
/// test that cuts it leaves the supervisor retrying against a gone
/// listener. Use [`fake_daemon_across_handovers`] to test the reconnect
/// itself.
pub async fn fake_reconnecting_client_on(path: &Path) -> (ReconnectingClient, FakeDaemon) {
    let daemon = fake_daemon_scripted_on(path, sample_ack());
    let client = ReconnectingClient::connect(path).await.unwrap();
    (client, daemon)
}

/// Binds `path` and starts the scripted fake without connecting a client
/// of its own, for a caller that performs its own connect.
///
/// Synchronous: the listener is bound before this returns, so a caller can
/// connect straight away without a sleep.
///
/// Panics if `path` cannot be bound.
#[must_use]
pub fn fake_daemon_scripted_on(path: &Path, ack: HelloAck) -> FakeDaemon {
    let listener = bind(path);
    let (script_tx, script_rx) = mpsc::channel(SCRIPT_CHANNEL_CAPACITY);
    let armed_list = Arc::new(Mutex::new(None));
    let armed_list_sequence = Arc::new(Mutex::new(VecDeque::new()));
    let armed_describe = Arc::new(Mutex::new(None));
    let armed_reply_then_event = Arc::new(Mutex::new(None));
    let armed_shutdown_then_unlink = Arc::new(Mutex::new(None));
    let armed_shutdown_never_unlink = Arc::new(AtomicBool::new(false));
    let list_flock_count = Arc::new(AtomicU64::new(0));
    let task = tokio::spawn(serve_scripted(
        listener,
        path.to_path_buf(),
        ack,
        script_rx,
        Arc::clone(&armed_list),
        Arc::clone(&armed_list_sequence),
        Arc::clone(&armed_describe),
        Arc::clone(&armed_reply_then_event),
        Arc::clone(&armed_shutdown_then_unlink),
        Arc::clone(&armed_shutdown_never_unlink),
        Arc::clone(&list_flock_count),
    ));
    FakeDaemon {
        script: script_tx,
        armed_list,
        armed_list_sequence,
        armed_describe,
        armed_reply_then_event,
        armed_shutdown_then_unlink,
        armed_shutdown_never_unlink,
        list_flock_count,
        task,
    }
}

/// Identical to [`fake_client_on`], named separately for tests whose whole
/// point is [`FakeDaemon::push`], [`FakeDaemon::overrun_by`] or
/// [`FakeDaemon::queue_reply_then_event`].
pub async fn fake_client_with_push(path: &Path) -> (Client, FakeDaemon) {
    fake_client_on(path).await
}

/// Binds `path` and serves every connection made to it. It handshakes with
/// `ack`, answers each request through `answer`, and forwards each
/// [`Envelope`] to the channel.
///
/// Unlike [`fake_client_answering`], which accepts exactly one connection:
/// a CLI verb opens its own. The task is detached, and runs until the
/// listener errors when the caller's `TempDir` goes away.
pub async fn fake_daemon_answering_with_ack(
    path: &Path,
    ack: HelloAck,
    answer: impl Fn(&Request) -> Response + Send + Sync + Clone + 'static,
) -> mpsc::UnboundedReceiver<Envelope> {
    let mut listener = bind(path);
    let (tx, rx) = mpsc::unbounded_channel();
    tokio::spawn(async move {
        while let Ok(stream) = listener.accept().await {
            let tx = tx.clone();
            let ack = ack.clone();
            let answer = answer.clone();
            tokio::spawn(async move {
                let mut frames = Framed::new(stream, codec());
                let _hello = handshake(&mut frames, ack).await;
                while let Some(Ok(frame)) = frames.next().await {
                    let Ok(envelope) = decode_frame::<Envelope>(&frame) else {
                        break;
                    };
                    let id = envelope.id;
                    let reply = answer(&envelope.body);
                    if tx.send(envelope).is_err() {
                        break;
                    }
                    write_reply(&mut frames, id, reply).await;
                }
            });
        }
    });
    rx
}

/// As [`fake_client_capturing_envelopes`], but `answer` decides each reply,
/// called with each decoded [`Request`] in arrival order. The envelope
/// reaches the channel before the reply is written.
///
/// The channel is unbounded, unlike every other one in this module: a test
/// reads these envelopes only after the call under test returns. The read
/// loop ends on a closed connection rather than panicking.
pub async fn fake_client_answering(
    path: &Path,
    answer: impl Fn(&Request) -> Response + Send + 'static,
) -> (Client, mpsc::UnboundedReceiver<Envelope>) {
    let mut listener = bind(path);
    let (tx, rx) = mpsc::unbounded_channel();
    tokio::spawn(async move {
        let mut frames = accept_handshaked(&mut listener, sample_ack()).await;
        while let Some(Ok(frame)) = frames.next().await {
            let Ok(envelope) = decode_frame::<Envelope>(&frame) else {
                break;
            };
            let id = envelope.id;
            let reply = answer(&envelope.body);
            if tx.send(envelope).is_err() {
                break;
            }
            write_reply(&mut frames, id, reply).await;
        }
    });
    let client = Client::connect(path).await.unwrap();
    (client, rx)
}

/// As [`fake_client_answering`], but `answer` may refuse: an `Err` is
/// written as the reply's [`RpcError`], for a caller that has to see a
/// daemon-side refusal come back as a failed request rather than as an
/// unexpected [`Response`].
///
/// `answer` is called per request in arrival order, so it can refuse one
/// request of a multi-request verb and answer the rest.
pub async fn fake_client_answering_refusals(
    path: &Path,
    answer: impl Fn(&Request) -> Result<Response, RpcError> + Send + 'static,
) -> (Client, mpsc::UnboundedReceiver<Envelope>) {
    let mut listener = bind(path);
    let (tx, rx) = mpsc::unbounded_channel();
    tokio::spawn(async move {
        let mut frames = accept_handshaked(&mut listener, sample_ack()).await;
        while let Some(Ok(frame)) = frames.next().await {
            let Ok(envelope) = decode_frame::<Envelope>(&frame) else {
                break;
            };
            let id = envelope.id;
            let answer = answer(&envelope.body);
            // Forwarded before the reply is written, as in
            // [`fake_client_answering`]: a test reads these envelopes after
            // the call under test returns.
            if tx.send(envelope).is_err() {
                break;
            }
            match answer {
                Ok(response) => write_reply(&mut frames, id, response).await,
                Err(err) => write_err(&mut frames, id, err.code, err.message).await,
            }
        }
    });
    let client = Client::connect(path).await.unwrap();
    (client, rx)
}

/// As [`fake_client_answering_refusals`], but `answer` also names the
/// events written straight after its reply, for a verb whose request opens
/// a stream, such as `Request::Attach`.
///
/// Reply then events, in that order, as a shepherd sends them.
pub async fn fake_client_answering_with_events(
    path: &Path,
    answer: impl Fn(&Request) -> (Result<Response, RpcError>, Vec<BusEvent>) + Send + 'static,
) -> (Client, mpsc::UnboundedReceiver<Envelope>) {
    fake_client_leaving_unanswered(path, move |request| Some(answer(request))).await
}

/// As [`fake_client_answering_with_events`], but `answer` returns `None` for
/// a request the shepherd never answers, for a test of a caller whose
/// request is still waiting.
///
/// The envelope is still forwarded onto the returned channel, and later
/// requests are still read and answered.
pub async fn fake_client_leaving_unanswered(
    path: &Path,
    answer: impl Fn(&Request) -> Option<(Result<Response, RpcError>, Vec<BusEvent>)> + Send + 'static,
) -> (Client, mpsc::UnboundedReceiver<Envelope>) {
    let mut listener = bind(path);
    let (tx, rx) = mpsc::unbounded_channel();
    tokio::spawn(async move {
        let mut frames = accept_handshaked(&mut listener, sample_ack()).await;
        while let Some(Ok(frame)) = frames.next().await {
            let Ok(envelope) = decode_frame::<Envelope>(&frame) else {
                break;
            };
            let id = envelope.id;
            let answered = answer(&envelope.body);
            if tx.send(envelope).is_err() {
                break;
            }
            let Some((reply, events)) = answered else {
                continue;
            };
            match reply {
                Ok(response) => write_reply(&mut frames, id, response).await,
                Err(err) => write_err(&mut frames, id, err.code, err.message).await,
            }
            for event in events {
                write_event(&mut frames, event).await;
            }
        }
    });
    let client = Client::connect(path).await.unwrap();
    (client, rx)
}

/// Binds `path`, handshakes with [`sample_ack`], and answers every request
/// with `Response::Pong` while forwarding each decoded [`Envelope`] onto
/// the returned channel, for asserting on what a `Client` puts on the wire
/// rather than on how the daemon answers.
pub async fn fake_client_capturing_envelopes(path: &Path) -> (Client, mpsc::Receiver<Envelope>) {
    fake_client_capturing_envelopes_with_ack(path, sample_ack()).await
}

/// As [`fake_client_capturing_envelopes`], but handshaking with a
/// caller-chosen [`HelloAck`], for a verb that reads the peer's protocol.
pub async fn fake_client_capturing_envelopes_with_ack(
    path: &Path,
    ack: HelloAck,
) -> (Client, mpsc::Receiver<Envelope>) {
    let mut listener = bind(path);
    let (tx, rx) = mpsc::channel(SCRIPT_CHANNEL_CAPACITY);
    tokio::spawn(async move {
        let mut frames = accept_handshaked(&mut listener, ack).await;
        loop {
            let envelope = read_envelope(&mut frames).await;
            let id = envelope.id;
            // Forwarded before the reply is sent, so an awaited
            // `Client::request` future finds its envelope already queued.
            if tx.send(envelope).await.is_err() {
                break;
            }
            write_reply(&mut frames, id, Response::Pong).await;
        }
    });
    let client = Client::connect(path).await.unwrap();
    (client, rx)
}

/// Binds `path`, handshakes with [`sample_ack`], and answers the one
/// request that arrives with an [`RpcError`] carrying `code` and `message`.
///
/// Backed by a [`FakeDaemon`] so the connection keeps serving afterward,
/// unlike a bespoke one-shot task that would die after the scripted reply.
pub async fn fake_client_replying_err(
    path: &Path,
    code: RpcErrorCode,
    message: &str,
) -> (Client, FakeDaemon) {
    let (client, daemon) = fake_client_on(path).await;
    daemon
        .script
        .send(ScriptCommand::ReplyErr(code, message.to_string()))
        .await
        .unwrap();
    (client, daemon)
}

/// Binds `path`, handshakes with [`sample_ack`], reads exactly two
/// envelopes, then answers the `ListFlock` one first and the `Ping` one
/// second, regardless of arrival order: proof that a `Client` routes
/// replies by id.
///
/// Backed by a [`FakeDaemon`], like [`fake_client_replying_err`].
pub async fn fake_client_out_of_order(path: &Path) -> (Client, FakeDaemon) {
    let (client, daemon) = fake_client_on(path).await;
    daemon
        .script
        .send(ScriptCommand::ArmOutOfOrder)
        .await
        .unwrap();
    (client, daemon)
}

/// Binds `path`, handshakes with [`sample_ack`], reads one envelope, and
/// sends a `BusEvent::Process` event before answering it: a sheep's bus
/// event can legitimately arrive ahead of the reply for the request that
/// caused it.
///
/// Backed by a [`FakeDaemon`], like [`fake_client_replying_err`].
pub async fn fake_client_event_then_reply(path: &Path) -> (Client, FakeDaemon) {
    let (client, daemon) = fake_client_on(path).await;
    daemon
        .script
        .send(ScriptCommand::EventThenReply)
        .await
        .unwrap();
    (client, daemon)
}

/// Binds `path`, handshakes with [`sample_ack`], then immediately drops the
/// connection, for testing that a `Client` fails every pending request with
/// `RequestError::Closed` rather than hanging.
pub async fn fake_client_that_closes_after_handshake(path: &Path) -> (Client, JoinHandle<()>) {
    let mut listener = bind(path);
    let task = tokio::spawn(async move {
        let _frames = accept_handshaked(&mut listener, sample_ack()).await;
        // Dropping `_frames` here closes the connection from this side.
    });
    let client = Client::connect(path).await.unwrap();
    (client, task)
}

/// Binds `path`, handshakes with [`sample_ack`], reads exactly one
/// envelope, then drops the connection without replying: for testing that
/// a request already accepted into the connection actor's `pending` map
/// fails with `RequestError::Closed` when the connection dies mid-flight.
/// Unlike [`fake_client_that_closes_after_handshake`], which never accepts
/// the request at all.
pub async fn fake_client_that_dies_mid_request(path: &Path) -> (Client, JoinHandle<()>) {
    let mut listener = bind(path);
    let task = tokio::spawn(async move {
        let mut frames = accept_handshaked(&mut listener, sample_ack()).await;
        let _envelope = read_envelope(&mut frames).await;
        // Dropping `frames` here, after reading, closes the connection
        // only once the actor has recorded the request as pending.
    });
    let client = Client::connect(path).await.unwrap();
    (client, task)
}

/// Binds `path`, handshakes with [`sample_ack`], then reads nothing and
/// replies to nothing, ever: for testing a `Client`'s own deadline against
/// a daemon that accepted the connection but stopped answering.
///
/// Returns `(Client, JoinHandle<()>)`, not `(Client, FakeDaemon)`:
/// `FakeDaemon`'s loop always answers some request promptly, and no
/// `ScriptCommand` means never answering.
pub async fn fake_client_that_never_replies(path: &Path) -> (Client, JoinHandle<()>) {
    let mut listener = bind(path);
    let task = tokio::spawn(async move {
        let _frames = accept_handshaked(&mut listener, sample_ack()).await;
        core::future::pending::<()>().await;
    });
    let client = Client::connect(path).await.unwrap();
    (client, task)
}

/// Binds `path`, handshakes with [`sample_ack`], and answers each request
/// with `response`. A request whose deadline is shorter than `needs` gets
/// `DeadlineExceeded`, as a real daemon answers it.
///
/// Decided from the envelope alone, with no sleep: a paused test clock
/// auto-advances past a real socket read, so a fake that waited out `needs`
/// would race the client's own timeout.
pub async fn fake_client_needing_budget(
    path: &Path,
    needs: Duration,
    response: Response,
) -> (Client, JoinHandle<()>) {
    let mut listener = bind(path);
    let task = tokio::spawn(async move {
        let mut frames = accept_handshaked(&mut listener, sample_ack()).await;
        loop {
            let envelope = read_envelope(&mut frames).await;
            let budget = Duration::from_millis(envelope.deadline_ms.unwrap_or(u64::MAX));
            if budget < needs {
                let message = format!("request deadline of {} ms expired", budget.as_millis());
                write_err(
                    &mut frames,
                    envelope.id,
                    RpcErrorCode::DeadlineExceeded,
                    message,
                )
                .await;
            } else {
                write_reply(&mut frames, envelope.id, response.clone()).await;
            }
        }
    });
    let client = Client::connect(path).await.unwrap();
    (client, task)
}