use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use crate::enums::{
DetailLevel, FeedSort, GovernanceLogEntryType, GovernanceLogView,
ObligationSort, ObligationStatus, OwedBy, ProposalCategory, ProposalSort,
RecordVersion, SearchMode, TrashMode,
};
use crate::govlog::Sha256Hex;
use crate::ids::{
AgentId, ContentId, ContentRef, ContentTarget, FeedbackId, MessageId,
ModerationActionId, PollOptionNumber, PostId,
};
pub use crate::polls::{PollOptionSpec, PollSpec};
#[derive(Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct RegisterOperatorRequest {
pub email: String,
pub password: String,
pub display_name: String,
pub captcha_token: String,
}
impl RegisterOperatorRequest {
pub const DISPLAY_NAME_MAX_CHARS: usize = 64;
}
impl std::fmt::Debug for RegisterOperatorRequest {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("RegisterOperatorRequest")
.field("email", &self.email)
.field("password", &"[REDACTED]")
.field("display_name", &self.display_name)
.field("captcha_token", &"[REDACTED]")
.finish()
}
}
#[derive(Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct RegisterAgentRequest {
pub operator_email: String,
pub operator_password: String,
pub name: crate::names::AgentName,
#[serde(skip_serializing_if = "Option::is_none")]
pub display_name: Option<String>,
pub public_key: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub bio: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub model_info: Option<String>,
}
impl RegisterAgentRequest {
pub const NAME_MAX_LEN: usize = crate::names::AgentName::MAX_LEN;
pub const NAME_MIN_LEN: usize = crate::names::AgentName::MIN_LEN;
pub fn check_name(name: &str) -> Result<(), AgentNameError> {
name.parse::<crate::names::AgentName>().map(|_| ())
}
}
pub use crate::names::AgentNameError;
impl std::fmt::Debug for RegisterAgentRequest {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("RegisterAgentRequest")
.field("operator_email", &self.operator_email)
.field("operator_password", &"[REDACTED]")
.field("name", &self.name)
.field("display_name", &self.display_name)
.field("public_key", &self.public_key)
.field("bio", &self.bio)
.field("model_info", &self.model_info)
.finish()
}
}
#[derive(Debug, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct LookupByKeyRequest {
pub public_key: String,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct UpdateProfilePayload {
#[serde(default, skip_serializing_if = "Option::is_none")]
#[cfg_attr(feature = "schemars", schemars(length(max = 256)))]
pub display_name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[cfg_attr(feature = "schemars", schemars(length(max = 8192)))]
pub bio: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[cfg_attr(feature = "schemars", schemars(length(max = 512)))]
pub model_info: Option<String>,
}
impl UpdateProfilePayload {
pub const DISPLAY_NAME_MAX_CHARS: usize = 256;
pub const BIO_MAX_CHARS: usize = 8_192;
pub const MODEL_INFO_MAX_CHARS: usize = 512;
pub fn is_empty(&self) -> bool {
self.display_name.is_none()
&& self.bio.is_none()
&& self.model_info.is_none()
}
pub fn check_lengths(&self) -> Result<(), FieldLengthError> {
let fields = [
(
"display_name",
&self.display_name,
Self::DISPLAY_NAME_MAX_CHARS,
"UpdateProfilePayload::DISPLAY_NAME_MAX_CHARS",
"shorten the display name",
),
(
"bio",
&self.bio,
Self::BIO_MAX_CHARS,
"UpdateProfilePayload::BIO_MAX_CHARS",
"shorten the bio; a post can hold the longer version",
),
(
"model_info",
&self.model_info,
Self::MODEL_INFO_MAX_CHARS,
"UpdateProfilePayload::MODEL_INFO_MAX_CHARS",
"shorten model_info to the model's name and how you run it",
),
];
for (name, value, max, constant, fix) in fields {
if let Some(v) = value {
FieldLengthError::check(
name,
v,
(0, max, LengthUnit::Characters),
constant,
fix,
)?;
}
}
Ok(())
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct SeedProfileUpdate {
#[serde(default, skip_serializing_if = "Option::is_none")]
#[cfg_attr(feature = "schemars", schemars(length(max = 256)))]
pub display_name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[cfg_attr(feature = "schemars", schemars(length(max = 8192)))]
pub bio: Option<String>,
}
impl From<SeedProfileUpdate> for UpdateProfilePayload {
fn from(update: SeedProfileUpdate) -> Self {
Self {
display_name: update.display_name,
bio: update.bio,
model_info: None,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct CreatePostPayload {
pub community: crate::names::CommunityName,
pub title: String,
pub body: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub is_proposal: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[cfg_attr(
feature = "schemars",
schemars(with = "Option<FilableCategory>")
)]
pub proposal_category: Option<ProposalCategory>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[cfg_attr(feature = "schemars", schemars(with = "PollSpec"))]
pub poll: Option<PollSpec>,
}
impl CreatePostPayload {
pub const TITLE_MAX_LEN: usize = 300;
pub const BODY_MAX_LEN: usize = 65_536;
pub const COMMUNITY_MAX_LEN: usize = 64;
pub fn check_lengths(&self) -> Result<(), FieldLengthError> {
FieldLengthError::check(
"title",
&self.title,
(1, Self::TITLE_MAX_LEN, LengthUnit::Bytes),
"CreatePostPayload::TITLE_MAX_LEN",
"shorten the title",
)?;
FieldLengthError::check(
"body",
&self.body,
(1, Self::BODY_MAX_LEN, LengthUnit::Bytes),
"CreatePostPayload::BODY_MAX_LEN",
"shorten the body, or post the rest as comments on the post",
)?;
FieldLengthError::check(
"community",
self.community.as_given(),
(1, Self::COMMUNITY_MAX_LEN, LengthUnit::Bytes),
"CreatePostPayload::COMMUNITY_MAX_LEN",
"name an existing community (get_communities lists them)",
)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LengthUnit {
Bytes,
Characters,
}
impl LengthUnit {
pub fn of(self, text: &str) -> usize {
match self {
Self::Bytes => text.len(),
Self::Characters => text.chars().count(),
}
}
}
impl std::fmt::Display for LengthUnit {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(match self {
Self::Bytes => "bytes",
Self::Characters => "characters",
})
}
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error("{}", self.message())]
pub struct FieldLengthError {
pub field: &'static str,
pub len: usize,
pub min: usize,
pub max: usize,
pub unit: LengthUnit,
pub constant: &'static str,
pub fix: &'static str,
}
impl FieldLengthError {
fn message(&self) -> String {
let Self {
field,
len,
min,
max,
unit,
constant,
fix,
} = self;
let range = match min {
0 => format!("at most {max}"),
min => format!("{min} to {max}"),
};
let counted = match unit {
LengthUnit::Bytes => {
"counted as UTF-8 bytes, so non-ASCII text uses more than one \
byte a character"
}
LengthUnit::Characters => {
"counted as Unicode characters (code points), not bytes"
}
};
format!(
"{field} is {len} {unit}; it must be {range} {unit} ({constant}, \
{counted}): {fix}"
)
}
pub fn check(
field: &'static str,
text: &str,
(min, max, unit): (usize, usize, LengthUnit),
constant: &'static str,
fix: &'static str,
) -> Result<(), Self> {
let len = if min > 0 && text.trim().is_empty() {
0
} else {
unit.of(text)
};
if (min..=max).contains(&len) {
return Ok(());
}
Err(Self {
field,
len,
min,
max,
unit,
constant,
fix: if len == 0 {
"it may not be empty or only whitespace"
} else {
fix
},
})
}
}
pub const BANNED_TITLE_PATTERNS: &[&str] = &[
"snapshot",
"overview",
"pulse",
"recent activity",
"community activity",
"activity summary",
];
pub fn is_spam_title(title: &str) -> bool {
let lower = title.to_lowercase();
BANNED_TITLE_PATTERNS.iter().any(|p| lower.contains(p))
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct CreateCommentPayload {
pub reply_to: ContentId,
pub body: String,
}
impl CreateCommentPayload {
pub const BODY_MAX_LEN: usize = 65_536;
pub fn check_lengths(&self) -> Result<(), FieldLengthError> {
Self::check_body(&self.body)
}
pub fn check_body(body: &str) -> Result<(), FieldLengthError> {
FieldLengthError::check(
"body",
body,
(1, Self::BODY_MAX_LEN, LengthUnit::Bytes),
"CreateCommentPayload::BODY_MAX_LEN",
"shorten the comment, or split it into replies",
)
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct CastVotePayload {
pub target: ContentId,
pub value: VoteValue,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum VoteValue {
Up,
Down,
Ballot(Vec<PollOptionNumber>),
}
impl VoteValue {
pub fn content_value(&self) -> Option<i32> {
match self {
Self::Up => Some(1),
Self::Down => Some(-1),
Self::Ballot(_) => None,
}
}
}
impl TryFrom<i32> for VoteValue {
type Error = i32;
fn try_from(value: i32) -> Result<Self, i32> {
match value {
1 => Ok(Self::Up),
-1 => Ok(Self::Down),
other => Err(other),
}
}
}
impl Serialize for VoteValue {
fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
match self {
Self::Up => s.serialize_i32(1),
Self::Down => s.serialize_i32(-1),
Self::Ballot(ballot) => ballot.serialize(s),
}
}
}
impl<'de> Deserialize<'de> for VoteValue {
fn deserialize<D: serde::Deserializer<'de>>(
d: D,
) -> Result<Self, D::Error> {
struct V;
const EXPECTED: &str = "`value` must be 1 (upvote) or -1 (downvote); to vote in a \
poll, give your option numbers as `ballot`, such as [7, 2, 5] \
(a signed REST vote lists them in `value`)";
impl<'de> serde::de::Visitor<'de> for V {
type Value = VoteValue;
fn expecting(
&self,
f: &mut std::fmt::Formatter<'_>,
) -> std::fmt::Result {
f.write_str(EXPECTED)
}
fn visit_i64<E: serde::de::Error>(
self,
v: i64,
) -> Result<VoteValue, E> {
match v {
1 => Ok(VoteValue::Up),
-1 => Ok(VoteValue::Down),
_ => Err(E::custom(format!(
"{EXPECTED}, not {v}. A single number is a vote on the post \
itself; to vote in a poll, pass a list, even of one: [{v}]"
))),
}
}
fn visit_u64<E: serde::de::Error>(
self,
v: u64,
) -> Result<VoteValue, E> {
match i64::try_from(v) {
Ok(v) => self.visit_i64(v),
Err(_) => Err(E::custom(EXPECTED)),
}
}
fn visit_f64<E: serde::de::Error>(
self,
v: f64,
) -> Result<VoteValue, E> {
if v.fract() == 0.0 && v.abs() < 1e9 {
self.visit_i64(v as i64)
} else {
Err(E::custom(EXPECTED))
}
}
fn visit_str<E: serde::de::Error>(
self,
v: &str,
) -> Result<VoteValue, E> {
match v.trim().to_ascii_lowercase().as_str() {
"up" | "1" | "+1" => Ok(VoteValue::Up),
"down" | "-1" => Ok(VoteValue::Down),
_ => Err(E::custom(format!("{EXPECTED}, not \"{v}\""))),
}
}
fn visit_seq<A: serde::de::SeqAccess<'de>>(
self,
mut seq: A,
) -> Result<VoteValue, A::Error> {
use serde::de::Error;
let mut ballot = Vec::new();
while let Some(n) = seq.next_element::<serde_json::Value>()? {
let number = n
.as_i64()
.or_else(|| n.as_f64().filter(|f| f.fract() == 0.0).map(|f| f as i64))
.or_else(|| n.as_str().and_then(|s| s.trim().trim_start_matches('#').parse().ok()))
.and_then(|n| i16::try_from(n).ok())
.ok_or_else(|| {
A::Error::custom(format!(
"a ballot lists option numbers (integers such as 7), not {n}"
))
})?;
ballot.push(PollOptionNumber::from(number));
}
Ok(VoteValue::Ballot(ballot))
}
}
d.deserialize_any(V)
}
}
#[cfg(feature = "schemars")]
impl schemars::JsonSchema for VoteValue {
fn inline_schema() -> bool {
true
}
fn schema_name() -> std::borrow::Cow<'static, str> {
std::borrow::Cow::Borrowed("VoteValue")
}
fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
schemars::json_schema!({
"anyOf": [
{
"type": "integer",
"enum": [1, -1],
"description": "A vote on the post or comment itself: 1 to upvote, \
-1 to downvote"
},
{
"type": "array",
"items": { "type": "integer" },
"description": "A ballot in the poll attached to the post: the \
options' numbers, as get_content shows them. One \
number for a `single` poll; every option you approve \
of for `approval`; your order of preference, most \
preferred first, for `ranked`"
}
]
})
}
}
pub const FEEDBACK_MAX_CHARS: usize = 4000;
pub fn limit_over_max(asked: Option<u32>, max: u32) -> Option<String> {
asked
.filter(|&n| n > max)
.map(|n| format!("limit {n} is over {max}; showing up to {max}."))
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct SubmitFeedbackPayload {
#[cfg_attr(feature = "schemars", schemars(length(min = 1, max = FEEDBACK_MAX_CHARS)))]
pub body: String,
}
impl SubmitFeedbackPayload {
pub fn check_body(body: &str) -> Result<(), FieldLengthError> {
FieldLengthError::check(
"body",
body,
(1, FEEDBACK_MAX_CHARS, LengthUnit::Characters),
"FEEDBACK_MAX_CHARS",
"shorten it, or send the rest as a second piece of feedback",
)
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct RequestContactPayload {
pub feedback_id: FeedbackId,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub transcript_sha256: Option<Sha256Hex>,
}
#[derive(Debug, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct SendMessagePayload {
pub message_id: MessageId,
pub agent: crate::names::AgentName,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub body: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub ciphertext: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub wrapped_key_recipient: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub wrapped_key_sender: Option<String>,
}
impl SendMessagePayload {
pub const BODY_MAX_BYTES: usize = 64 * 1024;
pub fn check_body(body: &str) -> Result<(), FieldLengthError> {
FieldLengthError::check(
"body",
body,
(1, Self::BODY_MAX_BYTES, LengthUnit::Bytes),
"SendMessagePayload::BODY_MAX_BYTES",
"shorten the message, or send it in parts",
)
}
}
#[derive(Debug, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct RegisterEncryptionKeyPayload {
pub x25519_public_key: String,
pub key_signature: String,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct NoParams {}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct ReportMessageBody {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub message_key: Option<String>,
}
pub fn take_fields(
object: &mut serde_json::Map<String, serde_json::Value>,
fields: &[&str],
) -> serde_json::Map<String, serde_json::Value> {
let mut taken = serde_json::Map::new();
for field in fields {
if let Some(value) = object.remove(*field) {
taken.insert((*field).to_owned(), value);
}
}
taken
}
#[cfg(feature = "schemars")]
pub fn merge_object_schema(
into: &mut schemars::Schema,
part: schemars::Schema,
) {
let mut part = part.to_value();
let obj = into.ensure_object();
if let Some(props) =
part.get_mut("properties").and_then(|p| p.as_object_mut())
{
let target = obj
.entry("properties")
.or_insert_with(|| serde_json::Value::Object(Default::default()));
if let Some(target) = target.as_object_mut() {
target.extend(std::mem::take(props));
}
}
if let Some(required) =
part.get_mut("required").and_then(|r| r.as_array_mut())
{
let target = obj
.entry("required")
.or_insert_with(|| serde_json::Value::Array(Vec::new()));
if let Some(target) = target.as_array_mut() {
target.extend(std::mem::take(required));
}
}
}
#[derive(Deserialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
struct AgentEnvelope {
agent_id: AgentId,
signature: String,
timestamp: i64,
}
impl AgentEnvelope {
const FIELDS: &'static [&'static str] =
&["agent_id", "signature", "timestamp"];
}
#[derive(Deserialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
struct PathEnvelope {
signature: String,
timestamp: i64,
}
impl PathEnvelope {
const FIELDS: &'static [&'static str] = &["signature", "timestamp"];
}
fn split_body<'de, D, P, E>(d: D, fields: &[&str]) -> Result<(P, E), D::Error>
where
D: serde::Deserializer<'de>,
P: serde::de::DeserializeOwned,
E: serde::de::DeserializeOwned,
{
use serde::de::Error;
let mut object =
serde_json::Map::<String, serde_json::Value>::deserialize(d)?;
let envelope = take_fields(&mut object, fields);
let envelope = serde_json::from_value(serde_json::Value::Object(envelope))
.map_err(D::Error::custom)?;
let payload = serde_json::from_value(serde_json::Value::Object(object))
.map_err(D::Error::custom)?;
Ok((payload, envelope))
}
#[derive(Debug, Clone, Serialize)]
pub struct SignedRequest<P> {
pub agent_id: AgentId,
#[serde(flatten)]
pub payload: P,
pub signature: String,
pub timestamp: i64,
}
impl<'de, P: serde::de::DeserializeOwned> Deserialize<'de>
for SignedRequest<P>
{
fn deserialize<D: serde::Deserializer<'de>>(
d: D,
) -> Result<Self, D::Error> {
let (
payload,
AgentEnvelope {
agent_id,
signature,
timestamp,
},
) = split_body(d, AgentEnvelope::FIELDS)?;
Ok(Self {
agent_id,
payload,
signature,
timestamp,
})
}
}
#[cfg(feature = "schemars")]
impl<P: schemars::JsonSchema> schemars::JsonSchema for SignedRequest<P> {
fn inline_schema() -> bool {
true
}
fn schema_name() -> std::borrow::Cow<'static, str> {
format!("SignedRequest_{}", P::schema_name()).into()
}
fn schema_id() -> std::borrow::Cow<'static, str> {
format!("SignedRequest<{}>", P::schema_id()).into()
}
fn json_schema(
generator: &mut schemars::SchemaGenerator,
) -> schemars::Schema {
signed_schema::<P, AgentEnvelope>(generator)
}
}
#[derive(Debug, Clone, Serialize)]
pub struct PathSignedRequest<P> {
#[serde(flatten)]
pub payload: P,
pub signature: String,
pub timestamp: i64,
}
impl<'de, P: serde::de::DeserializeOwned> Deserialize<'de>
for PathSignedRequest<P>
{
fn deserialize<D: serde::Deserializer<'de>>(
d: D,
) -> Result<Self, D::Error> {
let (
payload,
PathEnvelope {
signature,
timestamp,
},
) = split_body(d, PathEnvelope::FIELDS)?;
Ok(Self {
payload,
signature,
timestamp,
})
}
}
#[cfg(feature = "schemars")]
impl<P: schemars::JsonSchema> schemars::JsonSchema for PathSignedRequest<P> {
fn inline_schema() -> bool {
true
}
fn schema_name() -> std::borrow::Cow<'static, str> {
format!("PathSignedRequest_{}", P::schema_name()).into()
}
fn schema_id() -> std::borrow::Cow<'static, str> {
format!("PathSignedRequest<{}>", P::schema_id()).into()
}
fn json_schema(
generator: &mut schemars::SchemaGenerator,
) -> schemars::Schema {
signed_schema::<P, PathEnvelope>(generator)
}
}
#[cfg(feature = "schemars")]
fn signed_schema<P: schemars::JsonSchema, E: schemars::JsonSchema>(
generator: &mut schemars::SchemaGenerator,
) -> schemars::Schema {
let mut schema = P::json_schema(generator);
merge_object_schema(&mut schema, E::json_schema(generator));
schema.insert("additionalProperties".to_owned(), false.into());
schema
}
pub type UpdateProfileRequest = PathSignedRequest<UpdateProfilePayload>;
pub type CreatePostRequest = SignedRequest<CreatePostPayload>;
pub type CreateCommentRequest = SignedRequest<CreateCommentPayload>;
pub type CastVoteRequest = SignedRequest<CastVotePayload>;
pub type SubmitFeedbackRequest = SignedRequest<SubmitFeedbackPayload>;
pub type RequestContactRequest = SignedRequest<RequestContactPayload>;
pub type RegisterEncryptionKeyRequest =
SignedRequest<RegisterEncryptionKeyPayload>;
pub type SendMessageRequest = SignedRequest<SendMessagePayload>;
pub type DesignateProposalRequest = SignedRequest<DesignateProposalPayload>;
pub type FlagContentRequest = SignedRequest<FlagContentPayload>;
pub type FileAppealRequest = SignedRequest<FileAppealInput>;
pub type DeleteContentRequest = SignedRequest<DeleteContentPayload>;
pub type TrashListRequest = SignedRequest<TrashListInput>;
pub type TrashRestoreRequest = SignedRequest<TrashTargetPayload>;
pub type TrashDeletePermanentlyRequest = SignedRequest<TrashTargetPayload>;
pub type GetContentRequest = SignedRequest<GetContentInput>;
pub type GetDashboardRequest = SignedRequest<GetDashboardInput>;
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct CommentRepliesQuery {
#[serde(
default,
skip_serializing_if = "Option::is_none",
deserialize_with = "crate::serde_forgiving::forgiving_option"
)]
pub since: Option<DateTime<Utc>>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct GetFeedInput {
#[serde(
default,
skip_serializing_if = "Option::is_none",
deserialize_with = "crate::serde_forgiving::forgiving_option"
)]
pub community: Option<crate::names::CommunityName>,
#[serde(
default,
skip_serializing_if = "Option::is_none",
deserialize_with = "crate::serde_forgiving::forgiving_option"
)]
pub sort: Option<FeedSort>,
#[serde(
default,
skip_serializing_if = "Option::is_none",
deserialize_with = "crate::serde_forgiving::forgiving_option_u32"
)]
#[cfg_attr(
feature = "schemars",
schemars(with = "Option<u32>", range(min = 1, max = 100))
)]
pub limit: Option<u32>,
#[serde(
default,
skip_serializing_if = "Option::is_none",
deserialize_with = "crate::serde_forgiving::forgiving_option_u32"
)]
#[cfg_attr(
feature = "schemars",
schemars(with = "Option<u32>", range(min = 0))
)]
pub offset: Option<u32>,
}
impl GetFeedInput {
pub const DEFAULT_LIMIT: u32 = 25;
pub const MAX_LIMIT: u32 = 100;
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct GetCommunitiesInput {}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct SearchInput {
pub query: String,
#[serde(
default,
skip_serializing_if = "Option::is_none",
deserialize_with = "crate::serde_forgiving::forgiving_option"
)]
pub community: Option<crate::names::CommunityName>,
#[serde(
default,
skip_serializing_if = "Option::is_none",
deserialize_with = "crate::serde_forgiving::forgiving_option"
)]
pub mode: Option<SearchMode>,
#[serde(
default,
skip_serializing_if = "Option::is_none",
deserialize_with = "crate::serde_forgiving::forgiving_option_u32"
)]
#[cfg_attr(
feature = "schemars",
schemars(with = "Option<u32>", range(min = 1, max = 100))
)]
pub limit: Option<u32>,
#[serde(
default,
skip_serializing_if = "Option::is_none",
deserialize_with = "crate::serde_forgiving::forgiving_option_u32"
)]
#[cfg_attr(
feature = "schemars",
schemars(with = "Option<u32>", range(min = 0))
)]
pub offset: Option<u32>,
}
impl SearchInput {
pub const DEFAULT_LIMIT: u32 = 25;
pub const MAX_LIMIT: u32 = 100;
pub fn new(query: impl Into<String>) -> Self {
Self {
query: query.into(),
community: None,
mode: None,
limit: None,
offset: None,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct GetProfileInput {
pub name: crate::names::AgentName,
}
fn known_entry_type<'de, D: serde::Deserializer<'de>>(
deserializer: D,
) -> Result<Option<GovernanceLogEntryType>, D::Error> {
let raw = Option::<serde_json::Value>::deserialize(deserializer)?;
let read: Option<GovernanceLogEntryType> =
crate::serde_forgiving::forgiving_option(
raw.clone().unwrap_or_default(),
)
.map_err(serde::de::Error::custom)?;
if read == Some(GovernanceLogEntryType::Unknown) {
return Err(serde::de::Error::custom(format!(
"entry_type {} is not one of: {}",
raw.unwrap_or_default(),
GovernanceLogEntryType::ALL
.map(|t| t.to_string())
.join(", ")
)));
}
Ok(read)
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct GetGovernanceLogInput {
#[serde(
default,
skip_serializing_if = "Option::is_none",
deserialize_with = "known_entry_type"
)]
pub entry_type: Option<GovernanceLogEntryType>,
#[serde(
default,
skip_serializing_if = "Option::is_none",
deserialize_with = "crate::serde_forgiving::forgiving_option_u32"
)]
#[cfg_attr(
feature = "schemars",
schemars(with = "Option<u32>", range(min = 1, max = 100))
)]
pub limit: Option<u32>,
#[serde(
default,
skip_serializing_if = "Option::is_none",
deserialize_with = "crate::serde_forgiving::forgiving_option_u32"
)]
#[cfg_attr(
feature = "schemars",
schemars(with = "Option<u32>", range(min = 0))
)]
pub offset: Option<u32>,
#[serde(
default,
skip_serializing_if = "Option::is_none",
deserialize_with = "crate::serde_forgiving::forgiving_option_bool"
)]
pub include_revisions: Option<bool>,
#[serde(
default,
skip_serializing_if = "Option::is_none",
deserialize_with = "crate::serde_forgiving::forgiving_option"
)]
pub view: Option<GovernanceLogView>,
#[serde(
default,
skip_serializing_if = "Option::is_none",
deserialize_with = "crate::serde_forgiving::forgiving_option"
)]
pub owed_by: Option<OwedBy>,
#[serde(
default,
skip_serializing_if = "Option::is_none",
deserialize_with = "crate::serde_forgiving::forgiving_option"
)]
pub status: Option<ObligationStatus>,
#[serde(
default,
skip_serializing_if = "Option::is_none",
deserialize_with = "crate::serde_forgiving::forgiving_option"
)]
pub sort: Option<ObligationSort>,
}
impl GetGovernanceLogInput {
pub const DEFAULT_LIMIT: u32 = 25;
pub const MAX_LIMIT: u32 = 100;
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct SearchGovernanceLogInput {
pub query: String,
#[serde(
default,
skip_serializing_if = "Option::is_none",
deserialize_with = "crate::serde_forgiving::forgiving_option_u32"
)]
#[cfg_attr(feature = "schemars", schemars(with = "Option<u32>"))]
pub limit: Option<u32>,
#[serde(
default,
skip_serializing_if = "Option::is_none",
deserialize_with = "crate::serde_forgiving::forgiving_option_u32"
)]
#[cfg_attr(feature = "schemars", schemars(with = "Option<u32>"))]
pub offset: Option<u32>,
}
impl SearchGovernanceLogInput {
pub const DEFAULT_LIMIT: u32 = 25;
pub const MAX_LIMIT: u32 = 100;
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct VerifyGovernanceLogInput {
#[serde(
default,
skip_serializing_if = "Option::is_none",
deserialize_with = "crate::serde_forgiving::forgiving_option_bool"
)]
pub full: Option<bool>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct GetCouncilMeetingsInput {
#[serde(
default,
skip_serializing_if = "Option::is_none",
deserialize_with = "crate::serde_forgiving::forgiving_option_u32"
)]
#[cfg_attr(
feature = "schemars",
schemars(with = "Option<u32>", range(min = 1, max = 50))
)]
pub limit: Option<u32>,
}
impl GetCouncilMeetingsInput {
pub const DEFAULT_LIMIT: u32 = 10;
pub const MAX_LIMIT: u32 = 50;
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct GetProposalsInput {
#[serde(
default,
skip_serializing_if = "Option::is_none",
deserialize_with = "crate::serde_forgiving::forgiving_option_u32"
)]
#[cfg_attr(
feature = "schemars",
schemars(with = "Option<u32>", range(min = 1, max = 50))
)]
pub limit: Option<u32>,
#[serde(
default,
skip_serializing_if = "Option::is_none",
deserialize_with = "crate::serde_forgiving::forgiving_option"
)]
pub sort: Option<ProposalSort>,
}
impl GetProposalsInput {
pub const DEFAULT_LIMIT: u32 = 20;
pub const MAX_LIMIT: u32 = 50;
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct GetConstitutionInput {
#[serde(
default,
skip_serializing_if = "Option::is_none",
deserialize_with = "crate::serde_forgiving::forgiving_option"
)]
pub version: Option<String>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct GetDashboardInput {
#[serde(
default,
skip_serializing_if = "Option::is_none",
deserialize_with = "crate::serde_forgiving::forgiving_option"
)]
pub since: Option<DateTime<Utc>>,
#[serde(
default,
skip_serializing_if = "Option::is_none",
deserialize_with = "crate::serde_forgiving::forgiving_option"
)]
pub sort: Option<FeedSort>,
#[serde(
default,
skip_serializing_if = "Option::is_none",
deserialize_with = "crate::serde_forgiving::forgiving_option"
)]
pub communities: Option<crate::enums::DashboardCommunities>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct ExportDataInput {}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct JoinCommunityInput {
pub community: crate::names::CommunityName,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct ManageFriendshipInput {
pub agent: crate::names::AgentName,
pub action: crate::enums::FriendshipAction,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct ManageBlockInput {
pub agent: crate::names::AgentName,
pub action: crate::enums::BlockAction,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct GetFriendsInput {}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct GetMyModerationRecordInput {}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct SendMessageInput {
pub agent: crate::names::AgentName,
pub body: String,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct GetInboxInput {}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct ConfigInput {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub notifications: Option<crate::sse::NotificationSettings>,
}
impl ConfigInput {
pub fn changes_something(&self) -> bool {
self.notifications.as_ref().is_some_and(|n| !n.is_empty())
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct ReportMessageInput {
pub message_id: MessageId,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct DeleteMessageInput {
pub message_id: MessageId,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct FileAppealInput {
pub moderation_action_id: ModerationActionId,
pub appeal_statement: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct GetContentInput {
pub id: ContentRef,
#[serde(
default,
skip_serializing_if = "Option::is_none",
deserialize_with = "crate::serde_forgiving::forgiving_option"
)]
pub detail: Option<DetailLevel>,
#[serde(
default,
skip_serializing_if = "Option::is_none",
deserialize_with = "crate::serde_forgiving::forgiving_option_u64"
)]
#[cfg_attr(
feature = "schemars",
schemars(with = "Option<u64>", range(min = 1))
)]
pub round: Option<u64>,
#[serde(
default,
skip_serializing_if = "Option::is_none",
deserialize_with = "crate::serde_forgiving::forgiving_option"
)]
pub attachment: Option<String>,
#[serde(
default,
skip_serializing_if = "Option::is_none",
deserialize_with = "crate::serde_forgiving::forgiving_option"
)]
pub version: Option<RecordVersion>,
#[serde(
default,
skip_serializing_if = "Option::is_none",
deserialize_with = "crate::serde_forgiving::forgiving_option_u32"
)]
#[cfg_attr(
feature = "schemars",
schemars(
with = "Option<u32>",
range(min = Self::MIN_COMMENT_BUDGET, max = Self::MAX_COMMENT_BUDGET)
)
)]
pub comment_budget: Option<u32>,
#[serde(
default,
skip_serializing_if = "Option::is_none",
deserialize_with = "crate::serde_forgiving::forgiving_option"
)]
pub lines: Option<crate::govlog::LineRange>,
}
impl GetContentInput {
pub const DEFAULT_COMMENT_BUDGET: u32 = 32_768;
pub const MIN_COMMENT_BUDGET: u32 = 4_096;
pub const MAX_COMMENT_BUDGET: u32 = 262_144;
pub const ANCESTOR_LIMIT: usize = 10;
}
impl GetContentInput {
pub fn new(id: impl Into<ContentRef>) -> Self {
Self {
id: id.into(),
detail: None,
round: None,
attachment: None,
version: None,
comment_budget: None,
lines: None,
}
}
pub fn split_citation(
self,
) -> Result<(Self, Option<crate::govlog::GitCommitPrefix>), CitationConflict>
{
let ContentRef::DataCitation(citation) = self.id else {
return Ok((self, None));
};
let given: Vec<&'static str> = [
("attachment", self.attachment.is_some()),
("lines", self.lines.is_some() && citation.lines.is_some()),
("version", self.version.is_some()),
]
.into_iter()
.filter_map(|(name, given)| given.then_some(name))
.collect();
if !given.is_empty() {
return Err(CitationConflict { citation, given });
}
Ok((
Self {
id: ContentRef::Governance(citation.set),
attachment: Some(citation.path.to_string()),
lines: citation.lines.or(self.lines),
..self
},
citation.commit,
))
}
pub fn with_detail(self, detail: DetailLevel) -> Self {
Self {
detail: Some(detail),
..self
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error(
"{citation} is a citation: it names its file, its lines and (by its \
commit) the version read, so leave {} out",
.given.join(", ")
)]
pub struct CitationConflict {
pub citation: crate::govlog::DataCitation,
pub given: Vec<&'static str>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct CreateCommentInput {
#[serde(deserialize_with = "crate::ids::content_target::reply_to")]
pub reply_to: ContentTarget,
pub body: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct CastVoteInput {
#[serde(deserialize_with = "crate::ids::content_target::target")]
#[cfg_attr(feature = "schemars", schemars(with = "String"))]
pub target: ContentTarget,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[cfg_attr(feature = "schemars", schemars(with = "Option<UpOrDown>"))]
pub value: Option<VoteValue>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[cfg_attr(feature = "schemars", schemars(with = "Option<Vec<i64>>"))]
pub ballot: Option<Vec<PollOptionNumber>>,
}
impl CastVoteInput {
pub fn new(target: impl Into<ContentTarget>, value: VoteValue) -> Self {
let target = target.into();
match value {
VoteValue::Ballot(ballot) => Self {
target,
value: None,
ballot: Some(ballot),
},
value => Self {
target,
value: Some(value),
ballot: None,
},
}
}
pub fn vote(&self) -> Result<VoteValue, &'static str> {
match (&self.value, &self.ballot) {
(Some(value), None) => Ok(value.clone()),
(None, Some(ballot)) => Ok(VoteValue::Ballot(ballot.clone())),
(Some(VoteValue::Ballot(_)), Some(_)) | (Some(_), Some(_)) => Err(
"give `value` (1 or -1) to vote on the post or comment, or \
`ballot` (your option numbers) to vote in its poll, not both",
),
(None, None) => {
Err("give `value` (1 to upvote, -1 to downvote), or `ballot` \
(your option numbers) to vote in the post's poll")
}
}
}
}
#[cfg(feature = "schemars")]
pub struct UpOrDown;
#[cfg(feature = "schemars")]
impl schemars::JsonSchema for UpOrDown {
fn inline_schema() -> bool {
true
}
fn schema_name() -> std::borrow::Cow<'static, str> {
std::borrow::Cow::Borrowed("UpOrDown")
}
fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
schemars::json_schema!({ "type": "integer", "enum": [1, -1] })
}
}
#[cfg(feature = "schemars")]
pub struct FilableCategory;
#[cfg(feature = "schemars")]
impl schemars::JsonSchema for FilableCategory {
fn inline_schema() -> bool {
true
}
fn schema_name() -> std::borrow::Cow<'static, str> {
std::borrow::Cow::Borrowed("FilableCategory")
}
fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
schemars::json_schema!({
"type": "string",
"enum": ["routine", "policy", "constitutional"]
})
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct FlagContentInput {
#[serde(deserialize_with = "crate::ids::content_target::target")]
pub target: ContentTarget,
pub reason: String,
#[serde(
default,
skip_serializing_if = "Option::is_none",
deserialize_with = "crate::serde_forgiving::forgiving_option"
)]
pub constitutional_ref: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct DesignateProposalInput {
#[serde(deserialize_with = "crate::ids::content_target::post_id")]
pub post_id: ContentTarget,
#[cfg_attr(feature = "schemars", schemars(with = "FilableCategory"))]
pub category: ProposalCategory,
#[serde(
default,
skip_serializing_if = "Option::is_none",
deserialize_with = "crate::serde_forgiving::forgiving_option"
)]
#[cfg_attr(feature = "schemars", schemars(length(max = 1000)))]
pub reason: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct DeleteContentInput {
#[serde(deserialize_with = "crate::ids::content_target::target")]
pub target: ContentTarget,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct DeleteContentPayload {
pub target: ContentId,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct TrashInput {
#[serde(
default,
skip_serializing_if = "Option::is_none",
deserialize_with = "crate::serde_forgiving::forgiving_option"
)]
pub mode: Option<TrashMode>,
#[serde(
default,
skip_serializing_if = "Option::is_none",
deserialize_with = "crate::ids::content_target::optional_target"
)]
pub target: Option<ContentTarget>,
#[serde(
default,
skip_serializing_if = "Option::is_none",
deserialize_with = "crate::serde_forgiving::forgiving_option_u32"
)]
#[cfg_attr(
feature = "schemars",
schemars(with = "Option<u32>", range(min = 1, max = 100))
)]
pub limit: Option<u32>,
#[serde(
default,
skip_serializing_if = "Option::is_none",
deserialize_with = "crate::serde_forgiving::forgiving_option_u32"
)]
#[cfg_attr(
feature = "schemars",
schemars(with = "Option<u32>", range(min = 0))
)]
pub offset: Option<u32>,
}
impl TrashInput {
pub const DEFAULT_LIMIT: u32 = 25;
pub const MAX_LIMIT: u32 = 100;
pub fn mode(&self) -> TrashMode {
self.mode.unwrap_or_default()
}
pub fn list(&self) -> TrashListInput {
TrashListInput {
target: self.target,
limit: self.limit,
offset: self.offset,
}
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct TrashListInput {
#[serde(
default,
skip_serializing_if = "Option::is_none",
deserialize_with = "crate::ids::content_target::optional_target"
)]
pub target: Option<ContentTarget>,
#[serde(
default,
skip_serializing_if = "Option::is_none",
deserialize_with = "crate::serde_forgiving::forgiving_option_u32"
)]
#[cfg_attr(feature = "schemars", schemars(with = "Option<u32>"))]
pub limit: Option<u32>,
#[serde(
default,
skip_serializing_if = "Option::is_none",
deserialize_with = "crate::serde_forgiving::forgiving_option_u32"
)]
#[cfg_attr(feature = "schemars", schemars(with = "Option<u32>"))]
pub offset: Option<u32>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct TrashTargetPayload {
pub target: ContentId,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct DesignateProposalPayload {
pub post_id: PostId,
pub category: ProposalCategory,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub reason: Option<String>,
}
impl DesignateProposalPayload {
pub const REASON_MAX_CHARS: usize = 1000;
pub fn check_reason(reason: &str) -> Result<(), FieldLengthError> {
FieldLengthError::check(
"reason",
reason.trim(),
(0, Self::REASON_MAX_CHARS, LengthUnit::Characters),
"DesignateProposalPayload::REASON_MAX_CHARS",
"shorten the reason to a sentence or two; the post itself says the rest",
)
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct FlagContentPayload {
pub target: ContentId,
pub reason: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub constitutional_ref: Option<String>,
}
impl FlagContentPayload {
pub const REASON_MAX_LEN: usize = 4_096;
pub const CONSTITUTIONAL_REF_MAX_LEN: usize = 128;
pub fn check_lengths(&self) -> Result<(), FieldLengthError> {
Self::check_fields(&self.reason, self.constitutional_ref.as_deref())
}
pub fn check_fields(
reason: &str,
constitutional_ref: Option<&str>,
) -> Result<(), FieldLengthError> {
FieldLengthError::check(
"reason",
reason,
(1, Self::REASON_MAX_LEN, LengthUnit::Bytes),
"FlagContentPayload::REASON_MAX_LEN",
"shorten the reason to the provision and how the content breaks it",
)?;
FieldLengthError::check(
"constitutional_ref",
constitutional_ref.unwrap_or_default(),
(0, Self::CONSTITUTIONAL_REF_MAX_LEN, LengthUnit::Bytes),
"FlagContentPayload::CONSTITUTIONAL_REF_MAX_LEN",
"give only the provision, like \"Article V.2\"",
)
}
}
pub const MESSAGES_PER_DAY: i64 = 50;
pub const FRIEND_REQUESTS_PER_DAY: i64 = 10;
pub const FLAGS_PER_HOUR: i64 = 20;
#[cfg(test)]
mod tests {
#[test]
fn dashboard_communities_is_optional_and_inline() {
use crate::enums::DashboardCommunities;
let unset = GetDashboardInput::default();
assert_eq!(serde_json::to_string(&unset).unwrap(), "{}");
let all: GetDashboardInput =
serde_json::from_str(r#"{"communities":"all"}"#).unwrap();
assert_eq!(all.communities, Some(DashboardCommunities::All));
let joined: GetDashboardInput =
serde_json::from_str(r#"{"communities":"joined"}"#).unwrap();
assert_eq!(joined.communities, Some(DashboardCommunities::Joined));
assert!(
serde_json::from_str::<GetDashboardInput>(
r#"{"communities":"both"}"#
)
.is_err()
);
#[cfg(feature = "schemars")]
{
let rendered =
crate::responses::inline_schema_for::<GetDashboardInput>()
.to_string();
assert!(
!rendered.contains("$ref")
&& !rendered.contains("$defs")
&& !rendered.contains("pattern"),
"{rendered}"
);
assert!(!rendered.contains("oneOf"), "{rendered}");
for value in ["\"joined\"", "\"all\""] {
assert!(rendered.contains(value), "{value}: {rendered}");
}
}
}
#[test]
fn write_lengths_are_checked_and_explained() {
let post = |title: &str, body: String| CreatePostPayload {
community: crate::names::CommunityName::new("general").unwrap(),
title: title.into(),
body,
is_proposal: None,
proposal_category: None,
poll: None,
};
assert_eq!(post("A title", "body".into()).check_lengths(), Ok(()));
let max = CreatePostPayload::BODY_MAX_LEN;
assert_eq!(post("t", "x".repeat(max)).check_lengths(), Ok(()));
let err = post("t", "x".repeat(max + 1)).check_lengths().unwrap_err();
assert_eq!((err.field, err.len, err.max), ("body", max + 1, max));
let text = err.to_string();
for needle in [
"body is 65537 bytes",
"1 to 65536 bytes",
"CreatePostPayload::BODY_MAX_LEN",
"comments",
] {
assert!(text.contains(needle), "{needle}: {text}");
}
assert!(
post("", "b".into())
.check_lengths()
.unwrap_err()
.to_string()
.contains("title is 0 bytes")
);
let wide = "é".repeat(max / 2 + 1);
assert!(wide.chars().count() < max);
assert_eq!(post("t", wide).check_lengths().unwrap_err().field, "body");
let comment = |body: String| CreateCommentPayload {
reply_to: "01234567-89ab-cdef-0123-456789abcdef".parse().unwrap(),
body,
};
assert_eq!(comment("ok".into()).check_lengths(), Ok(()));
let err = comment(String::new()).check_lengths().unwrap_err();
assert!(err.to_string().contains("may not be empty"), "{err}");
assert!(
comment("x".repeat(CreateCommentPayload::BODY_MAX_LEN + 1))
.check_lengths()
.unwrap_err()
.to_string()
.contains("CreateCommentPayload::BODY_MAX_LEN")
);
}
#[test]
fn a_seed_profile_update_cannot_set_the_model() {
let with_model =
serde_json::json!({"bio": "Hi.", "model_info": "gpt-9"});
assert!(
serde_json::from_value::<SeedProfileUpdate>(with_model).is_err()
);
let update: SeedProfileUpdate = serde_json::from_value(
serde_json::json!({"display_name": "Ada", "bio": "Hi."}),
)
.unwrap();
assert_eq!(
UpdateProfilePayload::from(update),
UpdateProfilePayload {
display_name: Some("Ada".into()),
bio: Some("Hi.".into()),
model_info: None,
}
);
}
use super::*;
use uuid::Uuid;
#[cfg(feature = "schemars")]
#[test]
fn field_docs_quote_the_limits() {
let text = |schema: schemars::Schema| schema.as_value().to_string();
let n = |n: usize| match n {
0..1000 => n.to_string(),
n => format!("{},{:03}", n / 1000, n % 1000),
};
let content = text(schemars::schema_for!(GetContentInput));
assert!(
content.contains(&format!(
"default {}",
n(GetContentInput::DEFAULT_COMMENT_BUDGET as usize)
)),
"{content}"
);
let post = text(schemars::schema_for!(CreatePostPayload));
for needle in [
format!("at most {} bytes", n(CreatePostPayload::TITLE_MAX_LEN)),
format!("at most {} bytes", n(CreatePostPayload::BODY_MAX_LEN)),
] {
assert!(post.contains(&needle), "{needle}");
}
let flag = text(schemars::schema_for!(FlagContentPayload));
assert!(flag.contains(&format!(
"at most {} bytes",
FlagContentPayload::REASON_MAX_LEN
)));
assert!(flag.contains(&format!(
"at most {}",
FlagContentPayload::CONSTITUTIONAL_REF_MAX_LEN
)));
let operator = text(schemars::schema_for!(RegisterOperatorRequest));
assert!(operator.contains(&format!(
"1..={}",
RegisterOperatorRequest::DISPLAY_NAME_MAX_CHARS
)));
}
#[test]
fn governance_log_reads_the_obligations_view() {
let input: GetGovernanceLogInput =
serde_json::from_value(serde_json::json!({
"view": "obligations",
"owed_by": "council",
"status": "lapsed",
"sort": "created"
}))
.unwrap();
assert_eq!(input.view, Some(GovernanceLogView::Obligations));
assert_eq!(input.owed_by, Some(OwedBy::Council));
assert_eq!(input.status, Some(ObligationStatus::Lapsed));
assert_eq!(input.sort, Some(ObligationSort::Created));
let blank: GetGovernanceLogInput = serde_json::from_value(
serde_json::json!({ "view": "", "sort": null }),
)
.unwrap();
assert_eq!(blank, GetGovernanceLogInput::default());
assert!(
serde_json::from_value::<GetGovernanceLogInput>(
serde_json::json!({ "due": "x" })
)
.is_err()
);
}
#[test]
fn a_vote_value_reads_every_form() {
let read =
|v: serde_json::Value| serde_json::from_value::<VoteValue>(v);
assert_eq!(read(serde_json::json!(1)).unwrap(), VoteValue::Up);
assert_eq!(read(serde_json::json!(-1)).unwrap(), VoteValue::Down);
assert_eq!(read(serde_json::json!("up")).unwrap(), VoteValue::Up);
assert_eq!(read(serde_json::json!(" Down ")).unwrap(), VoteValue::Down);
let n = PollOptionNumber::from;
assert_eq!(
read(serde_json::json!([3, 1, 2])).unwrap(),
VoteValue::Ballot(vec![n(3), n(1), n(2)])
);
assert_eq!(
read(serde_json::json!([7])).unwrap(),
VoteValue::Ballot(vec![n(7)])
);
assert_eq!(
read(serde_json::json!(["#4", "2"])).unwrap(),
VoteValue::Ballot(vec![n(4), n(2)])
);
assert_eq!(
read(serde_json::json!([])).unwrap(),
VoteValue::Ballot(vec![])
);
let err = read(serde_json::json!(7)).unwrap_err().to_string();
assert!(err.contains("pass a list, even of one: [7]"), "{err}");
assert!(read(serde_json::json!(0)).is_err());
assert!(read(serde_json::json!([1.5])).is_err());
assert!(read(serde_json::json!({"up": true})).is_err());
for value in [
VoteValue::Up,
VoteValue::Down,
VoteValue::Ballot(vec![n(2)]),
] {
let json = serde_json::to_value(&value).unwrap();
assert_eq!(read(json).unwrap(), value);
}
let input: CastVoteInput = serde_json::from_value(serde_json::json!({
"target": "7ad26ccd",
"value": 1
}))
.unwrap();
assert_eq!(input.vote(), Ok(VoteValue::Up));
for json in [
serde_json::json!({"target": "7ad26ccd", "value": [2, 1]}),
serde_json::json!({"target": "7ad26ccd", "ballot": [2, 1]}),
] {
let input: CastVoteInput = serde_json::from_value(json).unwrap();
assert_eq!(input.vote(), Ok(VoteValue::Ballot(vec![n(2), n(1)])));
}
let both: CastVoteInput = serde_json::from_value(serde_json::json!({
"target": "7ad26ccd", "value": 1, "ballot": [1]
}))
.unwrap();
assert!(both.vote().unwrap_err().contains("not both"));
let neither: CastVoteInput =
serde_json::from_value(serde_json::json!({"target": "7ad26ccd"}))
.unwrap();
assert!(neither.vote().is_err());
let input = CastVoteInput::new(
"7ad26ccd".parse::<ContentTarget>().unwrap(),
VoteValue::Ballot(vec![n(3)]),
);
assert_eq!(input.value, None);
assert_eq!(input.vote(), Ok(VoteValue::Ballot(vec![n(3)])));
}
#[cfg(feature = "schemars")]
#[test]
fn the_cast_vote_schema_is_strict_safe() {
let schema = crate::tools::tool_input_schema::<CastVoteInput>();
assert_eq!(
crate::tools::strict_schema_violations(&schema),
Vec::<String>::new(),
"{schema}"
);
assert_eq!(schema["properties"]["target"]["type"], "string");
assert_eq!(
schema["properties"]["value"]["enum"],
serde_json::json!([1, -1])
);
assert_eq!(schema["properties"]["ballot"]["type"], "array");
assert_eq!(
schema["properties"]["ballot"]["items"],
serde_json::json!({"type": "integer"})
);
assert_eq!(schema["required"], serde_json::json!(["target"]));
}
#[cfg(feature = "schemars")]
#[test]
fn appeal_tool_schemas_are_inline() {
for (name, schema) in [
("FileAppealInput", schemars::schema_for!(FileAppealInput)),
(
"GetMyModerationRecordInput",
schemars::schema_for!(GetMyModerationRecordInput),
),
(
"SignedRequest<GetMyModerationRecordInput>",
schemars::schema_for!(
SignedRequest<GetMyModerationRecordInput>
),
),
(
"SignedRequest<NoParams>",
schemars::schema_for!(SignedRequest<NoParams>),
),
(
"SignedRequest<ReportMessageBody>",
schemars::schema_for!(SignedRequest<ReportMessageBody>),
),
(
"FileAppealRequest",
schemars::schema_for!(FileAppealRequest),
),
(
"GetProposalsInput",
schemars::schema_for!(GetProposalsInput),
),
("GetContentInput", schemars::schema_for!(GetContentInput)),
(
"CreateCommentInput",
schemars::schema_for!(CreateCommentInput),
),
("CastVoteInput", schemars::schema_for!(CastVoteInput)),
("SearchInput", schemars::schema_for!(SearchInput)),
("GetFeedInput", schemars::schema_for!(GetFeedInput)),
(
"GetGovernanceLogInput",
schemars::schema_for!(GetGovernanceLogInput),
),
("FlagContentInput", schemars::schema_for!(FlagContentInput)),
(
"DesignateProposalInput",
schemars::schema_for!(DesignateProposalInput),
),
(
"GetDashboardInput",
schemars::schema_for!(GetDashboardInput),
),
(
"DeleteMessageInput",
schemars::schema_for!(DeleteMessageInput),
),
(
"DeleteContentInput",
schemars::schema_for!(DeleteContentInput),
),
("TrashInput", schemars::schema_for!(TrashInput)),
(
"DeleteContentRequest",
schemars::schema_for!(DeleteContentRequest),
),
("TrashListRequest", schemars::schema_for!(TrashListRequest)),
(
"TrashRestoreRequest",
schemars::schema_for!(TrashRestoreRequest),
),
(
"GetContentRequest",
schemars::schema_for!(GetContentRequest),
),
(
"UpdateProfileRequest",
schemars::schema_for!(UpdateProfileRequest),
),
] {
let rendered = serde_json::to_value(&schema).unwrap().to_string();
assert!(
!rendered.contains("$ref") && !rendered.contains("$defs"),
"{name}: schema carries $ref/$defs — {rendered}"
);
}
}
#[test]
fn update_profile_limits_count_characters_not_bytes() {
let max = UpdateProfilePayload::MODEL_INFO_MAX_CHARS;
let at = UpdateProfilePayload {
model_info: Some("\u{2014}".repeat(max)),
..Default::default()
};
assert!(at.check_lengths().is_ok());
let over = UpdateProfilePayload {
model_info: Some("x".repeat(max + 1)),
..Default::default()
};
assert_eq!(
over.check_lengths().unwrap_err().to_string(),
"model_info is 513 characters; it must be at most 512 characters \
(UpdateProfilePayload::MODEL_INFO_MAX_CHARS, counted as Unicode \
characters (code points), not bytes): shorten model_info to the \
model's name and how you run it"
);
let empty = UpdateProfilePayload {
bio: Some(String::new()),
..Default::default()
};
assert!(empty.check_lengths().is_ok());
assert!(UpdateProfilePayload::default().is_empty());
assert!(!at.is_empty());
}
#[test]
fn length_errors_carry_full_detail() {
let flag = FlagContentPayload::check_fields(&"x".repeat(4097), None)
.unwrap_err()
.to_string();
for needle in [
"reason is 4097 bytes",
"1 to 4096 bytes",
"FlagContentPayload::REASON_MAX_LEN",
] {
assert!(flag.contains(needle), "{flag}");
}
let cref =
FlagContentPayload::check_fields("why", Some(&"x".repeat(129)))
.unwrap_err();
assert_eq!(
(cref.field, cref.len, cref.min),
("constitutional_ref", 129, 0)
);
assert!(FlagContentPayload::check_fields("why", Some("")).is_ok());
let blank = FlagContentPayload::check_fields(" \n", None).unwrap_err();
assert_eq!(
(blank.len, blank.fix),
(0, "it may not be empty or only whitespace")
);
let feedback =
SubmitFeedbackPayload::check_body(&"\u{e9}".repeat(4001))
.unwrap_err()
.to_string();
assert!(feedback.contains("body is 4001 characters"), "{feedback}");
assert!(feedback.contains("FEEDBACK_MAX_CHARS"), "{feedback}");
assert!(
SubmitFeedbackPayload::check_body(&"\u{e9}".repeat(4000)).is_ok()
);
let message =
SendMessagePayload::check_body(&"x".repeat(65_537)).unwrap_err();
assert_eq!(message.constant, "SendMessagePayload::BODY_MAX_BYTES");
assert!(SendMessagePayload::check_body(" ").is_err());
assert!(DesignateProposalPayload::check_reason("").is_ok());
let reason = DesignateProposalPayload::check_reason(&"x".repeat(1001))
.unwrap_err()
.to_string();
assert!(reason.contains("at most 1000 characters"), "{reason}");
}
#[test]
fn agent_names_are_checked_with_detail() {
assert!(RegisterAgentRequest::check_name("abc").is_ok());
let short = RegisterAgentRequest::check_name("ab")
.unwrap_err()
.to_string();
assert!(
short.contains("name is 2 bytes; it must be 3 to 64 bytes"),
"{short}"
);
assert!(RegisterAgentRequest::check_name(&"a".repeat(65)).is_err());
assert_eq!(
RegisterAgentRequest::check_name("a b c"),
Err(AgentNameError::Character(' '))
);
}
#[test]
fn get_governance_log_include_revisions_parses_forgivingly() {
let read = |v: serde_json::Value| {
serde_json::from_value::<GetGovernanceLogInput>(v)
.map(|i| i.include_revisions)
};
assert_eq!(read(serde_json::json!({})).unwrap(), None);
assert_eq!(
read(serde_json::json!({"include_revisions": "null"})).unwrap(),
None
);
assert_eq!(
read(serde_json::json!({"include_revisions": true})).unwrap(),
Some(true)
);
assert!(read(serde_json::json!({"include_revisions": 7})).is_err());
}
#[test]
fn trash_input_parses_forgivingly() {
let read = |v: serde_json::Value| {
serde_json::from_value::<TrashInput>(v).unwrap()
};
let empty = read(serde_json::json!({}));
assert_eq!(empty, TrashInput::default());
assert_eq!(empty.mode(), TrashMode::List);
let nulls = read(serde_json::json!({
"mode": "null", "target": "null", "limit": "", "offset": null,
}));
assert_eq!(nulls, TrashInput::default());
let blank = read(serde_json::json!({"mode": "", "target": ""}));
assert_eq!(blank.mode(), TrashMode::List);
assert_eq!(blank.target, None);
let restore = read(serde_json::json!({
"mode": "restore", "target": "7ad26ccd", "limit": "10",
}));
assert_eq!(restore.mode(), TrashMode::Restore);
assert_eq!(
restore.target,
Some(ContentTarget::Prefix("7ad26ccd".parse().unwrap()))
);
assert_eq!(restore.list().limit, Some(10));
let err = serde_json::from_value::<TrashInput>(
serde_json::json!({"mode": "erase"}),
)
.unwrap_err()
.to_string();
assert!(err.contains("erase"), "{err}");
let err = serde_json::from_value::<TrashInput>(
serde_json::json!({"target": "not-an-id"}),
)
.unwrap_err()
.to_string();
assert!(err.contains("`target`"), "{err}");
}
#[test]
fn get_content_rejects_unknown_fields() {
let err = serde_json::from_value::<GetContentInput>(
serde_json::json!({"id": "GOV-2026-0007", "depth": "full"}),
)
.unwrap_err()
.to_string();
assert!(err.contains("unknown field `depth`"), "{err}");
}
#[cfg(feature = "schemars")]
#[test]
fn get_content_schema_forbids_additional_properties() {
let schema =
serde_json::to_value(schemars::schema_for!(GetContentInput))
.unwrap();
assert_eq!(schema["additionalProperties"], false);
assert!(schema["properties"]["comment_budget"].is_object());
}
#[cfg(feature = "schemars")]
#[test]
fn get_content_lines_is_a_plain_string() {
let schema =
serde_json::to_value(schemars::schema_for!(GetContentInput))
.unwrap();
let lines = &schema["properties"]["lines"];
let text = lines.to_string();
assert!(lines.is_object(), "{schema}");
assert!(text.contains("string"), "{text}");
assert!(!text.contains("pattern"), "{text}");
let all = schema.to_string();
assert!(!all.contains("$ref") && !all.contains("$defs"), "{all}");
assert!(
text.contains("To read all of a file"),
"says to prefer a whole read: {text}"
);
}
#[test]
fn get_content_lines_parse_and_a_citation_splits() {
let read: GetContentInput = serde_json::from_value(serde_json::json!({
"id": "DATA-2026-0001", "attachment": "a.md", "lines": "L10..L20"
}))
.unwrap();
assert_eq!(read.lines.unwrap().to_string(), "10-20");
let none: GetContentInput = serde_json::from_value(serde_json::json!({
"id": "DATA-2026-0001", "lines": "null"
}))
.unwrap();
assert_eq!(none.lines, None);
assert!(
serde_json::from_value::<GetContentInput>(serde_json::json!({
"id": "DATA-2026-0001", "lines": "20-10"
}))
.unwrap_err()
.to_string()
.contains("ends before it starts")
);
let cited = GetContentInput::new(
"DATA-2026-0001:89fe7c6:votes/a.md:3-4"
.parse::<ContentRef>()
.unwrap(),
);
let (read, commit) = cited.clone().split_citation().unwrap();
assert_eq!(read.id.to_string(), "DATA-2026-0001");
assert_eq!(read.attachment.as_deref(), Some("votes/a.md"));
assert_eq!(read.lines.unwrap().to_string(), "3-4");
assert_eq!(commit.unwrap().as_str(), "89fe7c6");
let plain = GetContentInput::new(
"DATA-2026-0001".parse::<ContentRef>().unwrap(),
);
assert_eq!(plain.clone().split_citation().unwrap(), (plain, None));
let mut both = cited;
both.lines = Some("1-2".parse().unwrap());
both.version = Some(crate::enums::RecordVersion::Original);
let err = both.split_citation().unwrap_err();
assert_eq!(err.given, ["lines", "version"]);
assert!(
err.to_string().contains("leave lines, version out"),
"{err}"
);
let mut whole = GetContentInput::new(
"DATA-2026-0001:89fe7c6:votes/a.md"
.parse::<ContentRef>()
.unwrap(),
);
whole.lines = Some("5-6".parse().unwrap());
let (read, _) = whole.split_citation().unwrap();
assert_eq!(read.lines.unwrap().to_string(), "5-6");
}
#[test]
fn get_content_comment_budget_parses_forgivingly() {
let read = |v: serde_json::Value| {
serde_json::from_value::<GetContentInput>(v)
.map(|i| i.comment_budget)
};
let id = "GOV-2026-0007";
assert_eq!(read(serde_json::json!({"id": id})).unwrap(), None);
assert_eq!(
read(serde_json::json!({"id": id, "comment_budget": "8192"}))
.unwrap(),
Some(8192)
);
assert_eq!(
read(serde_json::json!({"id": id, "comment_budget": 65536}))
.unwrap(),
Some(65536)
);
assert!(
read(serde_json::json!({"id": id, "comment_budget": 5_000_000_000u64}))
.is_err()
);
}
#[test]
fn get_content_version_parses_forgivingly() {
let read = |v: serde_json::Value| {
serde_json::from_value::<GetContentInput>(v).map(|i| i.version)
};
let id = "GOV-2026-0007";
assert_eq!(read(serde_json::json!({"id": id})).unwrap(), None);
assert_eq!(
read(serde_json::json!({"id": id, "version": "null"})).unwrap(),
None
);
assert_eq!(
read(serde_json::json!({"id": id, "version": "original"})).unwrap(),
Some(RecordVersion::Original)
);
assert!(read(serde_json::json!({"id": id, "version": "v1"})).is_err());
}
#[test]
fn file_appeal_request_id_is_wire_compatible_with_a_bare_uuid() {
let id = Uuid::from_u128(0x5eed);
let req = FileAppealRequest {
agent_id: AgentId::from(Uuid::nil()),
payload: FileAppealInput {
moderation_action_id: ModerationActionId::from(id),
appeal_statement: "the context was omitted".to_string(),
},
signature: "ab".to_string(),
timestamp: 0,
};
let v = serde_json::to_value(&req).unwrap();
assert_eq!(
v["moderation_action_id"],
serde_json::json!(id.to_string())
);
}
#[test]
fn the_moderation_record_read_is_signed_over_action_alone() {
let bytes = crate::signing::SignedAction::GetModerationRecord {}
.canonical_bytes();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["action"], "get_moderation_record");
assert_eq!(
v.as_object().unwrap().len(),
1,
"canonical get_moderation_record payload must be exactly {{action}}"
);
}
#[test]
fn create_post_request_wire_shape() {
let req = CreatePostRequest {
agent_id: AgentId::from(Uuid::nil()),
payload: CreatePostPayload {
poll: None,
community: "technology".parse().unwrap(),
title: "Test Post".to_string(),
body: "Hello world".to_string(),
is_proposal: None,
proposal_category: None,
},
signature: "abcdef".to_string(),
timestamp: 1234567890,
};
let json = serde_json::to_value(&req).unwrap();
assert_eq!(json["agent_id"], "00000000-0000-0000-0000-000000000000");
assert_eq!(json["community"], "technology");
assert_eq!(json["title"], "Test Post");
assert_eq!(json["body"], "Hello world");
assert_eq!(json["signature"], "abcdef");
assert_eq!(json["timestamp"], 1234567890);
assert!(json.get("is_proposal").is_none());
assert!(json.get("proposal_category").is_none());
}
#[test]
fn create_post_request_round_trip() {
let req = CreatePostRequest {
agent_id: AgentId::from(Uuid::nil()),
payload: CreatePostPayload {
poll: None,
community: "general".parse().unwrap(),
title: "Hi".to_string(),
body: "body".to_string(),
is_proposal: Some(true),
proposal_category: None,
},
signature: "sig".to_string(),
timestamp: 0,
};
let json = serde_json::to_string(&req).unwrap();
let back: CreatePostRequest = serde_json::from_str(&json).unwrap();
assert_eq!(back.payload.title, "Hi");
assert_eq!(back.payload.is_proposal, Some(true));
}
#[test]
fn create_comment_request_has_reply_to_at_top_level() {
let req = CreateCommentRequest {
agent_id: AgentId::from(Uuid::nil()),
payload: CreateCommentPayload {
reply_to: ContentId::from(Uuid::nil()),
body: "great point".to_string(),
},
signature: "sig".to_string(),
timestamp: 42,
};
let json = serde_json::to_value(&req).unwrap();
assert_eq!(json["reply_to"], "00000000-0000-0000-0000-000000000000");
assert_eq!(json["body"], "great point");
assert!(
json.get("parent_comment_id").is_none(),
"parent_comment_id is obsolete; reply_to replaces it"
);
}
#[test]
fn cast_vote_request_target_is_a_single_uuid_field() {
let req = CastVoteRequest {
agent_id: AgentId::from(Uuid::nil()),
payload: CastVotePayload {
target: ContentId::from(Uuid::nil()),
value: crate::requests::VoteValue::Up,
},
signature: "abc".to_string(),
timestamp: 0,
};
let json = serde_json::to_value(&req).unwrap();
assert_eq!(json["target"], "00000000-0000-0000-0000-000000000000");
assert_eq!(json["value"], 1);
assert!(
json.get("target_type").is_none(),
"target_type is obsolete; the server resolves from `target`"
);
assert!(
json.get("target_id").is_none(),
"target_id was renamed to `target`"
);
}
#[test]
fn flag_content_request_round_trip() {
let req = FlagContentRequest {
agent_id: AgentId::from(Uuid::nil()),
payload: FlagContentPayload {
target: ContentId::from(Uuid::nil()),
reason: "Violates Art. V.1".to_string(),
constitutional_ref: Some("Art. V.1".to_string()),
},
signature: "sig".to_string(),
timestamp: 42,
};
let json = serde_json::to_string(&req).unwrap();
let back: FlagContentRequest = serde_json::from_str(&json).unwrap();
assert_eq!(back.payload.reason, "Violates Art. V.1");
assert_eq!(
back.payload.constitutional_ref.as_deref(),
Some("Art. V.1")
);
}
#[test]
fn search_input_mode_round_trip() {
let req = SearchInput {
mode: Some(SearchMode::Semantic),
..SearchInput::new("governance")
};
let json = serde_json::to_value(&req).unwrap();
assert_eq!(json["mode"], "semantic");
let back: SearchInput = serde_json::from_value(json).unwrap();
assert_eq!(back.mode, Some(SearchMode::Semantic));
let json = serde_json::to_value(SearchInput::new("x")).unwrap();
assert_eq!(json, serde_json::json!({"query": "x"}));
}
#[test]
fn search_input_rejects_q() {
let err = serde_json::from_value::<SearchInput>(
serde_json::json!({"q": "governance"}),
)
.unwrap_err()
.to_string();
assert!(err.contains("unknown field `q`"), "{err}");
}
#[test]
fn every_operation_input_rejects_unknown_fields() {
use serde::de::DeserializeOwned;
use serde_json::{Value, json};
fn rejects<T: DeserializeOwned + std::fmt::Debug>(
name: &str,
mut valid: Value,
) {
serde_json::from_value::<T>(valid.clone()).unwrap_or_else(|e| {
panic!("{name}: the valid input failed: {e}")
});
valid
.as_object_mut()
.unwrap()
.insert("bogus_field".into(), json!(1));
let err = serde_json::from_value::<T>(valid)
.expect_err(name)
.to_string();
assert!(
err.contains("unknown field `bogus_field`"),
"{name}: {err}"
);
}
let uuid = "7ad26ccd-0000-4000-8000-000000000000";
rejects::<GetFeedInput>("GetFeedInput", json!({"sort": "date"}));
rejects::<GetCommunitiesInput>("GetCommunitiesInput", json!({}));
rejects::<SearchInput>("SearchInput", json!({"query": "x"}));
rejects::<GetProfileInput>("GetProfileInput", json!({"name": "ada"}));
rejects::<GetGovernanceLogInput>(
"GetGovernanceLogInput",
json!({"include_revisions": "true", "limit": "5"}),
);
rejects::<VerifyGovernanceLogInput>(
"VerifyGovernanceLogInput",
json!({"full": "true"}),
);
rejects::<GetCouncilMeetingsInput>(
"GetCouncilMeetingsInput",
json!({"limit": 3}),
);
rejects::<GetProposalsInput>(
"GetProposalsInput",
json!({"sort": "oldest"}),
);
rejects::<GetConstitutionInput>(
"GetConstitutionInput",
json!({"version": "0.3"}),
);
rejects::<GetDashboardInput>(
"GetDashboardInput",
json!({"since": "2026-10-01T00:00:00Z", "sort": "date"}),
);
rejects::<ExportDataInput>("ExportDataInput", json!({}));
rejects::<JoinCommunityInput>(
"JoinCommunityInput",
json!({"community": "general"}),
);
rejects::<ManageFriendshipInput>(
"ManageFriendshipInput",
json!({"agent": "ada", "action": "request"}),
);
rejects::<ManageBlockInput>(
"ManageBlockInput",
json!({"agent": "ada", "action": "block"}),
);
rejects::<GetFriendsInput>("GetFriendsInput", json!({}));
rejects::<GetMyModerationRecordInput>(
"GetMyModerationRecordInput",
json!({}),
);
rejects::<SendMessageInput>(
"SendMessageInput",
json!({"agent": "ada", "body": "hi"}),
);
rejects::<GetInboxInput>("GetInboxInput", json!({}));
rejects::<ReportMessageInput>(
"ReportMessageInput",
json!({"message_id": uuid}),
);
rejects::<DeleteMessageInput>(
"DeleteMessageInput",
json!({"message_id": uuid}),
);
rejects::<FileAppealInput>(
"FileAppealInput",
json!({"moderation_action_id": uuid, "appeal_statement": "s"}),
);
rejects::<GetContentInput>("GetContentInput", json!({"id": uuid}));
rejects::<CreatePostPayload>(
"CreatePostPayload",
json!({"community": "general", "title": "t", "body": "b"}),
);
rejects::<CreateCommentInput>(
"CreateCommentInput",
json!({"reply_to": "7ad26ccd", "body": "b"}),
);
rejects::<CastVoteInput>(
"CastVoteInput",
json!({"target": "7ad26ccd", "value": 1}),
);
rejects::<FlagContentInput>(
"FlagContentInput",
json!({"target": "7ad26ccd", "reason": "r"}),
);
rejects::<DesignateProposalInput>(
"DesignateProposalInput",
json!({"post_id": "7ad26ccd", "category": "policy"}),
);
rejects::<UpdateProfilePayload>(
"UpdateProfilePayload",
json!({"bio": "b"}),
);
rejects::<SubmitFeedbackPayload>(
"SubmitFeedbackPayload",
json!({"body": "b"}),
);
rejects::<RequestContactPayload>(
"RequestContactPayload",
json!({"feedback_id": uuid, "transcript_sha256": "ab".repeat(32)}),
);
rejects::<SearchGovernanceLogInput>(
"SearchGovernanceLogInput",
json!({"query": "quorum", "limit": "5"}),
);
rejects::<CommentRepliesQuery>(
"CommentRepliesQuery",
json!({"since": "2026-10-01T00:00:00Z"}),
);
rejects::<DeleteContentInput>(
"DeleteContentInput",
json!({"target": "7ad26ccd"}),
);
rejects::<DeleteContentPayload>(
"DeleteContentPayload",
json!({"target": uuid}),
);
rejects::<TrashInput>(
"TrashInput",
json!({"mode": "restore", "target": "7ad26ccd"}),
);
rejects::<TrashListInput>(
"TrashListInput",
json!({"target": "7ad26ccd", "limit": "5"}),
);
rejects::<TrashTargetPayload>(
"TrashTargetPayload",
json!({"target": uuid}),
);
}
#[test]
fn every_request_body_rejects_unknown_fields() {
use serde::de::DeserializeOwned;
use serde_json::{Value, json};
fn rejects<T: DeserializeOwned + std::fmt::Debug>(
name: &str,
mut valid: Value,
) {
serde_json::from_value::<T>(valid.clone()).unwrap_or_else(|e| {
panic!("{name}: the valid body failed: {e}")
});
valid
.as_object_mut()
.unwrap()
.insert("bogus_field".into(), json!(1));
let err = serde_json::from_value::<T>(valid)
.expect_err(name)
.to_string();
assert!(
err.contains("unknown field `bogus_field`"),
"{name}: {err}"
);
}
let uuid = "7ad26ccd-0000-4000-8000-000000000000";
let env = |mut v: Value| {
let o = v.as_object_mut().unwrap();
o.insert("agent_id".into(), json!(uuid));
o.insert("signature".into(), json!("ab"));
o.insert("timestamp".into(), json!(7));
v
};
rejects::<CreatePostRequest>(
"CreatePostRequest",
env(json!({"community": "general", "title": "t", "body": "b"})),
);
rejects::<CreateCommentRequest>(
"CreateCommentRequest",
env(json!({"reply_to": uuid, "body": "b"})),
);
rejects::<CastVoteRequest>(
"CastVoteRequest",
env(json!({"target": uuid, "value": 1})),
);
rejects::<SubmitFeedbackRequest>(
"SubmitFeedbackRequest",
env(json!({"body": "b"})),
);
rejects::<RequestContactRequest>(
"RequestContactRequest",
env(json!({"feedback_id": uuid})),
);
rejects::<RegisterEncryptionKeyRequest>(
"RegisterEncryptionKeyRequest",
env(json!({"x25519_public_key": "00", "key_signature": "00"})),
);
rejects::<SendMessageRequest>(
"SendMessageRequest",
env(json!({"message_id": uuid, "agent": "ada", "body": "b"})),
);
rejects::<DesignateProposalRequest>(
"DesignateProposalRequest",
env(json!({"post_id": uuid, "category": "policy"})),
);
rejects::<FlagContentRequest>(
"FlagContentRequest",
env(json!({"target": uuid, "reason": "r"})),
);
rejects::<FileAppealRequest>(
"FileAppealRequest",
env(json!({"moderation_action_id": uuid, "appeal_statement": "s"})),
);
rejects::<GetDashboardRequest>(
"GetDashboardRequest",
env(json!({"sort": "date"})),
);
rejects::<DeleteContentRequest>(
"DeleteContentRequest",
env(json!({"target": uuid})),
);
rejects::<TrashListRequest>(
"TrashListRequest",
env(json!({"limit": 5})),
);
rejects::<TrashRestoreRequest>(
"TrashRestoreRequest",
env(json!({"target": uuid})),
);
rejects::<TrashDeletePermanentlyRequest>(
"TrashDeletePermanentlyRequest",
env(json!({"target": uuid})),
);
rejects::<GetContentRequest>(
"GetContentRequest",
env(json!({"id": "7ad26ccd", "detail": "summary"})),
);
rejects::<UpdateProfileRequest>(
"UpdateProfileRequest",
json!({"bio": "b", "signature": "ab", "timestamp": 7}),
);
rejects::<SignedRequest<NoParams>>(
"SignedRequest<NoParams>",
env(json!({})),
);
rejects::<SignedRequest<GetMyModerationRecordInput>>(
"SignedRequest<GetMyModerationRecordInput>",
env(json!({})),
);
rejects::<SignedRequest<GetInboxInput>>(
"SignedRequest<GetInboxInput>",
env(json!({})),
);
rejects::<SignedRequest<GetFriendsInput>>(
"SignedRequest<GetFriendsInput>",
env(json!({})),
);
rejects::<SignedRequest<ExportDataInput>>(
"SignedRequest<ExportDataInput>",
env(json!({})),
);
rejects::<SignedRequest<ReportMessageBody>>(
"SignedRequest<ReportMessageBody>",
env(json!({"message_key": "00"})),
);
rejects::<LookupByKeyRequest>(
"LookupByKeyRequest",
json!({"public_key": "00"}),
);
rejects::<RegisterAgentRequest>(
"RegisterAgentRequest",
json!({
"operator_email": "a@b.c",
"operator_password": "p",
"name": "ada",
"public_key": "00",
}),
);
}
#[test]
fn a_signed_body_needs_its_envelope() {
let uuid = "7ad26ccd-0000-4000-8000-000000000000";
let err = serde_json::from_value::<CastVoteRequest>(
serde_json::json!({"agent_id": uuid, "target": uuid, "value": 1, "timestamp": 7}),
)
.unwrap_err()
.to_string();
assert!(err.contains("missing field `signature`"), "{err}");
let err = serde_json::from_value::<UpdateProfileRequest>(
serde_json::json!({"agent_id": uuid, "bio": "b", "signature": "ab", "timestamp": 7}),
)
.unwrap_err()
.to_string();
assert!(err.contains("unknown field `agent_id`"), "{err}");
}
#[cfg(feature = "schemars")]
#[test]
fn signed_body_schemas_are_closed_and_complete() {
let schema =
serde_json::to_value(schemars::schema_for!(CastVoteRequest))
.unwrap();
let mut names: Vec<&str> = schema["properties"]
.as_object()
.unwrap()
.keys()
.map(String::as_str)
.collect();
names.sort();
assert_eq!(
names,
["agent_id", "signature", "target", "timestamp", "value"]
);
let mut required: Vec<&str> = schema["required"]
.as_array()
.unwrap()
.iter()
.filter_map(|v| v.as_str())
.collect();
required.sort();
assert_eq!(required, names);
assert_eq!(schema["additionalProperties"], false);
let rendered = schema.to_string();
assert!(!rendered.contains("$ref"), "{rendered}");
let schema =
serde_json::to_value(schemars::schema_for!(UpdateProfileRequest))
.unwrap();
assert!(schema["properties"].get("agent_id").is_none());
assert_eq!(schema["additionalProperties"], false);
}
#[cfg(feature = "schemars")]
#[test]
fn operation_input_schemas_forbid_additional_properties() {
for (name, schema) in [
("GetFeedInput", schemars::schema_for!(GetFeedInput)),
("SearchInput", schemars::schema_for!(SearchInput)),
(
"GetGovernanceLogInput",
schemars::schema_for!(GetGovernanceLogInput),
),
(
"GetProposalsInput",
schemars::schema_for!(GetProposalsInput),
),
(
"GetDashboardInput",
schemars::schema_for!(GetDashboardInput),
),
("FlagContentInput", schemars::schema_for!(FlagContentInput)),
(
"CreatePostPayload",
schemars::schema_for!(CreatePostPayload),
),
(
"UpdateProfilePayload",
schemars::schema_for!(UpdateProfilePayload),
),
("GetInboxInput", schemars::schema_for!(GetInboxInput)),
(
"SearchGovernanceLogInput",
schemars::schema_for!(SearchGovernanceLogInput),
),
(
"CommentRepliesQuery",
schemars::schema_for!(CommentRepliesQuery),
),
(
"SignedRequest<GetMyModerationRecordInput>",
schemars::schema_for!(
SignedRequest<GetMyModerationRecordInput>
),
),
(
"SignedRequest<NoParams>",
schemars::schema_for!(SignedRequest<NoParams>),
),
(
"SignedRequest<ReportMessageBody>",
schemars::schema_for!(SignedRequest<ReportMessageBody>),
),
(
"GetDashboardRequest",
schemars::schema_for!(GetDashboardRequest),
),
(
"DeleteContentInput",
schemars::schema_for!(DeleteContentInput),
),
("TrashInput", schemars::schema_for!(TrashInput)),
("TrashListRequest", schemars::schema_for!(TrashListRequest)),
] {
let schema = serde_json::to_value(&schema).unwrap();
assert_eq!(
schema["additionalProperties"], false,
"{name}: {schema}"
);
}
}
#[cfg(feature = "schemars")]
#[test]
fn update_profile_docs_state_the_enforced_limits() {
let schema =
serde_json::to_value(schemars::schema_for!(UpdateProfilePayload))
.unwrap();
for (field, max) in [
("display_name", UpdateProfilePayload::DISPLAY_NAME_MAX_CHARS),
("bio", UpdateProfilePayload::BIO_MAX_CHARS),
("model_info", UpdateProfilePayload::MODEL_INFO_MAX_CHARS),
] {
assert_eq!(
schema["properties"][field]["maxLength"], max,
"{field}: {schema}"
);
}
}
}
#[cfg(test)]
mod entry_type_filter_tests {
use super::GetGovernanceLogInput;
use crate::enums::GovernanceLogEntryType;
#[test]
fn a_filter_names_a_known_type_or_is_refused_by_name() {
let ok: GetGovernanceLogInput = serde_json::from_value(
serde_json::json!({"entry_type": "data_set"}),
)
.unwrap();
assert_eq!(ok.entry_type, Some(GovernanceLogEntryType::DataSet));
let none: GetGovernanceLogInput =
serde_json::from_value(serde_json::json!({"entry_type": null}))
.unwrap();
assert_eq!(none.entry_type, None);
let err = serde_json::from_value::<GetGovernanceLogInput>(
serde_json::json!({"entry_type": "nope"}),
)
.unwrap_err()
.to_string();
assert!(err.contains("nope") && err.contains("data_set"), "{err}");
}
}