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