use super::classification::{CATEGORIES, QUALIFIERS};
use crate::error::ErrorCode;
use crate::models::Asset;
use crate::{Error, Result};
use serde_json::{json, Map, Value};
use std::{fmt, str::FromStr};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum MockOutcome {
Pending,
Failed,
Allowed,
Limited,
AgeRestricted,
Blocked,
Purged,
}
const OUTCOMES: [MockOutcome; 7] = [
MockOutcome::Pending,
MockOutcome::Failed,
MockOutcome::Allowed,
MockOutcome::Limited,
MockOutcome::AgeRestricted,
MockOutcome::Blocked,
MockOutcome::Purged,
];
impl MockOutcome {
pub fn as_str(self) -> &'static str {
match self {
Self::Pending => "pending",
Self::Failed => "failed",
Self::Allowed => "allowed",
Self::Limited => "limited",
Self::AgeRestricted => "age-restricted",
Self::Blocked => "blocked",
Self::Purged => "purged",
}
}
pub fn is_decided(self) -> bool {
!matches!(self, Self::Pending | Self::Failed)
}
fn action(self) -> &'static str {
match self {
Self::Limited => "limit",
Self::AgeRestricted => "age-restrict",
Self::Blocked => "block",
Self::Purged => "purge",
_ => "allow",
}
}
}
impl fmt::Display for MockOutcome {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
impl FromStr for MockOutcome {
type Err = Error;
fn from_str(value: &str) -> Result<Self> {
OUTCOMES
.into_iter()
.find(|outcome| outcome.as_str() == value)
.ok_or_else(|| {
let known: Vec<&str> = OUTCOMES.iter().map(|outcome| outcome.as_str()).collect();
invalid_argument(format!("status must be one of {}", known.join(", ")))
})
}
}
fn invalid_argument(message: impl Into<String>) -> Error {
Error::new(ErrorCode::InvalidArgument, message)
}
fn likelihood(score: f64) -> &'static str {
if score >= 0.8 {
"very-likely"
} else if score >= 0.6 {
"likely"
} else if score >= 0.4 {
"possible"
} else if score >= 0.2 {
"unlikely"
} else {
"very-unlikely"
}
}
fn is_score(score: f64) -> bool {
score.is_finite() && (0.0..=1.0).contains(&score)
}
#[derive(Clone, Debug, PartialEq)]
struct Flag {
category: &'static str,
score: f64,
qualifiers: Vec<(&'static str, f64)>,
}
#[derive(Clone, Debug, PartialEq)]
pub struct MockDecision {
status: MockOutcome,
flags: Vec<Flag>,
not_evaluated: Vec<&'static str>,
}
impl From<MockOutcome> for MockDecision {
fn from(status: MockOutcome) -> Self {
Self::new(status)
}
}
impl MockDecision {
pub fn new(status: MockOutcome) -> Self {
Self {
status,
flags: Vec::new(),
not_evaluated: Vec::new(),
}
}
pub fn status(&self) -> MockOutcome {
self.status
}
pub fn flag(mut self, category: &str, score: f64, qualifiers: &[(&str, f64)]) -> Result<Self> {
let category = self.check_new(category)?;
if !is_score(score) {
return Err(invalid_argument(format!(
"{category}'s score must be from 0 to 1"
)));
}
let known = QUALIFIERS
.iter()
.find(|(name, _)| *name == category)
.map_or(&[][..], |(_, qualifiers)| qualifiers);
let mut checked: Vec<(&'static str, f64)> = Vec::with_capacity(qualifiers.len());
for &(qualifier, qualifier_score) in qualifiers {
let Some(&qualifier) = known.iter().find(|known| **known == qualifier) else {
return Err(invalid_argument(format!(
"{qualifier} is not a qualifier of {category}"
)));
};
if !is_score(qualifier_score) {
return Err(invalid_argument(format!(
"{qualifier}'s score must be from 0 to 1"
)));
}
if checked.iter().any(|(seen, _)| *seen == qualifier) {
return Err(invalid_argument(format!("{qualifier} is listed twice")));
}
checked.push((qualifier, qualifier_score));
}
self.flags.push(Flag {
category,
score,
qualifiers: checked,
});
Ok(self)
}
pub fn not_evaluated(mut self, category: &str) -> Result<Self> {
let category = self.check_new(category)?;
self.not_evaluated.push(category);
Ok(self)
}
fn check_new(&self, category: &str) -> Result<&'static str> {
let Some(&known) = CATEGORIES.iter().find(|known| **known == category) else {
return Err(invalid_argument(format!(
"{category} is not a CalmLens category"
)));
};
if !self.status.is_decided() {
return Err(invalid_argument(format!(
"a {} decision has no findings",
self.status
)));
}
if self.not_evaluated.contains(&known) || self.flags.iter().any(|f| f.category == known) {
return Err(invalid_argument(format!(
"{known} is already in this decision"
)));
}
Ok(known)
}
fn score_of(&self, category: &str) -> f64 {
self.flags
.iter()
.find(|flag| flag.category == category)
.map_or(0.0, |flag| flag.score)
}
pub(super) fn flagged_categories(&self) -> Vec<&'static str> {
CATEGORIES
.iter()
.copied()
.filter(|category| !self.not_evaluated.contains(category))
.filter(|category| self.action(self.score_of(category)) != "allow")
.collect()
}
fn action(&self, score: f64) -> &'static str {
if self.status != MockOutcome::Allowed && score >= 0.5 {
self.status.action()
} else {
"allow"
}
}
pub(super) fn report(&self) -> Option<Map<String, Value>> {
if !self.status.is_decided() {
return None;
}
let evaluated: Vec<(&str, f64)> = CATEGORIES
.iter()
.filter(|category| !self.not_evaluated.contains(category))
.map(|category| (*category, self.score_of(category)))
.collect();
let mut categories = Map::new();
for category in CATEGORIES {
let result = if self.not_evaluated.contains(category) {
json!({"status": "not-evaluated", "reason": "not-supported"})
} else {
let score = self.score_of(category);
let flag = self.flags.iter().find(|flag| flag.category == *category);
let mut result = json!({
"status": "evaluated", "likelihood": likelihood(score), "score": score,
});
if let Some(flag) = flag.filter(|flag| !flag.qualifiers.is_empty()) {
result["qualifiers"] = flag
.qualifiers
.iter()
.map(|(qualifier, some_score)| {
let result = json!({
"status": "evaluated", "someScore": some_score,
"likelihood": likelihood(*some_score),
});
((*qualifier).to_owned(), result)
})
.collect::<Map<String, Value>>()
.into();
}
result
};
categories.insert((*category).to_owned(), result);
}
let policy_categories: Map<String, Value> = evaluated
.iter()
.map(|(category, score)| {
let action = self.action(*score);
(
(*category).to_owned(),
json!({"score": score, "action": action}),
)
})
.collect();
let mut report = Map::new();
report.insert(
"raw".into(),
json!({"categories": categories, "hashMatches": []}),
);
report.insert("categories".into(), policy_categories.into());
report.insert("explanationComplete".into(), true.into());
report.insert("source".into(), "policy".into());
report.insert("rule".into(), Value::Null);
report.insert("automatedStatus".into(), self.status.as_str().into());
report.insert("regions".into(), json!([]));
report.insert("linkSafety".into(), Value::Null);
report.insert("timeline".into(), Value::Null);
report.insert("flaggedCategories".into(), json!(self.flagged_categories()));
Some(report)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum MockModerationTrigger {
Upload,
Retry,
Rerun,
Complete,
}
impl MockModerationTrigger {
pub fn as_str(self) -> &'static str {
match self {
Self::Upload => "upload",
Self::Retry => "retry",
Self::Rerun => "rerun",
Self::Complete => "complete",
}
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct MockModerationContent {
pub bytes: Option<Vec<u8>>,
pub text: Option<String>,
}
#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct MockModerationInput {
pub asset: Asset,
pub content: MockModerationContent,
pub trigger: MockModerationTrigger,
pub queued: bool,
}
impl MockModerationInput {
pub fn default_decision(&self) -> MockDecision {
if self.queued && self.trigger != MockModerationTrigger::Complete {
MockOutcome::Pending.into()
} else {
MockOutcome::Allowed.into()
}
}
}
pub trait IntoMockDecision {
fn into_mock_decision(self) -> Result<MockDecision>;
}
impl IntoMockDecision for MockDecision {
fn into_mock_decision(self) -> Result<MockDecision> {
Ok(self)
}
}
impl IntoMockDecision for MockOutcome {
fn into_mock_decision(self) -> Result<MockDecision> {
Ok(self.into())
}
}
impl<T: IntoMockDecision> IntoMockDecision for Result<T> {
fn into_mock_decision(self) -> Result<MockDecision> {
self?.into_mock_decision()
}
}