Skip to main content

khive_runtime/events_split/
protocol.rs

1use super::events_count_read_budget::WireReadFailure;
2use khive_storage::event::{
3    EventGroupBy, EventPageQuery, EventPageWindow, IdempotentEventBatchResult,
4};
5use khive_storage::{BatchWriteSummary, Event, EventFilter, Page, PageRequest};
6use serde::{Deserialize, Serialize};
7use std::collections::BTreeMap;
8use uuid::Uuid;
9
10/// Request frame sent from a domain process to the events daemon.
11#[derive(Debug, Serialize, Deserialize)]
12#[serde(tag = "op", rename_all = "snake_case")]
13pub enum EventsRequest {
14    /// Fire-and-forget append lane. The daemon replies with a summary, but the
15    /// forwarder treats a failed reply as a counted drop, never an error to
16    /// the original caller.
17    AppendEvents {
18        protocol_version: u32,
19        namespace: String,
20        events: Vec<Event>,
21    },
22    /// ADR-133 audit-batch lane: real dispositions come back.
23    AppendEventsIdempotent {
24        protocol_version: u32,
25        namespace: String,
26        events: Vec<Event>,
27    },
28    GetEvent {
29        protocol_version: u32,
30        namespace: String,
31        id: Uuid,
32    },
33    QueryEvents {
34        protocol_version: u32,
35        namespace: String,
36        filter: EventFilter,
37        page: PageRequest,
38    },
39    QueryEventPage {
40        protocol_version: u32,
41        namespace: String,
42        query: EventPageQuery,
43    },
44    CountEvents {
45        protocol_version: u32,
46        namespace: String,
47        #[serde(default)]
48        operator_read_budget_secs: Option<u64>,
49        filter: EventFilter,
50    },
51    CountEventsGrouped {
52        protocol_version: u32,
53        namespace: String,
54        #[serde(default)]
55        operator_read_budget_secs: Option<u64>,
56        filter: EventFilter,
57        group_by: EventGroupBy,
58    },
59}
60
61#[cfg(unix)]
62impl EventsRequest {
63    pub(super) fn protocol_version(&self) -> u32 {
64        match self {
65            Self::AppendEvents {
66                protocol_version, ..
67            }
68            | Self::AppendEventsIdempotent {
69                protocol_version, ..
70            }
71            | Self::GetEvent {
72                protocol_version, ..
73            }
74            | Self::QueryEvents {
75                protocol_version, ..
76            }
77            | Self::QueryEventPage {
78                protocol_version, ..
79            }
80            | Self::CountEvents {
81                protocol_version, ..
82            }
83            | Self::CountEventsGrouped {
84                protocol_version, ..
85            } => *protocol_version,
86        }
87    }
88
89    pub(super) fn disconnect_cancellable(&self) -> bool {
90        matches!(
91            self,
92            Self::CountEvents { .. }
93                | Self::CountEventsGrouped { .. }
94                | Self::QueryEvents { .. }
95                | Self::QueryEventPage { .. }
96        )
97    }
98
99    pub(super) fn count_budget_secs(&self) -> Option<Option<u64>> {
100        match self {
101            Self::CountEvents {
102                operator_read_budget_secs,
103                ..
104            }
105            | Self::CountEventsGrouped {
106                operator_read_budget_secs,
107                ..
108            } => Some(*operator_read_budget_secs),
109            _ => None,
110        }
111    }
112
113    pub(super) fn namespace(&self) -> &str {
114        match self {
115            Self::AppendEvents { namespace, .. }
116            | Self::AppendEventsIdempotent { namespace, .. }
117            | Self::GetEvent { namespace, .. }
118            | Self::QueryEvents { namespace, .. }
119            | Self::QueryEventPage { namespace, .. }
120            | Self::CountEvents { namespace, .. }
121            | Self::CountEventsGrouped { namespace, .. } => namespace,
122        }
123    }
124}
125
126/// Response frame from the events daemon.
127#[derive(Debug, Serialize, Deserialize)]
128#[serde(tag = "kind", rename_all = "snake_case")]
129pub enum EventsResponse {
130    Appended {
131        summary: BatchWriteSummary,
132    },
133    Idempotent {
134        result: IdempotentEventBatchResult,
135    },
136    Event {
137        event: Option<Event>,
138    },
139    Pageful {
140        page: Page<Event>,
141    },
142    EventPageWindow {
143        window: EventPageWindow,
144    },
145    Count {
146        count: u64,
147    },
148    GroupedCount {
149        counts: BTreeMap<String, u64>,
150    },
151    /// Typed refusal. `retryable` distinguishes transient daemon-side
152    /// conditions from contract errors (bad frame, version skew).
153    /// `writer_task_failure` carries both request finality and whether the
154    /// remote writer seam terminated. The retryable bit cannot express that
155    /// distinction: an ordinary operation or COMMIT error may be transient or
156    /// permanent while its transaction is independently proven rolled back.
157    /// `None` means the error is not from a writer request. Cross-version
158    /// frames never reach this mapping because `dispatch_events_request`
159    /// refuses a mismatched version before any write executes.
160    Error {
161        message: String,
162        retryable: bool,
163        #[serde(default)]
164        writer_task_failure: Option<WireWriterTaskFailure>,
165        /// Optional native write evidence; older frames retain their legacy mapping.
166        #[serde(default, skip_serializing_if = "Option::is_none")]
167        sqlite_write_failure: Option<khive_storage::error::SqliteWriteFailure>,
168        #[serde(default, skip_serializing_if = "Option::is_none")]
169        read_failure: Option<WireReadFailure>,
170    },
171}
172
173/// Whether a writer-state error belongs to one failed request on a still-live
174/// seam or to a permanently retired writer task.
175#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
176#[serde(tag = "kind", rename_all = "snake_case")]
177pub enum WireWriterTaskFailure {
178    RequestFailed {
179        request_state: WireWriterTaskState,
180    },
181    TaskTerminated {
182        request_state: WireWriterTaskState,
183        #[serde(default, skip_serializing_if = "Option::is_none")]
184        sqlite_full_codes: Option<(i32, i32)>,
185    },
186}
187
188/// Wire mirror of [`khive_storage::WriterTaskRequestState`]. A separate type
189/// because the storage enum is not serializable and the wire shape must stay
190/// under this module's protocol-version control, not the storage crate's.
191#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
192#[serde(rename_all = "snake_case")]
193pub enum WireWriterTaskState {
194    NotStarted,
195    TransactionRolledBack,
196    SideEffectsUnknown,
197}
198
199impl From<khive_storage::WriterTaskRequestState> for WireWriterTaskState {
200    fn from(state: khive_storage::WriterTaskRequestState) -> Self {
201        use khive_storage::WriterTaskRequestState as S;
202        match state {
203            S::NotStarted => Self::NotStarted,
204            S::TransactionRolledBack => Self::TransactionRolledBack,
205            S::SideEffectsUnknown => Self::SideEffectsUnknown,
206        }
207    }
208}
209
210impl From<WireWriterTaskState> for khive_storage::WriterTaskRequestState {
211    fn from(state: WireWriterTaskState) -> Self {
212        use khive_storage::WriterTaskRequestState as S;
213        match state {
214            WireWriterTaskState::NotStarted => S::NotStarted,
215            WireWriterTaskState::TransactionRolledBack => S::TransactionRolledBack,
216            WireWriterTaskState::SideEffectsUnknown => S::SideEffectsUnknown,
217        }
218    }
219}