hawdb_search/
projection_consumer.rs1use crate::{SearchIndex, SearchProjectionCatchUpReport};
16use hawdb_core::{HawDBError, Result};
17use hawdb_storage::projection::{
18 SearchProjectionChangefeedReadiness, SearchProjectionChangefeedStatus,
19};
20use std::fmt;
21use std::num::NonZeroU64;
22
23#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
24pub struct SearchProjectionConsumerId(String);
25
26impl SearchProjectionConsumerId {
27 pub fn new(value: impl Into<String>) -> Result<Self> {
28 let value = value.into();
29 if value.is_empty()
30 || value.len() > 128
31 || !value
32 .bytes()
33 .all(|byte| byte.is_ascii_alphanumeric() || b"._-".contains(&byte))
34 {
35 return Err(HawDBError::Semantic(
36 "consumer ID must contain 1-128 ASCII letters, digits, '.', '_' or '-'".into(),
37 ));
38 }
39 Ok(Self(value))
40 }
41
42 pub fn as_str(&self) -> &str {
43 &self.0
44 }
45}
46
47#[derive(Debug, Clone, Copy, PartialEq, Eq)]
48pub struct SearchProjectionConsumerOptions {
49 max_idle_commits: NonZeroU64,
50}
51
52impl SearchProjectionConsumerOptions {
53 pub fn new(max_idle_commits: NonZeroU64) -> Self {
54 Self { max_idle_commits }
55 }
56 pub fn max_idle_commits(&self) -> NonZeroU64 {
57 self.max_idle_commits
58 }
59}
60
61#[derive(Debug)]
64pub struct SearchProjectionConsumer {
65 id: SearchProjectionConsumerId,
66 projection: crate::consumer::ConsumerProjection,
67}
68
69impl SearchProjectionConsumer {
70 #[doc(hidden)]
71 pub fn from_projection(
72 id: SearchProjectionConsumerId,
73 projection: crate::consumer::ConsumerProjection,
74 ) -> Self {
75 Self { id, projection }
76 }
77
78 pub fn id(&self) -> &SearchProjectionConsumerId {
79 &self.id
80 }
81
82 #[doc(hidden)]
83 pub fn projection(&self) -> &crate::consumer::ConsumerProjection {
84 &self.projection
85 }
86
87 #[doc(hidden)]
88 pub fn projection_mut(&mut self) -> &mut crate::consumer::ConsumerProjection {
89 &mut self.projection
90 }
91
92 pub fn search_index(&self) -> Result<&SearchIndex> {
93 self.projection.require_completed_view()?;
94 self.projection.index()
95 }
96
97 pub fn vector_index_descriptor(&self) -> Result<Option<&hawdb_core::VectorIndexDescriptor>> {
98 self.projection.vector_index_descriptor()
99 }
100
101 #[doc(hidden)]
102 pub fn canonical_vector_source_epoch(&self) -> Result<Option<u64>> {
103 self.projection.canonical_vector_source_epoch()
104 }
105
106 pub fn document_count(&self) -> Result<usize> {
107 self.projection.document_count()
108 }
109
110 pub fn projection_freshness(&self) -> Result<crate::SearchProjectionFreshness> {
111 self.projection.projection_freshness()
112 }
113
114 pub fn pin(
116 &self,
117 permit: &hawdb_qos::RuntimePermit,
118 ) -> Result<crate::consumer::ConsumerReadPin> {
119 self.projection.pin(permit)
120 }
121}
122
123#[derive(Debug, Clone, PartialEq, Eq)]
124pub enum SearchProjectionConsumerState {
125 Unverified,
126 Active,
127 RebuildRequired(SearchProjectionConsumerRebuildReason),
128}
129
130#[derive(Debug, Clone, PartialEq, Eq)]
131pub enum SearchProjectionConsumerRebuildReason {
132 DatabaseIdentityMismatch,
133 ProjectionIdentityMismatch,
134 CheckpointMismatch,
135 SourceRewound,
136 RetentionLimitExceeded { resume_floor_commit_epoch: u64 },
137 Expired { expires_at_commit_epoch: u64 },
138 UntrackedProjectionMutation,
139 RegistryUnavailable,
140}
141
142#[derive(Debug, Clone, PartialEq, Eq)]
143pub struct SearchProjectionConsumerStatus {
144 pub consumer_id: SearchProjectionConsumerId,
145 pub state: SearchProjectionConsumerState,
146 pub durable_complete_through_commit_epoch: Option<u64>,
147 pub expires_at_commit_epoch: u64,
148 pub minimum_valid_consumer_commit_epoch: Option<u64>,
149 pub changefeed: SearchProjectionChangefeedStatus,
150}
151
152#[derive(Debug, Clone, PartialEq, Eq)]
153pub struct SearchProjectionConsumerReadiness {
154 pub consumer: SearchProjectionConsumerStatus,
155 pub changefeed: SearchProjectionChangefeedReadiness,
156}
157
158impl SearchProjectionConsumerReadiness {
159 pub fn is_ready(&self) -> bool {
160 self.consumer.state == SearchProjectionConsumerState::Active && self.changefeed.ready
161 }
162}
163
164#[derive(Debug, Clone, PartialEq, Eq)]
165pub struct SearchProjectionConsumerCatchUpReport {
166 pub catch_up: SearchProjectionCatchUpReport,
167 pub consumer: SearchProjectionConsumerStatus,
168}
169
170#[derive(Debug)]
171pub enum SearchProjectionConsumerError {
172 Database(HawDBError),
173 InvalidHandle,
174 AlreadyRegistered,
175 RegistryFull,
176 SourceNotDurable,
177 RebuildRequired(SearchProjectionConsumerRebuildReason),
178}
179
180impl fmt::Display for SearchProjectionConsumerError {
181 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
182 match self {
183 Self::Database(error) => error.fmt(formatter),
184 Self::InvalidHandle => formatter.write_str("invalid search projection consumer handle"),
185 Self::AlreadyRegistered => {
186 formatter.write_str("search projection consumer is already registered")
187 }
188 Self::RegistryFull => {
189 formatter.write_str("search projection consumer registry is full")
190 }
191 Self::SourceNotDurable => formatter.write_str(
192 "search projection consumer requires a durable source outside a WAL sync group",
193 ),
194 Self::RebuildRequired(reason) => write!(
195 formatter,
196 "search projection consumer requires rebuild: {reason:?}"
197 ),
198 }
199 }
200}
201
202impl std::error::Error for SearchProjectionConsumerError {
203 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
204 match self {
205 Self::Database(error) => Some(error),
206 _ => None,
207 }
208 }
209}
210
211impl From<HawDBError> for SearchProjectionConsumerError {
212 fn from(error: HawDBError) -> Self {
213 Self::Database(error)
214 }
215}
216
217pub type SearchProjectionConsumerResult<T> = std::result::Result<T, SearchProjectionConsumerError>;
218
219mod registry;
220
221#[doc(hidden)]
222pub use registry::{ConsumerRegistry, Record, MAX_CONSUMERS};
223
224#[cfg(test)]
225mod tests {
226 use super::{SearchProjectionConsumerId, SearchProjectionConsumerOptions};
227 use std::num::NonZeroU64;
228
229 #[test]
230 fn consumer_contract_keeps_identifier_and_lease_bounds() {
231 assert!(SearchProjectionConsumerId::new("consumer_A-1.v2").is_ok());
232 assert!(SearchProjectionConsumerId::new("bad/id").is_err());
233 assert!(SearchProjectionConsumerId::new("a".repeat(128)).is_ok());
234 assert!(SearchProjectionConsumerId::new("a".repeat(129)).is_err());
235
236 let options = SearchProjectionConsumerOptions::new(NonZeroU64::new(7).unwrap());
237 assert_eq!(options.max_idle_commits().get(), 7);
238 }
239}