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 count_budget_secs(&self) -> Option<Option<u64>> {
90        match self {
91            Self::CountEvents {
92                operator_read_budget_secs,
93                ..
94            }
95            | Self::CountEventsGrouped {
96                operator_read_budget_secs,
97                ..
98            } => Some(*operator_read_budget_secs),
99            _ => None,
100        }
101    }
102
103    pub(super) fn namespace(&self) -> &str {
104        match self {
105            Self::AppendEvents { namespace, .. }
106            | Self::AppendEventsIdempotent { namespace, .. }
107            | Self::GetEvent { namespace, .. }
108            | Self::QueryEvents { namespace, .. }
109            | Self::QueryEventPage { namespace, .. }
110            | Self::CountEvents { namespace, .. }
111            | Self::CountEventsGrouped { namespace, .. } => namespace,
112        }
113    }
114}
115
116/// Response frame from the events daemon.
117#[derive(Debug, Serialize, Deserialize)]
118#[serde(tag = "kind", rename_all = "snake_case")]
119pub enum EventsResponse {
120    Appended {
121        summary: BatchWriteSummary,
122    },
123    Idempotent {
124        result: IdempotentEventBatchResult,
125    },
126    Event {
127        event: Option<Event>,
128    },
129    Pageful {
130        page: Page<Event>,
131    },
132    EventPageWindow {
133        window: EventPageWindow,
134    },
135    Count {
136        count: u64,
137    },
138    GroupedCount {
139        counts: BTreeMap<String, u64>,
140    },
141    /// Typed refusal. `retryable` distinguishes transient daemon-side
142    /// conditions from contract errors (bad frame, version skew).
143    /// `writer_task_failure` carries both request finality and whether the
144    /// remote writer seam terminated. The retryable bit cannot express that
145    /// distinction: an ordinary operation or COMMIT error may be transient or
146    /// permanent while its transaction is independently proven rolled back.
147    /// `None` means the error is not from a writer request. Cross-version
148    /// frames never reach this mapping because `dispatch_events_request`
149    /// refuses a mismatched version before any write executes.
150    Error {
151        message: String,
152        retryable: bool,
153        #[serde(default)]
154        writer_task_failure: Option<WireWriterTaskFailure>,
155        /// Optional native write evidence; older frames retain their legacy mapping.
156        #[serde(default, skip_serializing_if = "Option::is_none")]
157        sqlite_write_failure: Option<khive_storage::error::SqliteWriteFailure>,
158        #[serde(default, skip_serializing_if = "Option::is_none")]
159        read_failure: Option<WireReadFailure>,
160    },
161}
162
163/// Whether a writer-state error belongs to one failed request on a still-live
164/// seam or to a permanently retired writer task.
165#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
166#[serde(tag = "kind", rename_all = "snake_case")]
167pub enum WireWriterTaskFailure {
168    RequestFailed {
169        request_state: WireWriterTaskState,
170    },
171    TaskTerminated {
172        request_state: WireWriterTaskState,
173        #[serde(default, skip_serializing_if = "Option::is_none")]
174        sqlite_full_codes: Option<(i32, i32)>,
175    },
176}
177
178/// Wire mirror of [`khive_storage::WriterTaskRequestState`]. A separate type
179/// because the storage enum is not serializable and the wire shape must stay
180/// under this module's protocol-version control, not the storage crate's.
181#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
182#[serde(rename_all = "snake_case")]
183pub enum WireWriterTaskState {
184    NotStarted,
185    TransactionRolledBack,
186    SideEffectsUnknown,
187}
188
189impl From<khive_storage::WriterTaskRequestState> for WireWriterTaskState {
190    fn from(state: khive_storage::WriterTaskRequestState) -> Self {
191        use khive_storage::WriterTaskRequestState as S;
192        match state {
193            S::NotStarted => Self::NotStarted,
194            S::TransactionRolledBack => Self::TransactionRolledBack,
195            S::SideEffectsUnknown => Self::SideEffectsUnknown,
196        }
197    }
198}
199
200impl From<WireWriterTaskState> for khive_storage::WriterTaskRequestState {
201    fn from(state: WireWriterTaskState) -> Self {
202        use khive_storage::WriterTaskRequestState as S;
203        match state {
204            WireWriterTaskState::NotStarted => S::NotStarted,
205            WireWriterTaskState::TransactionRolledBack => S::TransactionRolledBack,
206            WireWriterTaskState::SideEffectsUnknown => S::SideEffectsUnknown,
207        }
208    }
209}