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, PartialEq, Eq, Serialize, Deserialize)]
176#[serde(tag = "kind", rename_all = "snake_case")]
177pub enum WireWriterTaskFailure {
178    RequestFailed {
179        request_state: WireWriterTaskState,
180        #[serde(default, skip_serializing_if = "Option::is_none")]
181        evidence: Option<WireWriterFailureEvidence>,
182    },
183    TaskTerminated {
184        request_state: WireWriterTaskState,
185        #[serde(default, skip_serializing_if = "Option::is_none")]
186        sqlite_full_codes: Option<(i32, i32)>,
187    },
188}
189
190/// Additive evidence keeps the legacy request-failed envelope readable by old peers.
191#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
192#[serde(tag = "kind", rename_all = "snake_case")]
193pub enum WireWriterFailureEvidence {
194    WriteOutcomeUnknown,
195    OwnerUnavailable {
196        operation: String,
197        cause: WireWriterOwnerCause,
198    },
199    RouteViolation {
200        operation: String,
201    },
202}
203
204#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
205#[serde(tag = "kind", rename_all = "snake_case")]
206pub enum WireWriterOwnerCause {
207    Pool { operation: String, message: String },
208    NoRuntime,
209}
210
211/// Wire mirror of [`khive_storage::WriterTaskRequestState`]. A separate type
212/// because the storage enum is not serializable and the wire shape must stay
213/// under this module's protocol-version control, not the storage crate's.
214#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
215#[serde(rename_all = "snake_case")]
216pub enum WireWriterTaskState {
217    NotStarted,
218    TransactionRolledBack,
219    SideEffectsUnknown,
220}
221
222impl From<khive_storage::WriterTaskRequestState> for WireWriterTaskState {
223    fn from(state: khive_storage::WriterTaskRequestState) -> Self {
224        use khive_storage::WriterTaskRequestState as S;
225        match state {
226            S::NotStarted => Self::NotStarted,
227            S::TransactionRolledBack => Self::TransactionRolledBack,
228            S::SideEffectsUnknown => Self::SideEffectsUnknown,
229        }
230    }
231}
232
233impl From<WireWriterTaskState> for khive_storage::WriterTaskRequestState {
234    fn from(state: WireWriterTaskState) -> Self {
235        use khive_storage::WriterTaskRequestState as S;
236        match state {
237            WireWriterTaskState::NotStarted => S::NotStarted,
238            WireWriterTaskState::TransactionRolledBack => S::TransactionRolledBack,
239            WireWriterTaskState::SideEffectsUnknown => S::SideEffectsUnknown,
240        }
241    }
242}