use std::fmt;
use crate::entry::Entry;
use crate::error::{Error, Result};
use crate::fields::{self, Limits};
use crate::task::{IDENTITY_MAX_LEN, Task, UNKNOWN};
const RESERVED: [&str; 10] = [
"task_id",
"model_type",
"model_id",
"task_name",
"model_name",
"status",
"error_type",
"error",
"worker_id",
"processing_ms",
];
pub(crate) const ECHOED: [&str; 2] = ["embedder_key", "metadata"];
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Status {
Success,
Error,
}
impl Status {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Success => "success",
Self::Error => "error",
}
}
}
impl fmt::Display for Status {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
impl std::str::FromStr for Status {
type Err = Error;
fn from_str(s: &str) -> Result<Self> {
match s {
"success" => Ok(Self::Success),
"error" => Ok(Self::Error),
_ => Err(Error::InvalidValue {
field: "status".to_owned(),
expected: "`success` or `error`",
}),
}
}
}
#[derive(Clone, PartialEq, Eq)]
pub struct TaskResult {
fields: Vec<(String, String)>,
}
impl TaskResult {
#[must_use]
pub fn success(task_id: impl Into<String>) -> ResultBuilder {
ResultBuilder::new(Some(task_id.into()), Status::Success, None)
}
#[must_use]
pub fn failure(task_id: impl Into<String>, message: impl Into<String>) -> ResultBuilder {
ResultBuilder::new(Some(task_id.into()), Status::Error, Some(message.into()))
}
pub fn from_entry(entry: &Entry) -> Result<Self> {
Self::from_raw(&entry.fields, &Limits::default())
}
pub fn from_raw(raw: &[(Vec<u8>, Vec<u8>)], limits: &Limits) -> Result<Self> {
let fields = fields::decode(raw, limits)?;
validate(&fields)?;
Ok(Self { fields })
}
pub fn from_fields(fields: Vec<(String, String)>) -> Result<Self> {
fields::check_strings(&fields, &Limits::default())?;
validate(&fields)?;
Ok(Self { fields })
}
#[must_use]
pub fn task_id(&self) -> &str {
self.get("task_id").unwrap_or_default()
}
#[must_use]
pub fn status(&self) -> Status {
if self.get("status") == Some("error") {
Status::Error
} else {
Status::Success
}
}
#[must_use]
pub fn is_success(&self) -> bool {
self.status() == Status::Success
}
#[must_use]
pub fn error(&self) -> Option<&str> {
self.get("error")
}
#[must_use]
pub fn error_type(&self) -> Option<&str> {
self.get("error_type")
}
#[must_use]
pub fn model_type(&self) -> Option<&str> {
self.get("model_type")
}
#[must_use]
pub fn model_id(&self) -> Option<&str> {
self.get("model_id")
}
#[must_use]
pub fn task_name(&self) -> Option<&str> {
self.get("task_name")
}
#[must_use]
pub fn model_name(&self) -> Option<&str> {
self.get("model_name")
}
#[must_use]
pub fn worker_id(&self) -> Option<&str> {
self.get("worker_id")
}
#[must_use]
pub fn processing_ms(&self) -> Option<u64> {
self.get("processing_ms").and_then(|ms| ms.parse().ok())
}
#[must_use]
pub fn get(&self, name: &str) -> Option<&str> {
fields::get(&self.fields, name)
}
#[must_use]
pub fn fields(&self) -> &[(String, String)] {
&self.fields
}
#[must_use]
pub fn into_fields(self) -> Vec<(String, String)> {
self.fields
}
}
impl fmt::Debug for TaskResult {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("TaskResult")
.field("task_id", &self.task_id())
.field("status", &self.status())
.field("error_type", &self.error_type())
.field(
"fields",
&self.fields.iter().map(|(name, _)| name.as_str()).collect::<Vec<_>>(),
)
.finish_non_exhaustive()
}
}
fn validate(fields: &[(String, String)]) -> Result<()> {
match fields::get(fields, "task_id") {
None => return Err(Error::MissingField("task_id")),
Some("") => return Err(Error::EmptyField("task_id")),
Some(_) => {}
}
fields::get(fields, "status")
.ok_or(Error::MissingField("status"))?
.parse::<Status>()?;
Ok(())
}
fn is_error_type(error_type: &str) -> bool {
error_type.starts_with(|c: char| c.is_ascii_lowercase())
&& error_type
.bytes()
.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_')
}
#[derive(Clone)]
pub struct ResultBuilder {
task_id: Option<String>,
model_type: Option<String>,
model_id: Option<String>,
task_name: Option<String>,
model_name: Option<String>,
status: Status,
error_type: Option<String>,
error: Option<String>,
worker_id: Option<String>,
processing_ms: Option<u64>,
echoed: Vec<(String, String)>,
extra: Vec<(String, String)>,
}
impl ResultBuilder {
const fn new(task_id: Option<String>, status: Status, error: Option<String>) -> Self {
Self {
task_id,
model_type: None,
model_id: None,
task_name: None,
model_name: None,
status,
error_type: None,
error,
worker_id: None,
processing_ms: None,
echoed: Vec::new(),
extra: Vec::new(),
}
}
#[must_use]
pub fn echo(mut self, task: &Task) -> Self {
self.model_type = Some(identity(Some(task.model_type())));
self.model_id = Some(identity(Some(task.model_id())));
self.task_name = Some(identity(Some(task.task_name())));
self.model_name = Some(task.model_name().to_owned());
for name in ECHOED {
if let Some(value) = task.get(name) {
self.echoed.push((name.to_owned(), value.to_owned()));
}
}
self
}
#[must_use]
pub fn model_type(mut self, model_type: impl Into<String>) -> Self {
self.model_type = Some(model_type.into());
self
}
#[must_use]
pub fn model_id(mut self, model_id: impl Into<String>) -> Self {
self.model_id = Some(model_id.into());
self
}
#[must_use]
pub fn task_name(mut self, task_name: impl Into<String>) -> Self {
self.task_name = Some(task_name.into());
self
}
#[must_use]
pub fn model_name(mut self, model_name: impl Into<String>) -> Self {
self.model_name = Some(model_name.into());
self
}
#[must_use]
pub fn error_type(mut self, error_type: impl Into<String>) -> Self {
self.error_type = Some(error_type.into());
self
}
#[must_use]
pub fn worker_id(mut self, worker_id: impl Into<String>) -> Self {
self.worker_id = Some(worker_id.into());
self
}
#[must_use]
pub const fn processing_ms(mut self, processing_ms: u64) -> Self {
self.processing_ms = Some(processing_ms);
self
}
#[must_use]
pub fn field(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
self.extra.push((name.into(), value.into()));
self
}
pub fn build(self) -> Result<TaskResult> {
self.build_within(&Limits::default())
}
pub(crate) fn build_within(self, limits: &Limits) -> Result<TaskResult> {
if let Some((name, _)) = self.extra.iter().find(|(name, _)| RESERVED.contains(&name.as_str())) {
return Err(Error::ReservedField(name.clone()));
}
if self.status == Status::Error
&& let Some(error_type) = &self.error_type
&& !is_error_type(error_type)
{
return Err(Error::InvalidValue {
field: "error_type".to_owned(),
expected: "lowercase snake case, such as `unsupported_model`",
});
}
let fields = self.into_fields();
fields::check_strings(&fields, limits)?;
validate(&fields)?;
Ok(TaskResult { fields })
}
pub(crate) fn into_fields(self) -> Vec<(String, String)> {
let mut fields = Vec::with_capacity(10 + self.echoed.len() + self.extra.len());
let mut push = |name: &str, value: Option<String>| {
if let Some(value) = value {
fields.push((name.to_owned(), value));
}
};
push("task_id", self.task_id);
push("model_type", self.model_type);
push("model_id", self.model_id);
push("task_name", self.task_name);
push("model_name", self.model_name);
push("status", Some(self.status.as_str().to_owned()));
if self.status == Status::Error {
push("error_type", self.error_type);
push("error", self.error);
}
push("worker_id", self.worker_id);
push("processing_ms", self.processing_ms.map(|ms| ms.to_string()));
fields.extend(self.echoed);
fields.extend(self.extra);
fields
}
pub(crate) fn into_error(mut self, message: String, error_type: &str) -> Self {
self.status = Status::Error;
self.error = Some(message);
self.error_type = Some(error_type.to_owned());
self.extra.clear();
self
}
pub(crate) fn for_raw(raw: &[(Vec<u8>, Vec<u8>)], task_id: Option<&str>, status: Status, error: String) -> Self {
let text = |name: &str| {
raw.iter()
.rev()
.find(|(key, _)| key == name.as_bytes())
.and_then(|(_, value)| std::str::from_utf8(value).ok())
};
let mut builder = Self::new(task_id.map(str::to_owned), status, Some(error));
builder.model_type = Some(identity(text("model_type")));
builder.model_id = Some(identity(text("model_id")));
builder.task_name = Some(identity(text("task_name")));
builder.model_name = Some(text("model_name").unwrap_or_default().to_owned());
for name in ECHOED {
if let Some(value) = text(name) {
builder.echoed.push((name.to_owned(), value.to_owned()));
}
}
builder
}
pub(crate) fn is_error(&self) -> bool {
self.status == Status::Error
}
pub(crate) fn without_echoes(mut self) -> Self {
self.echoed.clear();
self
}
pub(crate) fn bare(self) -> Self {
self.cut(1024, 1024)
}
pub(crate) fn cut(self, echo: usize, model_name: usize) -> Self {
let short = |value: Option<String>| value.filter(|value| !value.is_empty() && value.len() <= echo);
let task_id = self.task_id.filter(|id| id.len() <= 1024);
let mut bare = Self::new(task_id, self.status, self.error);
bare.model_type = Some(short(self.model_type).unwrap_or_else(|| UNKNOWN.to_owned()));
bare.model_id = Some(short(self.model_id).unwrap_or_else(|| UNKNOWN.to_owned()));
bare.task_name = Some(short(self.task_name).unwrap_or_else(|| UNKNOWN.to_owned()));
bare.model_name = Some(
self.model_name
.filter(|value| value.len() <= model_name)
.unwrap_or_default(),
);
bare.error_type = self.error_type;
bare.worker_id = self.worker_id;
bare.processing_ms = self.processing_ms;
bare
}
}
fn identity(value: Option<&str>) -> String {
value
.filter(|value| !value.is_empty() && value.len() <= IDENTITY_MAX_LEN)
.unwrap_or(UNKNOWN)
.to_owned()
}
impl fmt::Debug for ResultBuilder {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ResultBuilder")
.field("task_id", &self.task_id)
.field("status", &self.status)
.field(
"extra",
&self.extra.iter().map(|(name, _)| name.as_str()).collect::<Vec<_>>(),
)
.finish_non_exhaustive()
}
}