Skip to main content

kival_sdk/wire/
objects.rs

1//! Object and object-version wire protocol types.
2
3use chrono::{DateTime, Utc};
4pub use kival_types::ObjectListOrder;
5use kival_types::{MembershipRole, ObjectRole};
6use schemars::JsonSchema;
7use serde::{Deserialize, Deserializer, Serialize, de};
8use serde_json::Value;
9use uuid::Uuid;
10
11use crate::{ArchiveListStatus, ArchiveStatus, ListParams};
12
13/// Object collection query parameters.
14#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
15pub struct ObjectListParams {
16    /// Maximum number of objects to return.
17    pub limit: Option<i64>,
18
19    /// Opaque pagination cursor.
20    pub cursor: Option<String>,
21
22    /// Archive status filter.
23    #[serde(default)]
24    pub status: ArchiveListStatus,
25
26    /// Sort order.
27    #[serde(default)]
28    pub order: ObjectListOrder,
29
30    /// Restricts the list to the authenticated user's favorites when set.
31    pub favorited: Option<bool>,
32
33    /// Restricts the list by the authenticated user's personal pin state.
34    pub pinned: Option<bool>,
35}
36
37impl Default for ObjectListParams {
38    fn default() -> Self {
39        Self {
40            limit: None,
41            cursor: None,
42            status: ArchiveListStatus::Active,
43            order: ObjectListOrder::Created,
44            favorited: None,
45            pinned: None,
46        }
47    }
48}
49
50impl ObjectListParams {
51    /// Returns the normalized page limit.
52    #[must_use]
53    pub fn limit(&self) -> i64 {
54        ListParams { limit: self.limit, cursor: self.cursor.clone() }.limit()
55    }
56}
57
58/// Request body for creating an object.
59#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
60#[serde(deny_unknown_fields)]
61pub struct CreateObjectRequest {
62    /// Object title.
63    pub title: String,
64
65    /// Initial object body.
66    #[serde(default)]
67    pub body: String,
68
69    /// Initial flat object metadata.
70    #[serde(default = "empty_object")]
71    #[schemars(with = "std::collections::BTreeMap<String, Value>")]
72    pub metadata: Value,
73}
74
75/// Request body for updating an object with optimistic concurrency control.
76#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
77#[serde(deny_unknown_fields)]
78pub struct UpdateObjectRequest {
79    /// Expected current version ID for optimistic concurrency control.
80    ///
81    /// The update fails with `409 Conflict` if the object has changed since this version was read.
82    pub expected_current_version_id: Uuid,
83
84    /// New object title. Omitted values inherit from the current version.
85    #[serde(
86        default,
87        skip_serializing_if = "Option::is_none",
88        deserialize_with = "deserialize_non_null_option"
89    )]
90    pub title: Option<String>,
91
92    /// New object body. Omitted values inherit from the current version.
93    #[serde(
94        default,
95        skip_serializing_if = "Option::is_none",
96        deserialize_with = "deserialize_non_null_option"
97    )]
98    pub body: Option<String>,
99
100    /// New flat object metadata. Omitted values inherit from the current version.
101    #[serde(
102        default,
103        skip_serializing_if = "Option::is_none",
104        deserialize_with = "deserialize_non_null_option"
105    )]
106    pub metadata: Option<Value>,
107}
108
109/// Deserializes an optional field while rejecting an explicit JSON `null`.
110///
111/// Missing fields are supplied by `#[serde(default)]` as `None`; present fields
112/// must contain a concrete value.
113fn deserialize_non_null_option<'de, D, T>(deserializer: D) -> Result<Option<T>, D::Error>
114where
115    D: Deserializer<'de>,
116    T: Deserialize<'de>,
117{
118    Option::<T>::deserialize(deserializer)?
119        .map(Some)
120        .ok_or_else(|| de::Error::custom("null is not allowed; omit the field instead"))
121}
122
123/// Object resource.
124#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
125pub struct ObjectResource {
126    /// Object ID.
127    pub id: Uuid,
128
129    /// Parent workspace ID.
130    pub workspace_id: Uuid,
131
132    /// Current version ID.
133    pub current_version_id: Option<Uuid>,
134
135    /// Title projected from the current immutable version.
136    pub title: String,
137
138    /// Lifecycle status.
139    pub status: ArchiveStatus,
140
141    /// User that created this object.
142    pub created_by: Option<Uuid>,
143
144    /// User that archived this object.
145    pub archived_by: Option<Uuid>,
146
147    /// Creation timestamp.
148    pub created_at: DateTime<Utc>,
149
150    /// Last update timestamp.
151    pub updated_at: DateTime<Utc>,
152
153    /// Archive timestamp.
154    pub archived_at: Option<DateTime<Utc>>,
155}
156
157/// Object resource enriched with scan-oriented workspace-list information.
158#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
159pub struct ObjectListItem {
160    /// Core object resource.
161    #[serde(flatten)]
162    pub object: ObjectResource,
163
164    /// Username that created the current object version.
165    #[serde(skip_serializing_if = "Option::is_none")]
166    pub updated_by_username: Option<String>,
167
168    /// Display name of the user that created the current object version.
169    #[serde(skip_serializing_if = "Option::is_none")]
170    pub updated_by_display_name: Option<String>,
171
172    /// Updater's active workspace role.
173    #[serde(skip_serializing_if = "Option::is_none")]
174    pub updated_by_workspace_role: Option<MembershipRole>,
175
176    /// Updater's effective access role for this object.
177    #[serde(skip_serializing_if = "Option::is_none")]
178    pub updated_by_object_role: Option<ObjectRole>,
179
180    /// Number of visible active object connections.
181    pub connection_count: i64,
182
183    /// Number of unresolved, unexpired commentary threads.
184    pub unresolved_thread_count: i64,
185
186    /// Whether the authenticated user has favorited this object.
187    pub favorited: bool,
188
189    /// Whether the authenticated user has pinned this object.
190    pub pinned: bool,
191
192    /// Time at which the authenticated user pinned this object.
193    pub pinned_at: Option<DateTime<Utc>>,
194}
195
196impl std::ops::Deref for ObjectListItem {
197    type Target = ObjectResource;
198
199    fn deref(&self) -> &Self::Target {
200        &self.object
201    }
202}
203
204/// Object version summary.
205#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
206pub struct ObjectVersion {
207    /// Version ID.
208    pub id: Uuid,
209
210    /// Object ID.
211    pub object_id: Uuid,
212
213    /// Monotonic version number within the object.
214    pub version_number: i64,
215
216    /// Version title.
217    pub title: String,
218
219    /// Version body.
220    pub body: String,
221
222    /// Version metadata.
223    #[schemars(with = "std::collections::BTreeMap<String, Value>")]
224    pub metadata: Value,
225
226    /// User that created this version.
227    pub created_by: Option<Uuid>,
228
229    /// Username of the user that created this version.
230    #[serde(skip_serializing_if = "Option::is_none")]
231    pub created_by_username: Option<String>,
232
233    /// Display name of the user that created this version.
234    #[serde(skip_serializing_if = "Option::is_none")]
235    pub created_by_display_name: Option<String>,
236
237    /// Creator's current effective workspace role.
238    #[serde(skip_serializing_if = "Option::is_none")]
239    pub created_by_workspace_role: Option<MembershipRole>,
240
241    /// Creator's current effective access role for this object.
242    #[serde(skip_serializing_if = "Option::is_none")]
243    pub created_by_object_role: Option<ObjectRole>,
244
245    /// Creation timestamp.
246    pub created_at: DateTime<Utc>,
247}
248
249/// Request to reuse an existing object attachment.
250#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
251#[serde(deny_unknown_fields)]
252pub struct ReuseObjectAttachmentRequest {
253    /// Authorized source attachment ID.
254    pub source_attachment_id: Uuid,
255
256    /// Optional target object version ID.
257    pub version_id: Option<Uuid>,
258}
259
260/// Query parameters for uploading an object attachment.
261#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
262pub struct UploadObjectAttachmentParams {
263    /// Optional object version ID this attachment belongs to.
264    pub version_id: Option<Uuid>,
265
266    /// Optional attachment display name.
267    pub name: Option<String>,
268
269    /// Optional media type.
270    pub media_type: Option<String>,
271
272    /// Optional attachment metadata as a flat JSON object string.
273    pub metadata: Option<String>,
274}
275
276/// Object attachment resource.
277#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
278pub struct ObjectAttachment {
279    /// Attachment ID.
280    pub id: Uuid,
281
282    /// Parent workspace ID.
283    pub workspace_id: Uuid,
284
285    /// Parent object ID.
286    pub object_id: Uuid,
287
288    /// Optional object version ID.
289    #[serde(skip_serializing_if = "Option::is_none")]
290    pub version_id: Option<Uuid>,
291
292    /// Stable SHA-256 content reference for the attachment bytes.
293    pub content_ref: String,
294
295    /// Stored attachment length in bytes.
296    pub size_bytes: u64,
297
298    /// Best-effort provenance for a reused attachment.
299    ///
300    /// This is cleared if the source attachment is deleted.
301    #[serde(skip_serializing_if = "Option::is_none")]
302    pub source_attachment_id: Option<Uuid>,
303
304    /// Optional attachment display name.
305    #[serde(skip_serializing_if = "Option::is_none")]
306    pub name: Option<String>,
307
308    /// Optional media type.
309    #[serde(skip_serializing_if = "Option::is_none")]
310    pub media_type: Option<String>,
311
312    /// Attachment metadata.
313    #[schemars(with = "std::collections::BTreeMap<String, Value>")]
314    pub metadata: Value,
315
316    /// User that created this attachment.
317    pub created_by: Option<Uuid>,
318
319    /// Creation timestamp.
320    pub created_at: DateTime<Utc>,
321}
322
323/// Object attachment response envelope.
324#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
325pub struct ObjectAttachmentResponse {
326    /// Object attachment resource.
327    pub attachment: ObjectAttachment,
328}
329
330/// Object response envelope.
331#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
332pub struct ObjectResponse {
333    /// Object resource.
334    pub object: ObjectResource,
335
336    /// Current version, if present.
337    #[serde(skip_serializing_if = "Option::is_none")]
338    pub current_version: Option<ObjectVersion>,
339
340    /// Effective role derived from the authenticated user's object authority.
341    /// API-key scopes remain an additional restriction for API-key requests.
342    pub effective_role: ObjectRole,
343}
344
345/// Object version response envelope.
346#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
347pub struct ObjectVersionResponse {
348    /// Object version resource.
349    pub version: ObjectVersion,
350}
351
352/// Wikilink derived from an immutable object version.
353#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
354pub struct ObjectVersionWikilink {
355    /// Normalized title target authored inside the double brackets.
356    pub raw_target: String,
357
358    /// Optional display text authored after the `|` separator.
359    #[serde(skip_serializing_if = "Option::is_none")]
360    pub display_text: Option<String>,
361
362    /// Resolved target object when the requesting user can read it.
363    #[serde(skip_serializing_if = "Option::is_none")]
364    pub target_object_id: Option<Uuid>,
365}
366
367/// Object-version wikilink response envelope.
368#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
369pub struct ObjectVersionWikilinksResponse {
370    /// Wikilinks in authored source order.
371    pub items: Vec<ObjectVersionWikilink>,
372}
373
374/// Returns an empty JSON object value.
375fn empty_object() -> Value {
376    Value::Object(serde_json::Map::new())
377}