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