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: Vec<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    /// Store-local name of the referenced entity.
244    pub target_entity: String,
245    /// Scalar primary-key field on that entity.
246    pub target_field: String,
247    /// Reverse lookup used by strong references.
248    pub index: Option<String>,
249    /// Stable target store key for a weak reference within this canister.
250    pub weak_store: Option<String>,
251    /// Referencing scalar member for a directly embedded record.
252    pub member: Option<String>,
253}
254
255///
256/// IndexView
257/// An index in the inspected schema.
258///
259#[derive(Debug, serde::Deserialize, serde::Serialize)]
260pub struct IndexView {
261    /// Target of a strong reference over all index components.
262    pub reference: Option<String>,
263    /// Index name.
264    pub name: String,
265    /// Component fields in index order.
266    pub fields: Vec<String>,
267    /// Whether the key must be unique.
268    pub unique: bool,
269    /// Whether rows with absent components are excluded.
270    pub present_only: bool,
271    /// Required Boolean membership condition, when declared.
272    pub filter: Option<(String, bool)>,
273}
274
275///
276/// TypeView
277/// A named type in the inspected schema.
278///
279#[derive(Debug, serde::Deserialize, serde::Serialize)]
280pub struct TypeView {
281    /// Schema name.
282    pub name: String,
283    /// Type category.
284    pub kind: String,
285    /// Declared fields, variants or collection roles.
286    pub members: Vec<TypeMemberView>,
287}
288
289///
290/// TypeMemberView
291/// One member of a named schema type.
292///
293#[derive(Debug, serde::Deserialize, serde::Serialize)]
294pub struct TypeMemberView {
295    /// Member name.
296    pub name: String,
297    /// Member type.
298    #[serde(rename = "type")]
299    pub kind: String,
300    /// Whether the member permits absence.
301    pub optional: bool,
302    /// Constraints and metadata.
303    pub info: String,
304}
305
306///
307/// FilterComparison
308/// Comparison carried by a fixture filter.
309///
310#[derive(Clone, Debug, serde::Deserialize, serde::Serialize, Copy)]
311#[cfg_attr(feature = "console", derive(clap::ValueEnum))]
312pub enum FilterComparison {
313    /// Equal.
314    Eq,
315    /// Unequal.
316    Ne,
317    /// Less than.
318    Lt,
319    /// At most.
320    Le,
321    /// Greater than.
322    Gt,
323    /// At least.
324    Ge,
325    /// Prefix match.
326    StartsWith,
327    /// Suffix match.
328    EndsWith,
329    /// Substring match.
330    Contains,
331}
332
333///
334/// ComparisonFilter
335/// A field compared with a typed right operand.
336///
337#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
338pub struct ComparisonFilter<T> {
339    /// Left field.
340    pub field: String,
341    /// Comparison to apply.
342    pub op: FilterComparison,
343    /// Right operand.
344    pub operand: T,
345}
346
347///
348/// FieldRange
349/// Three field names in a range predicate.
350///
351#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
352pub struct FieldRange {
353    /// Tested field.
354    pub field: String,
355    /// Lower end.
356    pub lower: String,
357    /// Upper end.
358    pub upper: String,
359}
360
361/// Row predicates carried by the local query and retained-aggregate commands.
362#[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)]
363pub struct RowFilters {
364    /// Lower bound, upper bound, prefix, suffix and substring on BinaryObject.payload.
365    pub payload: PayloadFilters,
366    /// Left field, comparison, right field.
367    pub compare: Option<ComparisonFilter<String>>,
368    /// Field, comparison and length threshold.
369    pub length: Option<ComparisonFilter<u32>>,
370    /// Require a value in this optional field.
371    pub present: Option<String>,
372    /// Require absence in this optional field.
373    pub absent: Option<String>,
374    /// Field, comparison and exact UTF-8 literal.
375    pub text: Option<ComparisonFilter<String>>,
376    /// Field and Boolean equality operand.
377    pub boolean: Option<(String, bool)>,
378    /// Field, inclusive lower field and inclusive upper field.
379    pub between_fields: Option<FieldRange>,
380    /// Field, lower field and upper field for the strict outside-range comparison.
381    pub not_between_fields: Option<FieldRange>,
382}
383
384/// Selection shared by the private retained fixture when starting and resuming a job.
385#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
386pub struct RetainedSelection {
387    /// Entity name.
388    pub entity: String,
389    /// Aggregate selection.
390    pub select: String,
391    /// Minimum, category and entry ID restrictions.
392    pub entity_filters: EntityFilters,
393    /// Maximum output groups.
394    pub limit: u32,
395    /// Inclusive lower and upper group bounds.
396    pub group_bounds: GroupBounds,
397    /// Completed-group order.
398    pub group_order: Option<FixtureGroupOrder>,
399    /// Row predicates.
400    pub filters: RowFilters,
401    /// Input fields and overall descending flag.
402    pub order: (Vec<String>, bool),
403}
404
405/// One bounded step of a retained fixture query.
406#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
407pub struct RetainedResume {
408    /// Original query.
409    pub selection: RetainedSelection,
410    /// Retained job handle.
411    pub handle: Vec<u8>,
412    /// Last saved step.
413    pub sequence: u64,
414    /// Input work allowance.
415    pub work: u32,
416    /// Output byte allowance.
417    pub bytes: u32,
418    /// Maximum results per page.
419    pub page_size: u32,
420    /// Previous result cursor.
421    pub after: Option<Vec<u8>>,
422}
423
424/// Display columns, rows and continuation shared by ordinary and retained results.
425#[derive(Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
426pub struct DisplayPage {
427    /// Display column names.
428    pub columns: Vec<String>,
429    /// Display cells in column order.
430    pub rows: Vec<Vec<String>>,
431    /// Encoded continuation for a paged read.
432    pub next: Option<Vec<u8>>,
433}
434
435/// Progress reported by the local fixture after one retained query step.
436#[derive(Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
437pub struct RetainedProgress {
438    /// Last saved step.
439    pub sequence: u64,
440    /// Candidates examined so far.
441    pub examined: u64,
442    /// Input bytes examined so far.
443    pub input_bytes: u64,
444    /// Encoded result bytes in this step.
445    pub output_bytes: u64,
446    /// Current phase and any completed result.
447    pub phase: RetainedPhase,
448}
449
450/// Only a completed job has output.
451#[derive(Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
452pub enum RetainedPhase {
453    /// Additional input remains.
454    Running,
455    /// Completed rows and continuation.
456    Complete(DisplayPage),
457    /// Source rows changed.
458    Invalidated,
459    /// Job lifetime elapsed.
460    Expired,
461}
462
463impl RetainedPhase {
464    /// Name used by console progress messages.
465    #[must_use]
466    pub const fn label(&self) -> &'static str {
467        match self {
468            Self::Running => "Running",
469            Self::Complete(_) => "Complete",
470            Self::Invalidated => "Invalidated",
471            Self::Expired => "Expired",
472        }
473    }
474}
475
476/// Render bytes using two lowercase hexadecimal digits per byte and the supplied display prefix.
477#[must_use]
478pub fn lowercase_hex(bytes: &[u8], prefix: &str) -> String {
479    const DIGITS: &[u8; 16] = b"0123456789abcdef";
480    let mut output = String::with_capacity(prefix.len() + bytes.len() * 2);
481    output.push_str(prefix);
482    for &byte in bytes {
483        output.push(char::from(DIGITS[usize::from(byte >> 4)]));
484        output.push(char::from(DIGITS[usize::from(byte & 15)]));
485    }
486    output
487}