@mark1russell7/harness 0.16.18 → 0.16.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -5,35 +5,86 @@
5
5
  //! schedule of the format rigor-schedule/1 and a list of requests. Arrival i of a stream sends request i modulo
6
6
  //! the length of the list. Each request is the whole text of an HTTP/1.1 request.
7
7
  //!
8
- //! Each stream has its own connection, thus a slow reply delays only the arrivals of its own stream.
8
+ //! Each stream has its own connections, thus a slow reply delays only the arrivals of its own stream.
9
9
  //! One shared connection gives each request the queue of all the requests before it. Then a heavy
10
10
  //! stream moves each other stream, and the noise of one tenant on the others cannot be measured.
11
11
  //!
12
- //! The driver opens each connection and writes ready. Then it waits for the file --go. Then it
13
- //! sends each arrival at its time, and a send does not wait for a reply (coordinated omission).
14
- //! The requests of a stream share its connection, and the replies come in their order. The lines
15
- //! sent and replied name the stream (k) and the arrival (i), and a replied line names the status.
16
- //! It ends with a done line when each connection has each reply or has ended. An error, an end or
17
- //! the deadline leaves the rest without a reply.
12
+ //! The field connections of a stream sets how its arrivals go to the server:
13
+ //! - {"mode":"pipeline"} is the default. The stream has one connection. Each arrival goes at its
14
+ //! time, also when the replies before it are not in (HTTP/1.1 pipelining). The replies come in
15
+ //! the order of the requests.
16
+ //! - {"mode":"pool","size":n}: the stream keeps n connections, each with one request in flight at
17
+ //! most. A due arrival takes the connection that is idle for the longest time. With no idle
18
+ //! connection, it waits in the queue of its stream, in the order of the schedule. A connection
19
+ //! that ends leaves the pool, and the driver does not open it again.
20
+ //! - {"mode":"fresh"}: each arrival gets a new connection. The connect starts at the planned time
21
+ //! and does not block the other streams. The request goes when the connect is done, and the
22
+ //! driver closes the connection after the reply. A failed connect is an error of that arrival only.
23
+ //!
24
+ //! A fresh stream leaves each closed connection in TIME_WAIT on the client, thus a high rate can use
25
+ //! all the local ports. A pool needs a keep-alive time of the server above the idle time of each
26
+ //! connection, else the server closes connections and the pool gets smaller.
27
+ //!
28
+ //! The driver opens each connection of each pipeline and each pool, and writes ready. Then it waits
29
+ //! for the file --go. Then it sends each arrival at its time, and a send does not wait for a reply
30
+ //! (coordinated omission). The lines sent and replied name the stream (k) and the arrival (i), and a
31
+ //! replied line names the status. In a pool and in a fresh stream, the replies can come out of
32
+ //! order: each replied line names the arrival of its own connection. There, a sent line also gives
33
+ //! the time that the arrival waited for its connection, in ns (wait): for an idle connection of the
34
+ //! pool, or for the connect. That wait is not a lag of the driver. It ends with a done line when each
35
+ //! stream has each reply or can send no more. An error, an end or the deadline leaves the rest
36
+ //! without a reply.
18
37
 
19
38
  use harness_native::{arrivals_in, emit, emit_at};
20
39
  use prober::{errno_name, monotonic_ns};
21
40
  use serde_json::{json, Value};
41
+ use std::collections::VecDeque;
22
42
  use std::error::Error;
23
43
  use std::io::{ErrorKind, Read, Write};
24
- use std::net::TcpStream;
25
- use std::os::fd::AsRawFd;
44
+ use std::net::{SocketAddr, TcpStream, ToSocketAddrs};
45
+ use std::os::fd::{AsRawFd, FromRawFd};
26
46
  use std::path::Path;
27
47
  use std::time::Duration;
28
48
 
29
49
  /// The longest head of a response that the driver reads: more is an error of the server.
30
50
  const HEAD_LIMIT: usize = 65_536;
31
51
 
32
- /// One stream of a plan: its key, its arrivals in ns from the start, and its requests.
52
+ /// The most connections of the pool of one stream.
53
+ const POOL_LIMIT: u64 = 1024;
54
+
55
+ /// How a stream sends its arrivals to the server.
56
+ #[derive(Clone, Copy, Debug, PartialEq, Eq)]
57
+ enum Mode {
58
+ /// one connection, and each arrival goes at its time while the replies before it are not in
59
+ Pipeline,
60
+ /// this count of kept connections, each with one request in flight at most
61
+ Pool(usize),
62
+ /// a new connection for each arrival, closed after its reply
63
+ Fresh,
64
+ }
65
+
66
+ /// One stream of a plan: its key, its arrivals in ns from the start, its requests and its mode.
33
67
  struct Stream {
34
68
  key: String,
35
69
  times: Vec<u64>,
36
70
  requests: Vec<Vec<u8>>,
71
+ mode: Mode,
72
+ }
73
+
74
+ /// The mode of the field connections of the stream `key`. A stream with no such field is a pipeline.
75
+ fn mode_of(key: &str, connections: &Value) -> Result<Mode, String> {
76
+ if connections.is_null() {
77
+ return Ok(Mode::Pipeline);
78
+ }
79
+ match connections["mode"].as_str() {
80
+ Some("pipeline") => Ok(Mode::Pipeline),
81
+ Some("fresh") => Ok(Mode::Fresh),
82
+ Some("pool") => match connections["size"].as_u64() {
83
+ Some(size) if (1..=POOL_LIMIT).contains(&size) => Ok(Mode::Pool(size as usize)),
84
+ _ => Err(format!("the pool of the stream {key} has the size {}: a whole number from 1 to {POOL_LIMIT}", connections["size"])),
85
+ },
86
+ _ => Err(format!("the stream {key} has the connections {connections}: the mode is pipeline, pool or fresh")),
87
+ }
37
88
  }
38
89
 
39
90
  /// The streams of a file of the format systems-load/1.
@@ -64,7 +115,8 @@ fn plan_of(text: &str) -> Result<Vec<Stream>, Box<dyn Error>> {
64
115
  if requests.is_empty() {
65
116
  return Err(format!("the stream {key} has no request").into());
66
117
  }
67
- Ok(Stream { key, times, requests })
118
+ let mode = mode_of(&key, &stream["connections"])?;
119
+ Ok(Stream { key, times, requests, mode })
68
120
  })
69
121
  .collect()
70
122
  }
@@ -143,7 +195,15 @@ fn response_length(bytes: &[u8]) -> Result<Option<(usize, u16)>, String> {
143
195
  }
144
196
  }
145
197
 
146
- /// One stream on its connection, and where it is in its schedule.
198
+ /// The sink of the lines of the driver: the event, its stamp on CLOCK_MONOTONIC, and its fields.
199
+ type Out<'a> = &'a mut dyn FnMut(&str, u64, Value);
200
+
201
+ /// The name of the errno of an error, or of 0 for an error with no errno.
202
+ fn errno_of(error: &std::io::Error) -> String {
203
+ errno_name(error.raw_os_error().unwrap_or(0))
204
+ }
205
+
206
+ /// One stream on its connection in the mode pipeline, and where it is in its schedule.
147
207
  struct Connection {
148
208
  stream: Stream,
149
209
  socket: TcpStream,
@@ -159,8 +219,8 @@ struct Connection {
159
219
  }
160
220
 
161
221
  impl Connection {
162
- fn open(host: &str, port: u16, stream: Stream) -> std::io::Result<Self> {
163
- let socket = TcpStream::connect((host, port))?;
222
+ fn open(address: SocketAddr, stream: Stream) -> std::io::Result<Self> {
223
+ let socket = TcpStream::connect(address)?;
164
224
  socket.set_nodelay(true)?;
165
225
  socket.set_nonblocking(true)?;
166
226
  Ok(Self { stream, socket, next: 0, written: 0, answered: 0, blocked: false, open: true, buffer: Vec::new() })
@@ -170,13 +230,13 @@ impl Connection {
170
230
  !self.open || self.answered == self.stream.times.len()
171
231
  }
172
232
 
173
- fn fail(&mut self, out: &mut dyn FnMut(&str, u64, Value), error: &std::io::Error) {
174
- out("error", monotonic_ns(), json!({ "k": self.stream.key, "errno": errno_name(error.raw_os_error().unwrap_or(0)) }));
233
+ fn fail(&mut self, out: Out<'_>, error: &std::io::Error) {
234
+ out("error", monotonic_ns(), json!({ "k": self.stream.key, "errno": errno_of(error) }));
175
235
  self.open = false;
176
236
  }
177
237
 
178
238
  /// Writes each arrival that is due at `start`, until the socket takes no more.
179
- fn send_due(&mut self, start: u64, out: &mut dyn FnMut(&str, u64, Value)) {
239
+ fn send_due(&mut self, start: u64, out: Out<'_>) {
180
240
  while self.open && !self.blocked && self.next < self.stream.times.len() && monotonic_ns() >= start + self.stream.times[self.next] {
181
241
  let request = &self.stream.requests[self.next % self.stream.requests.len()];
182
242
  let t = monotonic_ns();
@@ -192,7 +252,7 @@ impl Connection {
192
252
  Err(error) if error.kind() == ErrorKind::WouldBlock => self.blocked = true,
193
253
  Err(error) if error.kind() == ErrorKind::Interrupted => {}
194
254
  Err(error) => {
195
- out("error", monotonic_ns(), json!({ "k": self.stream.key, "errno": errno_name(error.raw_os_error().unwrap_or(0)) }));
255
+ out("error", monotonic_ns(), json!({ "k": self.stream.key, "errno": errno_of(&error) }));
196
256
  self.open = false;
197
257
  }
198
258
  }
@@ -200,7 +260,7 @@ impl Connection {
200
260
  }
201
261
 
202
262
  /// Reads what the socket holds, and gives a replied line for each whole response.
203
- fn receive(&mut self, buf: &mut [u8], out: &mut dyn FnMut(&str, u64, Value)) {
263
+ fn receive(&mut self, buf: &mut [u8], out: Out<'_>) {
204
264
  while self.open {
205
265
  match self.socket.read(buf) {
206
266
  Ok(0) => {
@@ -219,7 +279,7 @@ impl Connection {
219
279
  }
220
280
  }
221
281
 
222
- fn take_responses(&mut self, t: u64, out: &mut dyn FnMut(&str, u64, Value)) {
282
+ fn take_responses(&mut self, t: u64, out: Out<'_>) {
223
283
  loop {
224
284
  match response_length(&self.buffer) {
225
285
  Ok(None) => return,
@@ -236,39 +296,420 @@ impl Connection {
236
296
  }
237
297
  }
238
298
  }
299
+
300
+ /// The entry of ppoll() for this connection. A negative fd is skipped by ppoll(), and its revents stay 0.
301
+ fn poll(&self) -> libc::pollfd {
302
+ let writing = if self.blocked { libc::POLLOUT } else { 0 };
303
+ let fd = if self.open { self.socket.as_raw_fd() } else { -1 };
304
+ libc::pollfd { fd, events: libc::POLLIN | libc::POLLRDHUP | writing, revents: 0 }
305
+ }
306
+
307
+ fn handle(&mut self, events: i16, buf: &mut [u8], out: Out<'_>) {
308
+ if events & libc::POLLOUT != 0 {
309
+ self.blocked = false;
310
+ }
311
+ if events & !libc::POLLOUT != 0 {
312
+ self.receive(buf, out);
313
+ }
314
+ }
239
315
  }
240
316
 
241
- /// Waits up to `ns` for the open connections. A wait in ms is too coarse for a schedule, thus this
242
- /// one is ppoll(). It gives the revents of each connection, 0 for one that is not open.
243
- fn wait_for(connections: &[Connection], ns: u64) -> std::io::Result<Vec<i16>> {
244
- let mut polled: Vec<libc::pollfd> = connections
245
- .iter()
246
- .map(|connection| {
247
- let writing = if connection.blocked { libc::POLLOUT } else { 0 };
248
- // a negative fd is skipped by ppoll(), and its revents stay 0
249
- let fd = if connection.open { connection.socket.as_raw_fd() } else { -1 };
250
- libc::pollfd { fd, events: libc::POLLIN | libc::POLLRDHUP | writing, revents: 0 }
251
- })
252
- .collect();
317
+ /// The one arrival that a connection of a pool or of a fresh stream carries.
318
+ #[derive(Clone, Copy, Debug)]
319
+ struct Flight {
320
+ i: usize,
321
+ /// the bytes of the request already written
322
+ written: usize,
323
+ /// the time that the arrival waited for its connection, in ns: for an idle connection, or for the connect
324
+ wait: u64,
325
+ /// the request is all written
326
+ sent: bool,
327
+ }
328
+
329
+ /// One connection of a pool or of a fresh stream.
330
+ struct Link {
331
+ socket: TcpStream,
332
+ /// the number of the connection in its stream, from 0
333
+ c: usize,
334
+ /// the start of a connect that is not done yet
335
+ connecting: Option<u64>,
336
+ flight: Option<Flight>,
337
+ /// the socket took no more bytes: the next write waits for POLLOUT
338
+ blocked: bool,
339
+ open: bool,
340
+ /// the connection stays open after a reply (a pool), or closes (a fresh stream)
341
+ keep: bool,
342
+ /// the time from which the connection has no request in flight
343
+ idle_since: u64,
344
+ /// the bytes received and not yet a whole response
345
+ buffer: Vec<u8>,
346
+ }
347
+
348
+ impl Link {
349
+ fn idle(&self) -> bool {
350
+ self.open && self.connecting.is_none() && self.flight.is_none()
351
+ }
352
+
353
+ /// The fields of a line about this connection: the stream, the connection and its arrival, if any.
354
+ fn fields(&self, stream: &Stream) -> Value {
355
+ let mut fields = json!({ "k": stream.key, "c": self.c });
356
+ if let Some(flight) = self.flight {
357
+ fields["i"] = json!(flight.i);
358
+ }
359
+ fields
360
+ }
361
+
362
+ fn end(&mut self, stream: &Stream, event: &str, t: u64, extra: Value, out: Out<'_>) {
363
+ let mut fields = self.fields(stream);
364
+ if let (Some(fields), Value::Object(extra)) = (fields.as_object_mut(), extra) {
365
+ fields.extend(extra);
366
+ }
367
+ out(event, t, fields);
368
+ self.open = false;
369
+ }
370
+
371
+ fn fail(&mut self, stream: &Stream, out: Out<'_>, error: &std::io::Error) {
372
+ self.end(stream, "error", monotonic_ns(), json!({ "errno": errno_of(error) }), out);
373
+ }
374
+
375
+ /// Writes the request of the flight until it is all written or the socket takes no more. It gives
376
+ /// true when the request becomes all written.
377
+ fn write(&mut self, stream: &Stream, out: Out<'_>) -> bool {
378
+ while self.open && !self.blocked && self.connecting.is_none() {
379
+ let Some(flight) = self.flight else { return false };
380
+ if flight.sent {
381
+ return false;
382
+ }
383
+ let request = &stream.requests[flight.i % stream.requests.len()];
384
+ let t = monotonic_ns();
385
+ match self.socket.write(&request[flight.written..]) {
386
+ Ok(n) => {
387
+ let written = flight.written + n;
388
+ let sent = written == request.len();
389
+ self.flight = Some(Flight { written, sent, ..flight });
390
+ if sent {
391
+ out("sent", t, json!({ "k": stream.key, "i": flight.i, "wait": flight.wait }));
392
+ return true;
393
+ }
394
+ }
395
+ Err(error) if error.kind() == ErrorKind::WouldBlock => self.blocked = true,
396
+ Err(error) if error.kind() == ErrorKind::Interrupted => {}
397
+ Err(error) => self.fail(stream, out, &error),
398
+ }
399
+ }
400
+ false
401
+ }
402
+
403
+ /// Reads what the socket holds, and gives a replied line for the response of the flight.
404
+ fn receive(&mut self, stream: &Stream, buf: &mut [u8], out: Out<'_>) {
405
+ while self.open {
406
+ match self.socket.read(buf) {
407
+ Ok(0) => self.end(stream, "eof", monotonic_ns(), json!({}), out),
408
+ Ok(n) => {
409
+ let t = monotonic_ns();
410
+ self.buffer.extend_from_slice(&buf[..n]);
411
+ self.take_response(stream, t, out);
412
+ }
413
+ Err(error) if error.kind() == ErrorKind::WouldBlock => return,
414
+ Err(error) if error.kind() == ErrorKind::Interrupted => {}
415
+ Err(error) => self.fail(stream, out, &error),
416
+ }
417
+ }
418
+ }
419
+
420
+ fn take_response(&mut self, stream: &Stream, t: u64, out: Out<'_>) {
421
+ while self.open {
422
+ match response_length(&self.buffer) {
423
+ Ok(None) => return,
424
+ Ok(Some((length, status))) => match self.flight {
425
+ Some(flight) if flight.sent => {
426
+ self.buffer.drain(..length);
427
+ out("replied", t, json!({ "k": stream.key, "i": flight.i, "status": status }));
428
+ self.flight = None;
429
+ self.idle_since = t;
430
+ // a fresh stream closes its connection after the reply
431
+ self.open = self.keep;
432
+ }
433
+ _ => self.end(stream, "error", t, json!({ "why": "a response with no whole request before it" }), out),
434
+ },
435
+ Err(why) => self.end(stream, "error", t, json!({ "why": why }), out),
436
+ }
437
+ }
438
+ }
439
+
440
+ /// The entry of ppoll() for this connection: a connect waits for POLLOUT only.
441
+ fn poll(&self) -> libc::pollfd {
442
+ let fd = if self.open { self.socket.as_raw_fd() } else { -1 };
443
+ let events = if self.connecting.is_some() {
444
+ libc::POLLOUT
445
+ } else {
446
+ libc::POLLIN | libc::POLLRDHUP | if self.blocked { libc::POLLOUT } else { 0 }
447
+ };
448
+ libc::pollfd { fd, events, revents: 0 }
449
+ }
450
+
451
+ fn handle(&mut self, stream: &Stream, events: i16, buf: &mut [u8], out: Out<'_>) {
452
+ if !self.open || events == 0 {
453
+ return;
454
+ }
455
+ if let Some(begun) = self.connecting {
456
+ // the connect is over: SO_ERROR tells if it failed
457
+ match self.socket.take_error() {
458
+ Ok(None) => {
459
+ let now = monotonic_ns();
460
+ self.connecting = None;
461
+ self.idle_since = now;
462
+ if let Some(flight) = self.flight.as_mut() {
463
+ flight.wait = now.saturating_sub(begun);
464
+ }
465
+ }
466
+ Ok(Some(error)) | Err(error) => self.fail(stream, out, &error),
467
+ }
468
+ return;
469
+ }
470
+ if events & libc::POLLOUT != 0 {
471
+ self.blocked = false;
472
+ }
473
+ if events & !libc::POLLOUT != 0 {
474
+ self.receive(stream, buf, out);
475
+ }
476
+ }
477
+ }
478
+
479
+ /// The address `address` as a sockaddr for connect(), with its length.
480
+ fn sockaddr_of(address: &SocketAddr) -> (libc::sockaddr_storage, libc::socklen_t) {
481
+ // SAFETY: a sockaddr_storage of zero bytes is a valid value
482
+ let mut storage: libc::sockaddr_storage = unsafe { std::mem::zeroed() };
483
+ match address {
484
+ SocketAddr::V4(v4) => {
485
+ // SAFETY: a sockaddr_storage is large enough for a sockaddr_in, and aligned for it
486
+ let sin = unsafe { &mut *(&mut storage as *mut libc::sockaddr_storage).cast::<libc::sockaddr_in>() };
487
+ sin.sin_family = libc::AF_INET as libc::sa_family_t;
488
+ sin.sin_port = v4.port().to_be();
489
+ // the octets are in the order of the network, and s_addr holds them in that order
490
+ sin.sin_addr.s_addr = u32::from_ne_bytes(v4.ip().octets());
491
+ (storage, std::mem::size_of::<libc::sockaddr_in>() as libc::socklen_t)
492
+ }
493
+ SocketAddr::V6(v6) => {
494
+ // SAFETY: a sockaddr_storage is large enough for a sockaddr_in6, and aligned for it
495
+ let sin6 = unsafe { &mut *(&mut storage as *mut libc::sockaddr_storage).cast::<libc::sockaddr_in6>() };
496
+ sin6.sin6_family = libc::AF_INET6 as libc::sa_family_t;
497
+ sin6.sin6_port = v6.port().to_be();
498
+ sin6.sin6_flowinfo = v6.flowinfo();
499
+ sin6.sin6_addr.s6_addr = v6.ip().octets();
500
+ sin6.sin6_scope_id = v6.scope_id();
501
+ (storage, std::mem::size_of::<libc::sockaddr_in6>() as libc::socklen_t)
502
+ }
503
+ }
504
+ }
505
+
506
+ /// Starts a connect to `address` that does not block. It gives the socket, and true when the connect
507
+ /// is already done. Else the socket gives POLLOUT when the connect is over, and SO_ERROR tells if it failed.
508
+ fn connect_start(address: &SocketAddr) -> std::io::Result<(TcpStream, bool)> {
509
+ let family = if address.is_ipv4() { libc::AF_INET } else { libc::AF_INET6 };
510
+ // SAFETY: socket() takes no pointer
511
+ let fd = unsafe { libc::socket(family, libc::SOCK_STREAM | libc::SOCK_NONBLOCK | libc::SOCK_CLOEXEC, 0) };
512
+ if fd < 0 {
513
+ return Err(std::io::Error::last_os_error());
514
+ }
515
+ // SAFETY: the fd is new and open, and the TcpStream owns it from here: it closes it on each path
516
+ let socket = unsafe { TcpStream::from_raw_fd(fd) };
517
+ socket.set_nodelay(true)?;
518
+ let (storage, length) = sockaddr_of(address);
519
+ // SAFETY: the storage lives on this frame, and `length` is the size of the address in it
520
+ let code = unsafe { libc::connect(fd, (&storage as *const libc::sockaddr_storage).cast::<libc::sockaddr>(), length) };
521
+ if code == 0 {
522
+ return Ok((socket, true));
523
+ }
524
+ let error = std::io::Error::last_os_error();
525
+ if error.raw_os_error() == Some(libc::EINPROGRESS) {
526
+ Ok((socket, false))
527
+ } else {
528
+ Err(error)
529
+ }
530
+ }
531
+
532
+ /// One stream in the mode pool or fresh: its connections, and where it is in its schedule.
533
+ struct Pool {
534
+ stream: Stream,
535
+ address: SocketAddr,
536
+ links: Vec<Link>,
537
+ /// the due arrivals of a pool that wait for an idle connection, in the order of the schedule
538
+ queue: VecDeque<usize>,
539
+ /// the next arrival that is not yet due
540
+ next: usize,
541
+ /// the arrivals with their request all written
542
+ sent: usize,
543
+ /// the connections opened so far: the number of the next one
544
+ opened: usize,
545
+ }
546
+
547
+ impl Pool {
548
+ /// Opens each connection of a pool, or none for a fresh stream.
549
+ fn open(address: SocketAddr, stream: Stream) -> std::io::Result<Self> {
550
+ let size = if let Mode::Pool(size) = stream.mode { size } else { 0 };
551
+ let mut links = Vec::with_capacity(size);
552
+ for c in 0..size {
553
+ let socket = TcpStream::connect(address)?;
554
+ socket.set_nodelay(true)?;
555
+ socket.set_nonblocking(true)?;
556
+ links.push(Link { socket, c, connecting: None, flight: None, blocked: false, open: true, keep: true, idle_since: monotonic_ns(), buffer: Vec::new() });
557
+ }
558
+ Ok(Self { stream, address, links, queue: VecDeque::new(), next: 0, sent: 0, opened: size })
559
+ }
560
+
561
+ /// Tells if the stream can do no more: each arrival is due and over, or each connection of the pool ended.
562
+ fn finished(&self) -> bool {
563
+ let over = self.next == self.stream.times.len() && self.queue.is_empty() && self.links.iter().all(|link| link.flight.is_none());
564
+ over || (matches!(self.stream.mode, Mode::Pool(_)) && self.links.is_empty())
565
+ }
566
+
567
+ /// Starts a connect for the arrival `i` of a fresh stream. A failed connect is an error of that arrival only.
568
+ fn connect(&mut self, i: usize, out: Out<'_>) {
569
+ let begun = monotonic_ns();
570
+ match connect_start(&self.address) {
571
+ Ok((socket, done)) => {
572
+ let now = monotonic_ns();
573
+ let flight = Flight { i, written: 0, wait: if done { now.saturating_sub(begun) } else { 0 }, sent: false };
574
+ let connecting = if done { None } else { Some(begun) };
575
+ self.links.push(Link { socket, c: self.opened, connecting, flight: Some(flight), blocked: false, open: true, keep: false, idle_since: now, buffer: Vec::new() });
576
+ self.opened += 1;
577
+ }
578
+ Err(error) => out("error", monotonic_ns(), json!({ "k": self.stream.key, "i": i, "errno": errno_of(&error) })),
579
+ }
580
+ }
581
+
582
+ /// Takes each arrival that is due at `start`, gives it a connection, and writes each request that can go.
583
+ fn send_due(&mut self, start: u64, out: Out<'_>) {
584
+ let now = monotonic_ns();
585
+ while self.next < self.stream.times.len() && now >= start + self.stream.times[self.next] {
586
+ let i = self.next;
587
+ self.next += 1;
588
+ match self.stream.mode {
589
+ Mode::Fresh => self.connect(i, out),
590
+ _ => self.queue.push_back(i),
591
+ }
592
+ }
593
+ // each queued arrival takes the connection that is idle for the longest time
594
+ while let Some(&i) = self.queue.front() {
595
+ let idle = self.links.iter().enumerate().filter(|(_, link)| link.idle()).min_by_key(|(_, link)| link.idle_since).map(|(at, _)| at);
596
+ let Some(at) = idle else { break };
597
+ self.queue.pop_front();
598
+ let due = start + self.stream.times[i];
599
+ let link = &mut self.links[at];
600
+ link.flight = Some(Flight { i, written: 0, wait: link.idle_since.saturating_sub(due), sent: false });
601
+ }
602
+ for link in self.links.iter_mut() {
603
+ if link.write(&self.stream, out) {
604
+ self.sent += 1;
605
+ }
606
+ }
607
+ self.links.retain(|link| link.open);
608
+ }
609
+
610
+ fn handle(&mut self, polled: &[libc::pollfd], buf: &mut [u8], out: Out<'_>) {
611
+ for (link, entry) in self.links.iter_mut().zip(polled) {
612
+ link.handle(&self.stream, entry.revents, buf, out);
613
+ }
614
+ self.links.retain(|link| link.open);
615
+ }
616
+ }
617
+
618
+ /// One stream of the driver, in its mode.
619
+ enum Flow {
620
+ Pipeline(Connection),
621
+ Pool(Pool),
622
+ }
623
+
624
+ impl Flow {
625
+ fn stream(&self) -> &Stream {
626
+ match self {
627
+ Flow::Pipeline(connection) => &connection.stream,
628
+ Flow::Pool(pool) => &pool.stream,
629
+ }
630
+ }
631
+
632
+ fn send_due(&mut self, start: u64, out: Out<'_>) {
633
+ match self {
634
+ Flow::Pipeline(connection) => connection.send_due(start, out),
635
+ Flow::Pool(pool) => pool.send_due(start, out),
636
+ }
637
+ }
638
+
639
+ fn finished(&self) -> bool {
640
+ match self {
641
+ Flow::Pipeline(connection) => connection.finished(),
642
+ Flow::Pool(pool) => pool.finished(),
643
+ }
644
+ }
645
+
646
+ /// The count of arrivals with their request all written.
647
+ fn sent(&self) -> usize {
648
+ match self {
649
+ Flow::Pipeline(connection) => connection.next,
650
+ Flow::Pool(pool) => pool.sent,
651
+ }
652
+ }
653
+
654
+ /// The time of the next arrival that the stream can send, in ns from the start.
655
+ fn due(&self) -> Option<u64> {
656
+ match self {
657
+ Flow::Pipeline(connection) if connection.open && !connection.blocked => connection.stream.times.get(connection.next).copied(),
658
+ Flow::Pipeline(_) => None,
659
+ Flow::Pool(pool) => pool.stream.times.get(pool.next).copied(),
660
+ }
661
+ }
662
+
663
+ /// Adds the entries of ppoll() for the connections of this stream.
664
+ fn polls(&self, polled: &mut Vec<libc::pollfd>) {
665
+ match self {
666
+ Flow::Pipeline(connection) => polled.push(connection.poll()),
667
+ Flow::Pool(pool) => polled.extend(pool.links.iter().map(Link::poll)),
668
+ }
669
+ }
670
+
671
+ /// Reads the revents of the entries that `polls` added, in the same order.
672
+ fn handle(&mut self, polled: &[libc::pollfd], buf: &mut [u8], out: Out<'_>) {
673
+ match self {
674
+ Flow::Pipeline(connection) => {
675
+ if let Some(entry) = polled.first() {
676
+ connection.handle(entry.revents, buf, out);
677
+ }
678
+ }
679
+ Flow::Pool(pool) => pool.handle(polled, buf, out),
680
+ }
681
+ }
682
+ }
683
+
684
+ /// Waits up to `ns` for the connections of `polled`, and sets their revents. A wait in ms is too
685
+ /// coarse for a schedule, thus this one is ppoll(). With no entry, it is a sleep.
686
+ fn wait_for(polled: &mut [libc::pollfd], ns: u64) -> std::io::Result<()> {
253
687
  let time = libc::timespec { tv_sec: (ns / 1_000_000_000) as libc::time_t, tv_nsec: (ns % 1_000_000_000) as libc::c_long };
254
- // SAFETY: the pollfds and the timespec live on this frame, with their exact count, and no signal mask
255
- match unsafe { libc::ppoll(polled.as_mut_ptr(), polled.len() as libc::nfds_t, &time, std::ptr::null()) } {
256
- -1 if std::io::Error::last_os_error().kind() == ErrorKind::Interrupted => Ok(vec![0; connections.len()]),
257
- -1 => Err(std::io::Error::last_os_error()),
258
- _ => Ok(polled.iter().map(|entry| entry.revents).collect()),
688
+ // SAFETY: the pollfds and the timespec live past the call, with their exact count, and no signal mask
689
+ if unsafe { libc::ppoll(polled.as_mut_ptr(), polled.len() as libc::nfds_t, &time, std::ptr::null()) } == -1 {
690
+ let error = std::io::Error::last_os_error();
691
+ if error.kind() != ErrorKind::Interrupted {
692
+ return Err(error);
693
+ }
694
+ for entry in polled.iter_mut() {
695
+ entry.revents = 0;
696
+ }
259
697
  }
698
+ Ok(())
260
699
  }
261
700
 
262
- /// Runs the schedule of each connection from `start`, until each connection is finished or the
263
- /// deadline passes. A wait is at most `tick` ns.
264
- fn drive(connections: &mut [Connection], start: u64, deadline: u64, tick: u64, out: &mut dyn FnMut(&str, u64, Value)) -> Result<(), Box<dyn Error>> {
701
+ /// Runs the schedule of each stream from `start`, until each stream is finished or the deadline
702
+ /// passes. A wait is at most `tick` ns.
703
+ fn drive(flows: &mut [Flow], start: u64, deadline: u64, tick: u64, out: Out<'_>) -> Result<(), Box<dyn Error>> {
265
704
  let mut buf = vec![0u8; 65_536];
705
+ let mut polled: Vec<libc::pollfd> = Vec::new();
706
+ let mut counts: Vec<usize> = Vec::with_capacity(flows.len());
266
707
  loop {
267
- for connection in connections.iter_mut() {
268
- connection.send_due(start, out);
708
+ for flow in flows.iter_mut() {
709
+ flow.send_due(start, out);
269
710
  }
270
- if connections.iter().all(Connection::finished) {
271
- let requests: usize = connections.iter().map(|connection| connection.next).sum();
711
+ if flows.iter().all(Flow::finished) {
712
+ let requests: usize = flows.iter().map(Flow::sent).sum();
272
713
  out("done", monotonic_ns(), json!({ "requests": requests }));
273
714
  return Ok(());
274
715
  }
@@ -277,20 +718,19 @@ fn drive(connections: &mut [Connection], start: u64, deadline: u64, tick: u64, o
277
718
  out("deadline", now, json!({}));
278
719
  return Ok(());
279
720
  }
280
- let due = connections
281
- .iter()
282
- .filter(|connection| connection.open && !connection.blocked)
283
- .filter_map(|connection| connection.stream.times.get(connection.next))
284
- .map(|at| (start + at).saturating_sub(now))
285
- .fold(tick, u64::min);
286
- let revents = wait_for(connections, due)?;
287
- for (connection, events) in connections.iter_mut().zip(revents) {
288
- if events & libc::POLLOUT != 0 {
289
- connection.blocked = false;
290
- }
291
- if events & !libc::POLLOUT != 0 {
292
- connection.receive(&mut buf, out);
293
- }
721
+ let due = flows.iter().filter_map(Flow::due).map(|at| (start + at).saturating_sub(now)).fold(tick, u64::min);
722
+ polled.clear();
723
+ counts.clear();
724
+ for flow in flows.iter() {
725
+ let before = polled.len();
726
+ flow.polls(&mut polled);
727
+ counts.push(polled.len() - before);
728
+ }
729
+ wait_for(&mut polled, due)?;
730
+ let mut at = 0;
731
+ for (flow, count) in flows.iter_mut().zip(counts.iter().copied()) {
732
+ flow.handle(&polled[at..at + count], &mut buf, out);
733
+ at += count;
294
734
  }
295
735
  }
296
736
  }
@@ -323,15 +763,24 @@ fn run() -> Result<(), Box<dyn Error>> {
323
763
  let streams = plan_of(&std::fs::read_to_string(&args.plan)?)?;
324
764
  emit("start", json!({ "boot_id": boot_id, "mode": "load", "streams": streams.len() }));
325
765
  let deadline = monotonic_ns() + args.max.as_nanos() as u64;
326
- let mut connections = Vec::with_capacity(streams.len());
766
+ let address = (args.host.as_str(), args.port).to_socket_addrs()?.next().ok_or("the target's host has no address")?;
767
+ let mut flows = Vec::with_capacity(streams.len());
327
768
  for stream in streams {
328
769
  let key = stream.key.clone();
329
- let connection = Connection::open(&args.host, args.port, stream)?;
330
- // the harness finds the socket of a stream in the records of the kernel by this address
331
- emit("connected", json!({ "k": key, "local": connection.socket.local_addr()?.to_string() }));
332
- connections.push(connection);
770
+ // the harness finds the socket of a stream in the records of the kernel by its local address
771
+ if stream.mode == Mode::Pipeline {
772
+ let connection = Connection::open(address, stream)?;
773
+ emit("connected", json!({ "k": key, "local": connection.socket.local_addr()?.to_string() }));
774
+ flows.push(Flow::Pipeline(connection));
775
+ } else {
776
+ let pool = Pool::open(address, stream)?;
777
+ for link in &pool.links {
778
+ emit("connected", json!({ "k": key, "c": link.c, "local": link.socket.local_addr()?.to_string() }));
779
+ }
780
+ flows.push(Flow::Pool(pool));
781
+ }
333
782
  }
334
- emit("ready", json!({ "streams": connections.len() }));
783
+ emit("ready", json!({ "streams": flows.len() }));
335
784
  while !Path::new(&args.go).exists() {
336
785
  if monotonic_ns() > deadline {
337
786
  emit("deadline", json!({}));
@@ -340,9 +789,9 @@ fn run() -> Result<(), Box<dyn Error>> {
340
789
  std::thread::sleep(args.sample);
341
790
  }
342
791
  let start = monotonic_ns();
343
- let arrivals: usize = connections.iter().map(|connection| connection.stream.times.len()).sum();
344
- emit_at("scheduled", start, json!({ "streams": connections.len(), "arrivals": arrivals }));
345
- drive(&mut connections, start, deadline, args.sample.as_nanos() as u64, &mut |event, t, fields| emit_at(event, t, fields))
792
+ let arrivals: usize = flows.iter().map(|flow| flow.stream().times.len()).sum();
793
+ emit_at("scheduled", start, json!({ "streams": flows.len(), "arrivals": arrivals }));
794
+ drive(&mut flows, start, deadline, args.sample.as_nanos() as u64, &mut |event, t, fields| emit_at(event, t, fields))
346
795
  }
347
796
 
348
797
  fn main() {
@@ -411,6 +860,7 @@ mod tests {
411
860
  assert_eq!(streams[0].key, "t0");
412
861
  assert_eq!(streams[0].times, [0, 1_500_000]);
413
862
  assert_eq!(streams[0].requests, [b"A".to_vec(), b"B".to_vec()]);
863
+ assert_eq!(streams[0].mode, Mode::Pipeline);
414
864
  assert!(plan_of(r#"{"format":"other","streams":[]}"#).is_err());
415
865
  assert!(plan_of(r#"{"format":"systems-load/1","streams":[]}"#).is_err());
416
866
  let twice = format!(r#"{{"format":"systems-load/1","streams":[{{"key":"a","schedule":{schedule},"requests":["A"]}},{{"key":"a","schedule":{schedule},"requests":["A"]}}]}}"#);
@@ -419,7 +869,22 @@ mod tests {
419
869
  assert!(plan_of(&none).is_err());
420
870
  }
421
871
 
422
- /// A server that answers each request of each connection with OK, after `delay` for the key `slow`.
872
+ #[test]
873
+ fn a_plan_gives_the_mode_of_each_stream_and_refuses_a_bad_one() {
874
+ let schedule = r#"{"format":"rigor-schedule/1","times":[0]}"#;
875
+ let with = |connections: &str| plan_of(&format!(r#"{{"format":"systems-load/1","streams":[{{"key":"a","schedule":{schedule},"requests":["A"],"connections":{connections}}}]}}"#));
876
+ assert_eq!(with(r#"{"mode":"pipeline"}"#).unwrap()[0].mode, Mode::Pipeline);
877
+ assert_eq!(with(r#"{"mode":"pool","size":8}"#).unwrap()[0].mode, Mode::Pool(8));
878
+ assert_eq!(with(r#"{"mode":"pool","size":1024}"#).unwrap()[0].mode, Mode::Pool(1024));
879
+ assert_eq!(with(r#"{"mode":"fresh"}"#).unwrap()[0].mode, Mode::Fresh);
880
+ assert_eq!(with("null").unwrap()[0].mode, Mode::Pipeline);
881
+ for bad in [r#"{"mode":"pool"}"#, r#"{"mode":"pool","size":0}"#, r#"{"mode":"pool","size":1025}"#, r#"{"mode":"pool","size":1.5}"#, r#"{"mode":"pool","size":-1}"#, r#"{"mode":"other"}"#, r#"{}"#, r#""pool""#] {
882
+ assert!(with(bad).is_err(), "{bad}");
883
+ }
884
+ }
885
+
886
+ /// A server that answers each request of each connection with OK, after `delay` for a request with
887
+ /// the word `slow`. It takes `connections` connections, and answers the requests of one connection in order.
423
888
  fn serve(connections: usize, slow: Duration) -> u16 {
424
889
  let listener = TcpListener::bind("127.0.0.1:0").unwrap();
425
890
  let port = listener.local_addr().unwrap().port();
@@ -449,26 +914,42 @@ mod tests {
449
914
  port
450
915
  }
451
916
 
917
+ fn local(port: u16) -> SocketAddr {
918
+ SocketAddr::from(([127, 0, 0, 1], port))
919
+ }
920
+
921
+ fn request(path: &str) -> Vec<u8> {
922
+ format!("GET /{path} HTTP/1.1\r\nHost: t\r\n\r\n").into_bytes()
923
+ }
924
+
452
925
  fn stream(key: &str, times: &[u64]) -> Stream {
453
- let request = format!("GET /{key} HTTP/1.1\r\nHost: t\r\n\r\n");
454
- Stream { key: key.into(), times: times.to_vec(), requests: vec![request.into_bytes()] }
926
+ Stream { key: key.into(), times: times.to_vec(), requests: vec![request(key)], mode: Mode::Pipeline }
927
+ }
928
+
929
+ const MS: u64 = 1_000_000;
930
+
931
+ /// Runs the flows for at most 10 s, and gives their lines and the start.
932
+ fn lines_of(flows: &mut [Flow]) -> (Vec<(String, u64, Value)>, u64) {
933
+ let mut events: Vec<(String, u64, Value)> = Vec::new();
934
+ let start = monotonic_ns();
935
+ drive(flows, start, start + 10_000 * MS, MS, &mut |event, t, fields| events.push((event.into(), t, fields))).unwrap();
936
+ (events, start)
937
+ }
938
+
939
+ /// The lines `event` of the stream `key`, in their order.
940
+ fn of<'a>(events: &'a [(String, u64, Value)], event: &'a str, key: &'a str) -> impl Iterator<Item = &'a (String, u64, Value)> + 'a {
941
+ events.iter().filter(move |(ev, _, fields)| ev == event && fields["k"] == key)
455
942
  }
456
943
 
457
944
  #[test]
458
945
  fn each_stream_gets_each_reply_and_a_slow_stream_delays_only_itself() {
459
946
  let port = serve(2, Duration::from_millis(200));
460
- let ms = 1_000_000;
461
- let mut connections = vec![
462
- Connection::open("127.0.0.1", port, stream("slow", &[0, ms, 2 * ms])).unwrap(),
463
- Connection::open("127.0.0.1", port, stream("fast", &[0, ms, 2 * ms])).unwrap(),
947
+ let mut flows = vec![
948
+ Flow::Pipeline(Connection::open(local(port), stream("slow", &[0, MS, 2 * MS])).unwrap()),
949
+ Flow::Pipeline(Connection::open(local(port), stream("fast", &[0, MS, 2 * MS])).unwrap()),
464
950
  ];
465
- let mut events: Vec<(String, u64, Value)> = Vec::new();
466
- let start = monotonic_ns();
467
- let deadline = start + 10_000 * ms;
468
- drive(&mut connections, start, deadline, ms, &mut |event, t, fields| events.push((event.into(), t, fields))).unwrap();
469
- let replied = |key: &str| -> Vec<u64> {
470
- events.iter().filter(|(event, _, fields)| event == "replied" && fields["k"] == key).map(|(_, t, _)| t - start).collect()
471
- };
951
+ let (events, start) = lines_of(&mut flows);
952
+ let replied = |key: &str| -> Vec<u64> { of(&events, "replied", key).map(|(_, t, _)| t - start).collect() };
472
953
  assert_eq!(replied("slow").len(), 3);
473
954
  assert_eq!(replied("fast").len(), 3);
474
955
  assert!(events.iter().filter(|(event, _, _)| event == "replied").all(|(_, _, fields)| fields["status"] == 200));
@@ -476,6 +957,61 @@ mod tests {
476
957
  assert!(replied("fast")[2] < replied("slow")[0], "{events:?}");
477
958
  let sent = events.iter().filter(|(event, _, _)| event == "sent").count();
478
959
  assert_eq!(sent, 6);
960
+ // a pipeline gives no wait: its lines stay as they were
961
+ assert!(events.iter().filter(|(event, _, _)| event == "sent").all(|(_, _, fields)| fields.get("wait").is_none()));
479
962
  assert_eq!(events.last().map(|(event, _, fields)| (event.as_str(), fields["requests"].clone())), Some(("done", json!(6))));
480
963
  }
964
+
965
+ #[test]
966
+ fn a_pool_sends_one_request_on_each_connection_and_a_fast_reply_passes_a_slow_one() {
967
+ let port = serve(2, Duration::from_millis(200));
968
+ // the arrivals 0 and 2 are slow, and the arrivals 1 and 3 are fast
969
+ let pooled = Stream { requests: vec![request("slow"), request("fast")], mode: Mode::Pool(2), ..stream("p", &[0, MS, 2 * MS, 3 * MS]) };
970
+ let mut flows = vec![Flow::Pool(Pool::open(local(port), pooled).unwrap())];
971
+ let (events, start) = lines_of(&mut flows);
972
+ let replied: Vec<u64> = of(&events, "replied", "p").map(|(_, _, fields)| fields["i"].as_u64().unwrap()).collect();
973
+ let mut each = replied.clone();
974
+ each.sort_unstable();
975
+ assert_eq!(each, [0, 1, 2, 3], "{events:?}");
976
+ // the fast arrival 1 replies before the slow arrival 0, on its own connection
977
+ let at = |i: u64| replied.iter().position(|&each| each == i).unwrap();
978
+ assert!(at(1) < at(0), "{events:?}");
979
+ // the arrival 3 waits for a connection: a slow reply ends first. That wait is not a lag of the driver
980
+ let sent = |i: u64| of(&events, "sent", "p").find(|(_, _, fields)| fields["i"] == i).cloned().unwrap();
981
+ let (_, t, fields) = sent(3);
982
+ let wait = fields["wait"].as_u64().unwrap();
983
+ assert!(wait >= 100 * MS, "{events:?}");
984
+ let lag = (t - start) as i64 - wait as i64 - (3 * MS) as i64;
985
+ assert!(lag.abs() < (50 * MS) as i64, "the lag {lag} ns, {events:?}");
986
+ assert_eq!(sent(0).2["wait"], 0);
987
+ assert_eq!(events.last().map(|(event, _, fields)| (event.as_str(), fields["requests"].clone())), Some(("done", json!(4))));
988
+ }
989
+
990
+ #[test]
991
+ fn a_fresh_stream_opens_a_connection_for_each_arrival_and_its_requests_overlap() {
992
+ let port = serve(3, Duration::from_millis(200));
993
+ let fresh = Stream { mode: Mode::Fresh, ..stream("slow", &[0, MS, 2 * MS]) };
994
+ let mut flows = vec![Flow::Pool(Pool::open(local(port), fresh).unwrap())];
995
+ let (events, start) = lines_of(&mut flows);
996
+ let replied: Vec<u64> = of(&events, "replied", "slow").map(|(_, t, _)| t - start).collect();
997
+ assert_eq!(replied.len(), 3, "{events:?}");
998
+ // one connection would answer the three in turn, after 600 ms
999
+ assert!(replied.iter().all(|&t| t < 500 * MS), "{events:?}");
1000
+ assert!(of(&events, "sent", "slow").all(|(_, _, fields)| fields["wait"].as_u64().is_some()));
1001
+ assert!(!events.iter().any(|(event, _, _)| event == "error" || event == "eof"), "{events:?}");
1002
+ assert_eq!(events.last().map(|(event, _, fields)| (event.as_str(), fields["requests"].clone())), Some(("done", json!(3))));
1003
+ }
1004
+
1005
+ #[test]
1006
+ fn a_failed_connect_of_a_fresh_stream_is_an_error_of_its_arrival_only() {
1007
+ // a port with no listener refuses each connect
1008
+ let port = TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port();
1009
+ let fresh = Stream { mode: Mode::Fresh, ..stream("gone", &[0, 5 * MS]) };
1010
+ let mut flows = vec![Flow::Pool(Pool::open(local(port), fresh).unwrap())];
1011
+ let (events, _) = lines_of(&mut flows);
1012
+ let failed: Vec<Value> = of(&events, "error", "gone").map(|(_, _, fields)| fields["i"].clone()).collect();
1013
+ assert_eq!(failed, [json!(0), json!(1)], "{events:?}");
1014
+ assert!(of(&events, "error", "gone").all(|(_, _, fields)| fields["errno"] == "ECONNREFUSED"), "{events:?}");
1015
+ assert_eq!(events.last().map(|(event, _, fields)| (event.as_str(), fields["requests"].clone())), Some(("done", json!(0))));
1016
+ }
481
1017
  }