Skip to main content

ic_db_cli/
lib.rs

1//! Transport types shared by the local DB console and its fixture canister.
2#![forbid(unsafe_code)]
3
4#[cfg(feature = "fixture-wire")]
5pub mod fixture_wire;
6
7#[cfg(feature = "host")]
8pub mod host;
9
10/// A local query result, in the fixture's positional Wire field order.
11#[derive(Debug, serde::Deserialize, serde::Serialize)]
12pub struct ConsolePage {
13    /// Displayed rows and their continuation.
14    pub page: DisplayPage,
15    /// Examined query candidates.
16    pub examined: u32,
17    /// Fetched source rows.
18    pub fetched: u32,
19    /// Encoded result bytes before transport framing.
20    pub output_bytes: u32,
21}
22
23/// Byte predicates on the fixture payload column.
24#[derive(Clone, Default, Debug, serde::Deserialize, serde::Serialize)]
25pub struct PayloadFilters {
26    /// Inclusive lower bound.
27    pub minimum: Option<Vec<u8>>,
28    /// Inclusive upper bound.
29    pub maximum: Option<Vec<u8>>,
30    /// Required prefix.
31    pub prefix: Option<Vec<u8>>,
32    /// Required suffix.
33    pub suffix: Option<Vec<u8>>,
34    /// Required contiguous bytes.
35    pub contains: Option<Vec<u8>>,
36}
37
38/// Entity restrictions shared by ordinary and retained fixture queries.
39#[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)]
40#[cfg_attr(feature = "console", derive(clap::Args))]
41pub struct EntityFilters {
42    /// Entry.amount >= VALUE.
43    #[cfg_attr(feature = "console", arg(long = "min"))]
44    pub minimum: Option<u64>,
45    /// Entry.category == VALUE.
46    #[cfg_attr(feature = "console", arg(long))]
47    pub category: Option<u64>,
48    /// Document.entry_id == VALUE.
49    #[cfg_attr(feature = "console", arg(long))]
50    pub entry_id: Option<u64>,
51}
52
53/// Local query command in fixture Wire field order.
54#[derive(Debug, serde::Deserialize, serde::Serialize)]
55pub struct QueryRequest {
56    /// Selected entity.
57    pub entity: String,
58    /// Encoded continuation.
59    pub cursor: Option<Vec<u8>>,
60    /// Maximum rows per page.
61    pub limit: u32,
62    /// Restrictions on fixture entity fields.
63    pub entity_filters: EntityFilters,
64    /// Ordered field specifications.
65    pub order: Vec<String>,
66    /// Reverse traversal.
67    pub descending: bool,
68    /// Candidate budget.
69    pub work: u32,
70    /// Output byte budget.
71    pub bytes: u32,
72    /// Selected output.
73    pub select: String,
74    /// Grouping and predicates.
75    pub options: QueryOptions,
76}
77
78/// Options carried together by the query endpoint.
79#[derive(Debug, serde::Deserialize, serde::Serialize)]
80pub struct QueryOptions {
81    /// Request distinct output.
82    pub distinct: bool,
83    /// Lower and upper group bounds.
84    pub group_bounds: (Option<String>, Option<String>),
85    /// Group ordering.
86    pub group_order: Option<String>,
87    /// Row predicates.
88    pub filters: RowFilters,
89}
90
91/// Local fixture status.
92#[derive(Debug, serde::Deserialize, serde::Serialize)]
93pub struct Status {
94    /// Schema fingerprint.
95    pub schema: [u8; 32],
96    /// Store incarnation.
97    pub incarnation: [u8; 16],
98    /// Entry revision.
99    pub revision: u64,
100    /// Wasm linear memory pages.
101    pub pages: u64,
102}
103
104/// Local schema inspection reply.
105#[derive(Debug, serde::Deserialize, serde::Serialize)]
106pub struct SchemaResponse {
107    /// Fixture status.
108    pub status: Status,
109    /// Matching entities.
110    pub entities: Vec<EntityView>,
111    /// Named value types.
112    pub types: Vec<TypeView>,
113}
114
115/// Inspected entity.
116#[derive(Debug, serde::Deserialize, serde::Serialize)]
117pub struct EntityView {
118    /// Entity name.
119    pub name: String,
120    /// Schema entity identifier.
121    pub id: u32,
122    /// Primary key field.
123    pub primary: String,
124    /// Stored fields.
125    pub fields: Vec<FieldView>,
126    /// Declared indexes.
127    pub indexes: Vec<IndexView>,
128}
129
130/// Inspected entity field.
131#[derive(Debug, serde::Deserialize, serde::Serialize)]
132pub struct FieldView {
133    /// Field name.
134    pub name: String,
135    /// Field type.
136    pub kind: String,
137    /// Optionality.
138    pub optional: bool,
139    /// Constraints and metadata.
140    pub info: String,
141    /// Reference target and index.
142    pub reference: Option<(String, String)>,
143}
144
145///
146/// IndexView
147/// An index in the inspected schema.
148///
149#[derive(Debug, serde::Deserialize, serde::Serialize)]
150pub struct IndexView {
151    /// Index name.
152    pub name: String,
153    /// Component fields in index order.
154    pub fields: Vec<String>,
155    /// Whether the key must be unique.
156    pub unique: bool,
157    /// Whether rows with absent components are excluded.
158    pub present_only: bool,
159}
160
161///
162/// TypeView
163/// A named type in the inspected schema.
164///
165#[derive(Debug, serde::Deserialize, serde::Serialize)]
166pub struct TypeView {
167    /// Schema name.
168    pub name: String,
169    /// Type category.
170    pub kind: String,
171    /// Declared fields, variants or collection roles.
172    pub members: Vec<TypeMemberView>,
173}
174
175///
176/// TypeMemberView
177/// One member of a named schema type.
178///
179#[derive(Debug, serde::Deserialize, serde::Serialize)]
180pub struct TypeMemberView {
181    /// Member name.
182    pub name: String,
183    /// Member type.
184    #[serde(rename = "type")]
185    pub kind: String,
186    /// Whether the member permits absence.
187    pub optional: bool,
188    /// Constraints and metadata.
189    pub info: String,
190}
191
192///
193/// FilterComparison
194/// Comparison carried by a fixture filter.
195///
196#[derive(Clone, Debug, serde::Deserialize, serde::Serialize, Copy)]
197#[cfg_attr(feature = "console", derive(clap::ValueEnum))]
198pub enum FilterComparison {
199    /// Equal.
200    Eq,
201    /// Unequal.
202    Ne,
203    /// Less than.
204    Lt,
205    /// At most.
206    Le,
207    /// Greater than.
208    Gt,
209    /// At least.
210    Ge,
211    /// Prefix match.
212    StartsWith,
213    /// Suffix match.
214    EndsWith,
215    /// Substring match.
216    Contains,
217}
218
219///
220/// ComparisonFilter
221/// A field compared with a typed right operand.
222///
223#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
224pub struct ComparisonFilter<T> {
225    /// Left field.
226    pub field: String,
227    /// Comparison to apply.
228    pub op: FilterComparison,
229    /// Right operand.
230    pub operand: T,
231}
232
233///
234/// FieldRange
235/// Three field names in a range predicate.
236///
237#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
238pub struct FieldRange {
239    /// Tested field.
240    pub field: String,
241    /// Lower end.
242    pub lower: String,
243    /// Upper end.
244    pub upper: String,
245}
246
247/// Row predicates carried by the local query and retained-aggregate commands.
248#[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)]
249pub struct RowFilters {
250    /// Lower bound, upper bound, prefix, suffix and substring on BinaryObject.payload.
251    pub payload: PayloadFilters,
252    /// Left field, comparison, right field.
253    pub compare: Option<ComparisonFilter<String>>,
254    /// Field, comparison and length threshold.
255    pub length: Option<ComparisonFilter<u32>>,
256    /// Require a value in this optional field.
257    pub present: Option<String>,
258    /// Require absence in this optional field.
259    pub absent: Option<String>,
260    /// Field, comparison and exact UTF-8 literal.
261    pub text: Option<ComparisonFilter<String>>,
262    /// Field and Boolean equality operand.
263    pub boolean: Option<(String, bool)>,
264    /// Field, inclusive lower field and inclusive upper field.
265    pub between_fields: Option<FieldRange>,
266    /// Field, lower field and upper field for the strict outside-range comparison.
267    pub not_between_fields: Option<FieldRange>,
268}
269
270/// Selection shared by the private retained fixture when starting and resuming a job.
271#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
272pub struct RetainedSelection {
273    /// Entity name.
274    pub entity: String,
275    /// Aggregate selection.
276    pub select: String,
277    /// Minimum, category and entry ID restrictions.
278    pub entity_filters: EntityFilters,
279    /// Maximum output groups.
280    pub limit: u32,
281    /// Inclusive lower and upper group bounds.
282    pub group_bounds: (Option<String>, Option<String>),
283    /// Completed-group order.
284    pub group_order: Option<String>,
285    /// Row predicates.
286    pub filters: RowFilters,
287    /// Input fields and overall descending flag.
288    pub order: (Vec<String>, bool),
289}
290
291/// One bounded step of a retained fixture query.
292#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
293pub struct RetainedResume {
294    /// Original query.
295    pub selection: RetainedSelection,
296    /// Retained job handle.
297    pub handle: Vec<u8>,
298    /// Last saved step.
299    pub sequence: u64,
300    /// Input work allowance.
301    pub work: u32,
302    /// Output byte allowance.
303    pub bytes: u32,
304    /// Maximum results per page.
305    pub page_size: u32,
306    /// Previous result cursor.
307    pub after: Option<Vec<u8>>,
308}
309
310/// Display columns, rows and continuation shared by ordinary and retained results.
311#[derive(Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
312pub struct DisplayPage {
313    /// Display column names.
314    pub columns: Vec<String>,
315    /// Display cells in column order.
316    pub rows: Vec<Vec<String>>,
317    /// Encoded continuation for a paged read.
318    pub next: Option<Vec<u8>>,
319}
320
321/// Progress reported by the local fixture after one retained query step.
322#[derive(Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
323pub struct RetainedProgress {
324    /// Last saved step.
325    pub sequence: u64,
326    /// Candidates examined so far.
327    pub examined: u64,
328    /// Input bytes examined so far.
329    pub input_bytes: u64,
330    /// Encoded result bytes in this step.
331    pub output_bytes: u64,
332    /// Current phase and any completed result.
333    pub phase: RetainedPhase,
334}
335
336/// Only a completed job has output.
337#[derive(Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
338pub enum RetainedPhase {
339    /// Additional input remains.
340    Running,
341    /// Completed rows and continuation.
342    Complete(DisplayPage),
343    /// Source rows changed.
344    Invalidated,
345    /// Job lifetime elapsed.
346    Expired,
347}
348
349impl RetainedPhase {
350    /// Name used by console progress messages.
351    #[must_use]
352    pub const fn label(&self) -> &'static str {
353        match self {
354            Self::Running => "Running",
355            Self::Complete(_) => "Complete",
356            Self::Invalidated => "Invalidated",
357            Self::Expired => "Expired",
358        }
359    }
360}
361
362/// Render bytes using two lowercase hexadecimal digits per byte and the supplied display prefix.
363#[must_use]
364pub fn lowercase_hex(bytes: &[u8], prefix: &str) -> String {
365    const DIGITS: &[u8; 16] = b"0123456789abcdef";
366    let mut output = String::with_capacity(prefix.len() + bytes.len() * 2);
367    output.push_str(prefix);
368    for &byte in bytes {
369        output.push(char::from(DIGITS[usize::from(byte >> 4)]));
370        output.push(char::from(DIGITS[usize::from(byte & 15)]));
371    }
372    output
373}