use std::fmt;
use crate::entry::Entry;
use crate::error::{Error, Result};
use crate::fields::{self, Limits};
pub const VERSION: &str = "1";
pub const FIELD_NAME_MAX_LEN: usize = 64;
const REQUIRED: [&str; 7] = [
"task_id",
"model_type",
"model_id",
"task_name",
"model_name",
"source",
"v",
];
pub const TASK_ID_MAX_LEN: usize = 64;
pub const APP_MAX_LEN: usize = 32;
pub const IDENTITY_MAX_LEN: usize = 256;
pub const UNKNOWN: &str = "unknown";
pub const REPLY_TO_MAX_LEN: usize = 128;
pub const RESERVED_FIELDS: [&str; 2] = ["requeue_count", "requeued_at"];
#[must_use]
pub fn task_id(app: &str) -> String {
format!("{app}_{}", ulid::Ulid::new())
}
#[must_use]
pub fn is_valid_task_id(task_id: &str) -> bool {
is_name(task_id, TASK_ID_MAX_LEN, true)
}
#[must_use]
pub fn is_valid_app(app: &str) -> bool {
is_name(app, APP_MAX_LEN, false)
}
pub(crate) fn is_name(name: &str, max: usize, upper: bool) -> bool {
(1..=max).contains(&name.len())
&& name.bytes().all(|b| {
b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_' || b == b'-' || (upper && b.is_ascii_uppercase())
})
}
fn is_reserved_payload(name: &str) -> bool {
name.starts_with('_') || RESERVED_FIELDS.contains(&name)
}
#[must_use]
pub fn reply_to(app: &str, modality: &str) -> String {
format!("results:{app}:{modality}")
}
#[must_use]
pub fn is_valid_reply_to(stream: &str) -> bool {
let segment = |part: &str| is_name(part, REPLY_TO_MAX_LEN, true);
let mut parts = stream.split(':');
stream.len() <= REPLY_TO_MAX_LEN
&& parts.next() == Some("results")
&& parts.next().is_some_and(segment)
&& parts.next().is_some_and(segment)
&& parts.next().is_none()
}
#[derive(Clone, PartialEq, Eq)]
pub struct Task {
fields: Vec<(String, String)>,
}
impl Task {
#[must_use]
pub fn builder(
source: impl Into<String>,
model_type: impl Into<String>,
model_id: impl Into<String>,
) -> TaskBuilder {
TaskBuilder {
source: source.into(),
model_type: model_type.into(),
model_id: model_id.into(),
task_id: None,
task_name: "default".to_owned(),
model_name: String::new(),
reply_to: None,
extra: Vec::new(),
}
}
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.required("task_id")
}
#[must_use]
pub fn model_type(&self) -> &str {
self.required("model_type")
}
#[must_use]
pub fn model_id(&self) -> &str {
self.required("model_id")
}
#[must_use]
pub fn task_name(&self) -> &str {
self.required("task_name")
}
#[must_use]
pub fn model_name(&self) -> &str {
self.required("model_name")
}
#[must_use]
pub fn source(&self) -> &str {
self.required("source")
}
#[must_use]
pub fn reply_to(&self) -> Option<&str> {
self.get("reply_to").filter(|reply_to| !reply_to.is_empty())
}
#[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
}
pub fn extra(&self) -> impl Iterator<Item = (&str, &str)> {
self.fields
.iter()
.filter(|(name, _)| !is_reserved(name))
.map(|(name, value)| (name.as_str(), value.as_str()))
}
#[must_use]
pub fn into_fields(self) -> Vec<(String, String)> {
self.fields
}
pub(crate) fn wire_fields(&self) -> Vec<(String, String)> {
with_version(self.fields.clone())
}
fn required(&self, name: &str) -> &str {
self.get(name).unwrap_or_default()
}
}
impl fmt::Debug for Task {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Task")
.field("task_id", &self.task_id())
.field("task_name", &self.task_name())
.field("source", &self.source())
.field(
"fields",
&self.fields.iter().map(|(name, _)| name.as_str()).collect::<Vec<_>>(),
)
.finish_non_exhaustive()
}
}
fn is_reserved(name: &str) -> bool {
REQUIRED.contains(&name) || name == "reply_to"
}
fn validate(fields: &[(String, String)]) -> Result<()> {
match fields::get(fields, "v") {
None | Some("" | VERSION) => {}
Some(other) => return Err(Error::UnsupportedVersion(other.chars().take(32).collect())),
}
for name in REQUIRED {
if name != "v" && fields::get(fields, name).is_none() {
return Err(Error::MissingField(name));
}
}
for name in NON_EMPTY {
if fields::get(fields, name).is_some_and(str::is_empty) {
return Err(Error::EmptyField(name));
}
}
if !fields::get(fields, "task_id").is_some_and(is_valid_task_id) {
return Err(invalid("task_id", TASK_ID_EXPECTED));
}
Ok(())
}
fn with_version(mut fields: Vec<(String, String)>) -> Vec<(String, String)> {
if let Some((_, value)) = fields.iter_mut().find(|(name, _)| name == "v") {
if value.is_empty() {
VERSION.clone_into(value);
}
return fields;
}
let at = fields
.iter()
.position(|(name, _)| name == "source")
.map_or(fields.len(), |source| source + 1);
fields.insert(at, ("v".to_owned(), VERSION.to_owned()));
fields
}
const NON_EMPTY: [&str; 5] = ["task_id", "model_type", "model_id", "task_name", "source"];
fn is_field_name(name: &str) -> bool {
is_name(name, FIELD_NAME_MAX_LEN, false) && !name.contains('-') && !name.starts_with(|c: char| c.is_ascii_digit())
}
const TASK_ID_EXPECTED: &str = "1 to 64 ASCII letters, digits, `_` and `-`";
fn invalid(field: &str, expected: &'static str) -> Error {
Error::InvalidValue {
field: field.to_owned(),
expected,
}
}
#[derive(Clone)]
pub struct TaskBuilder {
source: String,
model_type: String,
model_id: String,
task_id: Option<String>,
task_name: String,
model_name: String,
reply_to: Option<String>,
extra: Vec<(String, String)>,
}
impl TaskBuilder {
#[must_use]
pub fn task_id(mut self, task_id: impl Into<String>) -> Self {
self.task_id = Some(task_id.into());
self
}
#[must_use]
pub fn task_name(mut self, task_name: impl Into<String>) -> Self {
self.task_name = task_name.into();
self
}
#[must_use]
pub fn model_name(mut self, model_name: impl Into<String>) -> Self {
self.model_name = model_name.into();
self
}
#[must_use]
pub fn reply_to(mut self, reply_to: impl Into<String>) -> Self {
let reply_to = reply_to.into();
self.reply_to = (!reply_to.is_empty()).then_some(reply_to);
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<Task> {
for (name, value) in [
("source", &self.source),
("model_type", &self.model_type),
("model_id", &self.model_id),
("task_name", &self.task_name),
] {
if value.is_empty() {
return Err(Error::EmptyField(name));
}
}
for (name, value) in [
("model_type", &self.model_type),
("model_id", &self.model_id),
("task_name", &self.task_name),
] {
if value.len() > IDENTITY_MAX_LEN {
return Err(invalid(name, "at most 256 bytes"));
}
}
if !is_valid_app(&self.source) {
return Err(invalid(
"source",
"1 to 32 lowercase ASCII letters, digits, `_` and `-`",
));
}
if let Some((name, _)) = self
.extra
.iter()
.find(|(name, _)| is_reserved(name) || is_reserved_payload(name))
{
return Err(Error::ReservedField(name.clone()));
}
if let Some((name, _)) = self.extra.iter().find(|(name, _)| !is_field_name(name)) {
return Err(Error::InvalidValue {
field: name.clone(),
expected: "a field name of 1 to 64 lowercase ASCII letters, digits and `_`, not starting with a digit",
});
}
let task_id = match self.task_id {
Some(id) if !id.is_empty() => id,
_ => task_id(&self.source),
};
if !is_valid_task_id(&task_id) {
return Err(invalid("task_id", TASK_ID_EXPECTED));
}
if self
.reply_to
.as_deref()
.is_some_and(|reply_to| !is_valid_reply_to(reply_to))
{
return Err(invalid(
"reply_to",
"`results:<app>:<kind>` of at most 128 bytes, each part ASCII letters, digits, `_` and `-`",
));
}
let mut fields = vec![
("task_id".to_owned(), task_id),
("model_type".to_owned(), self.model_type),
("model_id".to_owned(), self.model_id),
("task_name".to_owned(), self.task_name),
("model_name".to_owned(), self.model_name),
("source".to_owned(), self.source),
("v".to_owned(), VERSION.to_owned()),
];
if let Some(reply_to) = self.reply_to {
fields.push(("reply_to".to_owned(), reply_to));
}
fields.extend(self.extra);
fields::check_strings(&fields, &Limits::default())?;
Ok(Task { fields })
}
}
impl fmt::Debug for TaskBuilder {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("TaskBuilder")
.field("source", &self.source)
.field("task_id", &self.task_id)
.field(
"extra",
&self.extra.iter().map(|(name, _)| name.as_str()).collect::<Vec<_>>(),
)
.finish_non_exhaustive()
}
}