Skip to main content

kival_types/
lib.rs

1//! Canonical vocabulary shared across Kival's internal and public Rust interfaces.
2//!
3//! These types name concepts whose meaning is shared by the kernel and the HTTP
4//! contract. Transport-specific request and response models do not belong here.
5
6#![cfg_attr(not(test), warn(unused_crate_dependencies))]
7#![cfg_attr(docsrs, feature(doc_cfg))]
8
9use uuid::Uuid;
10
11/// Defines the stable API-key scope vocabulary from one source list.
12macro_rules! api_key_scopes {
13    (
14        $(
15            $(#[$meta:meta])*
16            $variant:ident => $wire_name:literal
17        ),+ $(,)?
18    ) => {
19        /// Capability granted to an API key.
20        #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
21        #[cfg_attr(feature = "wire", derive(serde::Serialize, serde::Deserialize, schemars::JsonSchema))]
22        pub enum ApiKeyScope {
23            $(
24                $(#[$meta])*
25                #[cfg_attr(feature = "wire", serde(rename = $wire_name))]
26                $variant,
27            )+
28        }
29
30        impl ApiKeyScope {
31            /// All supported scopes in stable declaration order.
32            pub const ALL: &[Self] = &[
33                $(Self::$variant,)+
34            ];
35
36            /// Returns the stable stored and serialized scope name.
37            #[must_use]
38            pub const fn as_str(self) -> &'static str {
39                match self {
40                    $(Self::$variant => $wire_name,)+
41                }
42            }
43        }
44
45        impl std::str::FromStr for ApiKeyScope {
46            type Err = ();
47
48            fn from_str(value: &str) -> Result<Self, Self::Err> {
49                match value {
50                    $($wire_name => Ok(Self::$variant),)+
51                    _ => Err(()),
52                }
53            }
54        }
55    };
56}
57
58api_key_scopes! {
59    /// Discover and inspect permitted workspaces.
60    WorkspaceRead => "workspaces:read",
61    /// Modify the metadata and lifecycle of permitted existing workspaces.
62    /// Also satisfies `workspaces:read`.
63    WorkspaceWrite => "workspaces:write",
64    /// Read, list, and search objects.
65    ObjectRead => "objects:read",
66    /// Create, update, archive, and unarchive objects.
67    /// Also satisfies `objects:read`.
68    ObjectWrite => "objects:write",
69    /// Read attachment metadata and content.
70    AttachmentRead => "attachments:read",
71    /// Upload and reuse attachments.
72    /// Also satisfies `attachments:read`.
73    AttachmentWrite => "attachments:write",
74    /// Read graphs, backlinks, and edges.
75    GraphRead => "graph:read",
76    /// Create and revoke graph edges.
77    /// Also satisfies `graph:read`.
78    GraphWrite => "graph:write",
79    /// Read workspace and object activity.
80    EventRead => "events:read",
81    /// Receive ephemeral realtime invalidations for resources the key may read.
82    RealtimeRead => "realtime:read",
83    /// Manage workspace memberships, workspace group links, and object grants.
84    AccessManage => "access:manage",
85    /// Access API-key-enabled global user, group, and event operations.
86    /// The owning user's current authority remains the upper bound.
87    Admin => "admin",
88}
89
90impl ApiKeyScope {
91    /// Returns whether this granted scope satisfies a route requiring `required`.
92    ///
93    /// Write scopes include the corresponding read capability because mutations may inspect or
94    /// return the current resource state. Other scopes remain exact.
95    #[must_use]
96    pub const fn permits(self, required: Self) -> bool {
97        match required {
98            Self::WorkspaceRead => matches!(self, Self::WorkspaceRead | Self::WorkspaceWrite),
99            Self::WorkspaceWrite => matches!(self, Self::WorkspaceWrite),
100            Self::ObjectRead => matches!(self, Self::ObjectRead | Self::ObjectWrite),
101            Self::ObjectWrite => matches!(self, Self::ObjectWrite),
102            Self::AttachmentRead => matches!(self, Self::AttachmentRead | Self::AttachmentWrite),
103            Self::AttachmentWrite => matches!(self, Self::AttachmentWrite),
104            Self::GraphRead => matches!(self, Self::GraphRead | Self::GraphWrite),
105            Self::GraphWrite => matches!(self, Self::GraphWrite),
106            Self::EventRead => matches!(self, Self::EventRead),
107            Self::RealtimeRead => matches!(self, Self::RealtimeRead),
108            Self::AccessManage => matches!(self, Self::AccessManage),
109            Self::Admin => matches!(self, Self::Admin),
110        }
111    }
112}
113
114/// Object permission role.
115#[derive(Debug, Clone, Copy, PartialEq, Eq)]
116#[cfg_attr(feature = "wire", derive(serde::Serialize, serde::Deserialize, schemars::JsonSchema))]
117#[cfg_attr(feature = "wire", serde(rename_all = "lowercase"))]
118pub enum ObjectRole {
119    /// Read access plus participation in object commentary.
120    Viewer,
121    /// Viewer capabilities plus canonical object editing.
122    Editor,
123    /// Editor capabilities plus object administration and grant management.
124    Admin,
125}
126
127impl ObjectRole {
128    /// Returns the stable stored and serialized representation.
129    #[must_use]
130    pub const fn as_str(self) -> &'static str {
131        match self {
132            Self::Viewer => "viewer",
133            Self::Editor => "editor",
134            Self::Admin => "admin",
135        }
136    }
137
138    /// Parses a role from its stable stored and serialized representation.
139    #[must_use]
140    pub fn parse(value: &str) -> Option<Self> {
141        value.parse().ok()
142    }
143}
144
145impl std::str::FromStr for ObjectRole {
146    type Err = ();
147
148    fn from_str(value: &str) -> Result<Self, Self::Err> {
149        match value {
150            "viewer" => Ok(Self::Viewer),
151            "editor" => Ok(Self::Editor),
152            "admin" => Ok(Self::Admin),
153            _ => Err(()),
154        }
155    }
156}
157
158impl std::fmt::Display for ObjectRole {
159    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
160        formatter.write_str(self.as_str())
161    }
162}
163
164/// Membership role for groups and workspaces.
165#[derive(Debug, Clone, Copy, PartialEq, Eq)]
166#[cfg_attr(feature = "wire", derive(serde::Serialize, serde::Deserialize, schemars::JsonSchema))]
167#[cfg_attr(feature = "wire", serde(rename_all = "lowercase"))]
168pub enum MembershipRole {
169    /// Regular member access.
170    Member,
171    /// Administrative access.
172    Admin,
173}
174
175impl MembershipRole {
176    /// Returns the stable stored and serialized representation.
177    #[must_use]
178    pub const fn as_str(self) -> &'static str {
179        match self {
180            Self::Member => "member",
181            Self::Admin => "admin",
182        }
183    }
184}
185
186impl std::str::FromStr for MembershipRole {
187    type Err = ();
188
189    fn from_str(value: &str) -> Result<Self, Self::Err> {
190        match value {
191            "member" => Ok(Self::Member),
192            "admin" => Ok(Self::Admin),
193            _ => Err(()),
194        }
195    }
196}
197
198impl std::fmt::Display for MembershipRole {
199    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
200        formatter.write_str(self.as_str())
201    }
202}
203
204/// Principal targeted by an object grant.
205#[derive(Debug, Clone, Copy, PartialEq, Eq)]
206#[cfg_attr(feature = "wire", derive(serde::Serialize, serde::Deserialize, schemars::JsonSchema))]
207#[cfg_attr(feature = "wire", serde(tag = "type", content = "id", rename_all = "snake_case"))]
208pub enum GrantPrincipal {
209    /// User principal.
210    User(Uuid),
211    /// Group principal.
212    Group(Uuid),
213}
214
215/// Archive lifecycle status shared by archivable resources.
216#[derive(Debug, Clone, Copy, PartialEq, Eq)]
217#[cfg_attr(feature = "wire", derive(serde::Serialize, serde::Deserialize, schemars::JsonSchema))]
218#[cfg_attr(feature = "wire", serde(rename_all = "lowercase"))]
219pub enum ArchiveStatus {
220    /// Active resource.
221    Active,
222    /// Archived resource.
223    Archived,
224}
225
226impl ArchiveStatus {
227    /// Returns the stable stored and serialized representation.
228    #[must_use]
229    pub const fn as_str(self) -> &'static str {
230        match self {
231            Self::Active => "active",
232            Self::Archived => "archived",
233        }
234    }
235}
236
237impl std::str::FromStr for ArchiveStatus {
238    type Err = ();
239
240    fn from_str(value: &str) -> Result<Self, Self::Err> {
241        match value {
242            "active" => Ok(Self::Active),
243            "archived" => Ok(Self::Archived),
244            _ => Err(()),
245        }
246    }
247}
248
249impl std::fmt::Display for ArchiveStatus {
250    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
251        formatter.write_str(self.as_str())
252    }
253}
254
255/// Archive status filter for collection queries.
256#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
257#[cfg_attr(feature = "wire", derive(serde::Serialize, serde::Deserialize, schemars::JsonSchema))]
258#[cfg_attr(feature = "wire", serde(rename_all = "lowercase"))]
259pub enum ArchiveListStatus {
260    /// Only active resources.
261    #[default]
262    Active,
263    /// Only archived resources.
264    Archived,
265    /// Active and archived resources.
266    All,
267}
268
269impl ArchiveListStatus {
270    /// Returns the stable query representation.
271    #[must_use]
272    pub const fn as_str(self) -> &'static str {
273        match self {
274            Self::Active => "active",
275            Self::Archived => "archived",
276            Self::All => "all",
277        }
278    }
279}
280
281/// User lifecycle status.
282#[derive(Debug, Clone, Copy, PartialEq, Eq)]
283#[cfg_attr(feature = "wire", derive(serde::Serialize, serde::Deserialize, schemars::JsonSchema))]
284#[cfg_attr(feature = "wire", serde(rename_all = "lowercase"))]
285pub enum UserStatus {
286    /// Active user.
287    Active,
288    /// Disabled user.
289    Disabled,
290}
291
292impl UserStatus {
293    /// Returns the stable stored and serialized representation.
294    #[must_use]
295    pub const fn as_str(self) -> &'static str {
296        match self {
297            Self::Active => "active",
298            Self::Disabled => "disabled",
299        }
300    }
301}
302
303impl std::str::FromStr for UserStatus {
304    type Err = ();
305
306    fn from_str(value: &str) -> Result<Self, Self::Err> {
307        match value {
308            "active" => Ok(Self::Active),
309            "disabled" => Ok(Self::Disabled),
310            _ => Err(()),
311        }
312    }
313}
314
315impl std::fmt::Display for UserStatus {
316    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
317        formatter.write_str(self.as_str())
318    }
319}
320
321/// User lifecycle selector for administration queries.
322#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
323#[cfg_attr(feature = "wire", derive(serde::Serialize, serde::Deserialize, schemars::JsonSchema))]
324#[cfg_attr(feature = "wire", serde(rename_all = "lowercase"))]
325pub enum UserListStatus {
326    /// Only active users.
327    #[default]
328    Active,
329    /// Only disabled users.
330    Disabled,
331    /// Active and disabled users.
332    All,
333}
334
335impl UserListStatus {
336    /// Returns the stable query representation.
337    #[must_use]
338    pub const fn as_str(self) -> &'static str {
339        match self {
340            Self::Active => "active",
341            Self::Disabled => "disabled",
342            Self::All => "all",
343        }
344    }
345}
346
347/// Sort order for object collection queries.
348#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
349#[cfg_attr(feature = "wire", derive(serde::Serialize, serde::Deserialize, schemars::JsonSchema))]
350#[cfg_attr(feature = "wire", serde(rename_all = "lowercase"))]
351pub enum ObjectListOrder {
352    /// Sort by creation time, newest first.
353    #[default]
354    Created,
355    /// Sort by last update time, newest first.
356    Updated,
357}
358
359impl ObjectListOrder {
360    /// Returns the stable query representation.
361    #[must_use]
362    pub const fn as_str(self) -> &'static str {
363        match self {
364            Self::Created => "created",
365            Self::Updated => "updated",
366        }
367    }
368}
369
370/// Search document category.
371#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
372#[cfg_attr(feature = "wire", derive(serde::Serialize, serde::Deserialize, schemars::JsonSchema))]
373#[cfg_attr(feature = "wire", serde(rename_all = "lowercase"))]
374pub enum SearchCategory {
375    /// Object-version title.
376    Title,
377    /// Object-version body.
378    Body,
379    /// Serialized object-version metadata.
380    Metadata,
381}
382
383impl SearchCategory {
384    /// Returns the stable stored and serialized representation.
385    #[must_use]
386    pub const fn as_str(self) -> &'static str {
387        match self {
388            Self::Title => "title",
389            Self::Body => "body",
390            Self::Metadata => "metadata",
391        }
392    }
393}
394
395impl std::str::FromStr for SearchCategory {
396    type Err = ();
397
398    fn from_str(value: &str) -> Result<Self, Self::Err> {
399        match value {
400            "title" => Ok(Self::Title),
401            "body" => Ok(Self::Body),
402            "metadata" => Ok(Self::Metadata),
403            _ => Err(()),
404        }
405    }
406}
407
408impl std::fmt::Display for SearchCategory {
409    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
410        formatter.write_str(self.as_str())
411    }
412}
413
414/// Search match classification.
415#[derive(Debug, Clone, Copy, PartialEq, Eq)]
416#[cfg_attr(feature = "wire", derive(serde::Serialize, serde::Deserialize, schemars::JsonSchema))]
417#[cfg_attr(feature = "wire", serde(rename_all = "snake_case"))]
418pub enum SearchMatchKind {
419    /// Full-text match.
420    Text,
421    /// Literal substring match.
422    Literal,
423    /// Exact category match.
424    Exact,
425}
426
427impl SearchMatchKind {
428    /// Returns the stable stored and serialized representation.
429    #[must_use]
430    pub const fn as_str(self) -> &'static str {
431        match self {
432            Self::Text => "text",
433            Self::Literal => "literal",
434            Self::Exact => "exact",
435        }
436    }
437}
438
439impl std::str::FromStr for SearchMatchKind {
440    type Err = ();
441
442    fn from_str(value: &str) -> Result<Self, Self::Err> {
443        match value {
444            "text" => Ok(Self::Text),
445            "literal" => Ok(Self::Literal),
446            "exact" => Ok(Self::Exact),
447            _ => Err(()),
448        }
449    }
450}
451
452impl std::fmt::Display for SearchMatchKind {
453    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
454        formatter.write_str(self.as_str())
455    }
456}
457
458/// Current lifecycle state of a comment body.
459#[derive(Debug, Clone, Copy, PartialEq, Eq)]
460#[cfg_attr(feature = "wire", derive(serde::Serialize, serde::Deserialize, schemars::JsonSchema))]
461#[cfg_attr(feature = "wire", serde(rename_all = "snake_case"))]
462pub enum CommentStatus {
463    /// Body remains available.
464    Active,
465    /// Body was removed by a user or administrator.
466    Deleted,
467    /// Body was removed by retention.
468    Expired,
469}
470
471/// Search matching mode.
472#[derive(Debug, Clone, Copy, PartialEq, Eq)]
473#[cfg_attr(feature = "wire", derive(serde::Serialize, serde::Deserialize, schemars::JsonSchema))]
474#[cfg_attr(feature = "wire", serde(rename_all = "snake_case"))]
475pub enum SearchMode {
476    /// Full-text or literal matching, with low-ranked partial-term fallback for plain multi-word
477    /// queries.
478    Auto,
479    /// `PostgreSQL` web-search full-text matching.
480    Text,
481    /// Contiguous literal substring matching.
482    Literal,
483    /// Complete-value equality matching.
484    Exact,
485}
486
487impl SearchMode {
488    /// Returns the stable query representation.
489    #[must_use]
490    pub const fn as_str(self) -> &'static str {
491        match self {
492            Self::Auto => "auto",
493            Self::Text => "text",
494            Self::Literal => "literal",
495            Self::Exact => "exact",
496        }
497    }
498}
499
500/// Traversal direction for an object-centered graph.
501#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
502#[cfg_attr(feature = "wire", derive(serde::Serialize, serde::Deserialize, schemars::JsonSchema))]
503#[cfg_attr(feature = "wire", serde(rename_all = "lowercase"))]
504pub enum ObjectGraphDirection {
505    /// Follow edges from source to target.
506    Outgoing,
507    /// Follow edges from target to source.
508    Incoming,
509    /// Follow edges in both directions.
510    #[default]
511    Both,
512}
513
514impl ObjectGraphDirection {
515    /// Returns the stable query representation.
516    #[must_use]
517    pub const fn as_str(self) -> &'static str {
518        match self {
519            Self::Outgoing => "outgoing",
520            Self::Incoming => "incoming",
521            Self::Both => "both",
522        }
523    }
524
525    /// Parses a traversal direction.
526    #[must_use]
527    pub fn parse(value: &str) -> Option<Self> {
528        match value {
529            "outgoing" => Some(Self::Outgoing),
530            "incoming" => Some(Self::Incoming),
531            "both" => Some(Self::Both),
532            _ => None,
533        }
534    }
535}
536
537impl std::fmt::Display for ObjectGraphDirection {
538    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
539        formatter.write_str(self.as_str())
540    }
541}
542
543/// Event sequence ordering.
544#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
545#[cfg_attr(feature = "wire", derive(serde::Serialize, serde::Deserialize, schemars::JsonSchema))]
546#[cfg_attr(feature = "wire", serde(rename_all = "lowercase"))]
547pub enum EventOrder {
548    /// Oldest events first.
549    #[default]
550    Asc,
551    /// Newest events first.
552    Desc,
553}
554
555impl EventOrder {
556    /// Returns the stable query representation.
557    #[must_use]
558    pub const fn as_str(self) -> &'static str {
559        match self {
560            Self::Asc => "asc",
561            Self::Desc => "desc",
562        }
563    }
564}
565
566impl std::str::FromStr for EventOrder {
567    type Err = &'static str;
568
569    fn from_str(value: &str) -> Result<Self, Self::Err> {
570        match value {
571            "asc" => Ok(Self::Asc),
572            "desc" => Ok(Self::Desc),
573            _ => Err("expected `asc` or `desc`"),
574        }
575    }
576}
577
578impl std::fmt::Display for EventOrder {
579    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
580        formatter.write_str(self.as_str())
581    }
582}
583
584#[cfg(test)]
585mod tests {
586    use super::{
587        ApiKeyScope, ArchiveStatus, EventOrder, MembershipRole, ObjectRole, SearchMatchKind,
588        UserStatus,
589    };
590
591    #[test]
592    fn event_order_names_round_trip() {
593        for (value, order) in [("asc", EventOrder::Asc), ("desc", EventOrder::Desc)] {
594            assert_eq!(value.parse(), Ok(order));
595            assert_eq!(order.to_string(), value);
596        }
597        assert!("newest".parse::<EventOrder>().is_err());
598    }
599
600    #[test]
601    fn api_key_scope_names_round_trip() {
602        for scope in ApiKeyScope::ALL {
603            assert_eq!(scope.as_str().parse(), Ok(*scope));
604        }
605    }
606
607    #[test]
608    fn stored_roles_and_statuses_round_trip() {
609        for role in [ObjectRole::Viewer, ObjectRole::Editor, ObjectRole::Admin] {
610            assert_eq!(role.as_str().parse(), Ok(role));
611        }
612        for role in [MembershipRole::Member, MembershipRole::Admin] {
613            assert_eq!(role.as_str().parse(), Ok(role));
614        }
615        for status in [ArchiveStatus::Active, ArchiveStatus::Archived] {
616            assert_eq!(status.as_str().parse(), Ok(status));
617        }
618        for status in [UserStatus::Active, UserStatus::Disabled] {
619            assert_eq!(status.as_str().parse(), Ok(status));
620        }
621        for kind in [SearchMatchKind::Text, SearchMatchKind::Literal, SearchMatchKind::Exact] {
622            assert_eq!(kind.as_str().parse(), Ok(kind));
623        }
624    }
625
626    #[test]
627    fn api_key_write_scopes_include_corresponding_read_scope() {
628        for (write, read) in [
629            (ApiKeyScope::WorkspaceWrite, ApiKeyScope::WorkspaceRead),
630            (ApiKeyScope::ObjectWrite, ApiKeyScope::ObjectRead),
631            (ApiKeyScope::AttachmentWrite, ApiKeyScope::AttachmentRead),
632            (ApiKeyScope::GraphWrite, ApiKeyScope::GraphRead),
633        ] {
634            assert!(write.permits(write));
635            assert!(write.permits(read));
636            assert!(!read.permits(write));
637        }
638    }
639
640    #[test]
641    fn unrelated_api_key_scopes_do_not_imply_each_other() {
642        assert!(!ApiKeyScope::Admin.permits(ApiKeyScope::ObjectRead));
643        assert!(!ApiKeyScope::ObjectWrite.permits(ApiKeyScope::AttachmentRead));
644        assert!(!ApiKeyScope::RealtimeRead.permits(ApiKeyScope::ObjectRead));
645        assert!(!ApiKeyScope::RealtimeRead.permits(ApiKeyScope::EventRead));
646        assert!(!ApiKeyScope::EventRead.permits(ApiKeyScope::RealtimeRead));
647        assert!(!ApiKeyScope::AccessManage.permits(ApiKeyScope::WorkspaceRead));
648    }
649}