ic-db-cli 0.42.0

Local fixture console for IC DB
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
//! Transport types shared by the local DB console and its fixture canister.
#![forbid(unsafe_code)]

#[cfg(feature = "fixture-codec")]
pub mod fixture_codec;

#[cfg(feature = "host")]
pub mod host;

/// A local query result, in the fixture's positional field order.
#[derive(Debug, PartialEq, Eq, serde::Deserialize, serde::Serialize)]
pub struct ConsolePage {
    /// Displayed rows and their continuation.
    pub page: DisplayPage,
    /// Examined query candidates.
    pub examined: u32,
    /// Fetched source rows.
    pub fetched: u32,
    /// Encoded result bytes before transport framing.
    pub output_bytes: u32,
}

/// Byte predicates on the fixture payload column.
#[derive(Clone, Default, Debug, serde::Deserialize, serde::Serialize)]
pub struct PayloadFilters {
    /// Inclusive lower bound.
    pub minimum: Option<Vec<u8>>,
    /// Inclusive upper bound.
    pub maximum: Option<Vec<u8>>,
    /// Required prefix.
    pub prefix: Option<Vec<u8>>,
    /// Required suffix.
    pub suffix: Option<Vec<u8>>,
    /// Required contiguous bytes.
    pub contains: Option<Vec<u8>>,
}

/// Entity restrictions shared by ordinary and retained fixture queries.
#[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)]
#[cfg_attr(feature = "console", derive(clap::Args))]
pub struct EntityFilters {
    /// Entry.amount >= VALUE.
    #[cfg_attr(feature = "console", arg(long = "min"))]
    pub minimum: Option<u64>,
    /// Entry.category == VALUE.
    #[cfg_attr(feature = "console", arg(long))]
    pub category: Option<u64>,
    /// Document.entry_id == VALUE.
    #[cfg_attr(feature = "console", arg(long))]
    pub entry_id: Option<u64>,
}

/// Local query command in fixture fixture field order.
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct QueryRequest {
    /// Selected entity.
    pub entity: String,
    /// Encoded continuation.
    pub cursor: Option<Vec<u8>>,
    /// Maximum rows per page.
    pub limit: u32,
    /// Restrictions on fixture entity fields.
    pub entity_filters: EntityFilters,
    /// Ordered field specifications.
    pub order: Vec<String>,
    /// Reverse traversal.
    pub descending: bool,
    /// Candidate budget.
    pub work: u32,
    /// Output byte budget.
    pub bytes: u32,
    /// Selected output.
    pub select: String,
    /// Grouping and predicates.
    pub options: QueryOptions,
}

/// Inclusive group result bounds in positional fixture order.
#[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)]
#[cfg_attr(feature = "console", derive(clap::Args))]
pub struct GroupBounds {
    /// For grouped summaries, prefix each bound with count:, sum: or avg:.
    /// Keep completed aggregate values >= VALUE, parsed as the exact result type.
    /// Signed sums accept negatives; Decimal results accept fractions at their scale.
    /// Note min/max bounds are literal text in UTF-8 byte order, without normalization.
    /// Integer results reject fractions; threshold text is bounded to 64 bytes.
    #[cfg_attr(feature = "console", arg(long, allow_hyphen_values = true))]
    pub group_min: Option<String>,
    /// Keep completed aggregate values <= VALUE; same exact types as --group-min.
    /// Both bounds are inclusive and apply before ordering or output limits.
    #[cfg_attr(feature = "console", arg(long, allow_hyphen_values = true))]
    pub group_max: Option<String>,
}

/// Actions in the fixed local migration demonstration.
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(from = "u8")]
pub enum MigrationAction {
    /// Seed the source database.
    Seed,
    /// Freeze ordinary source access.
    Freeze,
    /// Copy a bounded batch.
    Copy,
    /// Validate the target.
    Validate,
    /// Publish the validated target.
    Publish,
    /// Clean up the retired source.
    Cleanup,
    /// Read the published target.
    ReadTarget,
    /// Read the source.
    ReadSource,
    /// Refuse an unknown fixture action without touching backing.
    Unknown,
}

// The fixture takes one raw byte, including invalid actions above the Postcard
// single-byte varint range. Preserve its ordinary error reply for those callers.
impl From<u8> for MigrationAction {
    fn from(value: u8) -> Self {
        [
            Self::Seed,
            Self::Freeze,
            Self::Copy,
            Self::Validate,
            Self::Publish,
            Self::Cleanup,
            Self::ReadTarget,
            Self::ReadSource,
        ]
        .get(usize::from(value))
        .copied()
        .unwrap_or(Self::Unknown)
    }
}

/// Ordering accepted by the local fixture for completed groups.
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[cfg_attr(feature = "console", derive(clap::ValueEnum))]
pub enum FixtureGroupOrder {
    /// The `key` ordering.
    Key,
    /// The `key-desc` ordering.
    KeyDesc,
    /// The `first` ordering.
    First,
    /// The `asc` ordering.
    Asc,
    /// The `desc` ordering.
    Desc,
    /// The `count:asc` ordering.
    #[cfg_attr(feature = "console", value(name = "count:asc"))]
    CountAsc,
    /// The `count:desc` ordering.
    #[cfg_attr(feature = "console", value(name = "count:desc"))]
    CountDesc,
    /// The `sum:asc` ordering.
    #[cfg_attr(feature = "console", value(name = "sum:asc"))]
    SumAsc,
    /// The `sum:desc` ordering.
    #[cfg_attr(feature = "console", value(name = "sum:desc"))]
    SumDesc,
    /// The `avg:asc` ordering.
    #[cfg_attr(feature = "console", value(name = "avg:asc"))]
    AvgAsc,
    /// The `avg:desc` ordering.
    #[cfg_attr(feature = "console", value(name = "avg:desc"))]
    AvgDesc,
}

/// Options carried together by the query endpoint.
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct QueryOptions {
    /// Request distinct output.
    pub distinct: bool,
    /// Lower and upper group bounds.
    pub group_bounds: GroupBounds,
    /// Group ordering.
    pub group_order: Option<FixtureGroupOrder>,
    /// Row predicates.
    pub filters: RowFilters,
}

/// Local fixture status.
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct Status {
    /// Schema fingerprint.
    pub schema: [u8; 32],
    /// Store incarnation.
    pub incarnation: [u8; 16],
    /// Entry revision.
    pub revision: u64,
    /// Wasm linear memory pages.
    pub pages: u64,
}

/// Local schema inspection reply.
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct SchemaResponse {
    /// Fixture status.
    pub status: Status,
    /// Matching entities.
    pub entities: Vec<EntityView>,
    /// Named value types.
    pub types: Vec<TypeView>,
}

/// Inspected entity.
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct EntityView {
    /// Entity name.
    pub name: String,
    /// Primary key field.
    #[serde(rename = "primary_key")]
    pub primary: String,
    /// Stored fields.
    pub fields: Vec<FieldView>,
    /// Declared indexes.
    pub indexes: Vec<IndexView>,
}

/// Inspected entity field.
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct FieldView {
    /// Field name.
    pub name: String,
    /// Field type.
    #[serde(rename = "type")]
    pub kind: String,
    /// Optionality.
    pub optional: bool,
    /// Constraints and metadata.
    pub info: String,
    /// Reference target and index.
    pub reference: Option<ReferenceView>,
}

/// Target and supporting index of an inspected reference.
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct ReferenceView {
    /// Qualified target field.
    pub target: String,
    /// Supporting index name.
    pub index: String,
}

///
/// IndexView
/// An index in the inspected schema.
///
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct IndexView {
    /// Index name.
    pub name: String,
    /// Component fields in index order.
    pub fields: Vec<String>,
    /// Whether the key must be unique.
    pub unique: bool,
    /// Whether rows with absent components are excluded.
    pub present_only: bool,
}

///
/// TypeView
/// A named type in the inspected schema.
///
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct TypeView {
    /// Schema name.
    pub name: String,
    /// Type category.
    pub kind: String,
    /// Declared fields, variants or collection roles.
    pub members: Vec<TypeMemberView>,
}

///
/// TypeMemberView
/// One member of a named schema type.
///
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct TypeMemberView {
    /// Member name.
    pub name: String,
    /// Member type.
    #[serde(rename = "type")]
    pub kind: String,
    /// Whether the member permits absence.
    pub optional: bool,
    /// Constraints and metadata.
    pub info: String,
}

///
/// FilterComparison
/// Comparison carried by a fixture filter.
///
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize, Copy)]
#[cfg_attr(feature = "console", derive(clap::ValueEnum))]
pub enum FilterComparison {
    /// Equal.
    Eq,
    /// Unequal.
    Ne,
    /// Less than.
    Lt,
    /// At most.
    Le,
    /// Greater than.
    Gt,
    /// At least.
    Ge,
    /// Prefix match.
    StartsWith,
    /// Suffix match.
    EndsWith,
    /// Substring match.
    Contains,
}

///
/// ComparisonFilter
/// A field compared with a typed right operand.
///
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct ComparisonFilter<T> {
    /// Left field.
    pub field: String,
    /// Comparison to apply.
    pub op: FilterComparison,
    /// Right operand.
    pub operand: T,
}

///
/// FieldRange
/// Three field names in a range predicate.
///
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct FieldRange {
    /// Tested field.
    pub field: String,
    /// Lower end.
    pub lower: String,
    /// Upper end.
    pub upper: String,
}

/// Row predicates carried by the local query and retained-aggregate commands.
#[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)]
pub struct RowFilters {
    /// Lower bound, upper bound, prefix, suffix and substring on BinaryObject.payload.
    pub payload: PayloadFilters,
    /// Left field, comparison, right field.
    pub compare: Option<ComparisonFilter<String>>,
    /// Field, comparison and length threshold.
    pub length: Option<ComparisonFilter<u32>>,
    /// Require a value in this optional field.
    pub present: Option<String>,
    /// Require absence in this optional field.
    pub absent: Option<String>,
    /// Field, comparison and exact UTF-8 literal.
    pub text: Option<ComparisonFilter<String>>,
    /// Field and Boolean equality operand.
    pub boolean: Option<(String, bool)>,
    /// Field, inclusive lower field and inclusive upper field.
    pub between_fields: Option<FieldRange>,
    /// Field, lower field and upper field for the strict outside-range comparison.
    pub not_between_fields: Option<FieldRange>,
}

/// Selection shared by the private retained fixture when starting and resuming a job.
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct RetainedSelection {
    /// Entity name.
    pub entity: String,
    /// Aggregate selection.
    pub select: String,
    /// Minimum, category and entry ID restrictions.
    pub entity_filters: EntityFilters,
    /// Maximum output groups.
    pub limit: u32,
    /// Inclusive lower and upper group bounds.
    pub group_bounds: GroupBounds,
    /// Completed-group order.
    pub group_order: Option<FixtureGroupOrder>,
    /// Row predicates.
    pub filters: RowFilters,
    /// Input fields and overall descending flag.
    pub order: (Vec<String>, bool),
}

/// One bounded step of a retained fixture query.
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct RetainedResume {
    /// Original query.
    pub selection: RetainedSelection,
    /// Retained job handle.
    pub handle: Vec<u8>,
    /// Last saved step.
    pub sequence: u64,
    /// Input work allowance.
    pub work: u32,
    /// Output byte allowance.
    pub bytes: u32,
    /// Maximum results per page.
    pub page_size: u32,
    /// Previous result cursor.
    pub after: Option<Vec<u8>>,
}

/// Display columns, rows and continuation shared by ordinary and retained results.
#[derive(Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct DisplayPage {
    /// Display column names.
    pub columns: Vec<String>,
    /// Display cells in column order.
    pub rows: Vec<Vec<String>>,
    /// Encoded continuation for a paged read.
    pub next: Option<Vec<u8>>,
}

/// Progress reported by the local fixture after one retained query step.
#[derive(Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct RetainedProgress {
    /// Last saved step.
    pub sequence: u64,
    /// Candidates examined so far.
    pub examined: u64,
    /// Input bytes examined so far.
    pub input_bytes: u64,
    /// Encoded result bytes in this step.
    pub output_bytes: u64,
    /// Current phase and any completed result.
    pub phase: RetainedPhase,
}

/// Only a completed job has output.
#[derive(Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum RetainedPhase {
    /// Additional input remains.
    Running,
    /// Completed rows and continuation.
    Complete(DisplayPage),
    /// Source rows changed.
    Invalidated,
    /// Job lifetime elapsed.
    Expired,
}

impl RetainedPhase {
    /// Name used by console progress messages.
    #[must_use]
    pub const fn label(&self) -> &'static str {
        match self {
            Self::Running => "Running",
            Self::Complete(_) => "Complete",
            Self::Invalidated => "Invalidated",
            Self::Expired => "Expired",
        }
    }
}

/// Render bytes using two lowercase hexadecimal digits per byte and the supplied display prefix.
#[must_use]
pub fn lowercase_hex(bytes: &[u8], prefix: &str) -> String {
    const DIGITS: &[u8; 16] = b"0123456789abcdef";
    let mut output = String::with_capacity(prefix.len() + bytes.len() * 2);
    output.push_str(prefix);
    for &byte in bytes {
        output.push(char::from(DIGITS[usize::from(byte >> 4)]));
        output.push(char::from(DIGITS[usize::from(byte & 15)]));
    }
    output
}