|
| 1 | +use std::{ |
| 2 | + net::Ipv4Addr, |
| 3 | + sync::{ |
| 4 | + Arc, |
| 5 | + atomic::{AtomicU16, Ordering}, |
| 6 | + }, |
| 7 | +}; |
| 8 | + |
| 9 | +use anyhow::{Context, Result}; |
| 10 | +use bincode::config::standard; |
| 11 | +use test_utils::ports::{ALLOCATOR_PORT, Request, Response}; |
| 12 | +use tokio::{ |
| 13 | + io::{AsyncReadExt, AsyncWriteExt}, |
| 14 | + net::{TcpListener, TcpStream}, |
| 15 | +}; |
| 16 | +use tokio_util::task::TaskTracker; |
| 17 | + |
| 18 | +#[tokio::main] |
| 19 | +async fn main() -> Result<()> { |
| 20 | + let tasks = TaskTracker::new(); |
| 21 | + let counter = Arc::new(AtomicU16::new(2048)); |
| 22 | + |
| 23 | + let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, ALLOCATOR_PORT)) |
| 24 | + .await |
| 25 | + .context("allocator port is in use")?; |
| 26 | + |
| 27 | + loop { |
| 28 | + let Ok((stream, _)) = listener.accept().await else { |
| 29 | + continue; |
| 30 | + }; |
| 31 | + tasks.spawn(alloc(stream, counter.clone())); |
| 32 | + } |
| 33 | +} |
| 34 | + |
| 35 | +async fn alloc(mut stream: TcpStream, ctr: Arc<AtomicU16>) -> Result<()> { |
| 36 | + let len = stream.read_u32().await?; |
| 37 | + let mut buf = vec![0; len as usize]; |
| 38 | + stream.read_exact(&mut buf).await?; |
| 39 | + match bincode::decode_from_slice(&buf, standard())? { |
| 40 | + (Request::Alloc(n), _) => { |
| 41 | + let mut ports = Vec::new(); |
| 42 | + for _ in 0..n { |
| 43 | + loop { |
| 44 | + let port = ctr.fetch_add(1, Ordering::Relaxed); |
| 45 | + if TcpListener::bind((Ipv4Addr::LOCALHOST, port)).await.is_ok() { |
| 46 | + ports.push(port); |
| 47 | + break; |
| 48 | + } |
| 49 | + } |
| 50 | + } |
| 51 | + buf.clear(); |
| 52 | + bincode::encode_into_std_write(Response::Ports(ports), &mut buf, standard())?; |
| 53 | + stream |
| 54 | + .write_u32(buf.len().try_into().expect("response fits into u32 bytes")) |
| 55 | + .await?; |
| 56 | + stream.write_all(&buf).await?; |
| 57 | + } |
| 58 | + } |
| 59 | + Ok(()) |
| 60 | +} |
0 commit comments