From 4c55fd320dd458d50497e8f0d7d0235535f8b7a2 Mon Sep 17 00:00:00 2001 From: Nikaidou Haruki Date: Sat, 6 Sep 2025 18:16:30 +0900 Subject: [PATCH] impl UDP sward --- Cargo.lock | 2 + ubw-sward/Cargo.toml | 2 + ubw-sward/src/udp/random_flood.rs | 69 +++++++++++++++++++++++++++++++ 3 files changed, 73 insertions(+) diff --git a/Cargo.lock b/Cargo.lock index 2b39830..b93522c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1568,9 +1568,11 @@ version = "0.1.0" dependencies = [ "bytes", "compact_str", + "libc", "rand", "regex", "reqwest", + "socket2", "thiserror", "tokio", "tokio-util", diff --git a/ubw-sward/Cargo.toml b/ubw-sward/Cargo.toml index e87c0b7..188426d 100644 --- a/ubw-sward/Cargo.toml +++ b/ubw-sward/Cargo.toml @@ -12,6 +12,8 @@ rand = {workspace = true} thiserror = {workspace = true} compact_str = {workspace = true} bytes = {workspace = true} +libc = "0.2" +socket2 = "0.6" wyrand = "0.3" regex = "1.11" tokio-util = "0.7" \ No newline at end of file diff --git a/ubw-sward/src/udp/random_flood.rs b/ubw-sward/src/udp/random_flood.rs index e69de29..3989dfd 100644 --- a/ubw-sward/src/udp/random_flood.rs +++ b/ubw-sward/src/udp/random_flood.rs @@ -0,0 +1,69 @@ +use std::pin::Pin; +use std::sync::Arc; +use std::task::{Context, Poll}; +use tokio::net::UdpSocket; +use tower::Service; + +#[derive(Clone)] +pub struct UdpSward { + socket: Arc, + sent_count: usize, +} + +impl UdpSward { + pub fn new(socket: Arc) -> Self { + Self { + socket, + sent_count: 0, + } + } +} + +#[derive(Clone, Copy)] +pub struct SizedUdpRequest { + pub bytes: [u8; N], +} + +impl Service> for UdpSward { + type Response = usize; + type Error = std::io::Error; + type Future = Pin> + Send>>; + + fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll> { + Poll::Ready(Ok(())) + } + + fn call(&mut self, req: SizedUdpRequest) -> Self::Future { + self.sent_count += 1; + let socket = self.socket.clone(); + Box::pin(async move { + socket.send(&req.bytes).await + }) + } +} + +#[derive(Clone)] +pub struct BoxedUdpRequest(pub Box<[u8]>); + +impl Service for UdpSward { + type Response = usize; + type Error = std::io::Error; + type Future = Pin> + Send>>; + fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll> { + Poll::Ready(Ok(())) + } + fn call(&mut self, req: BoxedUdpRequest) -> Self::Future { + self.sent_count += 1; + let socket = self.socket.clone(); + Box::pin(async move { + socket.send(&req.0).await + }) + } +} + +impl tower::load::Load for UdpSward { + type Metric = usize; + fn load(&self) -> Self::Metric { + self.sent_count + } +} \ No newline at end of file