use std::sync::Arc;
use std::sync::atomic::Ordering;
use legit_streams::{Context, Failure, INVALID_TASK, Reply, Task, UNSUPPORTED_MODEL};
use serde_json::Value;
use super::{Counters, FAST_SOURCES, Fetcher, MODEL_NAME};
use crate::distance::{compare_pair, invalid_pair};
use crate::hasher::text_too_large;
use crate::request::{Id, Options, Request, Source, inline_bytes};
use crate::{DistanceError, MAX_OPTIONS_BYTES, Outcome, RequestError, Settings, Status, hash};
#[derive(Debug)]
pub(crate) struct Shared {
pub(crate) settings: Settings,
pub(crate) fetcher: Fetcher,
pub(crate) counters: Arc<Counters>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Lane {
Bulk,
Fast,
}
#[derive(Debug)]
pub(crate) struct Handler {
shared: Arc<Shared>,
lane: Lane,
}
impl Handler {
pub(crate) const fn new(shared: Arc<Shared>, lane: Lane) -> Self {
Self { shared, lane }
}
}
impl legit_streams::Handler for Handler {
fn handle(&self, task: &Task, context: &Context) -> Result<Reply, Failure> {
let counters = &self.shared.counters;
#[cfg(unix)]
let event = counters
.socket
.as_deref()
.map(|socket| socket.begin(self.lane == Lane::Fast, super::socket::task_kind(task)));
if self.lane == Lane::Bulk {
counters.in_flight.fetch_add(1, Ordering::Relaxed);
}
let answer = self.answer(task, context);
let elapsed = context.elapsed();
if let Err(failure) = &answer
&& !failure.is_abandon()
{
tracing::debug!(
entry = %context.entry_id(),
error_type = failure.error_type().unwrap_or_default(),
"A task was answered with an error"
);
}
let (done, failed, times) = match self.lane {
Lane::Bulk => {
counters.in_flight.fetch_sub(1, Ordering::Relaxed);
(&counters.done, &counters.failed, &counters.bulk_times)
}
Lane::Fast => (&counters.fast_done, &counters.fast_failed, &counters.fast_times),
};
times.record(elapsed);
let is_failure = matches!(&answer, Ok(Answer { failed: true, .. }) | Err(_));
done.fetch_add(1, Ordering::Relaxed);
if is_failure {
failed.fetch_add(1, Ordering::Relaxed);
}
if let Some(events) = &counters.events {
events.record(self.lane == Lane::Fast, is_failure, elapsed);
}
#[cfg(unix)]
if let Some(event) = event {
event.finish(!is_failure, elapsed);
}
answer.map(|answer| answer.reply)
}
}
struct Answer {
reply: Reply,
failed: bool,
}
fn present<'a>(task: &'a Task, name: &str) -> Option<&'a str> {
task.get(name).filter(|value| !value.is_empty())
}
impl Handler {
fn answer(&self, task: &Task, context: &Context) -> Result<Answer, Failure> {
#[cfg(test)]
assert!(task.get("panic_in_test").is_none(), "a handler panics, as a test asked");
let model = task.model_name();
if !model.is_empty() && model != MODEL_NAME {
return Err(Failure::new(
UNSUPPORTED_MODEL,
format!(
"this worker is `{MODEL_NAME}`; it serves no model `{model}`, and an empty `model_name` is fine"
),
)
.field("supported_models", format!("[\"{MODEL_NAME}\"]")));
}
let id = Id::Text(present(task, "id").unwrap_or(task.task_id()).to_owned());
let sources: Vec<&str> = [
task.get("text_data").map(|_| "text_data"),
present(task, "image_data").map(|_| "image_data"),
present(task, "image_url").map(|_| "image_url"),
]
.into_iter()
.flatten()
.collect();
let pair = (present(task, "a"), present(task, "b"));
if pair != (None, None) {
if !sources.is_empty() {
return Err(request_failure(
&Outcome::error(
Some(id),
RequestError::InvalidRequest,
"the task gives a source and a pair `a` and `b`; a task hashes one source or compares one pair",
),
Some(INVALID_TASK),
));
}
return distance(id, pair);
}
let name = match sources.as_slice() {
[name] => *name,
[] => {
let outcome = Outcome::error(
Some(id),
RequestError::NoSource,
"the task needs one source: `text_data`, `image_data` or `image_url`, or a pair `a` and `b`",
);
return Err(request_failure(&outcome, Some(INVALID_TASK)));
}
_ => {
let outcome = Outcome::error(
Some(id),
RequestError::NoSource,
format!(
"the task gives more than one source (`{}`); give exactly one",
sources.join("`, `")
),
);
return Err(request_failure(&outcome, None));
}
};
if self.lane == Lane::Fast && !FAST_SOURCES.contains(&name) {
let outcome = Outcome::error(
Some(id),
RequestError::NoSource,
format!("the fast lane takes `text_data` and pairs; send `{name}` to the bulk task stream"),
);
return Err(request_failure(&outcome, Some(INVALID_TASK)));
}
if name == "text_data"
&& let Some(message) = text_too_large(task.get(name).map_or(0, str::len), self.shared.settings)
{
return Err(request_failure(
&Outcome::error(Some(id), RequestError::TooLarge, message),
None,
));
}
let options = match present(task, "options") {
None => Err("the request has no `options`".to_owned()),
Some(options) if options.len() > MAX_OPTIONS_BYTES => Err(format!(
"`options` is `{}` bytes of JSON; it may be at most `{MAX_OPTIONS_BYTES}`",
options.len()
)),
Some(options) => match serde_json::from_str::<Value>(options) {
Err(error) => Err(format!("`options` isn't JSON: {error}")),
Ok(options) => Options::from_json(&options),
},
};
let options = match options {
Ok(options) => {
self.shared.counters.definitions.ask(&options);
options
}
Err(message) => {
return Err(request_failure(
&Outcome::error(Some(id), RequestError::InvalidOptions, message),
None,
));
}
};
if name == "image_url" {
context.checkpoint()?;
}
let (source, read_us) = match self.source(task, name, context) {
Ok(source) => source,
Err((code, message)) => return Err(request_failure(&Outcome::error(Some(id), code, message), None)),
};
let request = Request { id, source, options };
let mut outcome = hash(&request, self.shared.settings);
self.shared.counters.definitions.count(&outcome);
if let (Some(read_us), Some(timings)) = (read_us, outcome.timings.as_mut()) {
timings.read_us = Some(read_us);
timings.total_us = timings.total_us.saturating_add(read_us);
}
if outcome.status == Status::Error {
return Err(request_failure(&outcome, None));
}
Ok(Answer {
failed: outcome.is_failure(),
reply: Reply::new().field("result", outcome.to_json()),
})
}
fn source(
&self,
task: &Task,
name: &str,
context: &Context,
) -> Result<(Source, Option<u64>), (RequestError, String)> {
let value = task.get(name).unwrap_or_default();
match name {
"text_data" => Ok((Source::Text(value.to_owned()), None)),
"image_data" => inline_bytes("image_data", value).map(|bytes| (Source::Bytes(bytes), None)),
_ => {
let counters = &self.shared.counters;
match self.shared.fetcher.fetch(value) {
Ok(fetched) => {
counters.fetched.fetch_add(1, Ordering::Relaxed);
counters
.fetched_bytes
.fetch_add(fetched.bytes.len() as u64, Ordering::Relaxed);
let read_us = u64::try_from(fetched.elapsed.as_micros()).unwrap_or(u64::MAX);
Ok((Source::Bytes(fetched.bytes), Some(read_us)))
}
Err(error) => {
tracing::warn!(
entry = %context.entry_id(),
error_type = error.code.as_str(),
host = %super::url_host(value),
"An image_url couldn't be fetched"
);
Err((error.code, error.message))
}
}
}
}
}
}
fn request_failure(outcome: &Outcome, contract_code: Option<&str>) -> Failure {
let code = contract_code
.or_else(|| outcome.error_type.map(RequestError::as_str))
.unwrap_or(RequestError::Internal.as_str());
Failure::new(code, outcome.error.clone().unwrap_or_default()).field("result", outcome.to_json())
}
fn distance(id: Id, pair: (Option<&str>, Option<&str>)) -> Result<Answer, Failure> {
let comparison = match pair {
(Some(a), Some(b)) => compare_pair(id, a, b),
_ => invalid_pair(id, "a distance task needs `a` and `b`, each a stored hash or signature"),
};
let json = serde_json::to_string(&comparison).unwrap_or_default();
match comparison.error_type {
Some(code) => {
let contract_code = match code {
DistanceError::InvalidRequest => INVALID_TASK,
code => code.as_str(),
};
Err(Failure::new(contract_code, comparison.error.unwrap_or_default()).field("result", json))
}
None => Ok(Answer {
reply: Reply::new().field("result", json),
failed: false,
}),
}
}