Skip to main content

kival_sdk/wire/
commentary.rs

1//! Object commentary wire protocol types.
2
3use chrono::{DateTime, Utc};
4pub use kival_types::CommentStatus;
5use schemars::JsonSchema;
6use serde::{Deserialize, Serialize};
7use uuid::Uuid;
8
9use crate::ListResponse;
10
11/// Maximum number of Unicode scalar values accepted in one comment body.
12pub const COMMENT_BODY_MAX_CHARS: usize = 20_000;
13
14/// Maximum number of distinct users mentioned by one comment.
15pub const COMMENT_MENTION_MAX_USERS: usize = 50;
16
17/// Public identity embedded in a commentary response.
18#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
19pub struct CommentAuthor {
20    /// Stable user identifier.
21    pub id: Uuid,
22    /// Stable username.
23    pub username: String,
24    /// Current display name.
25    pub display_name: String,
26}
27
28/// A stable user mention attached to a comment.
29#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
30pub struct CommentMention {
31    /// Stable mentioned user identifier.
32    pub user_id: Uuid,
33    /// Current stable username.
34    pub username: String,
35    /// Current display name.
36    pub display_name: String,
37}
38
39/// Mutable commentary attached to an object.
40#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
41pub struct Comment {
42    /// Stable comment identifier.
43    pub id: Uuid,
44    /// Workspace security boundary.
45    pub workspace_id: Uuid,
46    /// Object that owns this commentary.
47    pub object_id: Uuid,
48    /// Stable thread identifier.
49    pub thread_id: Uuid,
50    /// Parent comment for a reply, or `None` for the thread root.
51    pub parent_comment_id: Option<Uuid>,
52    /// Current public identity of the comment author.
53    pub author: CommentAuthor,
54    /// Current lifecycle state.
55    pub status: CommentStatus,
56    /// Comment body while active.
57    pub body: Option<String>,
58    /// Explicit stable user mentions associated with the current body.
59    pub mentions: Vec<CommentMention>,
60    /// Creation timestamp.
61    pub created_at: DateTime<Utc>,
62    /// Last modification timestamp.
63    pub updated_at: DateTime<Utc>,
64    /// Most recent body-edit timestamp.
65    pub edited_at: Option<DateTime<Utc>>,
66    /// Soft-deletion timestamp.
67    pub deleted_at: Option<DateTime<Utc>>,
68    /// User who soft-deleted the comment.
69    pub deleted_by: Option<Uuid>,
70    /// Timestamp at which retention removed the body.
71    pub expired_at: Option<DateTime<Utc>>,
72    /// Explicit boundary consumed by retention workers.
73    pub retention_expires_at: Option<DateTime<Utc>>,
74}
75
76/// A top-level discussion with a bounded page of comments.
77#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
78pub struct CommentThread {
79    /// Stable thread identifier.
80    pub id: Uuid,
81    /// Workspace security boundary.
82    pub workspace_id: Uuid,
83    /// Object that owns this thread.
84    pub object_id: Uuid,
85    /// User who created the root comment.
86    pub created_by: Uuid,
87    /// Creation timestamp.
88    pub created_at: DateTime<Utc>,
89    /// Last thread activity timestamp.
90    pub updated_at: DateTime<Utc>,
91    /// Resolution timestamp, when resolved.
92    pub resolved_at: Option<DateTime<Utc>>,
93    /// User who most recently resolved the thread.
94    pub resolved_by: Option<Uuid>,
95    /// Explicit boundary consumed by retention workers.
96    pub retention_expires_at: Option<DateTime<Utc>>,
97    /// Comments ordered by creation time, with the root first.
98    pub comments: Vec<Comment>,
99    /// Opaque cursor for loading more comments in this thread.
100    #[serde(skip_serializing_if = "Option::is_none")]
101    pub comments_next_cursor: Option<String>,
102}
103
104/// User who may currently be mentioned from commentary on an object.
105#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
106pub struct CommentMentionCandidate {
107    /// Stable user identifier.
108    pub user_id: Uuid,
109    /// Stable username inserted into commentary.
110    pub username: String,
111    /// Current display name.
112    pub display_name: String,
113}
114
115/// Parameters for object-scoped mention autocomplete.
116#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
117pub struct CommentMentionCandidateParams {
118    /// Username prefix or display-name fragment. Empty values list the first candidates.
119    #[serde(default)]
120    pub q: String,
121    /// Maximum candidates to return. Defaults to 8 and is capped at 20.
122    pub limit: Option<i64>,
123}
124
125impl CommentMentionCandidateParams {
126    /// Returns the validated candidate limit.
127    ///
128    /// # Errors
129    ///
130    /// Returns an error when `limit` is less than one.
131    pub fn checked_limit(&self) -> Result<i64, &'static str> {
132        match self.limit {
133            Some(limit) if limit < 1 => Err("limit must be at least 1"),
134            Some(limit) => Ok(limit.min(20)),
135            None => Ok(8),
136        }
137    }
138}
139
140/// Request body for creating a top-level comment or reply.
141#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
142#[serde(deny_unknown_fields)]
143pub struct CreateCommentRequest {
144    /// Plain-text comment body.
145    pub body: String,
146    /// Additional stable IDs to mention. The server also resolves `@username` tokens in the body.
147    #[serde(default)]
148    pub mentioned_user_ids: Vec<Uuid>,
149}
150
151/// Request body for editing an existing comment.
152#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
153#[serde(deny_unknown_fields)]
154pub struct UpdateCommentRequest {
155    /// Complete replacement body.
156    pub body: String,
157    /// Additional replacement mentions. The server also resolves `@username` tokens in the body.
158    #[serde(default)]
159    pub mentioned_user_ids: Vec<Uuid>,
160}
161
162/// Single-comment response envelope.
163#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
164pub struct CommentResponse {
165    /// Created, edited, or deleted comment.
166    pub comment: Comment,
167}
168
169/// Single-thread response envelope.
170#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
171pub struct CommentThreadResponse {
172    /// Created or transitioned thread.
173    pub thread: CommentThread,
174}
175
176/// Object commentary list response.
177pub type CommentThreadListResponse = ListResponse<CommentThread>;
178
179/// Paginated comments in a single commentary thread.
180pub type CommentListResponse = ListResponse<Comment>;
181
182/// Object-scoped mention autocomplete response.
183pub type CommentMentionCandidateListResponse = ListResponse<CommentMentionCandidate>;
184
185#[cfg(test)]
186mod tests {
187    use super::*;
188
189    #[test]
190    fn mention_candidate_query_limits_are_validated() {
191        assert_eq!(CommentMentionCandidateParams::default().checked_limit(), Ok(8));
192        assert!(
193            CommentMentionCandidateParams { q: String::new(), limit: Some(0) }
194                .checked_limit()
195                .is_err()
196        );
197        assert_eq!(
198            CommentMentionCandidateParams { q: String::new(), limit: Some(25) }.checked_limit(),
199            Ok(20),
200        );
201    }
202
203    #[test]
204    fn create_request_rejects_unknown_fields() {
205        let result = serde_json::from_value::<CreateCommentRequest>(serde_json::json!({
206            "body": "hello",
207            "unexpected": true,
208        }));
209
210        assert!(result.is_err());
211    }
212}