use std::fmt;
use std::io;
use std::os::unix::net::{SocketAddr, UnixDatagram};
use std::path::{Path, PathBuf};
use std::sync::{Mutex, MutexGuard, PoisonError};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use legit_streams::Task;
pub const SOCKET_FORMAT: u32 = 1;
pub const MAX_DATAGRAM_BYTES: usize = 200;
pub const KIND_OTHER: u8 = 0;
pub const KIND_IMAGE: u8 = 1;
pub const KIND_TEXT: u8 = 2;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[non_exhaustive]
pub struct SocketEvent {
pub started_at: u64,
pub seq: u64,
pub finish: bool,
pub at_us: u64,
pub fast: bool,
pub slot: u32,
pub kind: u8,
pub ok: bool,
pub us: u64,
}
#[must_use]
pub fn socket_datagram(event: &SocketEvent) -> String {
let mut text = String::with_capacity(MAX_DATAGRAM_BYTES);
let _ = write_datagram(event, &mut text);
text
}
fn write_datagram(event: &SocketEvent, out: &mut impl fmt::Write) -> fmt::Result {
write!(
out,
r#"{{"v":{SOCKET_FORMAT},"w":{},"seq":{},"e":{},"t":{},"lane":{},"slot":{},"kind":{}"#,
event.started_at,
event.seq,
u8::from(event.finish),
event.at_us,
u8::from(event.fast),
event.slot,
event.kind,
)?;
if event.finish {
write!(out, r#","ok":{},"us":{}"#, u8::from(event.ok), event.us)?;
}
out.write_char('}')
}
struct Datagram {
bytes: [u8; MAX_DATAGRAM_BYTES],
len: usize,
}
impl fmt::Write for Datagram {
fn write_str(&mut self, text: &str) -> fmt::Result {
let end = self.len + text.len();
let room = self.bytes.get_mut(self.len..end).ok_or(fmt::Error)?;
room.copy_from_slice(text.as_bytes());
self.len = end;
Ok(())
}
}
pub(crate) fn task_kind(task: &Task) -> u8 {
let present = |name: &str| task.get(name).is_some_and(|value| !value.is_empty());
let text = task.get("text_data").is_some();
let image = present("image_data") || present("image_url");
if present("a") || present("b") {
return KIND_OTHER;
}
match (text, image) {
(true, false) => KIND_TEXT,
(false, true) => KIND_IMAGE,
_ => KIND_OTHER,
}
}
#[derive(Debug, Default)]
struct Slots {
held: Vec<u64>,
}
impl Slots {
fn with_room(slots: usize) -> Self {
Self {
held: Vec::with_capacity(slots.div_ceil(64)),
}
}
fn take(&mut self) -> u32 {
let word = match self.held.iter().position(|word| *word != u64::MAX) {
Some(word) => word,
None => {
self.held.push(0);
self.held.len() - 1
}
};
let bit = self.held[word].trailing_ones();
self.held[word] |= 1 << bit;
u32::try_from(word * 64).map_or(u32::MAX, |base| base.saturating_add(bit))
}
fn free(&mut self, slot: u32) {
let (word, bit) = (slot / 64, slot % 64);
if let Some(word) = usize::try_from(word).ok().and_then(|word| self.held.get_mut(word)) {
*word &= !(1 << bit);
}
}
}
#[derive(Debug)]
struct State {
seq: u64,
slots: [Slots; 2],
sent: u64,
dropped: u64,
failure: Option<io::ErrorKind>,
}
#[derive(Debug, Clone, Copy)]
struct Clock {
origin: Instant,
origin_us: u64,
started_at: u64,
}
impl Clock {
fn new(origin: Instant, wall: SystemTime) -> Self {
let origin_us = wall
.duration_since(UNIX_EPOCH)
.map_or(0, |since| u64::try_from(since.as_micros()).unwrap_or(u64::MAX));
Self {
origin,
origin_us,
started_at: origin_us / 1_000_000,
}
}
}
fn micros(duration: Duration) -> u64 {
u64::try_from(duration.as_micros()).unwrap_or(u64::MAX)
}
#[derive(Debug)]
pub struct EventsSocket {
path: PathBuf,
address: SocketAddr,
socket: UnixDatagram,
clock: Clock,
state: Mutex<State>,
}
impl EventsSocket {
pub fn new(path: impl AsRef<Path>) -> io::Result<Self> {
let path = path.as_ref();
if path.as_os_str().is_empty() {
return Err(io::Error::new(io::ErrorKind::InvalidInput, "the path names no socket"));
}
let address = SocketAddr::from_pathname(path).map_err(|_| {
io::Error::new(
io::ErrorKind::InvalidInput,
format!(
"the path is {} bytes, more than a Unix socket address holds",
path.as_os_str().len()
),
)
})?;
let socket = UnixDatagram::unbound()?;
socket.set_nonblocking(true)?;
Ok(Self {
path: path.to_path_buf(),
address,
socket,
clock: Clock::new(Instant::now(), SystemTime::now()),
state: Mutex::new(State {
seq: 0,
slots: [Slots::default(), Slots::default()],
sent: 0,
dropped: 0,
failure: None,
}),
})
}
pub(crate) fn for_server(mut self, origin: Instant, wall: SystemTime, jobs: usize, fast_jobs: usize) -> Self {
self.clock = Clock::new(origin, wall);
let state = self.state.get_mut().unwrap_or_else(PoisonError::into_inner);
state.slots = [Slots::with_room(jobs), Slots::with_room(fast_jobs)];
self
}
#[must_use]
pub fn path(&self) -> &Path {
&self.path
}
#[must_use]
pub const fn started_at(&self) -> u64 {
self.clock.started_at
}
#[must_use]
pub fn sent(&self) -> u64 {
self.lock().sent
}
#[must_use]
pub fn dropped(&self) -> u64 {
self.lock().dropped
}
fn lock(&self) -> MutexGuard<'_, State> {
self.state.lock().unwrap_or_else(PoisonError::into_inner)
}
pub fn begin(&self, fast: bool, kind: u8) -> SocketTask<'_> {
let mut state = self.lock();
let at = self.clock.origin.elapsed();
let slot = state.slots[usize::from(fast)].take();
state.seq += 1;
let event = SocketEvent {
started_at: self.clock.started_at,
seq: state.seq,
finish: false,
at_us: self.clock.origin_us.saturating_add(micros(at)),
fast,
slot,
kind,
ok: false,
us: 0,
};
self.send(&mut state, &event);
SocketTask {
socket: self,
fast,
slot,
kind,
began: at,
finished: false,
}
}
fn end(&self, task: &SocketTask<'_>, ok: bool, took: Option<Duration>) {
let mut state = self.lock();
let at = self.clock.origin.elapsed();
state.slots[usize::from(task.fast)].free(task.slot);
state.seq += 1;
let event = SocketEvent {
started_at: self.clock.started_at,
seq: state.seq,
finish: true,
at_us: self.clock.origin_us.saturating_add(micros(at)),
fast: task.fast,
slot: task.slot,
kind: task.kind,
ok,
us: micros(took.unwrap_or_else(|| at.saturating_sub(task.began))),
};
self.send(&mut state, &event);
}
fn send(&self, state: &mut State, event: &SocketEvent) {
let mut datagram = Datagram {
bytes: [0; MAX_DATAGRAM_BYTES],
len: 0,
};
let _ = write_datagram(event, &mut datagram);
match self.socket.send_to_addr(&datagram.bytes[..datagram.len], &self.address) {
Ok(_) => {
state.sent += 1;
state.failure = None;
}
Err(error) => {
state.dropped += 1;
let kind = error.kind();
let quiet = matches!(
kind,
io::ErrorKind::WouldBlock | io::ErrorKind::NotFound | io::ErrorKind::ConnectionRefused
);
if !quiet {
if state.failure != Some(kind) {
tracing::warn!(
path = %self.path.display(),
error = %error,
"Couldn't send to the events socket; the worker carries on"
);
}
state.failure = Some(kind);
}
}
}
}
}
#[derive(Debug)]
#[must_use = "dropping it at once sends the task's finish as a failure"]
pub struct SocketTask<'socket> {
socket: &'socket EventsSocket,
fast: bool,
slot: u32,
kind: u8,
began: Duration,
finished: bool,
}
impl SocketTask<'_> {
#[must_use]
pub const fn slot(&self) -> u32 {
self.slot
}
pub fn finish(mut self, ok: bool, took: Duration) {
self.socket.end(&self, ok, Some(took));
self.finished = true;
}
}
impl Drop for SocketTask<'_> {
fn drop(&mut self) {
if !self.finished {
self.socket.end(self, false, None);
}
}
}
#[cfg(test)]
mod tests {
use std::time::Duration;
use legit_streams::Task;
use super::{
EventsSocket, KIND_IMAGE, KIND_OTHER, KIND_TEXT, MAX_DATAGRAM_BYTES, Slots, SocketEvent, socket_datagram,
task_kind,
};
#[test]
fn the_longest_datagram_fits() {
let event = SocketEvent {
started_at: u64::MAX,
seq: u64::MAX,
finish: true,
at_us: u64::MAX,
fast: true,
slot: u32::MAX,
kind: u8::MAX,
ok: true,
us: u64::MAX,
};
let text = socket_datagram(&event);
assert_eq!(text.len(), 161, "{text}");
assert!(text.len() <= MAX_DATAGRAM_BYTES);
let event = SocketEvent {
kind: KIND_TEXT,
..event
};
assert_eq!(socket_datagram(&event).len(), 159);
}
#[test]
fn a_slot_is_the_lowest_free_and_freed_ones_are_taken_again() {
let mut slots = Slots::with_room(4);
let taken: Vec<u32> = (0..130).map(|_| slots.take()).collect();
assert_eq!(taken, (0..130).collect::<Vec<_>>());
slots.free(70);
slots.free(3);
assert_eq!((slots.take(), slots.take(), slots.take()), (3, 70, 130));
slots.free(1_000);
}
#[test]
fn a_kind_comes_from_the_payload_field() {
let task = |fields: &[(&str, &str)]| {
let mut builder = Task::builder("app", "post", "1");
for (name, value) in fields {
builder = builder.field(*name, *value);
}
builder.build().expect("a valid task")
};
assert_eq!(task_kind(&task(&[("text_data", "")])), KIND_TEXT);
assert_eq!(task_kind(&task(&[("image_data", "AAAA")])), KIND_IMAGE);
assert_eq!(
task_kind(&task(&[("image_url", "https://example.com/a.png")])),
KIND_IMAGE
);
assert_eq!(task_kind(&task(&[("a", "x"), ("b", "y")])), KIND_OTHER);
assert_eq!(
task_kind(&task(&[("text_data", "t"), ("image_data", "AAAA")])),
KIND_OTHER
);
assert_eq!(task_kind(&task(&[("text_data", "t"), ("a", "x")])), KIND_OTHER);
assert_eq!(task_kind(&task(&[("options", "{}")])), KIND_OTHER);
}
#[test]
fn a_task_dropped_without_its_finish_sends_it_failed_and_frees_its_slot() {
let socket = EventsSocket::new("/nonexistent-legit-hasher/events.sock").expect("a short path");
let first = socket.begin(false, KIND_TEXT);
let second = socket.begin(false, KIND_TEXT);
assert_eq!((first.slot(), second.slot()), (0, 1));
drop(first);
assert_eq!(socket.begin(false, KIND_TEXT).slot(), 0);
second.finish(true, Duration::ZERO);
assert_eq!((socket.sent(), socket.dropped()), (0, 6));
}
#[test]
fn a_handler_that_panics_still_sends_its_finish_failed_and_frees_its_slot() {
use std::os::unix::net::UnixDatagram;
use std::sync::Arc;
use legit_streams::{MemoryStreams, Producer, ResultReader, Streams};
use crate::serve::{ServeConfig, Server};
let directory = std::env::temp_dir().join(format!("legit-hasher-socket-panic-{}", std::process::id()));
std::fs::create_dir_all(&directory).expect("a directory");
let path = directory.join("events.sock");
let _ = std::fs::remove_file(&path);
let reader = UnixDatagram::bind(&path).expect("bound");
reader
.set_read_timeout(Some(Duration::from_secs(30)))
.expect("a timeout");
let mut config = ServeConfig::new("socket-panic", 1);
config.worker.concurrency = 1;
config.worker.read_block = Duration::from_millis(50);
config.fast = None;
let streams: Arc<dyn Streams> = Arc::new(MemoryStreams::new());
let socket = EventsSocket::new(&path).expect("a short path");
let server = Server::start_with_events_socket(config, Arc::clone(&streams), None, None, socket)
.expect("the server starts");
let producer = Producer::new(Arc::clone(&streams), "hash_tasks");
let results = ResultReader::new(Arc::clone(&streams), "hash_results", "readers", "reader");
let task = |panics: bool| {
let builder = Task::builder("app", "post", "1").field("text_data", "a text").field(
"options",
r#"{"format":1,"definitions":[{"id":"simhash-v1","tokens":"words"}]}"#,
);
let builder = if panics {
builder.field("panic_in_test", "1")
} else {
builder
};
builder.build().expect("a valid task")
};
let mut answered = Vec::new();
for panics in [true, false] {
producer.send(&task(panics)).expect("sent");
loop {
let read = results.read(10, Some(Duration::from_millis(50))).expect("read");
if let Some(entry) = read.into_iter().next() {
answered.push(entry.result.expect("a result").is_success());
break;
}
}
}
server.stop();
server.join().expect("the server stops");
assert_eq!(answered, [false, true], "the panic is answered as an error");
let mut buffer = [0u8; 256];
let events: Vec<serde_json::Value> = (0..4)
.map(|_| {
let length = reader.recv(&mut buffer).expect("a datagram");
serde_json::from_slice(&buffer[..length]).expect("JSON")
})
.collect();
let numbers = |key: &str| events.iter().map(|event| event[key].as_u64()).collect::<Vec<_>>();
assert_eq!(numbers("seq"), [Some(1), Some(2), Some(3), Some(4)]);
assert_eq!(numbers("e"), [Some(0), Some(1), Some(0), Some(1)]);
assert_eq!(numbers("slot"), [Some(0); 4], "the slot was freed and taken again");
assert_eq!(numbers("ok"), [None, Some(0), None, Some(1)]);
let _ = std::fs::remove_dir_all(&directory);
}
}