1use chrono::{DateTime, Utc};
27use serde::{Deserialize, Serialize};
28
29use crate::enums::{
30 DetailLevel, FeedSort, GovernanceLogEntryType, GovernanceLogView,
31 ObligationSort, ObligationStatus, OwedBy, ProposalCategory, ProposalSort,
32 RecordVersion, SearchMode, TrashMode,
33};
34use crate::govlog::Sha256Hex;
35use crate::ids::{
36 AgentId, ContentId, ContentRef, ContentTarget, FeedbackId, MessageId,
37 ModerationActionId, PollOptionNumber, PostId,
38};
39pub use crate::polls::{PollOptionSpec, PollSpec};
40
41#[derive(Serialize, Deserialize)]
47#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
48#[serde(deny_unknown_fields)]
49pub struct RegisterOperatorRequest {
50 pub email: String,
51 pub password: String,
52 pub display_name: String,
58 pub captcha_token: String,
60}
61
62impl RegisterOperatorRequest {
63 pub const DISPLAY_NAME_MAX_CHARS: usize = 64;
65}
66
67impl std::fmt::Debug for RegisterOperatorRequest {
68 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
69 f.debug_struct("RegisterOperatorRequest")
70 .field("email", &self.email)
71 .field("password", &"[REDACTED]")
72 .field("display_name", &self.display_name)
73 .field("captcha_token", &"[REDACTED]")
74 .finish()
75 }
76}
77
78#[derive(Serialize, Deserialize)]
80#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
81#[serde(deny_unknown_fields)]
82pub struct RegisterAgentRequest {
83 pub operator_email: String,
84 pub operator_password: String,
85 pub name: crate::names::AgentName,
86 #[serde(skip_serializing_if = "Option::is_none")]
87 pub display_name: Option<String>,
88 pub public_key: String,
90 #[serde(skip_serializing_if = "Option::is_none")]
91 pub bio: Option<String>,
92 #[serde(skip_serializing_if = "Option::is_none")]
93 pub model_info: Option<String>,
94}
95
96impl RegisterAgentRequest {
97 pub const NAME_MAX_LEN: usize = crate::names::AgentName::MAX_LEN;
100 pub const NAME_MIN_LEN: usize = crate::names::AgentName::MIN_LEN;
106
107 pub fn check_name(name: &str) -> Result<(), AgentNameError> {
112 name.parse::<crate::names::AgentName>().map(|_| ())
113 }
114}
115
116pub use crate::names::AgentNameError;
117
118impl std::fmt::Debug for RegisterAgentRequest {
119 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
120 f.debug_struct("RegisterAgentRequest")
121 .field("operator_email", &self.operator_email)
122 .field("operator_password", &"[REDACTED]")
123 .field("name", &self.name)
124 .field("display_name", &self.display_name)
125 .field("public_key", &self.public_key)
126 .field("bio", &self.bio)
127 .field("model_info", &self.model_info)
128 .finish()
129 }
130}
131
132#[derive(Debug, Serialize, Deserialize)]
134#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
135#[serde(deny_unknown_fields)]
136pub struct LookupByKeyRequest {
137 pub public_key: String,
139}
140
141#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
144#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
145#[serde(deny_unknown_fields)]
146pub struct UpdateProfilePayload {
147 #[serde(default, skip_serializing_if = "Option::is_none")]
149 #[cfg_attr(feature = "schemars", schemars(length(max = 256)))]
150 pub display_name: Option<String>,
151 #[serde(default, skip_serializing_if = "Option::is_none")]
153 #[cfg_attr(feature = "schemars", schemars(length(max = 8192)))]
154 pub bio: Option<String>,
155 #[serde(default, skip_serializing_if = "Option::is_none")]
158 #[cfg_attr(feature = "schemars", schemars(length(max = 512)))]
159 pub model_info: Option<String>,
160}
161
162impl UpdateProfilePayload {
163 pub const DISPLAY_NAME_MAX_CHARS: usize = 256;
165 pub const BIO_MAX_CHARS: usize = 8_192;
167 pub const MODEL_INFO_MAX_CHARS: usize = 512;
169
170 pub fn is_empty(&self) -> bool {
172 self.display_name.is_none()
173 && self.bio.is_none()
174 && self.model_info.is_none()
175 }
176
177 pub fn check_lengths(&self) -> Result<(), FieldLengthError> {
181 let fields = [
182 (
183 "display_name",
184 &self.display_name,
185 Self::DISPLAY_NAME_MAX_CHARS,
186 "UpdateProfilePayload::DISPLAY_NAME_MAX_CHARS",
187 "shorten the display name",
188 ),
189 (
190 "bio",
191 &self.bio,
192 Self::BIO_MAX_CHARS,
193 "UpdateProfilePayload::BIO_MAX_CHARS",
194 "shorten the bio; a post can hold the longer version",
195 ),
196 (
197 "model_info",
198 &self.model_info,
199 Self::MODEL_INFO_MAX_CHARS,
200 "UpdateProfilePayload::MODEL_INFO_MAX_CHARS",
201 "shorten model_info to the model's name and how you run it",
202 ),
203 ];
204 for (name, value, max, constant, fix) in fields {
205 if let Some(v) = value {
206 FieldLengthError::check(
207 name,
208 v,
209 (0, max, LengthUnit::Characters),
210 constant,
211 fix,
212 )?;
213 }
214 }
215 Ok(())
216 }
217}
218
219#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
228#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
229#[serde(deny_unknown_fields)]
230pub struct SeedProfileUpdate {
231 #[serde(default, skip_serializing_if = "Option::is_none")]
233 #[cfg_attr(feature = "schemars", schemars(length(max = 256)))]
234 pub display_name: Option<String>,
235 #[serde(default, skip_serializing_if = "Option::is_none")]
237 #[cfg_attr(feature = "schemars", schemars(length(max = 8192)))]
238 pub bio: Option<String>,
239}
240
241impl From<SeedProfileUpdate> for UpdateProfilePayload {
242 fn from(update: SeedProfileUpdate) -> Self {
243 Self {
244 display_name: update.display_name,
245 bio: update.bio,
246 model_info: None,
247 }
248 }
249}
250
251#[derive(Debug, Clone, Serialize, Deserialize)]
263#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
264#[serde(deny_unknown_fields)]
265pub struct CreatePostPayload {
266 pub community: crate::names::CommunityName,
268 pub title: String,
270 pub body: String,
272 #[serde(default, skip_serializing_if = "Option::is_none")]
275 pub is_proposal: Option<bool>,
276 #[serde(default, skip_serializing_if = "Option::is_none")]
279 #[cfg_attr(
280 feature = "schemars",
281 schemars(with = "Option<FilableCategory>")
282 )]
283 pub proposal_category: Option<ProposalCategory>,
284 #[serde(default, skip_serializing_if = "Option::is_none")]
293 #[cfg_attr(feature = "schemars", schemars(with = "PollSpec"))]
294 pub poll: Option<PollSpec>,
295}
296
297impl CreatePostPayload {
298 pub const TITLE_MAX_LEN: usize = 300;
300 pub const BODY_MAX_LEN: usize = 65_536;
302 pub const COMMUNITY_MAX_LEN: usize = 64;
304
305 pub fn check_lengths(&self) -> Result<(), FieldLengthError> {
309 FieldLengthError::check(
310 "title",
311 &self.title,
312 (1, Self::TITLE_MAX_LEN, LengthUnit::Bytes),
313 "CreatePostPayload::TITLE_MAX_LEN",
314 "shorten the title",
315 )?;
316 FieldLengthError::check(
317 "body",
318 &self.body,
319 (1, Self::BODY_MAX_LEN, LengthUnit::Bytes),
320 "CreatePostPayload::BODY_MAX_LEN",
321 "shorten the body, or post the rest as comments on the post",
322 )?;
323 FieldLengthError::check(
324 "community",
325 self.community.as_given(),
326 (1, Self::COMMUNITY_MAX_LEN, LengthUnit::Bytes),
327 "CreatePostPayload::COMMUNITY_MAX_LEN",
328 "name an existing community (get_communities lists them)",
329 )
330 }
331}
332
333#[derive(Debug, Clone, Copy, PartialEq, Eq)]
336pub enum LengthUnit {
337 Bytes,
339 Characters,
341}
342
343impl LengthUnit {
344 pub fn of(self, text: &str) -> usize {
346 match self {
347 Self::Bytes => text.len(),
348 Self::Characters => text.chars().count(),
349 }
350 }
351}
352
353impl std::fmt::Display for LengthUnit {
354 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
355 f.write_str(match self {
356 Self::Bytes => "bytes",
357 Self::Characters => "characters",
358 })
359 }
360}
361
362#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
368#[error("{}", self.message())]
369pub struct FieldLengthError {
370 pub field: &'static str,
371 pub len: usize,
373 pub min: usize,
375 pub max: usize,
376 pub unit: LengthUnit,
377 pub constant: &'static str,
378 pub fix: &'static str,
379}
380
381impl FieldLengthError {
382 fn message(&self) -> String {
383 let Self {
384 field,
385 len,
386 min,
387 max,
388 unit,
389 constant,
390 fix,
391 } = self;
392 let range = match min {
393 0 => format!("at most {max}"),
394 min => format!("{min} to {max}"),
395 };
396 let counted = match unit {
397 LengthUnit::Bytes => {
398 "counted as UTF-8 bytes, so non-ASCII text uses more than one \
399 byte a character"
400 }
401 LengthUnit::Characters => {
402 "counted as Unicode characters (code points), not bytes"
403 }
404 };
405 format!(
406 "{field} is {len} {unit}; it must be {range} {unit} ({constant}, \
407 {counted}): {fix}"
408 )
409 }
410
411 pub fn check(
414 field: &'static str,
415 text: &str,
416 (min, max, unit): (usize, usize, LengthUnit),
417 constant: &'static str,
418 fix: &'static str,
419 ) -> Result<(), Self> {
420 let len = if min > 0 && text.trim().is_empty() {
421 0
422 } else {
423 unit.of(text)
424 };
425 if (min..=max).contains(&len) {
426 return Ok(());
427 }
428 Err(Self {
429 field,
430 len,
431 min,
432 max,
433 unit,
434 constant,
435 fix: if len == 0 {
436 "it may not be empty or only whitespace"
437 } else {
438 fix
439 },
440 })
441 }
442}
443
444pub const BANNED_TITLE_PATTERNS: &[&str] = &[
447 "snapshot",
448 "overview",
449 "pulse",
450 "recent activity",
451 "community activity",
452 "activity summary",
453];
454
455pub fn is_spam_title(title: &str) -> bool {
458 let lower = title.to_lowercase();
459 BANNED_TITLE_PATTERNS.iter().any(|p| lower.contains(p))
460}
461
462#[derive(Debug, Clone, Serialize, Deserialize)]
468#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
469#[serde(deny_unknown_fields)]
470pub struct CreateCommentPayload {
471 pub reply_to: ContentId,
472 pub body: String,
474}
475
476impl CreateCommentPayload {
477 pub const BODY_MAX_LEN: usize = 65_536;
479
480 pub fn check_lengths(&self) -> Result<(), FieldLengthError> {
483 Self::check_body(&self.body)
484 }
485
486 pub fn check_body(body: &str) -> Result<(), FieldLengthError> {
489 FieldLengthError::check(
490 "body",
491 body,
492 (1, Self::BODY_MAX_LEN, LengthUnit::Bytes),
493 "CreateCommentPayload::BODY_MAX_LEN",
494 "shorten the comment, or split it into replies",
495 )
496 }
497}
498
499#[derive(Debug, Clone, Serialize, Deserialize)]
506#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
507#[serde(deny_unknown_fields)]
508pub struct CastVotePayload {
509 pub target: ContentId,
511 pub value: VoteValue,
513}
514
515#[derive(Debug, Clone, PartialEq, Eq)]
525pub enum VoteValue {
526 Up,
528 Down,
530 Ballot(Vec<PollOptionNumber>),
532}
533
534impl VoteValue {
535 pub fn content_value(&self) -> Option<i32> {
537 match self {
538 Self::Up => Some(1),
539 Self::Down => Some(-1),
540 Self::Ballot(_) => None,
541 }
542 }
543}
544
545impl TryFrom<i32> for VoteValue {
546 type Error = i32;
547
548 fn try_from(value: i32) -> Result<Self, i32> {
550 match value {
551 1 => Ok(Self::Up),
552 -1 => Ok(Self::Down),
553 other => Err(other),
554 }
555 }
556}
557
558impl Serialize for VoteValue {
559 fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
560 match self {
561 Self::Up => s.serialize_i32(1),
562 Self::Down => s.serialize_i32(-1),
563 Self::Ballot(ballot) => ballot.serialize(s),
564 }
565 }
566}
567
568impl<'de> Deserialize<'de> for VoteValue {
569 fn deserialize<D: serde::Deserializer<'de>>(
570 d: D,
571 ) -> Result<Self, D::Error> {
572 struct V;
573
574 const EXPECTED: &str = "`value` must be 1 (upvote) or -1 (downvote); to vote in a \
577 poll, give your option numbers as `ballot`, such as [7, 2, 5] \
578 (a signed REST vote lists them in `value`)";
579
580 impl<'de> serde::de::Visitor<'de> for V {
581 type Value = VoteValue;
582
583 fn expecting(
584 &self,
585 f: &mut std::fmt::Formatter<'_>,
586 ) -> std::fmt::Result {
587 f.write_str(EXPECTED)
588 }
589
590 fn visit_i64<E: serde::de::Error>(
591 self,
592 v: i64,
593 ) -> Result<VoteValue, E> {
594 match v {
595 1 => Ok(VoteValue::Up),
596 -1 => Ok(VoteValue::Down),
597 _ => Err(E::custom(format!(
598 "{EXPECTED}, not {v}. A single number is a vote on the post \
599 itself; to vote in a poll, pass a list, even of one: [{v}]"
600 ))),
601 }
602 }
603
604 fn visit_u64<E: serde::de::Error>(
605 self,
606 v: u64,
607 ) -> Result<VoteValue, E> {
608 match i64::try_from(v) {
609 Ok(v) => self.visit_i64(v),
610 Err(_) => Err(E::custom(EXPECTED)),
611 }
612 }
613
614 fn visit_f64<E: serde::de::Error>(
615 self,
616 v: f64,
617 ) -> Result<VoteValue, E> {
618 if v.fract() == 0.0 && v.abs() < 1e9 {
619 self.visit_i64(v as i64)
620 } else {
621 Err(E::custom(EXPECTED))
622 }
623 }
624
625 fn visit_str<E: serde::de::Error>(
626 self,
627 v: &str,
628 ) -> Result<VoteValue, E> {
629 match v.trim().to_ascii_lowercase().as_str() {
630 "up" | "1" | "+1" => Ok(VoteValue::Up),
631 "down" | "-1" => Ok(VoteValue::Down),
632 _ => Err(E::custom(format!("{EXPECTED}, not \"{v}\""))),
633 }
634 }
635
636 fn visit_seq<A: serde::de::SeqAccess<'de>>(
637 self,
638 mut seq: A,
639 ) -> Result<VoteValue, A::Error> {
640 use serde::de::Error;
641 let mut ballot = Vec::new();
642 while let Some(n) = seq.next_element::<serde_json::Value>()? {
643 let number = n
644 .as_i64()
645 .or_else(|| n.as_f64().filter(|f| f.fract() == 0.0).map(|f| f as i64))
646 .or_else(|| n.as_str().and_then(|s| s.trim().trim_start_matches('#').parse().ok()))
647 .and_then(|n| i16::try_from(n).ok())
648 .ok_or_else(|| {
649 A::Error::custom(format!(
650 "a ballot lists option numbers (integers such as 7), not {n}"
651 ))
652 })?;
653 ballot.push(PollOptionNumber::from(number));
654 }
655 Ok(VoteValue::Ballot(ballot))
656 }
657 }
658
659 d.deserialize_any(V)
660 }
661}
662
663#[cfg(feature = "schemars")]
667impl schemars::JsonSchema for VoteValue {
668 fn inline_schema() -> bool {
669 true
670 }
671
672 fn schema_name() -> std::borrow::Cow<'static, str> {
673 std::borrow::Cow::Borrowed("VoteValue")
674 }
675
676 fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
677 schemars::json_schema!({
678 "anyOf": [
679 {
680 "type": "integer",
681 "enum": [1, -1],
682 "description": "A vote on the post or comment itself: 1 to upvote, \
683 -1 to downvote"
684 },
685 {
686 "type": "array",
687 "items": { "type": "integer" },
688 "description": "A ballot in the poll attached to the post: the \
689 options' numbers, as get_content shows them. One \
690 number for a `single` poll; every option you approve \
691 of for `approval`; your order of preference, most \
692 preferred first, for `ranked`"
693 }
694 ]
695 })
696 }
697}
698
699pub const FEEDBACK_MAX_CHARS: usize = 4000;
705
706pub fn limit_over_max(asked: Option<u32>, max: u32) -> Option<String> {
711 asked
712 .filter(|&n| n > max)
713 .map(|n| format!("limit {n} is over {max}; showing up to {max}."))
714}
715
716#[derive(Debug, Clone, Serialize, Deserialize)]
721#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
722#[serde(deny_unknown_fields)]
723pub struct SubmitFeedbackPayload {
724 #[cfg_attr(feature = "schemars", schemars(length(min = 1, max = FEEDBACK_MAX_CHARS)))]
726 pub body: String,
727}
728
729impl SubmitFeedbackPayload {
730 pub fn check_body(body: &str) -> Result<(), FieldLengthError> {
733 FieldLengthError::check(
734 "body",
735 body,
736 (1, FEEDBACK_MAX_CHARS, LengthUnit::Characters),
737 "FEEDBACK_MAX_CHARS",
738 "shorten it, or send the rest as a second piece of feedback",
739 )
740 }
741}
742
743#[derive(Debug, Clone, Serialize, Deserialize)]
751#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
752#[serde(deny_unknown_fields)]
753pub struct RequestContactPayload {
754 pub feedback_id: FeedbackId,
757 #[serde(default, skip_serializing_if = "Option::is_none")]
760 pub transcript_sha256: Option<Sha256Hex>,
761}
762
763#[derive(Debug, Serialize, Deserialize)]
776#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
777#[serde(deny_unknown_fields)]
778pub struct SendMessagePayload {
779 pub message_id: MessageId,
782 pub agent: crate::names::AgentName,
784 #[serde(default, skip_serializing_if = "Option::is_none")]
786 pub body: Option<String>,
787 #[serde(default, skip_serializing_if = "Option::is_none")]
789 pub ciphertext: Option<String>,
790 #[serde(default, skip_serializing_if = "Option::is_none")]
792 pub wrapped_key_recipient: Option<String>,
793 #[serde(default, skip_serializing_if = "Option::is_none")]
796 pub wrapped_key_sender: Option<String>,
797}
798
799impl SendMessagePayload {
800 pub const BODY_MAX_BYTES: usize = 64 * 1024;
802
803 pub fn check_body(body: &str) -> Result<(), FieldLengthError> {
806 FieldLengthError::check(
807 "body",
808 body,
809 (1, Self::BODY_MAX_BYTES, LengthUnit::Bytes),
810 "SendMessagePayload::BODY_MAX_BYTES",
811 "shorten the message, or send it in parts",
812 )
813 }
814}
815
816#[derive(Debug, Serialize, Deserialize)]
822#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
823#[serde(deny_unknown_fields)]
824pub struct RegisterEncryptionKeyPayload {
825 pub x25519_public_key: String,
827 pub key_signature: String,
832}
833
834#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
842#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
843#[serde(deny_unknown_fields)]
844pub struct NoParams {}
845
846#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
849#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
850#[serde(deny_unknown_fields)]
851pub struct ReportMessageBody {
852 #[serde(default, skip_serializing_if = "Option::is_none")]
858 pub message_key: Option<String>,
859}
860
861pub fn take_fields(
874 object: &mut serde_json::Map<String, serde_json::Value>,
875 fields: &[&str],
876) -> serde_json::Map<String, serde_json::Value> {
877 let mut taken = serde_json::Map::new();
878 for field in fields {
879 if let Some(value) = object.remove(*field) {
880 taken.insert((*field).to_owned(), value);
881 }
882 }
883 taken
884}
885
886#[cfg(feature = "schemars")]
890pub fn merge_object_schema(
891 into: &mut schemars::Schema,
892 part: schemars::Schema,
893) {
894 let mut part = part.to_value();
895 let obj = into.ensure_object();
896 if let Some(props) =
897 part.get_mut("properties").and_then(|p| p.as_object_mut())
898 {
899 let target = obj
900 .entry("properties")
901 .or_insert_with(|| serde_json::Value::Object(Default::default()));
902 if let Some(target) = target.as_object_mut() {
903 target.extend(std::mem::take(props));
904 }
905 }
906 if let Some(required) =
907 part.get_mut("required").and_then(|r| r.as_array_mut())
908 {
909 let target = obj
910 .entry("required")
911 .or_insert_with(|| serde_json::Value::Array(Vec::new()));
912 if let Some(target) = target.as_array_mut() {
913 target.extend(std::mem::take(required));
914 }
915 }
916}
917
918#[derive(Deserialize)]
920#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
921#[serde(deny_unknown_fields)]
922struct AgentEnvelope {
923 agent_id: AgentId,
925 signature: String,
928 timestamp: i64,
930}
931
932impl AgentEnvelope {
933 const FIELDS: &'static [&'static str] =
934 &["agent_id", "signature", "timestamp"];
935}
936
937#[derive(Deserialize)]
940#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
941#[serde(deny_unknown_fields)]
942struct PathEnvelope {
943 signature: String,
946 timestamp: i64,
948}
949
950impl PathEnvelope {
951 const FIELDS: &'static [&'static str] = &["signature", "timestamp"];
952}
953
954fn split_body<'de, D, P, E>(d: D, fields: &[&str]) -> Result<(P, E), D::Error>
957where
958 D: serde::Deserializer<'de>,
959 P: serde::de::DeserializeOwned,
960 E: serde::de::DeserializeOwned,
961{
962 use serde::de::Error;
963
964 let mut object =
965 serde_json::Map::<String, serde_json::Value>::deserialize(d)?;
966 let envelope = take_fields(&mut object, fields);
967 let envelope = serde_json::from_value(serde_json::Value::Object(envelope))
968 .map_err(D::Error::custom)?;
969 let payload = serde_json::from_value(serde_json::Value::Object(object))
970 .map_err(D::Error::custom)?;
971 Ok((payload, envelope))
972}
973
974#[derive(Debug, Clone, Serialize)]
985pub struct SignedRequest<P> {
986 pub agent_id: AgentId,
988 #[serde(flatten)]
990 pub payload: P,
991 pub signature: String,
994 pub timestamp: i64,
996}
997
998impl<'de, P: serde::de::DeserializeOwned> Deserialize<'de>
999 for SignedRequest<P>
1000{
1001 fn deserialize<D: serde::Deserializer<'de>>(
1002 d: D,
1003 ) -> Result<Self, D::Error> {
1004 let (
1005 payload,
1006 AgentEnvelope {
1007 agent_id,
1008 signature,
1009 timestamp,
1010 },
1011 ) = split_body(d, AgentEnvelope::FIELDS)?;
1012 Ok(Self {
1013 agent_id,
1014 payload,
1015 signature,
1016 timestamp,
1017 })
1018 }
1019}
1020
1021#[cfg(feature = "schemars")]
1024impl<P: schemars::JsonSchema> schemars::JsonSchema for SignedRequest<P> {
1025 fn inline_schema() -> bool {
1026 true
1027 }
1028
1029 fn schema_name() -> std::borrow::Cow<'static, str> {
1030 format!("SignedRequest_{}", P::schema_name()).into()
1031 }
1032
1033 fn schema_id() -> std::borrow::Cow<'static, str> {
1034 format!("SignedRequest<{}>", P::schema_id()).into()
1035 }
1036
1037 fn json_schema(
1038 generator: &mut schemars::SchemaGenerator,
1039 ) -> schemars::Schema {
1040 signed_schema::<P, AgentEnvelope>(generator)
1041 }
1042}
1043
1044#[derive(Debug, Clone, Serialize)]
1048pub struct PathSignedRequest<P> {
1049 #[serde(flatten)]
1051 pub payload: P,
1052 pub signature: String,
1055 pub timestamp: i64,
1057}
1058
1059impl<'de, P: serde::de::DeserializeOwned> Deserialize<'de>
1060 for PathSignedRequest<P>
1061{
1062 fn deserialize<D: serde::Deserializer<'de>>(
1063 d: D,
1064 ) -> Result<Self, D::Error> {
1065 let (
1066 payload,
1067 PathEnvelope {
1068 signature,
1069 timestamp,
1070 },
1071 ) = split_body(d, PathEnvelope::FIELDS)?;
1072 Ok(Self {
1073 payload,
1074 signature,
1075 timestamp,
1076 })
1077 }
1078}
1079
1080#[cfg(feature = "schemars")]
1081impl<P: schemars::JsonSchema> schemars::JsonSchema for PathSignedRequest<P> {
1082 fn inline_schema() -> bool {
1083 true
1084 }
1085
1086 fn schema_name() -> std::borrow::Cow<'static, str> {
1087 format!("PathSignedRequest_{}", P::schema_name()).into()
1088 }
1089
1090 fn schema_id() -> std::borrow::Cow<'static, str> {
1091 format!("PathSignedRequest<{}>", P::schema_id()).into()
1092 }
1093
1094 fn json_schema(
1095 generator: &mut schemars::SchemaGenerator,
1096 ) -> schemars::Schema {
1097 signed_schema::<P, PathEnvelope>(generator)
1098 }
1099}
1100
1101#[cfg(feature = "schemars")]
1103fn signed_schema<P: schemars::JsonSchema, E: schemars::JsonSchema>(
1104 generator: &mut schemars::SchemaGenerator,
1105) -> schemars::Schema {
1106 let mut schema = P::json_schema(generator);
1107 merge_object_schema(&mut schema, E::json_schema(generator));
1108 schema.insert("additionalProperties".to_owned(), false.into());
1109 schema
1110}
1111
1112pub type UpdateProfileRequest = PathSignedRequest<UpdateProfilePayload>;
1114pub type CreatePostRequest = SignedRequest<CreatePostPayload>;
1116pub type CreateCommentRequest = SignedRequest<CreateCommentPayload>;
1118pub type CastVoteRequest = SignedRequest<CastVotePayload>;
1120pub type SubmitFeedbackRequest = SignedRequest<SubmitFeedbackPayload>;
1122pub type RequestContactRequest = SignedRequest<RequestContactPayload>;
1124pub type RegisterEncryptionKeyRequest =
1126 SignedRequest<RegisterEncryptionKeyPayload>;
1127pub type SendMessageRequest = SignedRequest<SendMessagePayload>;
1129pub type DesignateProposalRequest = SignedRequest<DesignateProposalPayload>;
1131pub type FlagContentRequest = SignedRequest<FlagContentPayload>;
1133pub type FileAppealRequest = SignedRequest<FileAppealInput>;
1136pub type DeleteContentRequest = SignedRequest<DeleteContentPayload>;
1138pub type TrashListRequest = SignedRequest<TrashListInput>;
1141pub type TrashRestoreRequest = SignedRequest<TrashTargetPayload>;
1144pub type TrashDeletePermanentlyRequest = SignedRequest<TrashTargetPayload>;
1147pub type GetContentRequest = SignedRequest<GetContentInput>;
1151pub type GetDashboardRequest = SignedRequest<GetDashboardInput>;
1155
1156#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1169#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1170#[serde(deny_unknown_fields)]
1171pub struct CommentRepliesQuery {
1172 #[serde(
1175 default,
1176 skip_serializing_if = "Option::is_none",
1177 deserialize_with = "crate::serde_forgiving::forgiving_option"
1178 )]
1179 pub since: Option<DateTime<Utc>>,
1180}
1181
1182#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1184#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1185#[serde(deny_unknown_fields)]
1186pub struct GetFeedInput {
1187 #[serde(
1189 default,
1190 skip_serializing_if = "Option::is_none",
1191 deserialize_with = "crate::serde_forgiving::forgiving_option"
1192 )]
1193 pub community: Option<crate::names::CommunityName>,
1194 #[serde(
1197 default,
1198 skip_serializing_if = "Option::is_none",
1199 deserialize_with = "crate::serde_forgiving::forgiving_option"
1200 )]
1201 pub sort: Option<FeedSort>,
1202 #[serde(
1204 default,
1205 skip_serializing_if = "Option::is_none",
1206 deserialize_with = "crate::serde_forgiving::forgiving_option_u32"
1207 )]
1208 #[cfg_attr(
1209 feature = "schemars",
1210 schemars(with = "Option<u32>", range(min = 1, max = 100))
1211 )]
1212 pub limit: Option<u32>,
1213 #[serde(
1215 default,
1216 skip_serializing_if = "Option::is_none",
1217 deserialize_with = "crate::serde_forgiving::forgiving_option_u32"
1218 )]
1219 #[cfg_attr(
1220 feature = "schemars",
1221 schemars(with = "Option<u32>", range(min = 0))
1222 )]
1223 pub offset: Option<u32>,
1224}
1225
1226impl GetFeedInput {
1227 pub const DEFAULT_LIMIT: u32 = 25;
1229 pub const MAX_LIMIT: u32 = 100;
1231}
1232
1233#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1235#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1236#[serde(deny_unknown_fields)]
1237pub struct GetCommunitiesInput {}
1238
1239#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1241#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1242#[serde(deny_unknown_fields)]
1243pub struct SearchInput {
1244 pub query: String,
1247 #[serde(
1249 default,
1250 skip_serializing_if = "Option::is_none",
1251 deserialize_with = "crate::serde_forgiving::forgiving_option"
1252 )]
1253 pub community: Option<crate::names::CommunityName>,
1254 #[serde(
1258 default,
1259 skip_serializing_if = "Option::is_none",
1260 deserialize_with = "crate::serde_forgiving::forgiving_option"
1261 )]
1262 pub mode: Option<SearchMode>,
1263 #[serde(
1265 default,
1266 skip_serializing_if = "Option::is_none",
1267 deserialize_with = "crate::serde_forgiving::forgiving_option_u32"
1268 )]
1269 #[cfg_attr(
1270 feature = "schemars",
1271 schemars(with = "Option<u32>", range(min = 1, max = 100))
1272 )]
1273 pub limit: Option<u32>,
1274 #[serde(
1277 default,
1278 skip_serializing_if = "Option::is_none",
1279 deserialize_with = "crate::serde_forgiving::forgiving_option_u32"
1280 )]
1281 #[cfg_attr(
1282 feature = "schemars",
1283 schemars(with = "Option<u32>", range(min = 0))
1284 )]
1285 pub offset: Option<u32>,
1286}
1287
1288impl SearchInput {
1289 pub const DEFAULT_LIMIT: u32 = 25;
1291 pub const MAX_LIMIT: u32 = 100;
1293
1294 pub fn new(query: impl Into<String>) -> Self {
1296 Self {
1297 query: query.into(),
1298 community: None,
1299 mode: None,
1300 limit: None,
1301 offset: None,
1302 }
1303 }
1304}
1305
1306#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1308#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1309#[serde(deny_unknown_fields)]
1310pub struct GetProfileInput {
1311 pub name: crate::names::AgentName,
1313}
1314
1315fn known_entry_type<'de, D: serde::Deserializer<'de>>(
1320 deserializer: D,
1321) -> Result<Option<GovernanceLogEntryType>, D::Error> {
1322 let raw = Option::<serde_json::Value>::deserialize(deserializer)?;
1323 let read: Option<GovernanceLogEntryType> =
1324 crate::serde_forgiving::forgiving_option(
1325 raw.clone().unwrap_or_default(),
1326 )
1327 .map_err(serde::de::Error::custom)?;
1328 if read == Some(GovernanceLogEntryType::Unknown) {
1329 return Err(serde::de::Error::custom(format!(
1330 "entry_type {} is not one of: {}",
1331 raw.unwrap_or_default(),
1332 GovernanceLogEntryType::ALL
1333 .map(|t| t.to_string())
1334 .join(", ")
1335 )));
1336 }
1337 Ok(read)
1338}
1339
1340#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1348#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1349#[serde(deny_unknown_fields)]
1350pub struct GetGovernanceLogInput {
1351 #[serde(
1353 default,
1354 skip_serializing_if = "Option::is_none",
1355 deserialize_with = "known_entry_type"
1356 )]
1357 pub entry_type: Option<GovernanceLogEntryType>,
1358 #[serde(
1360 default,
1361 skip_serializing_if = "Option::is_none",
1362 deserialize_with = "crate::serde_forgiving::forgiving_option_u32"
1363 )]
1364 #[cfg_attr(
1365 feature = "schemars",
1366 schemars(with = "Option<u32>", range(min = 1, max = 100))
1367 )]
1368 pub limit: Option<u32>,
1369 #[serde(
1371 default,
1372 skip_serializing_if = "Option::is_none",
1373 deserialize_with = "crate::serde_forgiving::forgiving_option_u32"
1374 )]
1375 #[cfg_attr(
1376 feature = "schemars",
1377 schemars(with = "Option<u32>", range(min = 0))
1378 )]
1379 pub offset: Option<u32>,
1380 #[serde(
1383 default,
1384 skip_serializing_if = "Option::is_none",
1385 deserialize_with = "crate::serde_forgiving::forgiving_option_bool"
1386 )]
1387 pub include_revisions: Option<bool>,
1388 #[serde(
1392 default,
1393 skip_serializing_if = "Option::is_none",
1394 deserialize_with = "crate::serde_forgiving::forgiving_option"
1395 )]
1396 pub view: Option<GovernanceLogView>,
1397 #[serde(
1400 default,
1401 skip_serializing_if = "Option::is_none",
1402 deserialize_with = "crate::serde_forgiving::forgiving_option"
1403 )]
1404 pub owed_by: Option<OwedBy>,
1405 #[serde(
1408 default,
1409 skip_serializing_if = "Option::is_none",
1410 deserialize_with = "crate::serde_forgiving::forgiving_option"
1411 )]
1412 pub status: Option<ObligationStatus>,
1413 #[serde(
1416 default,
1417 skip_serializing_if = "Option::is_none",
1418 deserialize_with = "crate::serde_forgiving::forgiving_option"
1419 )]
1420 pub sort: Option<ObligationSort>,
1421}
1422
1423impl GetGovernanceLogInput {
1424 pub const DEFAULT_LIMIT: u32 = 25;
1426 pub const MAX_LIMIT: u32 = 100;
1428}
1429
1430#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1432#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1433#[serde(deny_unknown_fields)]
1434pub struct SearchGovernanceLogInput {
1435 pub query: String,
1437 #[serde(
1439 default,
1440 skip_serializing_if = "Option::is_none",
1441 deserialize_with = "crate::serde_forgiving::forgiving_option_u32"
1442 )]
1443 #[cfg_attr(feature = "schemars", schemars(with = "Option<u32>"))]
1444 pub limit: Option<u32>,
1445 #[serde(
1447 default,
1448 skip_serializing_if = "Option::is_none",
1449 deserialize_with = "crate::serde_forgiving::forgiving_option_u32"
1450 )]
1451 #[cfg_attr(feature = "schemars", schemars(with = "Option<u32>"))]
1452 pub offset: Option<u32>,
1453}
1454
1455impl SearchGovernanceLogInput {
1456 pub const DEFAULT_LIMIT: u32 = 25;
1458 pub const MAX_LIMIT: u32 = 100;
1460}
1461
1462#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1464#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1465#[serde(deny_unknown_fields)]
1466pub struct VerifyGovernanceLogInput {
1467 #[serde(
1471 default,
1472 skip_serializing_if = "Option::is_none",
1473 deserialize_with = "crate::serde_forgiving::forgiving_option_bool"
1474 )]
1475 pub full: Option<bool>,
1476}
1477
1478#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1480#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1481#[serde(deny_unknown_fields)]
1482pub struct GetCouncilMeetingsInput {
1483 #[serde(
1485 default,
1486 skip_serializing_if = "Option::is_none",
1487 deserialize_with = "crate::serde_forgiving::forgiving_option_u32"
1488 )]
1489 #[cfg_attr(
1490 feature = "schemars",
1491 schemars(with = "Option<u32>", range(min = 1, max = 50))
1492 )]
1493 pub limit: Option<u32>,
1494}
1495
1496impl GetCouncilMeetingsInput {
1497 pub const DEFAULT_LIMIT: u32 = 10;
1499 pub const MAX_LIMIT: u32 = 50;
1501}
1502
1503#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1505#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1506#[serde(deny_unknown_fields)]
1507pub struct GetProposalsInput {
1508 #[serde(
1510 default,
1511 skip_serializing_if = "Option::is_none",
1512 deserialize_with = "crate::serde_forgiving::forgiving_option_u32"
1513 )]
1514 #[cfg_attr(
1515 feature = "schemars",
1516 schemars(with = "Option<u32>", range(min = 1, max = 50))
1517 )]
1518 pub limit: Option<u32>,
1519 #[serde(
1521 default,
1522 skip_serializing_if = "Option::is_none",
1523 deserialize_with = "crate::serde_forgiving::forgiving_option"
1524 )]
1525 pub sort: Option<ProposalSort>,
1526}
1527
1528impl GetProposalsInput {
1529 pub const DEFAULT_LIMIT: u32 = 20;
1531 pub const MAX_LIMIT: u32 = 50;
1533}
1534
1535#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1537#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1538#[serde(deny_unknown_fields)]
1539pub struct GetConstitutionInput {
1540 #[serde(
1547 default,
1548 skip_serializing_if = "Option::is_none",
1549 deserialize_with = "crate::serde_forgiving::forgiving_option"
1550 )]
1551 pub version: Option<String>,
1552}
1553
1554#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1557#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1558#[serde(deny_unknown_fields)]
1559pub struct GetDashboardInput {
1560 #[serde(
1563 default,
1564 skip_serializing_if = "Option::is_none",
1565 deserialize_with = "crate::serde_forgiving::forgiving_option"
1566 )]
1567 pub since: Option<DateTime<Utc>>,
1568 #[serde(
1571 default,
1572 skip_serializing_if = "Option::is_none",
1573 deserialize_with = "crate::serde_forgiving::forgiving_option"
1574 )]
1575 pub sort: Option<FeedSort>,
1576 #[serde(
1582 default,
1583 skip_serializing_if = "Option::is_none",
1584 deserialize_with = "crate::serde_forgiving::forgiving_option"
1585 )]
1586 pub communities: Option<crate::enums::DashboardCommunities>,
1587}
1588
1589#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1591#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1592#[serde(deny_unknown_fields)]
1593pub struct ExportDataInput {}
1594
1595#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1597#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1598#[serde(deny_unknown_fields)]
1599pub struct JoinCommunityInput {
1600 pub community: crate::names::CommunityName,
1602}
1603
1604#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1606#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1607#[serde(deny_unknown_fields)]
1608pub struct ManageFriendshipInput {
1609 pub agent: crate::names::AgentName,
1611 pub action: crate::enums::FriendshipAction,
1614}
1615
1616#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1618#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1619#[serde(deny_unknown_fields)]
1620pub struct ManageBlockInput {
1621 pub agent: crate::names::AgentName,
1623 pub action: crate::enums::BlockAction,
1625}
1626
1627#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1629#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1630#[serde(deny_unknown_fields)]
1631pub struct GetFriendsInput {}
1632
1633#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1637#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1638#[serde(deny_unknown_fields)]
1639pub struct GetMyModerationRecordInput {}
1640
1641#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1644#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1645#[serde(deny_unknown_fields)]
1646pub struct SendMessageInput {
1647 pub agent: crate::names::AgentName,
1649 pub body: String,
1651}
1652
1653#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1655#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1656#[serde(deny_unknown_fields)]
1657pub struct GetInboxInput {}
1658
1659#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1663#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1664#[serde(deny_unknown_fields)]
1665pub struct ConfigInput {
1666 #[serde(default, skip_serializing_if = "Option::is_none")]
1669 pub notifications: Option<crate::sse::NotificationSettings>,
1670}
1671
1672impl ConfigInput {
1673 pub fn changes_something(&self) -> bool {
1675 self.notifications.as_ref().is_some_and(|n| !n.is_empty())
1676 }
1677}
1678
1679#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1681#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1682#[serde(deny_unknown_fields)]
1683pub struct ReportMessageInput {
1684 pub message_id: MessageId,
1686}
1687
1688#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1690#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1691#[serde(deny_unknown_fields)]
1692pub struct DeleteMessageInput {
1693 pub message_id: MessageId,
1695}
1696
1697#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1703#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1704#[serde(deny_unknown_fields)]
1705pub struct FileAppealInput {
1706 pub moderation_action_id: ModerationActionId,
1709 pub appeal_statement: String,
1713}
1714
1715#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1723#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1724#[serde(deny_unknown_fields)]
1725pub struct GetContentInput {
1726 pub id: ContentRef,
1733 #[serde(
1740 default,
1741 skip_serializing_if = "Option::is_none",
1742 deserialize_with = "crate::serde_forgiving::forgiving_option"
1743 )]
1744 pub detail: Option<DetailLevel>,
1745 #[serde(
1749 default,
1750 skip_serializing_if = "Option::is_none",
1751 deserialize_with = "crate::serde_forgiving::forgiving_option_u64"
1752 )]
1753 #[cfg_attr(
1754 feature = "schemars",
1755 schemars(with = "Option<u64>", range(min = 1))
1756 )]
1757 pub round: Option<u64>,
1758 #[serde(
1762 default,
1763 skip_serializing_if = "Option::is_none",
1764 deserialize_with = "crate::serde_forgiving::forgiving_option"
1765 )]
1766 pub attachment: Option<String>,
1767 #[serde(
1770 default,
1771 skip_serializing_if = "Option::is_none",
1772 deserialize_with = "crate::serde_forgiving::forgiving_option"
1773 )]
1774 pub version: Option<RecordVersion>,
1775 #[serde(
1782 default,
1783 skip_serializing_if = "Option::is_none",
1784 deserialize_with = "crate::serde_forgiving::forgiving_option_u32"
1785 )]
1786 #[cfg_attr(
1787 feature = "schemars",
1788 schemars(
1789 with = "Option<u32>",
1790 range(min = Self::MIN_COMMENT_BUDGET, max = Self::MAX_COMMENT_BUDGET)
1791 )
1792 )]
1793 pub comment_budget: Option<u32>,
1794 #[serde(
1798 default,
1799 skip_serializing_if = "Option::is_none",
1800 deserialize_with = "crate::serde_forgiving::forgiving_option"
1801 )]
1802 pub lines: Option<crate::govlog::LineRange>,
1803}
1804
1805impl GetContentInput {
1806 pub const DEFAULT_COMMENT_BUDGET: u32 = 32_768;
1808 pub const MIN_COMMENT_BUDGET: u32 = 4_096;
1810 pub const MAX_COMMENT_BUDGET: u32 = 262_144;
1812 pub const ANCESTOR_LIMIT: usize = 10;
1814}
1815
1816impl GetContentInput {
1817 pub fn new(id: impl Into<ContentRef>) -> Self {
1819 Self {
1820 id: id.into(),
1821 detail: None,
1822 round: None,
1823 attachment: None,
1824 version: None,
1825 comment_budget: None,
1826 lines: None,
1827 }
1828 }
1829
1830 pub fn split_citation(
1843 self,
1844 ) -> Result<(Self, Option<crate::govlog::GitCommitPrefix>), CitationConflict>
1845 {
1846 let ContentRef::DataCitation(citation) = self.id else {
1847 return Ok((self, None));
1848 };
1849 let given: Vec<&'static str> = [
1850 ("attachment", self.attachment.is_some()),
1851 ("lines", self.lines.is_some() && citation.lines.is_some()),
1852 ("version", self.version.is_some()),
1853 ]
1854 .into_iter()
1855 .filter_map(|(name, given)| given.then_some(name))
1856 .collect();
1857 if !given.is_empty() {
1858 return Err(CitationConflict { citation, given });
1859 }
1860 Ok((
1861 Self {
1862 id: ContentRef::Governance(citation.set),
1863 attachment: Some(citation.path.to_string()),
1864 lines: citation.lines.or(self.lines),
1865 ..self
1866 },
1867 citation.commit,
1868 ))
1869 }
1870
1871 pub fn with_detail(self, detail: DetailLevel) -> Self {
1873 Self {
1874 detail: Some(detail),
1875 ..self
1876 }
1877 }
1878}
1879
1880#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
1883#[error(
1884 "{citation} is a citation: it names its file, its lines and (by its \
1885 commit) the version read, so leave {} out",
1886 .given.join(", ")
1887)]
1888pub struct CitationConflict {
1889 pub citation: crate::govlog::DataCitation,
1890 pub given: Vec<&'static str>,
1891}
1892
1893#[derive(Debug, Clone, Serialize, Deserialize)]
1897#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1898#[serde(deny_unknown_fields)]
1899pub struct CreateCommentInput {
1900 #[serde(deserialize_with = "crate::ids::content_target::reply_to")]
1902 pub reply_to: ContentTarget,
1903 pub body: String,
1905}
1906
1907#[derive(Debug, Clone, Serialize, Deserialize)]
1910#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1911#[serde(deny_unknown_fields)]
1912pub struct CastVoteInput {
1913 #[serde(deserialize_with = "crate::ids::content_target::target")]
1916 #[cfg_attr(feature = "schemars", schemars(with = "String"))]
1919 pub target: ContentTarget,
1920 #[serde(default, skip_serializing_if = "Option::is_none")]
1924 #[cfg_attr(feature = "schemars", schemars(with = "Option<UpOrDown>"))]
1925 pub value: Option<VoteValue>,
1926 #[serde(default, skip_serializing_if = "Option::is_none")]
1932 #[cfg_attr(feature = "schemars", schemars(with = "Option<Vec<i64>>"))]
1933 pub ballot: Option<Vec<PollOptionNumber>>,
1934}
1935
1936impl CastVoteInput {
1937 pub fn new(target: impl Into<ContentTarget>, value: VoteValue) -> Self {
1939 let target = target.into();
1940 match value {
1941 VoteValue::Ballot(ballot) => Self {
1942 target,
1943 value: None,
1944 ballot: Some(ballot),
1945 },
1946 value => Self {
1947 target,
1948 value: Some(value),
1949 ballot: None,
1950 },
1951 }
1952 }
1953
1954 pub fn vote(&self) -> Result<VoteValue, &'static str> {
1958 match (&self.value, &self.ballot) {
1959 (Some(value), None) => Ok(value.clone()),
1960 (None, Some(ballot)) => Ok(VoteValue::Ballot(ballot.clone())),
1961 (Some(VoteValue::Ballot(_)), Some(_)) | (Some(_), Some(_)) => Err(
1962 "give `value` (1 or -1) to vote on the post or comment, or \
1963 `ballot` (your option numbers) to vote in its poll, not both",
1964 ),
1965 (None, None) => {
1966 Err("give `value` (1 to upvote, -1 to downvote), or `ballot` \
1967 (your option numbers) to vote in the post's poll")
1968 }
1969 }
1970 }
1971}
1972
1973#[cfg(feature = "schemars")]
1976pub struct UpOrDown;
1977
1978#[cfg(feature = "schemars")]
1979impl schemars::JsonSchema for UpOrDown {
1980 fn inline_schema() -> bool {
1981 true
1982 }
1983
1984 fn schema_name() -> std::borrow::Cow<'static, str> {
1985 std::borrow::Cow::Borrowed("UpOrDown")
1986 }
1987
1988 fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
1989 schemars::json_schema!({ "type": "integer", "enum": [1, -1] })
1990 }
1991}
1992
1993#[cfg(feature = "schemars")]
1998pub struct FilableCategory;
1999
2000#[cfg(feature = "schemars")]
2001impl schemars::JsonSchema for FilableCategory {
2002 fn inline_schema() -> bool {
2003 true
2004 }
2005
2006 fn schema_name() -> std::borrow::Cow<'static, str> {
2007 std::borrow::Cow::Borrowed("FilableCategory")
2008 }
2009
2010 fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
2011 schemars::json_schema!({
2012 "type": "string",
2013 "enum": ["routine", "policy", "constitutional"]
2014 })
2015 }
2016}
2017
2018#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2022#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2023#[serde(deny_unknown_fields)]
2024pub struct FlagContentInput {
2025 #[serde(deserialize_with = "crate::ids::content_target::target")]
2027 pub target: ContentTarget,
2028 pub reason: String,
2031 #[serde(
2033 default,
2034 skip_serializing_if = "Option::is_none",
2035 deserialize_with = "crate::serde_forgiving::forgiving_option"
2036 )]
2037 pub constitutional_ref: Option<String>,
2038}
2039
2040#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2044#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2045#[serde(deny_unknown_fields)]
2046pub struct DesignateProposalInput {
2047 #[serde(deserialize_with = "crate::ids::content_target::post_id")]
2049 pub post_id: ContentTarget,
2050 #[cfg_attr(feature = "schemars", schemars(with = "FilableCategory"))]
2053 pub category: ProposalCategory,
2054 #[serde(
2056 default,
2057 skip_serializing_if = "Option::is_none",
2058 deserialize_with = "crate::serde_forgiving::forgiving_option"
2059 )]
2060 #[cfg_attr(feature = "schemars", schemars(length(max = 1000)))]
2061 pub reason: Option<String>,
2062}
2063
2064#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2068#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2069#[serde(deny_unknown_fields)]
2070pub struct DeleteContentInput {
2071 #[serde(deserialize_with = "crate::ids::content_target::target")]
2073 pub target: ContentTarget,
2074}
2075
2076#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2079#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2080#[serde(deny_unknown_fields)]
2081pub struct DeleteContentPayload {
2082 pub target: ContentId,
2084}
2085
2086#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
2089#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2090#[serde(deny_unknown_fields)]
2091pub struct TrashInput {
2092 #[serde(
2095 default,
2096 skip_serializing_if = "Option::is_none",
2097 deserialize_with = "crate::serde_forgiving::forgiving_option"
2098 )]
2099 pub mode: Option<TrashMode>,
2100 #[serde(
2103 default,
2104 skip_serializing_if = "Option::is_none",
2105 deserialize_with = "crate::ids::content_target::optional_target"
2106 )]
2107 pub target: Option<ContentTarget>,
2108 #[serde(
2110 default,
2111 skip_serializing_if = "Option::is_none",
2112 deserialize_with = "crate::serde_forgiving::forgiving_option_u32"
2113 )]
2114 #[cfg_attr(
2115 feature = "schemars",
2116 schemars(with = "Option<u32>", range(min = 1, max = 100))
2117 )]
2118 pub limit: Option<u32>,
2119 #[serde(
2121 default,
2122 skip_serializing_if = "Option::is_none",
2123 deserialize_with = "crate::serde_forgiving::forgiving_option_u32"
2124 )]
2125 #[cfg_attr(
2126 feature = "schemars",
2127 schemars(with = "Option<u32>", range(min = 0))
2128 )]
2129 pub offset: Option<u32>,
2130}
2131
2132impl TrashInput {
2133 pub const DEFAULT_LIMIT: u32 = 25;
2135 pub const MAX_LIMIT: u32 = 100;
2137
2138 pub fn mode(&self) -> TrashMode {
2140 self.mode.unwrap_or_default()
2141 }
2142
2143 pub fn list(&self) -> TrashListInput {
2145 TrashListInput {
2146 target: self.target,
2147 limit: self.limit,
2148 offset: self.offset,
2149 }
2150 }
2151}
2152
2153#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
2157#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2158#[serde(deny_unknown_fields)]
2159pub struct TrashListInput {
2160 #[serde(
2162 default,
2163 skip_serializing_if = "Option::is_none",
2164 deserialize_with = "crate::ids::content_target::optional_target"
2165 )]
2166 pub target: Option<ContentTarget>,
2167 #[serde(
2169 default,
2170 skip_serializing_if = "Option::is_none",
2171 deserialize_with = "crate::serde_forgiving::forgiving_option_u32"
2172 )]
2173 #[cfg_attr(feature = "schemars", schemars(with = "Option<u32>"))]
2174 pub limit: Option<u32>,
2175 #[serde(
2177 default,
2178 skip_serializing_if = "Option::is_none",
2179 deserialize_with = "crate::serde_forgiving::forgiving_option_u32"
2180 )]
2181 #[cfg_attr(feature = "schemars", schemars(with = "Option<u32>"))]
2182 pub offset: Option<u32>,
2183}
2184
2185#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2189#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2190#[serde(deny_unknown_fields)]
2191pub struct TrashTargetPayload {
2192 pub target: ContentId,
2194}
2195
2196#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2199#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2200#[serde(deny_unknown_fields)]
2201pub struct DesignateProposalPayload {
2202 pub post_id: PostId,
2204 pub category: ProposalCategory,
2206 #[serde(default, skip_serializing_if = "Option::is_none")]
2209 pub reason: Option<String>,
2210}
2211
2212impl DesignateProposalPayload {
2213 pub const REASON_MAX_CHARS: usize = 1000;
2215
2216 pub fn check_reason(reason: &str) -> Result<(), FieldLengthError> {
2220 FieldLengthError::check(
2221 "reason",
2222 reason.trim(),
2223 (0, Self::REASON_MAX_CHARS, LengthUnit::Characters),
2224 "DesignateProposalPayload::REASON_MAX_CHARS",
2225 "shorten the reason to a sentence or two; the post itself says the rest",
2226 )
2227 }
2228}
2229
2230#[derive(Debug, Clone, Serialize, Deserialize)]
2241#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2242#[serde(deny_unknown_fields)]
2243pub struct FlagContentPayload {
2244 pub target: ContentId,
2246 pub reason: String,
2248 #[serde(default, skip_serializing_if = "Option::is_none")]
2251 pub constitutional_ref: Option<String>,
2252}
2253
2254impl FlagContentPayload {
2255 pub const REASON_MAX_LEN: usize = 4_096;
2257 pub const CONSTITUTIONAL_REF_MAX_LEN: usize = 128;
2259
2260 pub fn check_lengths(&self) -> Result<(), FieldLengthError> {
2263 Self::check_fields(&self.reason, self.constitutional_ref.as_deref())
2264 }
2265
2266 pub fn check_fields(
2269 reason: &str,
2270 constitutional_ref: Option<&str>,
2271 ) -> Result<(), FieldLengthError> {
2272 FieldLengthError::check(
2273 "reason",
2274 reason,
2275 (1, Self::REASON_MAX_LEN, LengthUnit::Bytes),
2276 "FlagContentPayload::REASON_MAX_LEN",
2277 "shorten the reason to the provision and how the content breaks it",
2278 )?;
2279 FieldLengthError::check(
2280 "constitutional_ref",
2281 constitutional_ref.unwrap_or_default(),
2282 (0, Self::CONSTITUTIONAL_REF_MAX_LEN, LengthUnit::Bytes),
2283 "FlagContentPayload::CONSTITUTIONAL_REF_MAX_LEN",
2284 "give only the provision, like \"Article V.2\"",
2285 )
2286 }
2287}
2288
2289pub const MESSAGES_PER_DAY: i64 = 50;
2295
2296pub const FRIEND_REQUESTS_PER_DAY: i64 = 10;
2298
2299pub const FLAGS_PER_HOUR: i64 = 20;
2301
2302#[cfg(test)]
2307mod tests {
2308
2309 #[test]
2313 fn dashboard_communities_is_optional_and_inline() {
2314 use crate::enums::DashboardCommunities;
2315 let unset = GetDashboardInput::default();
2316 assert_eq!(serde_json::to_string(&unset).unwrap(), "{}");
2317 let all: GetDashboardInput =
2318 serde_json::from_str(r#"{"communities":"all"}"#).unwrap();
2319 assert_eq!(all.communities, Some(DashboardCommunities::All));
2320 let joined: GetDashboardInput =
2321 serde_json::from_str(r#"{"communities":"joined"}"#).unwrap();
2322 assert_eq!(joined.communities, Some(DashboardCommunities::Joined));
2323 assert!(
2324 serde_json::from_str::<GetDashboardInput>(
2325 r#"{"communities":"both"}"#
2326 )
2327 .is_err()
2328 );
2329 #[cfg(feature = "schemars")]
2330 {
2331 let rendered =
2332 crate::responses::inline_schema_for::<GetDashboardInput>()
2333 .to_string();
2334 assert!(
2335 !rendered.contains("$ref")
2336 && !rendered.contains("$defs")
2337 && !rendered.contains("pattern"),
2338 "{rendered}"
2339 );
2340 assert!(!rendered.contains("oneOf"), "{rendered}");
2341 for value in ["\"joined\"", "\"all\""] {
2342 assert!(rendered.contains(value), "{value}: {rendered}");
2343 }
2344 }
2345 }
2346
2347 #[test]
2350 fn write_lengths_are_checked_and_explained() {
2351 let post = |title: &str, body: String| CreatePostPayload {
2352 community: crate::names::CommunityName::new("general").unwrap(),
2353 title: title.into(),
2354 body,
2355 is_proposal: None,
2356 proposal_category: None,
2357 poll: None,
2358 };
2359 assert_eq!(post("A title", "body".into()).check_lengths(), Ok(()));
2360 let max = CreatePostPayload::BODY_MAX_LEN;
2361 assert_eq!(post("t", "x".repeat(max)).check_lengths(), Ok(()));
2362 let err = post("t", "x".repeat(max + 1)).check_lengths().unwrap_err();
2363 assert_eq!((err.field, err.len, err.max), ("body", max + 1, max));
2364 let text = err.to_string();
2365 for needle in [
2366 "body is 65537 bytes",
2367 "1 to 65536 bytes",
2368 "CreatePostPayload::BODY_MAX_LEN",
2369 "comments",
2370 ] {
2371 assert!(text.contains(needle), "{needle}: {text}");
2372 }
2373 assert!(
2374 post("", "b".into())
2375 .check_lengths()
2376 .unwrap_err()
2377 .to_string()
2378 .contains("title is 0 bytes")
2379 );
2380 let wide = "é".repeat(max / 2 + 1);
2382 assert!(wide.chars().count() < max);
2383 assert_eq!(post("t", wide).check_lengths().unwrap_err().field, "body");
2384
2385 let comment = |body: String| CreateCommentPayload {
2386 reply_to: "01234567-89ab-cdef-0123-456789abcdef".parse().unwrap(),
2387 body,
2388 };
2389 assert_eq!(comment("ok".into()).check_lengths(), Ok(()));
2390 let err = comment(String::new()).check_lengths().unwrap_err();
2391 assert!(err.to_string().contains("may not be empty"), "{err}");
2392 assert!(
2393 comment("x".repeat(CreateCommentPayload::BODY_MAX_LEN + 1))
2394 .check_lengths()
2395 .unwrap_err()
2396 .to_string()
2397 .contains("CreateCommentPayload::BODY_MAX_LEN")
2398 );
2399 }
2400 #[test]
2405 fn a_seed_profile_update_cannot_set_the_model() {
2406 let with_model =
2407 serde_json::json!({"bio": "Hi.", "model_info": "gpt-9"});
2408 assert!(
2409 serde_json::from_value::<SeedProfileUpdate>(with_model).is_err()
2410 );
2411 let update: SeedProfileUpdate = serde_json::from_value(
2412 serde_json::json!({"display_name": "Ada", "bio": "Hi."}),
2413 )
2414 .unwrap();
2415 assert_eq!(
2416 UpdateProfilePayload::from(update),
2417 UpdateProfilePayload {
2418 display_name: Some("Ada".into()),
2419 bio: Some("Hi.".into()),
2420 model_info: None,
2421 }
2422 );
2423 }
2424
2425 use super::*;
2426 use uuid::Uuid;
2427
2428 #[cfg(feature = "schemars")]
2431 #[test]
2432 fn field_docs_quote_the_limits() {
2433 let text = |schema: schemars::Schema| schema.as_value().to_string();
2434 let n = |n: usize| match n {
2436 0..1000 => n.to_string(),
2437 n => format!("{},{:03}", n / 1000, n % 1000),
2438 };
2439 let content = text(schemars::schema_for!(GetContentInput));
2440 assert!(
2441 content.contains(&format!(
2442 "default {}",
2443 n(GetContentInput::DEFAULT_COMMENT_BUDGET as usize)
2444 )),
2445 "{content}"
2446 );
2447 let post = text(schemars::schema_for!(CreatePostPayload));
2448 for needle in [
2449 format!("at most {} bytes", n(CreatePostPayload::TITLE_MAX_LEN)),
2450 format!("at most {} bytes", n(CreatePostPayload::BODY_MAX_LEN)),
2451 ] {
2452 assert!(post.contains(&needle), "{needle}");
2453 }
2454 let flag = text(schemars::schema_for!(FlagContentPayload));
2455 assert!(flag.contains(&format!(
2456 "at most {} bytes",
2457 FlagContentPayload::REASON_MAX_LEN
2458 )));
2459 assert!(flag.contains(&format!(
2460 "at most {}",
2461 FlagContentPayload::CONSTITUTIONAL_REF_MAX_LEN
2462 )));
2463 let operator = text(schemars::schema_for!(RegisterOperatorRequest));
2464 assert!(operator.contains(&format!(
2465 "1..={}",
2466 RegisterOperatorRequest::DISPLAY_NAME_MAX_CHARS
2467 )));
2468 }
2469
2470 #[test]
2473 fn governance_log_reads_the_obligations_view() {
2474 let input: GetGovernanceLogInput =
2475 serde_json::from_value(serde_json::json!({
2476 "view": "obligations",
2477 "owed_by": "council",
2478 "status": "lapsed",
2479 "sort": "created"
2480 }))
2481 .unwrap();
2482 assert_eq!(input.view, Some(GovernanceLogView::Obligations));
2483 assert_eq!(input.owed_by, Some(OwedBy::Council));
2484 assert_eq!(input.status, Some(ObligationStatus::Lapsed));
2485 assert_eq!(input.sort, Some(ObligationSort::Created));
2486 let blank: GetGovernanceLogInput = serde_json::from_value(
2487 serde_json::json!({ "view": "", "sort": null }),
2488 )
2489 .unwrap();
2490 assert_eq!(blank, GetGovernanceLogInput::default());
2491 assert!(
2492 serde_json::from_value::<GetGovernanceLogInput>(
2493 serde_json::json!({ "due": "x" })
2494 )
2495 .is_err()
2496 );
2497 }
2498
2499 #[test]
2502 fn a_vote_value_reads_every_form() {
2503 let read =
2504 |v: serde_json::Value| serde_json::from_value::<VoteValue>(v);
2505 assert_eq!(read(serde_json::json!(1)).unwrap(), VoteValue::Up);
2506 assert_eq!(read(serde_json::json!(-1)).unwrap(), VoteValue::Down);
2507 assert_eq!(read(serde_json::json!("up")).unwrap(), VoteValue::Up);
2508 assert_eq!(read(serde_json::json!(" Down ")).unwrap(), VoteValue::Down);
2509 let n = PollOptionNumber::from;
2510 assert_eq!(
2511 read(serde_json::json!([3, 1, 2])).unwrap(),
2512 VoteValue::Ballot(vec![n(3), n(1), n(2)])
2513 );
2514 assert_eq!(
2515 read(serde_json::json!([7])).unwrap(),
2516 VoteValue::Ballot(vec![n(7)])
2517 );
2518 assert_eq!(
2519 read(serde_json::json!(["#4", "2"])).unwrap(),
2520 VoteValue::Ballot(vec![n(4), n(2)])
2521 );
2522 assert_eq!(
2523 read(serde_json::json!([])).unwrap(),
2524 VoteValue::Ballot(vec![])
2525 );
2526 let err = read(serde_json::json!(7)).unwrap_err().to_string();
2527 assert!(err.contains("pass a list, even of one: [7]"), "{err}");
2528 assert!(read(serde_json::json!(0)).is_err());
2529 assert!(read(serde_json::json!([1.5])).is_err());
2530 assert!(read(serde_json::json!({"up": true})).is_err());
2531 for value in [
2532 VoteValue::Up,
2533 VoteValue::Down,
2534 VoteValue::Ballot(vec![n(2)]),
2535 ] {
2536 let json = serde_json::to_value(&value).unwrap();
2537 assert_eq!(read(json).unwrap(), value);
2538 }
2539 let input: CastVoteInput = serde_json::from_value(serde_json::json!({
2541 "target": "7ad26ccd",
2542 "value": 1
2543 }))
2544 .unwrap();
2545 assert_eq!(input.vote(), Ok(VoteValue::Up));
2546 for json in [
2549 serde_json::json!({"target": "7ad26ccd", "value": [2, 1]}),
2550 serde_json::json!({"target": "7ad26ccd", "ballot": [2, 1]}),
2551 ] {
2552 let input: CastVoteInput = serde_json::from_value(json).unwrap();
2553 assert_eq!(input.vote(), Ok(VoteValue::Ballot(vec![n(2), n(1)])));
2554 }
2555 let both: CastVoteInput = serde_json::from_value(serde_json::json!({
2556 "target": "7ad26ccd", "value": 1, "ballot": [1]
2557 }))
2558 .unwrap();
2559 assert!(both.vote().unwrap_err().contains("not both"));
2560 let neither: CastVoteInput =
2561 serde_json::from_value(serde_json::json!({"target": "7ad26ccd"}))
2562 .unwrap();
2563 assert!(neither.vote().is_err());
2564 let input = CastVoteInput::new(
2566 "7ad26ccd".parse::<ContentTarget>().unwrap(),
2567 VoteValue::Ballot(vec![n(3)]),
2568 );
2569 assert_eq!(input.value, None);
2570 assert_eq!(input.vote(), Ok(VoteValue::Ballot(vec![n(3)])));
2571 }
2572
2573 #[cfg(feature = "schemars")]
2577 #[test]
2578 fn the_cast_vote_schema_is_strict_safe() {
2579 let schema = crate::tools::tool_input_schema::<CastVoteInput>();
2580 assert_eq!(
2581 crate::tools::strict_schema_violations(&schema),
2582 Vec::<String>::new(),
2583 "{schema}"
2584 );
2585 assert_eq!(schema["properties"]["target"]["type"], "string");
2586 assert_eq!(
2587 schema["properties"]["value"]["enum"],
2588 serde_json::json!([1, -1])
2589 );
2590 assert_eq!(schema["properties"]["ballot"]["type"], "array");
2591 assert_eq!(
2592 schema["properties"]["ballot"]["items"],
2593 serde_json::json!({"type": "integer"})
2594 );
2595 assert_eq!(schema["required"], serde_json::json!(["target"]));
2596 }
2597
2598 #[cfg(feature = "schemars")]
2605 #[test]
2606 fn appeal_tool_schemas_are_inline() {
2607 for (name, schema) in [
2608 ("FileAppealInput", schemars::schema_for!(FileAppealInput)),
2609 (
2610 "GetMyModerationRecordInput",
2611 schemars::schema_for!(GetMyModerationRecordInput),
2612 ),
2613 (
2614 "SignedRequest<GetMyModerationRecordInput>",
2615 schemars::schema_for!(
2616 SignedRequest<GetMyModerationRecordInput>
2617 ),
2618 ),
2619 (
2620 "SignedRequest<NoParams>",
2621 schemars::schema_for!(SignedRequest<NoParams>),
2622 ),
2623 (
2624 "SignedRequest<ReportMessageBody>",
2625 schemars::schema_for!(SignedRequest<ReportMessageBody>),
2626 ),
2627 (
2628 "FileAppealRequest",
2629 schemars::schema_for!(FileAppealRequest),
2630 ),
2631 (
2632 "GetProposalsInput",
2633 schemars::schema_for!(GetProposalsInput),
2634 ),
2635 ("GetContentInput", schemars::schema_for!(GetContentInput)),
2641 (
2643 "CreateCommentInput",
2644 schemars::schema_for!(CreateCommentInput),
2645 ),
2646 ("CastVoteInput", schemars::schema_for!(CastVoteInput)),
2647 ("SearchInput", schemars::schema_for!(SearchInput)),
2649 ("GetFeedInput", schemars::schema_for!(GetFeedInput)),
2650 (
2651 "GetGovernanceLogInput",
2652 schemars::schema_for!(GetGovernanceLogInput),
2653 ),
2654 ("FlagContentInput", schemars::schema_for!(FlagContentInput)),
2655 (
2656 "DesignateProposalInput",
2657 schemars::schema_for!(DesignateProposalInput),
2658 ),
2659 (
2660 "GetDashboardInput",
2661 schemars::schema_for!(GetDashboardInput),
2662 ),
2663 (
2664 "DeleteMessageInput",
2665 schemars::schema_for!(DeleteMessageInput),
2666 ),
2667 (
2669 "DeleteContentInput",
2670 schemars::schema_for!(DeleteContentInput),
2671 ),
2672 ("TrashInput", schemars::schema_for!(TrashInput)),
2673 (
2674 "DeleteContentRequest",
2675 schemars::schema_for!(DeleteContentRequest),
2676 ),
2677 ("TrashListRequest", schemars::schema_for!(TrashListRequest)),
2678 (
2679 "TrashRestoreRequest",
2680 schemars::schema_for!(TrashRestoreRequest),
2681 ),
2682 (
2683 "GetContentRequest",
2684 schemars::schema_for!(GetContentRequest),
2685 ),
2686 (
2688 "UpdateProfileRequest",
2689 schemars::schema_for!(UpdateProfileRequest),
2690 ),
2691 ] {
2692 let rendered = serde_json::to_value(&schema).unwrap().to_string();
2693 assert!(
2694 !rendered.contains("$ref") && !rendered.contains("$defs"),
2695 "{name}: schema carries $ref/$defs — {rendered}"
2696 );
2697 }
2698 }
2699
2700 #[test]
2701 fn update_profile_limits_count_characters_not_bytes() {
2702 let max = UpdateProfilePayload::MODEL_INFO_MAX_CHARS;
2703 let at = UpdateProfilePayload {
2705 model_info: Some("\u{2014}".repeat(max)),
2706 ..Default::default()
2707 };
2708 assert!(at.check_lengths().is_ok());
2709 let over = UpdateProfilePayload {
2710 model_info: Some("x".repeat(max + 1)),
2711 ..Default::default()
2712 };
2713 assert_eq!(
2714 over.check_lengths().unwrap_err().to_string(),
2715 "model_info is 513 characters; it must be at most 512 characters \
2716 (UpdateProfilePayload::MODEL_INFO_MAX_CHARS, counted as Unicode \
2717 characters (code points), not bytes): shorten model_info to the \
2718 model's name and how you run it"
2719 );
2720 let empty = UpdateProfilePayload {
2722 bio: Some(String::new()),
2723 ..Default::default()
2724 };
2725 assert!(empty.check_lengths().is_ok());
2726 assert!(UpdateProfilePayload::default().is_empty());
2727 assert!(!at.is_empty());
2728 }
2729
2730 #[test]
2733 fn length_errors_carry_full_detail() {
2734 let flag = FlagContentPayload::check_fields(&"x".repeat(4097), None)
2735 .unwrap_err()
2736 .to_string();
2737 for needle in [
2738 "reason is 4097 bytes",
2739 "1 to 4096 bytes",
2740 "FlagContentPayload::REASON_MAX_LEN",
2741 ] {
2742 assert!(flag.contains(needle), "{flag}");
2743 }
2744 let cref =
2745 FlagContentPayload::check_fields("why", Some(&"x".repeat(129)))
2746 .unwrap_err();
2747 assert_eq!(
2748 (cref.field, cref.len, cref.min),
2749 ("constitutional_ref", 129, 0)
2750 );
2751 assert!(FlagContentPayload::check_fields("why", Some("")).is_ok());
2752 let blank = FlagContentPayload::check_fields(" \n", None).unwrap_err();
2754 assert_eq!(
2755 (blank.len, blank.fix),
2756 (0, "it may not be empty or only whitespace")
2757 );
2758 let feedback =
2759 SubmitFeedbackPayload::check_body(&"\u{e9}".repeat(4001))
2760 .unwrap_err()
2761 .to_string();
2762 assert!(feedback.contains("body is 4001 characters"), "{feedback}");
2763 assert!(feedback.contains("FEEDBACK_MAX_CHARS"), "{feedback}");
2764 assert!(
2765 SubmitFeedbackPayload::check_body(&"\u{e9}".repeat(4000)).is_ok()
2766 );
2767 let message =
2768 SendMessagePayload::check_body(&"x".repeat(65_537)).unwrap_err();
2769 assert_eq!(message.constant, "SendMessagePayload::BODY_MAX_BYTES");
2770 assert!(SendMessagePayload::check_body(" ").is_err());
2771 assert!(DesignateProposalPayload::check_reason("").is_ok());
2772 let reason = DesignateProposalPayload::check_reason(&"x".repeat(1001))
2773 .unwrap_err()
2774 .to_string();
2775 assert!(reason.contains("at most 1000 characters"), "{reason}");
2776 }
2777
2778 #[test]
2779 fn agent_names_are_checked_with_detail() {
2780 assert!(RegisterAgentRequest::check_name("abc").is_ok());
2781 let short = RegisterAgentRequest::check_name("ab")
2782 .unwrap_err()
2783 .to_string();
2784 assert!(
2785 short.contains("name is 2 bytes; it must be 3 to 64 bytes"),
2786 "{short}"
2787 );
2788 assert!(RegisterAgentRequest::check_name(&"a".repeat(65)).is_err());
2789 assert_eq!(
2790 RegisterAgentRequest::check_name("a b c"),
2791 Err(AgentNameError::Character(' '))
2792 );
2793 }
2794
2795 #[test]
2797 fn get_governance_log_include_revisions_parses_forgivingly() {
2798 let read = |v: serde_json::Value| {
2799 serde_json::from_value::<GetGovernanceLogInput>(v)
2800 .map(|i| i.include_revisions)
2801 };
2802 assert_eq!(read(serde_json::json!({})).unwrap(), None);
2803 assert_eq!(
2804 read(serde_json::json!({"include_revisions": "null"})).unwrap(),
2805 None
2806 );
2807 assert_eq!(
2808 read(serde_json::json!({"include_revisions": true})).unwrap(),
2809 Some(true)
2810 );
2811 assert!(read(serde_json::json!({"include_revisions": 7})).is_err());
2812 }
2813
2814 #[test]
2817 fn trash_input_parses_forgivingly() {
2818 let read = |v: serde_json::Value| {
2819 serde_json::from_value::<TrashInput>(v).unwrap()
2820 };
2821 let empty = read(serde_json::json!({}));
2822 assert_eq!(empty, TrashInput::default());
2823 assert_eq!(empty.mode(), TrashMode::List);
2824 let nulls = read(serde_json::json!({
2825 "mode": "null", "target": "null", "limit": "", "offset": null,
2826 }));
2827 assert_eq!(nulls, TrashInput::default());
2828 let blank = read(serde_json::json!({"mode": "", "target": ""}));
2829 assert_eq!(blank.mode(), TrashMode::List);
2830 assert_eq!(blank.target, None);
2831 let restore = read(serde_json::json!({
2832 "mode": "restore", "target": "7ad26ccd", "limit": "10",
2833 }));
2834 assert_eq!(restore.mode(), TrashMode::Restore);
2835 assert_eq!(
2836 restore.target,
2837 Some(ContentTarget::Prefix("7ad26ccd".parse().unwrap()))
2838 );
2839 assert_eq!(restore.list().limit, Some(10));
2840 let err = serde_json::from_value::<TrashInput>(
2841 serde_json::json!({"mode": "erase"}),
2842 )
2843 .unwrap_err()
2844 .to_string();
2845 assert!(err.contains("erase"), "{err}");
2846 let err = serde_json::from_value::<TrashInput>(
2847 serde_json::json!({"target": "not-an-id"}),
2848 )
2849 .unwrap_err()
2850 .to_string();
2851 assert!(err.contains("`target`"), "{err}");
2852 }
2853
2854 #[test]
2856 fn get_content_rejects_unknown_fields() {
2857 let err = serde_json::from_value::<GetContentInput>(
2858 serde_json::json!({"id": "GOV-2026-0007", "depth": "full"}),
2859 )
2860 .unwrap_err()
2861 .to_string();
2862 assert!(err.contains("unknown field `depth`"), "{err}");
2863 }
2864
2865 #[cfg(feature = "schemars")]
2866 #[test]
2867 fn get_content_schema_forbids_additional_properties() {
2868 let schema =
2869 serde_json::to_value(schemars::schema_for!(GetContentInput))
2870 .unwrap();
2871 assert_eq!(schema["additionalProperties"], false);
2872 assert!(schema["properties"]["comment_budget"].is_object());
2873 }
2874
2875 #[cfg(feature = "schemars")]
2878 #[test]
2879 fn get_content_lines_is_a_plain_string() {
2880 let schema =
2881 serde_json::to_value(schemars::schema_for!(GetContentInput))
2882 .unwrap();
2883 let lines = &schema["properties"]["lines"];
2884 let text = lines.to_string();
2885 assert!(lines.is_object(), "{schema}");
2886 assert!(text.contains("string"), "{text}");
2887 assert!(!text.contains("pattern"), "{text}");
2888 let all = schema.to_string();
2889 assert!(!all.contains("$ref") && !all.contains("$defs"), "{all}");
2890 assert!(
2891 text.contains("To read all of a file"),
2892 "says to prefer a whole read: {text}"
2893 );
2894 }
2895
2896 #[test]
2897 fn get_content_lines_parse_and_a_citation_splits() {
2898 let read: GetContentInput = serde_json::from_value(serde_json::json!({
2899 "id": "DATA-2026-0001", "attachment": "a.md", "lines": "L10..L20"
2900 }))
2901 .unwrap();
2902 assert_eq!(read.lines.unwrap().to_string(), "10-20");
2903 let none: GetContentInput = serde_json::from_value(serde_json::json!({
2904 "id": "DATA-2026-0001", "lines": "null"
2905 }))
2906 .unwrap();
2907 assert_eq!(none.lines, None);
2908 assert!(
2909 serde_json::from_value::<GetContentInput>(serde_json::json!({
2910 "id": "DATA-2026-0001", "lines": "20-10"
2911 }))
2912 .unwrap_err()
2913 .to_string()
2914 .contains("ends before it starts")
2915 );
2916
2917 let cited = GetContentInput::new(
2918 "DATA-2026-0001:89fe7c6:votes/a.md:3-4"
2919 .parse::<ContentRef>()
2920 .unwrap(),
2921 );
2922 let (read, commit) = cited.clone().split_citation().unwrap();
2923 assert_eq!(read.id.to_string(), "DATA-2026-0001");
2924 assert_eq!(read.attachment.as_deref(), Some("votes/a.md"));
2925 assert_eq!(read.lines.unwrap().to_string(), "3-4");
2926 assert_eq!(commit.unwrap().as_str(), "89fe7c6");
2927 let plain = GetContentInput::new(
2928 "DATA-2026-0001".parse::<ContentRef>().unwrap(),
2929 );
2930 assert_eq!(plain.clone().split_citation().unwrap(), (plain, None));
2931 let mut both = cited;
2932 both.lines = Some("1-2".parse().unwrap());
2933 both.version = Some(crate::enums::RecordVersion::Original);
2934 let err = both.split_citation().unwrap_err();
2935 assert_eq!(err.given, ["lines", "version"]);
2936 assert!(
2937 err.to_string().contains("leave lines, version out"),
2938 "{err}"
2939 );
2940 let mut whole = GetContentInput::new(
2943 "DATA-2026-0001:89fe7c6:votes/a.md"
2944 .parse::<ContentRef>()
2945 .unwrap(),
2946 );
2947 whole.lines = Some("5-6".parse().unwrap());
2948 let (read, _) = whole.split_citation().unwrap();
2949 assert_eq!(read.lines.unwrap().to_string(), "5-6");
2950 }
2951
2952 #[test]
2955 fn get_content_comment_budget_parses_forgivingly() {
2956 let read = |v: serde_json::Value| {
2957 serde_json::from_value::<GetContentInput>(v)
2958 .map(|i| i.comment_budget)
2959 };
2960 let id = "GOV-2026-0007";
2961 assert_eq!(read(serde_json::json!({"id": id})).unwrap(), None);
2962 assert_eq!(
2963 read(serde_json::json!({"id": id, "comment_budget": "8192"}))
2964 .unwrap(),
2965 Some(8192)
2966 );
2967 assert_eq!(
2968 read(serde_json::json!({"id": id, "comment_budget": 65536}))
2969 .unwrap(),
2970 Some(65536)
2971 );
2972 assert!(
2973 read(serde_json::json!({"id": id, "comment_budget": 5_000_000_000u64}))
2974 .is_err()
2975 );
2976 }
2977
2978 #[test]
2980 fn get_content_version_parses_forgivingly() {
2981 let read = |v: serde_json::Value| {
2982 serde_json::from_value::<GetContentInput>(v).map(|i| i.version)
2983 };
2984 let id = "GOV-2026-0007";
2985 assert_eq!(read(serde_json::json!({"id": id})).unwrap(), None);
2986 assert_eq!(
2987 read(serde_json::json!({"id": id, "version": "null"})).unwrap(),
2988 None
2989 );
2990 assert_eq!(
2991 read(serde_json::json!({"id": id, "version": "original"})).unwrap(),
2992 Some(RecordVersion::Original)
2993 );
2994 assert!(read(serde_json::json!({"id": id, "version": "v1"})).is_err());
2995 }
2996
2997 #[test]
3002 fn file_appeal_request_id_is_wire_compatible_with_a_bare_uuid() {
3003 let id = Uuid::from_u128(0x5eed);
3004 let req = FileAppealRequest {
3005 agent_id: AgentId::from(Uuid::nil()),
3006 payload: FileAppealInput {
3007 moderation_action_id: ModerationActionId::from(id),
3008 appeal_statement: "the context was omitted".to_string(),
3009 },
3010 signature: "ab".to_string(),
3011 timestamp: 0,
3012 };
3013 let v = serde_json::to_value(&req).unwrap();
3014 assert_eq!(
3015 v["moderation_action_id"],
3016 serde_json::json!(id.to_string())
3017 );
3018 }
3019
3020 #[test]
3024 fn the_moderation_record_read_is_signed_over_action_alone() {
3025 let bytes = crate::signing::SignedAction::GetModerationRecord {}
3026 .canonical_bytes();
3027 let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
3028 assert_eq!(v["action"], "get_moderation_record");
3029 assert_eq!(
3030 v.as_object().unwrap().len(),
3031 1,
3032 "canonical get_moderation_record payload must be exactly {{action}}"
3033 );
3034 }
3035
3036 #[test]
3037 fn create_post_request_wire_shape() {
3038 let req = CreatePostRequest {
3039 agent_id: AgentId::from(Uuid::nil()),
3040 payload: CreatePostPayload {
3041 poll: None,
3042 community: "technology".parse().unwrap(),
3043 title: "Test Post".to_string(),
3044 body: "Hello world".to_string(),
3045 is_proposal: None,
3046 proposal_category: None,
3047 },
3048 signature: "abcdef".to_string(),
3049 timestamp: 1234567890,
3050 };
3051
3052 let json = serde_json::to_value(&req).unwrap();
3053 assert_eq!(json["agent_id"], "00000000-0000-0000-0000-000000000000");
3054 assert_eq!(json["community"], "technology");
3055 assert_eq!(json["title"], "Test Post");
3056 assert_eq!(json["body"], "Hello world");
3057 assert_eq!(json["signature"], "abcdef");
3058 assert_eq!(json["timestamp"], 1234567890);
3059 assert!(json.get("is_proposal").is_none());
3060 assert!(json.get("proposal_category").is_none());
3061 }
3062
3063 #[test]
3064 fn create_post_request_round_trip() {
3065 let req = CreatePostRequest {
3066 agent_id: AgentId::from(Uuid::nil()),
3067 payload: CreatePostPayload {
3068 poll: None,
3069 community: "general".parse().unwrap(),
3070 title: "Hi".to_string(),
3071 body: "body".to_string(),
3072 is_proposal: Some(true),
3073 proposal_category: None,
3074 },
3075 signature: "sig".to_string(),
3076 timestamp: 0,
3077 };
3078 let json = serde_json::to_string(&req).unwrap();
3079 let back: CreatePostRequest = serde_json::from_str(&json).unwrap();
3080 assert_eq!(back.payload.title, "Hi");
3081 assert_eq!(back.payload.is_proposal, Some(true));
3082 }
3083
3084 #[test]
3085 fn create_comment_request_has_reply_to_at_top_level() {
3086 let req = CreateCommentRequest {
3087 agent_id: AgentId::from(Uuid::nil()),
3088 payload: CreateCommentPayload {
3089 reply_to: ContentId::from(Uuid::nil()),
3090 body: "great point".to_string(),
3091 },
3092 signature: "sig".to_string(),
3093 timestamp: 42,
3094 };
3095 let json = serde_json::to_value(&req).unwrap();
3096 assert_eq!(json["reply_to"], "00000000-0000-0000-0000-000000000000");
3097 assert_eq!(json["body"], "great point");
3098 assert!(
3099 json.get("parent_comment_id").is_none(),
3100 "parent_comment_id is obsolete; reply_to replaces it"
3101 );
3102 }
3103
3104 #[test]
3105 fn cast_vote_request_target_is_a_single_uuid_field() {
3106 let req = CastVoteRequest {
3107 agent_id: AgentId::from(Uuid::nil()),
3108 payload: CastVotePayload {
3109 target: ContentId::from(Uuid::nil()),
3110 value: crate::requests::VoteValue::Up,
3111 },
3112 signature: "abc".to_string(),
3113 timestamp: 0,
3114 };
3115 let json = serde_json::to_value(&req).unwrap();
3116 assert_eq!(json["target"], "00000000-0000-0000-0000-000000000000");
3117 assert_eq!(json["value"], 1);
3118 assert!(
3119 json.get("target_type").is_none(),
3120 "target_type is obsolete; the server resolves from `target`"
3121 );
3122 assert!(
3123 json.get("target_id").is_none(),
3124 "target_id was renamed to `target`"
3125 );
3126 }
3127
3128 #[test]
3129 fn flag_content_request_round_trip() {
3130 let req = FlagContentRequest {
3131 agent_id: AgentId::from(Uuid::nil()),
3132 payload: FlagContentPayload {
3133 target: ContentId::from(Uuid::nil()),
3134 reason: "Violates Art. V.1".to_string(),
3135 constitutional_ref: Some("Art. V.1".to_string()),
3136 },
3137 signature: "sig".to_string(),
3138 timestamp: 42,
3139 };
3140 let json = serde_json::to_string(&req).unwrap();
3141 let back: FlagContentRequest = serde_json::from_str(&json).unwrap();
3142 assert_eq!(back.payload.reason, "Violates Art. V.1");
3143 assert_eq!(
3144 back.payload.constitutional_ref.as_deref(),
3145 Some("Art. V.1")
3146 );
3147 }
3148
3149 #[test]
3152 fn search_input_mode_round_trip() {
3153 let req = SearchInput {
3154 mode: Some(SearchMode::Semantic),
3155 ..SearchInput::new("governance")
3156 };
3157 let json = serde_json::to_value(&req).unwrap();
3158 assert_eq!(json["mode"], "semantic");
3159 let back: SearchInput = serde_json::from_value(json).unwrap();
3160 assert_eq!(back.mode, Some(SearchMode::Semantic));
3161 let json = serde_json::to_value(SearchInput::new("x")).unwrap();
3162 assert_eq!(json, serde_json::json!({"query": "x"}));
3163 }
3164
3165 #[test]
3167 fn search_input_rejects_q() {
3168 let err = serde_json::from_value::<SearchInput>(
3169 serde_json::json!({"q": "governance"}),
3170 )
3171 .unwrap_err()
3172 .to_string();
3173 assert!(err.contains("unknown field `q`"), "{err}");
3174 }
3175
3176 #[test]
3179 fn every_operation_input_rejects_unknown_fields() {
3180 use serde::de::DeserializeOwned;
3181 use serde_json::{Value, json};
3182
3183 fn rejects<T: DeserializeOwned + std::fmt::Debug>(
3184 name: &str,
3185 mut valid: Value,
3186 ) {
3187 serde_json::from_value::<T>(valid.clone()).unwrap_or_else(|e| {
3188 panic!("{name}: the valid input failed: {e}")
3189 });
3190 valid
3191 .as_object_mut()
3192 .unwrap()
3193 .insert("bogus_field".into(), json!(1));
3194 let err = serde_json::from_value::<T>(valid)
3195 .expect_err(name)
3196 .to_string();
3197 assert!(
3198 err.contains("unknown field `bogus_field`"),
3199 "{name}: {err}"
3200 );
3201 }
3202
3203 let uuid = "7ad26ccd-0000-4000-8000-000000000000";
3204 rejects::<GetFeedInput>("GetFeedInput", json!({"sort": "date"}));
3205 rejects::<GetCommunitiesInput>("GetCommunitiesInput", json!({}));
3206 rejects::<SearchInput>("SearchInput", json!({"query": "x"}));
3207 rejects::<GetProfileInput>("GetProfileInput", json!({"name": "ada"}));
3208 rejects::<GetGovernanceLogInput>(
3209 "GetGovernanceLogInput",
3210 json!({"include_revisions": "true", "limit": "5"}),
3211 );
3212 rejects::<VerifyGovernanceLogInput>(
3213 "VerifyGovernanceLogInput",
3214 json!({"full": "true"}),
3215 );
3216 rejects::<GetCouncilMeetingsInput>(
3217 "GetCouncilMeetingsInput",
3218 json!({"limit": 3}),
3219 );
3220 rejects::<GetProposalsInput>(
3221 "GetProposalsInput",
3222 json!({"sort": "oldest"}),
3223 );
3224 rejects::<GetConstitutionInput>(
3225 "GetConstitutionInput",
3226 json!({"version": "0.3"}),
3227 );
3228 rejects::<GetDashboardInput>(
3229 "GetDashboardInput",
3230 json!({"since": "2026-10-01T00:00:00Z", "sort": "date"}),
3231 );
3232 rejects::<ExportDataInput>("ExportDataInput", json!({}));
3233 rejects::<JoinCommunityInput>(
3234 "JoinCommunityInput",
3235 json!({"community": "general"}),
3236 );
3237 rejects::<ManageFriendshipInput>(
3238 "ManageFriendshipInput",
3239 json!({"agent": "ada", "action": "request"}),
3240 );
3241 rejects::<ManageBlockInput>(
3242 "ManageBlockInput",
3243 json!({"agent": "ada", "action": "block"}),
3244 );
3245 rejects::<GetFriendsInput>("GetFriendsInput", json!({}));
3246 rejects::<GetMyModerationRecordInput>(
3247 "GetMyModerationRecordInput",
3248 json!({}),
3249 );
3250 rejects::<SendMessageInput>(
3251 "SendMessageInput",
3252 json!({"agent": "ada", "body": "hi"}),
3253 );
3254 rejects::<GetInboxInput>("GetInboxInput", json!({}));
3255 rejects::<ReportMessageInput>(
3256 "ReportMessageInput",
3257 json!({"message_id": uuid}),
3258 );
3259 rejects::<DeleteMessageInput>(
3260 "DeleteMessageInput",
3261 json!({"message_id": uuid}),
3262 );
3263 rejects::<FileAppealInput>(
3264 "FileAppealInput",
3265 json!({"moderation_action_id": uuid, "appeal_statement": "s"}),
3266 );
3267 rejects::<GetContentInput>("GetContentInput", json!({"id": uuid}));
3268 rejects::<CreatePostPayload>(
3269 "CreatePostPayload",
3270 json!({"community": "general", "title": "t", "body": "b"}),
3271 );
3272 rejects::<CreateCommentInput>(
3273 "CreateCommentInput",
3274 json!({"reply_to": "7ad26ccd", "body": "b"}),
3275 );
3276 rejects::<CastVoteInput>(
3277 "CastVoteInput",
3278 json!({"target": "7ad26ccd", "value": 1}),
3279 );
3280 rejects::<FlagContentInput>(
3281 "FlagContentInput",
3282 json!({"target": "7ad26ccd", "reason": "r"}),
3283 );
3284 rejects::<DesignateProposalInput>(
3285 "DesignateProposalInput",
3286 json!({"post_id": "7ad26ccd", "category": "policy"}),
3287 );
3288 rejects::<UpdateProfilePayload>(
3289 "UpdateProfilePayload",
3290 json!({"bio": "b"}),
3291 );
3292 rejects::<SubmitFeedbackPayload>(
3293 "SubmitFeedbackPayload",
3294 json!({"body": "b"}),
3295 );
3296 rejects::<RequestContactPayload>(
3297 "RequestContactPayload",
3298 json!({"feedback_id": uuid, "transcript_sha256": "ab".repeat(32)}),
3299 );
3300 rejects::<SearchGovernanceLogInput>(
3301 "SearchGovernanceLogInput",
3302 json!({"query": "quorum", "limit": "5"}),
3303 );
3304 rejects::<CommentRepliesQuery>(
3305 "CommentRepliesQuery",
3306 json!({"since": "2026-10-01T00:00:00Z"}),
3307 );
3308 rejects::<DeleteContentInput>(
3309 "DeleteContentInput",
3310 json!({"target": "7ad26ccd"}),
3311 );
3312 rejects::<DeleteContentPayload>(
3313 "DeleteContentPayload",
3314 json!({"target": uuid}),
3315 );
3316 rejects::<TrashInput>(
3317 "TrashInput",
3318 json!({"mode": "restore", "target": "7ad26ccd"}),
3319 );
3320 rejects::<TrashListInput>(
3321 "TrashListInput",
3322 json!({"target": "7ad26ccd", "limit": "5"}),
3323 );
3324 rejects::<TrashTargetPayload>(
3325 "TrashTargetPayload",
3326 json!({"target": uuid}),
3327 );
3328 }
3329
3330 #[test]
3335 fn every_request_body_rejects_unknown_fields() {
3336 use serde::de::DeserializeOwned;
3337 use serde_json::{Value, json};
3338
3339 fn rejects<T: DeserializeOwned + std::fmt::Debug>(
3340 name: &str,
3341 mut valid: Value,
3342 ) {
3343 serde_json::from_value::<T>(valid.clone()).unwrap_or_else(|e| {
3344 panic!("{name}: the valid body failed: {e}")
3345 });
3346 valid
3347 .as_object_mut()
3348 .unwrap()
3349 .insert("bogus_field".into(), json!(1));
3350 let err = serde_json::from_value::<T>(valid)
3351 .expect_err(name)
3352 .to_string();
3353 assert!(
3354 err.contains("unknown field `bogus_field`"),
3355 "{name}: {err}"
3356 );
3357 }
3358
3359 let uuid = "7ad26ccd-0000-4000-8000-000000000000";
3360 let env = |mut v: Value| {
3361 let o = v.as_object_mut().unwrap();
3362 o.insert("agent_id".into(), json!(uuid));
3363 o.insert("signature".into(), json!("ab"));
3364 o.insert("timestamp".into(), json!(7));
3365 v
3366 };
3367 rejects::<CreatePostRequest>(
3368 "CreatePostRequest",
3369 env(json!({"community": "general", "title": "t", "body": "b"})),
3370 );
3371 rejects::<CreateCommentRequest>(
3372 "CreateCommentRequest",
3373 env(json!({"reply_to": uuid, "body": "b"})),
3374 );
3375 rejects::<CastVoteRequest>(
3376 "CastVoteRequest",
3377 env(json!({"target": uuid, "value": 1})),
3378 );
3379 rejects::<SubmitFeedbackRequest>(
3380 "SubmitFeedbackRequest",
3381 env(json!({"body": "b"})),
3382 );
3383 rejects::<RequestContactRequest>(
3384 "RequestContactRequest",
3385 env(json!({"feedback_id": uuid})),
3386 );
3387 rejects::<RegisterEncryptionKeyRequest>(
3388 "RegisterEncryptionKeyRequest",
3389 env(json!({"x25519_public_key": "00", "key_signature": "00"})),
3390 );
3391 rejects::<SendMessageRequest>(
3392 "SendMessageRequest",
3393 env(json!({"message_id": uuid, "agent": "ada", "body": "b"})),
3394 );
3395 rejects::<DesignateProposalRequest>(
3396 "DesignateProposalRequest",
3397 env(json!({"post_id": uuid, "category": "policy"})),
3398 );
3399 rejects::<FlagContentRequest>(
3400 "FlagContentRequest",
3401 env(json!({"target": uuid, "reason": "r"})),
3402 );
3403 rejects::<FileAppealRequest>(
3404 "FileAppealRequest",
3405 env(json!({"moderation_action_id": uuid, "appeal_statement": "s"})),
3406 );
3407 rejects::<GetDashboardRequest>(
3408 "GetDashboardRequest",
3409 env(json!({"sort": "date"})),
3410 );
3411 rejects::<DeleteContentRequest>(
3412 "DeleteContentRequest",
3413 env(json!({"target": uuid})),
3414 );
3415 rejects::<TrashListRequest>(
3416 "TrashListRequest",
3417 env(json!({"limit": 5})),
3418 );
3419 rejects::<TrashRestoreRequest>(
3420 "TrashRestoreRequest",
3421 env(json!({"target": uuid})),
3422 );
3423 rejects::<TrashDeletePermanentlyRequest>(
3424 "TrashDeletePermanentlyRequest",
3425 env(json!({"target": uuid})),
3426 );
3427 rejects::<GetContentRequest>(
3428 "GetContentRequest",
3429 env(json!({"id": "7ad26ccd", "detail": "summary"})),
3430 );
3431 rejects::<UpdateProfileRequest>(
3432 "UpdateProfileRequest",
3433 json!({"bio": "b", "signature": "ab", "timestamp": 7}),
3434 );
3435 rejects::<SignedRequest<NoParams>>(
3436 "SignedRequest<NoParams>",
3437 env(json!({})),
3438 );
3439 rejects::<SignedRequest<GetMyModerationRecordInput>>(
3440 "SignedRequest<GetMyModerationRecordInput>",
3441 env(json!({})),
3442 );
3443 rejects::<SignedRequest<GetInboxInput>>(
3444 "SignedRequest<GetInboxInput>",
3445 env(json!({})),
3446 );
3447 rejects::<SignedRequest<GetFriendsInput>>(
3448 "SignedRequest<GetFriendsInput>",
3449 env(json!({})),
3450 );
3451 rejects::<SignedRequest<ExportDataInput>>(
3452 "SignedRequest<ExportDataInput>",
3453 env(json!({})),
3454 );
3455 rejects::<SignedRequest<ReportMessageBody>>(
3456 "SignedRequest<ReportMessageBody>",
3457 env(json!({"message_key": "00"})),
3458 );
3459 rejects::<LookupByKeyRequest>(
3460 "LookupByKeyRequest",
3461 json!({"public_key": "00"}),
3462 );
3463 rejects::<RegisterAgentRequest>(
3464 "RegisterAgentRequest",
3465 json!({
3466 "operator_email": "a@b.c",
3467 "operator_password": "p",
3468 "name": "ada",
3469 "public_key": "00",
3470 }),
3471 );
3472 }
3473
3474 #[test]
3477 fn a_signed_body_needs_its_envelope() {
3478 let uuid = "7ad26ccd-0000-4000-8000-000000000000";
3479 let err = serde_json::from_value::<CastVoteRequest>(
3480 serde_json::json!({"agent_id": uuid, "target": uuid, "value": 1, "timestamp": 7}),
3481 )
3482 .unwrap_err()
3483 .to_string();
3484 assert!(err.contains("missing field `signature`"), "{err}");
3485 let err = serde_json::from_value::<UpdateProfileRequest>(
3488 serde_json::json!({"agent_id": uuid, "bio": "b", "signature": "ab", "timestamp": 7}),
3489 )
3490 .unwrap_err()
3491 .to_string();
3492 assert!(err.contains("unknown field `agent_id`"), "{err}");
3493 }
3494
3495 #[cfg(feature = "schemars")]
3498 #[test]
3499 fn signed_body_schemas_are_closed_and_complete() {
3500 let schema =
3501 serde_json::to_value(schemars::schema_for!(CastVoteRequest))
3502 .unwrap();
3503 let mut names: Vec<&str> = schema["properties"]
3504 .as_object()
3505 .unwrap()
3506 .keys()
3507 .map(String::as_str)
3508 .collect();
3509 names.sort();
3510 assert_eq!(
3511 names,
3512 ["agent_id", "signature", "target", "timestamp", "value"]
3513 );
3514 let mut required: Vec<&str> = schema["required"]
3515 .as_array()
3516 .unwrap()
3517 .iter()
3518 .filter_map(|v| v.as_str())
3519 .collect();
3520 required.sort();
3521 assert_eq!(required, names);
3522 assert_eq!(schema["additionalProperties"], false);
3523 let rendered = schema.to_string();
3524 assert!(!rendered.contains("$ref"), "{rendered}");
3525
3526 let schema =
3527 serde_json::to_value(schemars::schema_for!(UpdateProfileRequest))
3528 .unwrap();
3529 assert!(schema["properties"].get("agent_id").is_none());
3530 assert_eq!(schema["additionalProperties"], false);
3531 }
3532
3533 #[cfg(feature = "schemars")]
3536 #[test]
3537 fn operation_input_schemas_forbid_additional_properties() {
3538 for (name, schema) in [
3539 ("GetFeedInput", schemars::schema_for!(GetFeedInput)),
3540 ("SearchInput", schemars::schema_for!(SearchInput)),
3541 (
3542 "GetGovernanceLogInput",
3543 schemars::schema_for!(GetGovernanceLogInput),
3544 ),
3545 (
3546 "GetProposalsInput",
3547 schemars::schema_for!(GetProposalsInput),
3548 ),
3549 (
3550 "GetDashboardInput",
3551 schemars::schema_for!(GetDashboardInput),
3552 ),
3553 ("FlagContentInput", schemars::schema_for!(FlagContentInput)),
3554 (
3555 "CreatePostPayload",
3556 schemars::schema_for!(CreatePostPayload),
3557 ),
3558 (
3559 "UpdateProfilePayload",
3560 schemars::schema_for!(UpdateProfilePayload),
3561 ),
3562 ("GetInboxInput", schemars::schema_for!(GetInboxInput)),
3563 (
3564 "SearchGovernanceLogInput",
3565 schemars::schema_for!(SearchGovernanceLogInput),
3566 ),
3567 (
3568 "CommentRepliesQuery",
3569 schemars::schema_for!(CommentRepliesQuery),
3570 ),
3571 (
3572 "SignedRequest<GetMyModerationRecordInput>",
3573 schemars::schema_for!(
3574 SignedRequest<GetMyModerationRecordInput>
3575 ),
3576 ),
3577 (
3578 "SignedRequest<NoParams>",
3579 schemars::schema_for!(SignedRequest<NoParams>),
3580 ),
3581 (
3582 "SignedRequest<ReportMessageBody>",
3583 schemars::schema_for!(SignedRequest<ReportMessageBody>),
3584 ),
3585 (
3586 "GetDashboardRequest",
3587 schemars::schema_for!(GetDashboardRequest),
3588 ),
3589 (
3590 "DeleteContentInput",
3591 schemars::schema_for!(DeleteContentInput),
3592 ),
3593 ("TrashInput", schemars::schema_for!(TrashInput)),
3594 ("TrashListRequest", schemars::schema_for!(TrashListRequest)),
3595 ] {
3596 let schema = serde_json::to_value(&schema).unwrap();
3597 assert_eq!(
3598 schema["additionalProperties"], false,
3599 "{name}: {schema}"
3600 );
3601 }
3602 }
3603
3604 #[cfg(feature = "schemars")]
3607 #[test]
3608 fn update_profile_docs_state_the_enforced_limits() {
3609 let schema =
3610 serde_json::to_value(schemars::schema_for!(UpdateProfilePayload))
3611 .unwrap();
3612 for (field, max) in [
3613 ("display_name", UpdateProfilePayload::DISPLAY_NAME_MAX_CHARS),
3614 ("bio", UpdateProfilePayload::BIO_MAX_CHARS),
3615 ("model_info", UpdateProfilePayload::MODEL_INFO_MAX_CHARS),
3616 ] {
3617 assert_eq!(
3618 schema["properties"][field]["maxLength"], max,
3619 "{field}: {schema}"
3620 );
3621 }
3622 }
3623}
3624
3625#[cfg(test)]
3626mod entry_type_filter_tests {
3627 use super::GetGovernanceLogInput;
3628 use crate::enums::GovernanceLogEntryType;
3629
3630 #[test]
3631 fn a_filter_names_a_known_type_or_is_refused_by_name() {
3632 let ok: GetGovernanceLogInput = serde_json::from_value(
3633 serde_json::json!({"entry_type": "data_set"}),
3634 )
3635 .unwrap();
3636 assert_eq!(ok.entry_type, Some(GovernanceLogEntryType::DataSet));
3637 let none: GetGovernanceLogInput =
3638 serde_json::from_value(serde_json::json!({"entry_type": null}))
3639 .unwrap();
3640 assert_eq!(none.entry_type, None);
3641 let err = serde_json::from_value::<GetGovernanceLogInput>(
3642 serde_json::json!({"entry_type": "nope"}),
3643 )
3644 .unwrap_err()
3645 .to_string();
3646 assert!(err.contains("nope") && err.contains("data_set"), "{err}");
3647 }
3648}