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-codec")]
5pub mod fixture_codec;
6
7#[cfg(feature = "host")]
8pub mod host;
9
10/// A local query result, in the fixture's positional field order.
11#[derive(Debug, PartialEq, Eq, 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 fixture 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/// Inclusive group result bounds in positional fixture order.
79#[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)]
80#[cfg_attr(feature = "console", derive(clap::Args))]
81pub struct GroupBounds {
82    /// For grouped summaries, prefix each bound with count:, sum: or avg:.
83    /// Keep completed aggregate values >= VALUE, parsed as the exact result type.
84    /// Signed sums accept negatives; Decimal results accept fractions at their scale.
85    /// Note min/max bounds are literal text in UTF-8 byte order, without normalization.
86    /// Integer results reject fractions; threshold text is bounded to 64 bytes.
87    #[cfg_attr(feature = "console", arg(long, allow_hyphen_values = true))]
88    pub group_min: Option<String>,
89    /// Keep completed aggregate values <= VALUE; same exact types as --group-min.
90    /// Both bounds are inclusive and apply before ordering or output limits.
91    #[cfg_attr(feature = "console", arg(long, allow_hyphen_values = true))]
92    pub group_max: Option<String>,
93}
94
95/// Actions in the fixed local migration demonstration.
96#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
97#[serde(from = "u8")]
98pub enum MigrationAction {
99    /// Seed the source database.
100    Seed,
101    /// Freeze ordinary source access.
102    Freeze,
103    /// Copy a bounded batch.
104    Copy,
105    /// Validate the target.
106    Validate,
107    /// Publish the validated target.
108    Publish,
109    /// Clean up the retired source.
110    Cleanup,
111    /// Read the published target.
112    ReadTarget,
113    /// Read the source.
114    ReadSource,
115    /// Refuse an unknown fixture action without touching backing.
116    Unknown,
117}
118
119// The fixture takes one raw byte, including invalid actions above the Postcard
120// single-byte varint range. Preserve its ordinary error reply for those callers.
121impl From<u8> for MigrationAction {
122    fn from(value: u8) -> Self {
123        [
124            Self::Seed,
125            Self::Freeze,
126            Self::Copy,
127            Self::Validate,
128            Self::Publish,
129            Self::Cleanup,
130            Self::ReadTarget,
131            Self::ReadSource,
132        ]
133        .get(usize::from(value))
134        .copied()
135        .unwrap_or(Self::Unknown)
136    }
137}
138
139/// Ordering accepted by the local fixture for completed groups.
140#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
141#[cfg_attr(feature = "console", derive(clap::ValueEnum))]
142pub enum FixtureGroupOrder {
143    /// The `key` ordering.
144    Key,
145    /// The `key-desc` ordering.
146    KeyDesc,
147    /// The `first` ordering.
148    First,
149    /// The `asc` ordering.
150    Asc,
151    /// The `desc` ordering.
152    Desc,
153    /// The `count:asc` ordering.
154    #[cfg_attr(feature = "console", value(name = "count:asc"))]
155    CountAsc,
156    /// The `count:desc` ordering.
157    #[cfg_attr(feature = "console", value(name = "count:desc"))]
158    CountDesc,
159    /// The `sum:asc` ordering.
160    #[cfg_attr(feature = "console", value(name = "sum:asc"))]
161    SumAsc,
162    /// The `sum:desc` ordering.
163    #[cfg_attr(feature = "console", value(name = "sum:desc"))]
164    SumDesc,
165    /// The `avg:asc` ordering.
166    #[cfg_attr(feature = "console", value(name = "avg:asc"))]
167    AvgAsc,
168    /// The `avg:desc` ordering.
169    #[cfg_attr(feature = "console", value(name = "avg:desc"))]
170    AvgDesc,
171}
172
173/// Options carried together by the query endpoint.
174#[derive(Debug, serde::Deserialize, serde::Serialize)]
175pub struct QueryOptions {
176    /// Request distinct output.
177    pub distinct: bool,
178    /// Lower and upper group bounds.
179    pub group_bounds: GroupBounds,
180    /// Group ordering.
181    pub group_order: Option<FixtureGroupOrder>,
182    /// Row predicates.
183    pub filters: RowFilters,
184}
185
186/// Local fixture status.
187#[derive(Debug, serde::Deserialize, serde::Serialize)]
188pub struct Status {
189    /// Schema fingerprint.
190    pub schema: [u8; 32],
191    /// Store incarnation.
192    pub incarnation: [u8; 16],
193    /// Entry revision.
194    pub revision: u64,
195    /// Wasm linear memory pages.
196    pub pages: u64,
197}
198
199/// Local schema inspection reply.
200#[derive(Debug, serde::Deserialize, serde::Serialize)]
201pub struct SchemaResponse {
202    /// Fixture status.
203    pub status: Status,
204    /// Matching entities.
205    pub entities: Vec<EntityView>,
206    /// Named value types.
207    pub types: Vec<TypeView>,
208}
209
210/// Inspected entity.
211#[derive(Debug, serde::Deserialize, serde::Serialize)]
212pub struct EntityView {
213    /// Entity name.
214    pub name: String,
215    /// Primary key field.
216    #[serde(rename = "primary_key")]
217    pub primary: String,
218    /// Stored fields.
219    pub fields: Vec<FieldView>,
220    /// Declared indexes.
221    pub indexes: Vec<IndexView>,
222}
223
224/// Inspected entity field.
225#[derive(Debug, serde::Deserialize, serde::Serialize)]
226pub struct FieldView {
227    /// Field name.
228    pub name: String,
229    /// Field type.
230    #[serde(rename = "type")]
231    pub kind: String,
232    /// Optionality.
233    pub optional: bool,
234    /// Constraints and metadata.
235    pub info: String,
236    /// Reference target and index.
237    pub reference: Option<ReferenceView>,
238}
239
240/// Target and supporting index of an inspected reference.
241#[derive(Debug, serde::Deserialize, serde::Serialize)]
242pub struct ReferenceView {
243    /// Qualified target field.
244    pub target: String,
245    /// Supporting index name.
246    pub index: String,
247}
248
249///
250/// IndexView
251/// An index in the inspected schema.
252///
253#[derive(Debug, serde::Deserialize, serde::Serialize)]
254pub struct IndexView {
255    /// Index name.
256    pub name: String,
257    /// Component fields in index order.
258    pub fields: Vec<String>,
259    /// Whether the key must be unique.
260    pub unique: bool,
261    /// Whether rows with absent components are excluded.
262    pub present_only: bool,
263}
264
265///
266/// TypeView
267/// A named type in the inspected schema.
268///
269#[derive(Debug, serde::Deserialize, serde::Serialize)]
270pub struct TypeView {
271    /// Schema name.
272    pub name: String,
273    /// Type category.
274    pub kind: String,
275    /// Declared fields, variants or collection roles.
276    pub members: Vec<TypeMemberView>,
277}
278
279///
280/// TypeMemberView
281/// One member of a named schema type.
282///
283#[derive(Debug, serde::Deserialize, serde::Serialize)]
284pub struct TypeMemberView {
285    /// Member name.
286    pub name: String,
287    /// Member type.
288    #[serde(rename = "type")]
289    pub kind: String,
290    /// Whether the member permits absence.
291    pub optional: bool,
292    /// Constraints and metadata.
293    pub info: String,
294}
295
296///
297/// FilterComparison
298/// Comparison carried by a fixture filter.
299///
300#[derive(Clone, Debug, serde::Deserialize, serde::Serialize, Copy)]
301#[cfg_attr(feature = "console", derive(clap::ValueEnum))]
302pub enum FilterComparison {
303    /// Equal.
304    Eq,
305    /// Unequal.
306    Ne,
307    /// Less than.
308    Lt,
309    /// At most.
310    Le,
311    /// Greater than.
312    Gt,
313    /// At least.
314    Ge,
315    /// Prefix match.
316    StartsWith,
317    /// Suffix match.
318    EndsWith,
319    /// Substring match.
320    Contains,
321}
322
323///
324/// ComparisonFilter
325/// A field compared with a typed right operand.
326///
327#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
328pub struct ComparisonFilter<T> {
329    /// Left field.
330    pub field: String,
331    /// Comparison to apply.
332    pub op: FilterComparison,
333    /// Right operand.
334    pub operand: T,
335}
336
337///
338/// FieldRange
339/// Three field names in a range predicate.
340///
341#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
342pub struct FieldRange {
343    /// Tested field.
344    pub field: String,
345    /// Lower end.
346    pub lower: String,
347    /// Upper end.
348    pub upper: String,
349}
350
351/// Row predicates carried by the local query and retained-aggregate commands.
352#[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)]
353pub struct RowFilters {
354    /// Lower bound, upper bound, prefix, suffix and substring on BinaryObject.payload.
355    pub payload: PayloadFilters,
356    /// Left field, comparison, right field.
357    pub compare: Option<ComparisonFilter<String>>,
358    /// Field, comparison and length threshold.
359    pub length: Option<ComparisonFilter<u32>>,
360    /// Require a value in this optional field.
361    pub present: Option<String>,
362    /// Require absence in this optional field.
363    pub absent: Option<String>,
364    /// Field, comparison and exact UTF-8 literal.
365    pub text: Option<ComparisonFilter<String>>,
366    /// Field and Boolean equality operand.
367    pub boolean: Option<(String, bool)>,
368    /// Field, inclusive lower field and inclusive upper field.
369    pub between_fields: Option<FieldRange>,
370    /// Field, lower field and upper field for the strict outside-range comparison.
371    pub not_between_fields: Option<FieldRange>,
372}
373
374/// Selection shared by the private retained fixture when starting and resuming a job.
375#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
376pub struct RetainedSelection {
377    /// Entity name.
378    pub entity: String,
379    /// Aggregate selection.
380    pub select: String,
381    /// Minimum, category and entry ID restrictions.
382    pub entity_filters: EntityFilters,
383    /// Maximum output groups.
384    pub limit: u32,
385    /// Inclusive lower and upper group bounds.
386    pub group_bounds: GroupBounds,
387    /// Completed-group order.
388    pub group_order: Option<FixtureGroupOrder>,
389    /// Row predicates.
390    pub filters: RowFilters,
391    /// Input fields and overall descending flag.
392    pub order: (Vec<String>, bool),
393}
394
395/// One bounded step of a retained fixture query.
396#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
397pub struct RetainedResume {
398    /// Original query.
399    pub selection: RetainedSelection,
400    /// Retained job handle.
401    pub handle: Vec<u8>,
402    /// Last saved step.
403    pub sequence: u64,
404    /// Input work allowance.
405    pub work: u32,
406    /// Output byte allowance.
407    pub bytes: u32,
408    /// Maximum results per page.
409    pub page_size: u32,
410    /// Previous result cursor.
411    pub after: Option<Vec<u8>>,
412}
413
414/// Display columns, rows and continuation shared by ordinary and retained results.
415#[derive(Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
416pub struct DisplayPage {
417    /// Display column names.
418    pub columns: Vec<String>,
419    /// Display cells in column order.
420    pub rows: Vec<Vec<String>>,
421    /// Encoded continuation for a paged read.
422    pub next: Option<Vec<u8>>,
423}
424
425/// Progress reported by the local fixture after one retained query step.
426#[derive(Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
427pub struct RetainedProgress {
428    /// Last saved step.
429    pub sequence: u64,
430    /// Candidates examined so far.
431    pub examined: u64,
432    /// Input bytes examined so far.
433    pub input_bytes: u64,
434    /// Encoded result bytes in this step.
435    pub output_bytes: u64,
436    /// Current phase and any completed result.
437    pub phase: RetainedPhase,
438}
439
440/// Only a completed job has output.
441#[derive(Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
442pub enum RetainedPhase {
443    /// Additional input remains.
444    Running,
445    /// Completed rows and continuation.
446    Complete(DisplayPage),
447    /// Source rows changed.
448    Invalidated,
449    /// Job lifetime elapsed.
450    Expired,
451}
452
453impl RetainedPhase {
454    /// Name used by console progress messages.
455    #[must_use]
456    pub const fn label(&self) -> &'static str {
457        match self {
458            Self::Running => "Running",
459            Self::Complete(_) => "Complete",
460            Self::Invalidated => "Invalidated",
461            Self::Expired => "Expired",
462        }
463    }
464}
465
466/// Render bytes using two lowercase hexadecimal digits per byte and the supplied display prefix.
467#[must_use]
468pub fn lowercase_hex(bytes: &[u8], prefix: &str) -> String {
469    const DIGITS: &[u8; 16] = b"0123456789abcdef";
470    let mut output = String::with_capacity(prefix.len() + bytes.len() * 2);
471    output.push_str(prefix);
472    for &byte in bytes {
473        output.push(char::from(DIGITS[usize::from(byte >> 4)]));
474        output.push(char::from(DIGITS[usize::from(byte & 15)]));
475    }
476    output
477}