use serde::{Deserialize, Serialize};
use uuid::Uuid;
macro_rules! define_id {
($(#[doc = $doc:expr])* $name:ident) => {
$(#[doc = $doc])*
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "sqlx", derive(sqlx::Type))]
#[cfg_attr(feature = "sqlx", sqlx(transparent))]
pub struct $name(Uuid);
impl $name {
pub fn new() -> Self {
Self(Uuid::new_v4())
}
pub fn as_uuid(&self) -> &Uuid {
&self.0
}
}
impl Default for $name {
fn default() -> Self {
Self::new()
}
}
impl std::fmt::Display for $name {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.0.fmt(f)
}
}
impl From<Uuid> for $name {
fn from(uuid: Uuid) -> Self {
Self(uuid)
}
}
impl From<$name> for Uuid {
fn from(id: $name) -> Self {
id.0
}
}
impl std::str::FromStr for $name {
type Err = uuid::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
s.parse::<Uuid>().map(Self)
}
}
#[cfg(feature = "schemars")]
impl schemars::JsonSchema for $name {
fn inline_schema() -> bool {
true
}
fn schema_name() -> std::borrow::Cow<'static, str> {
std::borrow::Cow::Borrowed(stringify!($name))
}
fn schema_id() -> std::borrow::Cow<'static, str> {
std::borrow::Cow::Borrowed(concat!(module_path!(), "::", stringify!($name)))
}
fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
schemars::json_schema!({
"type": "string",
"format": "uuid",
})
}
}
};
}
define_id! {
AgentId
}
define_id! {
ReactorId
}
define_id! {
OperatorId
}
define_id! {
PostId
}
define_id! {
CommentId
}
define_id! {
CommunityId
}
define_id! {
VoteId
}
define_id! {
ModerationActionId
}
define_id! {
ModerationNoteId
}
define_id! {
PromptArchiveId
}
define_id! {
AppealId
}
define_id! {
FlagId
}
define_id! {
CouncilMeetingId
}
define_id! {
AgendaItemId
}
define_id! {
DecisionId
}
define_id! {
BatchTrackingId
}
define_id! {
ThreadSummaryId
}
define_id! {
McpSessionId
}
define_id! {
EmailVerificationTokenId
}
define_id! {
PostEmbeddingId
}
define_id! {
DataExportId
}
define_id! {
RefreshTokenId
}
define_id! {
MessageId
}
define_id! {
ContentId
}
define_id! {
ModerationTargetId
}
impl From<PostId> for ModerationTargetId {
fn from(id: PostId) -> Self {
Self::from(*id.as_uuid())
}
}
impl From<CommentId> for ModerationTargetId {
fn from(id: CommentId) -> Self {
Self::from(*id.as_uuid())
}
}
impl From<MessageId> for ModerationTargetId {
fn from(id: MessageId) -> Self {
Self::from(*id.as_uuid())
}
}
impl From<AgentId> for ModerationTargetId {
fn from(id: AgentId) -> Self {
Self::from(*id.as_uuid())
}
}
impl From<ContentId> for ModerationTargetId {
fn from(id: ContentId) -> Self {
Self::from(*id.as_uuid())
}
}
impl From<PostId> for ContentId {
fn from(id: PostId) -> Self {
Self::from(*id.as_uuid())
}
}
impl From<CommentId> for ContentId {
fn from(id: CommentId) -> Self {
Self::from(*id.as_uuid())
}
}
impl From<PostOrCommentId> for ContentId {
fn from(id: PostOrCommentId) -> Self {
Self::from(id.as_uuid())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum PostOrCommentId {
Post(PostId),
Comment(CommentId),
}
impl PostOrCommentId {
pub fn as_uuid(&self) -> Uuid {
match self {
PostOrCommentId::Post(id) => *id.as_uuid(),
PostOrCommentId::Comment(id) => *id.as_uuid(),
}
}
pub fn is_post(&self) -> bool {
matches!(self, PostOrCommentId::Post(_))
}
pub fn is_comment(&self) -> bool {
matches!(self, PostOrCommentId::Comment(_))
}
pub fn as_post(&self) -> Option<PostId> {
match self {
PostOrCommentId::Post(id) => Some(*id),
PostOrCommentId::Comment(_) => None,
}
}
pub fn as_comment(&self) -> Option<CommentId> {
match self {
PostOrCommentId::Comment(id) => Some(*id),
PostOrCommentId::Post(_) => None,
}
}
pub fn kind_str(&self) -> &'static str {
match self {
PostOrCommentId::Post(_) => "post",
PostOrCommentId::Comment(_) => "comment",
}
}
}
impl From<PostId> for PostOrCommentId {
fn from(id: PostId) -> Self {
PostOrCommentId::Post(id)
}
}
impl From<CommentId> for PostOrCommentId {
fn from(id: CommentId) -> Self {
PostOrCommentId::Comment(id)
}
}
impl std::fmt::Display for PostOrCommentId {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}:{}", self.kind_str(), self.as_uuid())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn ids_are_unique() {
let a = AgentId::new();
let b = AgentId::new();
assert_ne!(a, b);
}
#[test]
fn serde_round_trip() {
let id = PostId::new();
let json = serde_json::to_string(&id).unwrap();
let deserialized: PostId = serde_json::from_str(&json).unwrap();
assert_eq!(id, deserialized);
}
#[test]
fn display_shows_uuid() {
let id = CommunityId::new();
let display = id.to_string();
assert_eq!(display.len(), 36);
assert!(display.contains('-'));
}
#[test]
fn from_uuid_round_trip() {
let uuid = Uuid::new_v4();
let id = AgentId::from(uuid);
let back: Uuid = id.into();
assert_eq!(uuid, back);
}
#[test]
fn every_id_round_trips_through_its_own_display() {
let agent = AgentId::new();
assert_eq!(agent.to_string().parse::<AgentId>().unwrap(), agent);
let action = ModerationActionId::new();
assert_eq!(
action.to_string().parse::<ModerationActionId>().unwrap(),
action
);
let content = ContentId::new();
assert_eq!(content.to_string().parse::<ContentId>().unwrap(), content);
}
#[test]
fn parsing_a_non_uuid_is_an_error_not_a_panic() {
assert!("not-a-uuid".parse::<ContentId>().is_err());
assert!("".parse::<ContentId>().is_err());
}
#[test]
fn content_id_is_wire_compatible_with_a_bare_uuid() {
let uuid = Uuid::new_v4();
let typed = ContentId::from(uuid);
assert_eq!(
serde_json::to_string(&typed).unwrap(),
serde_json::to_string(&uuid).unwrap()
);
}
#[test]
fn every_moderation_target_narrows_losslessly() {
let uuid = Uuid::new_v4();
for (label, got) in [
("PostId", ModerationTargetId::from(PostId::from(uuid))),
("CommentId", ModerationTargetId::from(CommentId::from(uuid))),
("MessageId", ModerationTargetId::from(MessageId::from(uuid))),
("AgentId", ModerationTargetId::from(AgentId::from(uuid))),
("ContentId", ModerationTargetId::from(ContentId::from(uuid))),
] {
assert_eq!(
got.as_uuid(),
&uuid,
"{label} -> ModerationTargetId lost the uuid"
);
}
}
#[test]
fn resolved_ids_narrow_to_content_id_losslessly() {
let uuid = Uuid::new_v4();
assert_eq!(
ContentId::from(PostId::from(uuid)).as_uuid(),
&uuid,
"PostId -> ContentId lost the uuid"
);
assert_eq!(
ContentId::from(CommentId::from(uuid)).as_uuid(),
&uuid,
"CommentId -> ContentId lost the uuid"
);
assert_eq!(
ContentId::from(PostOrCommentId::Comment(CommentId::from(uuid)))
.as_uuid(),
&uuid,
"PostOrCommentId -> ContentId lost the uuid"
);
}
#[test]
fn json_is_plain_uuid_string() {
let uuid = Uuid::new_v4();
let id = AgentId::from(uuid);
let id_json = serde_json::to_string(&id).unwrap();
let uuid_json = serde_json::to_string(&uuid).unwrap();
assert_eq!(id_json, uuid_json);
}
#[cfg(feature = "schemars")]
#[test]
fn id_json_schema_is_inlined() {
use schemars::JsonSchema;
assert!(
<PostId as JsonSchema>::inline_schema(),
"PostId::inline_schema() must return true to avoid $ref in containing schemas"
);
assert!(<AgentId as JsonSchema>::inline_schema());
assert!(<CommentId as JsonSchema>::inline_schema());
assert!(<CommunityId as JsonSchema>::inline_schema());
#[derive(schemars::JsonSchema)]
#[allow(dead_code)]
struct Container {
post_id: PostId,
agent_id: Option<AgentId>,
}
let schema = schemars::schema_for!(Container);
let value = serde_json::to_value(&schema).unwrap();
assert!(
value.get("$defs").is_none(),
"no $defs should be emitted for ID-only container; got schema: {value}"
);
let post_id = &value["properties"]["post_id"];
assert!(
post_id.get("$ref").is_none(),
"post_id must not be a $ref; got: {post_id}"
);
assert_eq!(post_id["type"], "string");
assert_eq!(post_id["format"], "uuid");
let agent_id = &value["properties"]["agent_id"];
assert!(
agent_id.get("$ref").is_none(),
"agent_id must not be a $ref; got: {agent_id}"
);
let agent_id_str = agent_id.to_string();
assert!(
!agent_id_str.contains("$ref"),
"agent_id schema must contain no $ref anywhere; got: {agent_id}"
);
assert!(
agent_id_str.contains("\"format\":\"uuid\""),
"agent_id should still carry format=uuid; got: {agent_id}"
);
}
#[test]
fn post_or_comment_post_variant() {
let inner = PostId::new();
let tagged = PostOrCommentId::Post(inner);
assert!(tagged.is_post());
assert!(!tagged.is_comment());
assert_eq!(tagged.as_post(), Some(inner));
assert_eq!(tagged.as_comment(), None);
assert_eq!(tagged.as_uuid(), *inner.as_uuid());
assert_eq!(tagged.kind_str(), "post");
}
#[test]
fn post_or_comment_comment_variant() {
let inner = CommentId::new();
let tagged = PostOrCommentId::Comment(inner);
assert!(tagged.is_comment());
assert!(!tagged.is_post());
assert_eq!(tagged.as_comment(), Some(inner));
assert_eq!(tagged.as_post(), None);
assert_eq!(tagged.as_uuid(), *inner.as_uuid());
assert_eq!(tagged.kind_str(), "comment");
}
#[test]
fn post_or_comment_from_conversions() {
let post = PostId::new();
let comment = CommentId::new();
let via_post: PostOrCommentId = post.into();
let via_comment: PostOrCommentId = comment.into();
assert_eq!(via_post, PostOrCommentId::Post(post));
assert_eq!(via_comment, PostOrCommentId::Comment(comment));
}
#[test]
fn post_or_comment_display_is_kind_colon_uuid() {
let post = PostId::new();
let tagged = PostOrCommentId::Post(post);
let rendered = tagged.to_string();
assert!(rendered.starts_with("post:"));
assert!(rendered.contains(&post.to_string()));
}
}