Skip to main content

kival_sdk/wire/
graph.rs

1//! Object graph and grant wire protocol types.
2
3use chrono::{DateTime, Utc};
4use schemars::JsonSchema;
5use serde::{Deserialize, Serialize};
6use uuid::Uuid;
7
8use crate::{ArchiveStatus, DEFAULT_LIMIT, MAX_LIMIT};
9
10/// Query parameters for object backlinks.
11///
12/// Omit both cursors on the initial request to fetch both backlink streams. On continuation
13/// requests, only streams with a supplied cursor are fetched; an omitted cursor means that stream
14/// is exhausted or is not being continued.
15#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize, JsonSchema)]
16pub struct ObjectBacklinksParams {
17    /// Maximum number of explicit edges and textual references to return per section.
18    pub limit: Option<i64>,
19    /// Opaque cursor for the next explicit-edge page.
20    pub edge_cursor: Option<String>,
21    /// Opaque cursor for the next textual-reference page.
22    pub reference_cursor: Option<String>,
23    /// Include archived source objects when the actor may read them.
24    #[serde(default)]
25    pub include_archived: bool,
26}
27
28impl ObjectBacklinksParams {
29    /// Returns the validated and capped result limit.
30    ///
31    /// # Errors
32    ///
33    /// Returns an error if the requested limit is less than one.
34    pub fn checked_limit(&self) -> Result<i64, &'static str> {
35        match self.limit {
36            Some(limit) if limit < 1 => Err("limit must be at least 1"),
37            Some(limit) => Ok(limit.min(MAX_LIMIT)),
38            None => Ok(DEFAULT_LIMIT),
39        }
40    }
41}
42
43/// Source object summary included with an explicit backlink.
44#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
45pub struct BacklinkSourceObject {
46    /// Source object ID.
47    pub id: Uuid,
48    /// Source object title.
49    pub title: String,
50    /// Source object lifecycle status.
51    pub status: ArchiveStatus,
52}
53
54/// Explicit inbound edge in a backlinks response.
55#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
56pub struct ObjectBacklink {
57    /// Edge ID.
58    pub edge_id: Uuid,
59    /// Visible source object summary.
60    pub source_object: BacklinkSourceObject,
61    /// Requested target object ID.
62    pub target_object_id: Uuid,
63    /// User that created the edge.
64    pub created_by: Option<Uuid>,
65    /// Edge creation timestamp.
66    pub created_at: DateTime<Utc>,
67}
68
69/// Derived textual reference pointing to an object.
70#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
71pub struct ObjectBacklinkReference {
72    /// Derived reference row ID.
73    pub reference_id: Uuid,
74    /// Reference syntax kind.
75    pub reference_kind: String,
76    /// Visible source object summary.
77    pub source_object: BacklinkSourceObject,
78    /// Source object version containing the reference.
79    pub source_version_id: Uuid,
80    /// Resolved target object ID.
81    pub target_object_id: Uuid,
82    /// Raw target text found in source content.
83    pub raw_target: String,
84    /// Optional display text.
85    #[serde(skip_serializing_if = "Option::is_none")]
86    pub display_text: Option<String>,
87    /// Inclusive UTF-8 byte offset in the source body.
88    pub span_start: i32,
89    /// Exclusive UTF-8 byte offset in the source body.
90    pub span_end: i32,
91    /// Reference creation timestamp.
92    pub created_at: DateTime<Utc>,
93}
94
95/// Object-centric inbound references.
96#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
97pub struct ObjectBacklinksResponse {
98    /// Requested target object ID.
99    pub object_id: Uuid,
100    /// Visible explicit inbound graph edges.
101    pub incoming_edges: Vec<ObjectBacklink>,
102    /// Opaque cursor for the next explicit-edge page.
103    #[serde(skip_serializing_if = "Option::is_none")]
104    pub next_edge_cursor: Option<String>,
105    /// Visible resolved textual references from current source versions.
106    pub incoming_references: Vec<ObjectBacklinkReference>,
107    /// Opaque cursor for the next textual-reference page.
108    #[serde(skip_serializing_if = "Option::is_none")]
109    pub next_reference_cursor: Option<String>,
110}
111
112pub use kival_types::{GrantPrincipal, ObjectGraphDirection, ObjectRole};
113
114/// Query parameters for a bounded object-centered graph.
115#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
116pub struct ObjectGraphParams {
117    /// Maximum traversal depth from the root.
118    pub depth: Option<i32>,
119    /// Traversal direction.
120    #[serde(default)]
121    pub direction: ObjectGraphDirection,
122    /// Maximum number of nodes to return.
123    #[serde(alias = "limit_nodes")]
124    pub max_nodes: Option<i64>,
125    /// Maximum number of edges to return.
126    #[serde(alias = "limit_edges")]
127    pub max_edges: Option<i64>,
128    /// Include the root node in the returned node set.
129    #[serde(default = "default_true")]
130    pub include_root: bool,
131}
132
133impl Default for ObjectGraphParams {
134    fn default() -> Self {
135        Self {
136            depth: None,
137            direction: ObjectGraphDirection::Both,
138            max_nodes: None,
139            max_edges: None,
140            include_root: true,
141        }
142    }
143}
144
145/// Node in an object-centered graph.
146#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
147pub struct ObjectGraphNode {
148    /// Object ID.
149    pub id: Uuid,
150    /// Workspace ID.
151    pub workspace_id: Uuid,
152    /// Current object version ID.
153    pub current_version_id: Option<Uuid>,
154    /// Title projected from the current immutable version.
155    pub title: String,
156    /// Object lifecycle status.
157    pub status: ArchiveStatus,
158    /// User that created the object.
159    pub created_by: Option<Uuid>,
160    /// Creation timestamp.
161    pub created_at: DateTime<Utc>,
162    /// Last update timestamp.
163    pub updated_at: DateTime<Utc>,
164    /// Shortest traversal distance from the root.
165    pub distance: i32,
166    /// Visible filtered incoming explicit-relationship count.
167    pub incoming_count: i64,
168    /// Visible filtered outgoing explicit-relationship count.
169    pub outgoing_count: i64,
170}
171
172/// Origin of a graph link projected into an object or workspace graph.
173#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
174#[serde(rename_all = "snake_case")]
175pub enum GraphEdgeKind {
176    /// Explicit relationship stored in the object-edge model.
177    Relationship,
178    /// Resolved reference authored in the source object's current version.
179    Reference,
180    /// The same directed graph link exists both explicitly and as a reference.
181    RelationshipAndReference,
182}
183
184/// Edge in an object-centered graph.
185#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
186pub struct ObjectGraphEdge {
187    /// Representative relationship or reference row ID.
188    pub id: Uuid,
189    /// Workspace ID.
190    pub workspace_id: Uuid,
191    /// Source object ID.
192    pub source_object_id: Uuid,
193    /// Target object ID.
194    pub target_object_id: Uuid,
195    /// How this directed graph link is represented in Kival.
196    pub kind: GraphEdgeKind,
197    /// User that created the representative relationship or source version.
198    pub created_by: Option<Uuid>,
199    /// Creation timestamp.
200    pub created_at: DateTime<Utc>,
201    /// Last update timestamp.
202    pub updated_at: DateTime<Utc>,
203}
204
205/// Structured object graph truncation details.
206#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
207pub struct ObjectGraphTruncation {
208    /// Whether traversal hit the node cap.
209    pub nodes: bool,
210    /// Whether the returned edge set hit the edge cap.
211    pub edges: bool,
212}
213
214/// Bounded authorized graph neighborhood around an object.
215#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
216pub struct ObjectGraphResponse {
217    /// Workspace ID.
218    pub workspace_id: Uuid,
219    /// Root object ID.
220    pub root_object_id: Uuid,
221    /// Applied traversal depth.
222    pub depth: i32,
223    /// Applied traversal direction.
224    pub direction: ObjectGraphDirection,
225    /// Applied maximum node count.
226    pub max_nodes: i64,
227    /// Applied maximum edge count.
228    pub max_edges: i64,
229    /// Whether any truncation occurred.
230    pub truncated: bool,
231    /// Structured truncation details.
232    pub truncation: ObjectGraphTruncation,
233    /// Visible local graph nodes.
234    pub nodes: Vec<ObjectGraphNode>,
235    /// Visible edges between returned nodes.
236    pub edges: Vec<ObjectGraphEdge>,
237}
238
239/// Returns true for serde defaults.
240const fn default_true() -> bool {
241    true
242}
243
244/// Query parameters for a bounded workspace graph projection.
245#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize, JsonSchema)]
246pub struct WorkspaceGraphParams {
247    /// Maximum number of nodes to return.
248    pub limit_nodes: Option<i64>,
249    /// Maximum number of edges to return.
250    pub limit_edges: Option<i64>,
251    /// Exclude nodes with no visible filtered relation.
252    #[serde(default)]
253    pub exclude_isolated: bool,
254}
255
256/// Node in a workspace graph projection.
257#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
258pub struct WorkspaceGraphNode {
259    /// Object ID.
260    pub id: Uuid,
261    /// Workspace ID.
262    pub workspace_id: Uuid,
263    /// Current object version ID.
264    pub current_version_id: Option<Uuid>,
265    /// Title projected from the current immutable version.
266    pub title: String,
267    /// Object lifecycle status.
268    pub status: ArchiveStatus,
269    /// User that created the object.
270    pub created_by: Option<Uuid>,
271    /// Creation timestamp.
272    pub created_at: DateTime<Utc>,
273    /// Last update timestamp.
274    pub updated_at: DateTime<Utc>,
275    /// Number of incoming explicit relationships in the visible filtered graph before edge
276    /// response truncation.
277    pub in_degree: i64,
278    /// Number of outgoing explicit relationships in the visible filtered graph before edge
279    /// response truncation.
280    pub out_degree: i64,
281}
282
283/// Edge in a workspace graph projection.
284#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
285pub struct WorkspaceGraphEdge {
286    /// Representative relationship or reference row ID.
287    pub id: Uuid,
288    /// Workspace ID.
289    pub workspace_id: Uuid,
290    /// Source object ID.
291    pub source_object_id: Uuid,
292    /// Target object ID.
293    pub target_object_id: Uuid,
294    /// How this directed graph link is represented in Kival.
295    pub kind: GraphEdgeKind,
296    /// User that created the representative relationship or source version.
297    pub created_by: Option<Uuid>,
298    /// Creation timestamp.
299    pub created_at: DateTime<Utc>,
300    /// Last update timestamp.
301    pub updated_at: DateTime<Utc>,
302}
303
304/// Applied workspace graph limits and truncation indicators.
305#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
306pub struct WorkspaceGraphLimits {
307    /// Applied node limit.
308    pub limit_nodes: i64,
309    /// Applied edge limit.
310    pub limit_edges: i64,
311    /// Whether more visible nodes matched.
312    pub has_more_nodes: bool,
313    /// Whether more visible edges matched between the returned nodes.
314    pub has_more_edges: bool,
315}
316
317/// Bounded workspace graph projection.
318#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
319pub struct WorkspaceGraphResponse {
320    /// Workspace ID.
321    pub workspace_id: Uuid,
322    /// Visible graph nodes.
323    pub nodes: Vec<WorkspaceGraphNode>,
324    /// Visible edges between returned nodes.
325    pub edges: Vec<WorkspaceGraphEdge>,
326    /// Applied limits and truncation indicators.
327    pub limits: WorkspaceGraphLimits,
328}
329
330/// Request body for creating an object edge.
331#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
332pub struct CreateObjectEdgeRequest {
333    /// Source object ID.
334    pub source_object_id: Uuid,
335
336    /// Target object ID.
337    pub target_object_id: Uuid,
338}
339
340/// Object edge resource.
341#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
342pub struct ObjectEdge {
343    /// Object edge ID.
344    pub id: Uuid,
345
346    /// Workspace ID.
347    pub workspace_id: Uuid,
348
349    /// Source object ID.
350    pub source_object_id: Uuid,
351
352    /// Target object ID.
353    pub target_object_id: Uuid,
354
355    /// User that created this edge.
356    pub created_by: Option<Uuid>,
357
358    /// User that revoked this edge.
359    pub revoked_by: Option<Uuid>,
360
361    /// Creation timestamp.
362    pub created_at: DateTime<Utc>,
363
364    /// Last update timestamp.
365    pub updated_at: DateTime<Utc>,
366
367    /// Revocation timestamp.
368    pub revoked_at: Option<DateTime<Utc>>,
369}
370
371/// Object edge response envelope.
372#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
373pub struct ObjectEdgeResponse {
374    /// Object edge resource.
375    pub edge: ObjectEdge,
376}
377
378/// Request body for creating an object grant.
379#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
380pub struct CreateObjectGrantRequest {
381    /// Grant principal.
382    pub principal: GrantPrincipal,
383
384    /// Object role.
385    pub object_role: ObjectRole,
386}
387
388/// Request body for updating an object grant.
389#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
390pub struct UpdateObjectGrantRequest {
391    /// New object role.
392    pub object_role: ObjectRole,
393}
394
395/// Object grant resource.
396#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
397pub struct ObjectGrant {
398    /// Object grant ID.
399    pub id: Uuid,
400
401    /// Workspace ID.
402    pub workspace_id: Uuid,
403
404    /// Object ID.
405    pub object_id: Uuid,
406
407    /// Principal user ID.
408    pub principal_user_id: Option<Uuid>,
409
410    /// Principal group ID.
411    pub principal_group_id: Option<Uuid>,
412
413    /// Object role.
414    pub object_role: ObjectRole,
415
416    /// User that created this grant.
417    pub created_by: Option<Uuid>,
418
419    /// User that revoked this grant.
420    pub revoked_by: Option<Uuid>,
421
422    /// Creation timestamp.
423    pub created_at: DateTime<Utc>,
424
425    /// Last update timestamp.
426    pub updated_at: DateTime<Utc>,
427
428    /// Revocation timestamp.
429    pub revoked_at: Option<DateTime<Utc>>,
430}
431
432/// Object grant response envelope.
433#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
434pub struct ObjectGrantResponse {
435    /// Object grant resource.
436    pub grant: ObjectGrant,
437}
438
439#[cfg(test)]
440mod tests {
441    use uuid::Uuid;
442
443    use crate::{DEFAULT_LIMIT, MAX_LIMIT, ObjectBacklinksParams, ObjectBacklinksResponse};
444
445    #[test]
446    fn backlinks_response_serializes_empty_references() {
447        let response = ObjectBacklinksResponse {
448            object_id: Uuid::from_u128(1),
449            incoming_edges: Vec::new(),
450            next_edge_cursor: None,
451            incoming_references: Vec::new(),
452            next_reference_cursor: None,
453        };
454
455        let value = serde_json::to_value(response).unwrap();
456        assert_eq!(value["incoming_references"], serde_json::json!([]));
457    }
458
459    #[test]
460    fn backlinks_query_defaults_and_caps_limit() {
461        assert_eq!(ObjectBacklinksParams::default().checked_limit(), Ok(DEFAULT_LIMIT));
462        assert_eq!(
463            ObjectBacklinksParams {
464                limit: Some(MAX_LIMIT + 1),
465                ..ObjectBacklinksParams::default()
466            }
467            .checked_limit(),
468            Ok(MAX_LIMIT)
469        );
470        assert_eq!(
471            ObjectBacklinksParams { limit: Some(0), ..ObjectBacklinksParams::default() }
472                .checked_limit(),
473            Err("limit must be at least 1")
474        );
475    }
476}