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