Skip to main content

laser_wire/
browse.rs

1use crate::control::{
2    GapAcceptance, OversizePolicy, Projection, ProjectionBinding, ProjectionHistory,
3    ProjectionKind, SchemaDef, SchemaSource, SourceSelector,
4};
5use crate::query::QueryError;
6use serde::{Deserialize, Serialize};
7
8/// A registered projection plus the bindings that route topics into it. The full
9/// picture of one materialized view: its extraction schema, expected content
10/// type, indexed fields, and where it applies.
11#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
12#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
13pub struct ProjectionInfo {
14    pub projection: Projection,
15    #[serde(default, skip_serializing_if = "Vec::is_empty")]
16    pub bindings: Vec<ProjectionBinding>,
17    /// How far each binding has materialized on the answering node, present
18    /// only when the request asked for it.
19    #[serde(default, skip_serializing_if = "Vec::is_empty")]
20    pub status: Vec<BindingStatus>,
21}
22
23/// One binding's materialization as the answering node sees it.
24#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
25#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
26pub struct BindingStatus {
27    #[serde(default, skip_serializing_if = "ProjectionHistory::is_append")]
28    pub history: ProjectionHistory,
29    pub source: SourceSelector,
30    pub index: String,
31    pub realization: RealizationState,
32    #[serde(default, skip_serializing_if = "Option::is_none")]
33    pub realization_reason: Option<String>,
34    /// The class of the last failed attempt to create the destination table,
35    /// present while realization is pending after a failure.
36    #[serde(default, skip_serializing_if = "Option::is_none")]
37    pub failure: Option<FailureClass>,
38    /// Why the binding makes no visible progress although no record holds it.
39    #[serde(default, skip_serializing_if = "Option::is_none")]
40    pub stall: Option<StallReason>,
41    /// Creation time of the source topic incarnation being materialized.
42    #[serde(default, skip_serializing_if = "Option::is_none")]
43    pub source_incarnation: Option<u64>,
44    #[serde(default, skip_serializing_if = "Vec::is_empty")]
45    pub partitions: Vec<PartitionProgress>,
46    /// Records or history gaps that stop a partition from advancing.
47    #[serde(default, skip_serializing_if = "Vec::is_empty")]
48    pub holds: Vec<Hold>,
49    /// Missing history an operator accepted for this source.
50    #[serde(default, skip_serializing_if = "Vec::is_empty")]
51    pub accepted_gaps: Vec<GapAcceptance>,
52    /// Records skipped from this binding's target and dead-lettered.
53    #[serde(default)]
54    pub skipped_records: u64,
55}
56
57/// Whether a binding's destination table exists.
58#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
59#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
60#[serde(rename_all = "snake_case")]
61#[non_exhaustive]
62pub enum RealizationState {
63    Pending,
64    /// Another node owns the shared destination and creates the table.
65    AwaitingOwner,
66    Realized,
67    #[serde(other)]
68    Unknown,
69}
70
71/// Why the destination table could not be created.
72#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
73#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
74#[serde(rename_all = "snake_case")]
75#[non_exhaustive]
76pub enum FailureClass {
77    /// The binding names a backend the server cannot resolve.
78    Configuration,
79    /// The destination refused the table definition.
80    Schema,
81    /// The destination refused the statement itself.
82    Poison,
83    /// The destination failed in a way no retry recovers.
84    Fatal,
85    /// The destination was briefly out of reach.
86    Transient,
87    /// The destination ran out of capacity.
88    Capacity,
89    /// The destination accepts no writes for now.
90    ReadOnly,
91    #[serde(other)]
92    Unknown,
93}
94
95/// What keeps a binding from visible progress when no record holds it.
96#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
97#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
98#[serde(rename_all = "snake_case")]
99#[non_exhaustive]
100pub enum StallReason {
101    /// The source topic does not exist.
102    SourceMissing,
103    /// The source partition heads could not be read.
104    SourceUnreadable,
105    /// The destination's progress could not be read.
106    DestinationUnreadable,
107    /// The destination refuses writes for now, so the projector waits.
108    Backpressure,
109    #[serde(other)]
110    Unknown,
111}
112
113/// One source partition's progress into a binding's destination.
114#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
115#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
116pub struct PartitionProgress {
117    pub partition_id: u32,
118    /// The last offset the source partition holds.
119    #[serde(default, skip_serializing_if = "Option::is_none")]
120    pub head_offset: Option<u64>,
121    /// The last offset the destination committed.
122    #[serde(default, skip_serializing_if = "Option::is_none")]
123    pub applied_offset: Option<u64>,
124    /// The first offset the binding materialized for this incarnation, when
125    /// the answering node observed it. Above zero, the history started late.
126    /// `None` means unknown, never complete.
127    #[serde(default, skip_serializing_if = "Option::is_none")]
128    pub first_offset: Option<u64>,
129}
130
131/// Why a partition does not advance.
132#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
133#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
134pub struct Hold {
135    pub partition_id: u32,
136    pub offset: u64,
137    pub cause: HoldCause,
138    pub reason: String,
139}
140
141/// What holds a partition.
142#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
143#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
144#[serde(rename_all = "snake_case")]
145#[non_exhaustive]
146pub enum HoldCause {
147    Extraction,
148    Schema,
149    Destination,
150    Oversize,
151    MissingHistory,
152    /// The binding was applied for an earlier incarnation of its source
153    /// stream. Apply it again to materialize the live one.
154    RetiredIncarnation,
155    #[serde(other)]
156    Unknown,
157}
158
159/// How far a materialization setup has come, weakest first.
160#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
161#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
162#[serde(rename_all = "snake_case")]
163#[non_exhaustive]
164pub enum MaterializationReadiness {
165    /// The definitions are durably appended.
166    Accepted,
167    /// The answering node applied the definitions.
168    Applied,
169    /// The destination table exists.
170    Realized,
171    /// The destination reached the source heads captured after apply.
172    CaughtUp,
173}
174
175impl BindingStatus {
176    /// The level this status proves on its own: `Realized` once the table
177    /// exists, else `Applied`. Catch-up needs a captured target, see
178    /// [`caught_up_to`](Self::caught_up_to).
179    pub fn readiness(&self) -> MaterializationReadiness {
180        if self.realization == RealizationState::Realized {
181            MaterializationReadiness::Realized
182        } else {
183            MaterializationReadiness::Applied
184        }
185    }
186
187    /// Whether this status reached every head `target` captured, on the same
188    /// source incarnation. A partition the target saw empty needs nothing.
189    pub fn caught_up_to(&self, target: &BindingStatus) -> bool {
190        self.realization == RealizationState::Realized
191            && !self.is_blocked()
192            && self.source_incarnation.is_some()
193            && self.source_incarnation == target.source_incarnation
194            && self.source == target.source
195            && self.index == target.index
196            && self.history == target.history
197            && target.partitions.iter().all(|wanted| {
198                wanted.head_offset.is_none_or(|head| {
199                    self.partitions.iter().any(|seen| {
200                        seen.partition_id == wanted.partition_id
201                            && seen.applied_offset.is_some_and(|applied| applied >= head)
202                    })
203                })
204            })
205    }
206
207    /// Whether a record or a history gap stops a partition.
208    pub fn is_blocked(&self) -> bool {
209        !self.holds.is_empty()
210    }
211
212    /// Whether the destination table failed in a way no retry recovers, so
213    /// the binding or its backend must change.
214    pub fn is_failed(&self) -> bool {
215        self.failure.is_some_and(FailureClass::is_permanent)
216    }
217
218    /// Whether the destination provably holds every record of the source
219    /// incarnation it has passed: every partition with progress started at
220    /// offset zero, no gap was accepted, no record was skipped and, under
221    /// `oversize`, no body is kept only by reference. An unknown first offset
222    /// is never complete, and a partition the binding never read is complete
223    /// only while no first offset above zero says its history expired unread.
224    pub fn history_complete(&self, oversize: OversizePolicy) -> bool {
225        self.history.is_append()
226            && self.realization == RealizationState::Realized
227            && self.source_incarnation.is_some()
228            && !self.is_blocked()
229            && oversize != OversizePolicy::Reference
230            && self.accepted_gaps.is_empty()
231            && self.skipped_records == 0
232            && self.partitions.iter().all(|partition| {
233                partition.first_offset == Some(0)
234                    || (partition.applied_offset.is_none() && partition.first_offset.is_none())
235            })
236    }
237}
238
239impl FailureClass {
240    /// Whether the failure lasts until the binding or its backend changes.
241    pub fn is_permanent(self) -> bool {
242        matches!(
243            self,
244            Self::Configuration | Self::Schema | Self::Poison | Self::Fatal
245        )
246    }
247}
248
249/// A writer schema plus its lifecycle state. A `dropped` schema is hidden
250/// from the active set and its id rejects re-registration with a different
251/// definition, but records stamped with the id keep decoding (ids are
252/// permanent). Wire mirrors stay constructible (wire-stability-bound, not
253/// API-stability-bound).
254#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
255#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
256pub struct SchemaInfo {
257    pub schema: SchemaDef,
258    #[serde(default)]
259    pub dropped: bool,
260}
261
262/// Request to read one projection's details by id.
263#[derive(Clone, Debug, Serialize, Deserialize)]
264#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
265pub struct GetProjection {
266    pub v: u32,
267    pub id: String,
268    /// Also report each binding's materialization status.
269    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
270    pub status: bool,
271}
272
273/// Request to list registered projections, optionally filtered. Empty filters
274/// list every projection. `topics` keeps projections bound to any of the named
275/// source topics. `name_contains` keeps those whose name contains the substring.
276/// `id_prefix` keeps those whose id starts with it. `search` is the single-box
277/// convenience that matches the substring against the name OR the id. `kinds`
278/// keeps projections of the named kinds. The filters compose (AND). The reply is one
279/// page of the matches in id order.
280#[derive(Clone, Debug, Default, Serialize, Deserialize)]
281#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
282pub struct ListProjections {
283    pub v: u32,
284    #[serde(default, skip_serializing_if = "Vec::is_empty")]
285    pub topics: Vec<String>,
286    #[serde(default, skip_serializing_if = "Option::is_none")]
287    pub name_contains: Option<String>,
288    #[serde(default, skip_serializing_if = "Option::is_none")]
289    pub id_prefix: Option<String>,
290    #[serde(default, skip_serializing_if = "Option::is_none")]
291    pub search: Option<String>,
292    #[serde(default, skip_serializing_if = "Vec::is_empty")]
293    pub kinds: Vec<ProjectionKind>,
294    /// The stream whose resources the listing covers. Required in stream
295    /// tenancy, where the server authorizes the stream and lists only its
296    /// resources.
297    #[serde(default, skip_serializing_if = "Option::is_none")]
298    pub stream: Option<String>,
299    /// The 1-based page. Zero reads the first page.
300    #[serde(default, skip_serializing_if = "is_zero")]
301    pub page: u32,
302    /// The projections per page. Zero leaves it to the server.
303    #[serde(default, skip_serializing_if = "is_zero")]
304    pub results: u32,
305}
306
307/// One page of a projection listing. `page` counts from 1.
308#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
309#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
310pub struct ProjectionPage {
311    pub items: Vec<ProjectionInfo>,
312    pub page: u32,
313    pub total_pages: u32,
314    pub total_results: u32,
315}
316
317/// Request to read one registered writer schema by id.
318#[derive(Clone, Debug, Serialize, Deserialize)]
319#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
320pub struct GetSchema {
321    pub v: u32,
322    pub id: u32,
323    /// The stream whose registry holds `id`. Absent for the deployment-wide
324    /// registry.
325    #[serde(default, skip_serializing_if = "Option::is_none")]
326    pub stream: Option<String>,
327}
328
329/// Request to list registered writer schemas, optionally filtered.
330/// `name_contains` keeps those whose optional name contains the substring, and
331/// an absent filter lists every schema. The filter lives here, not only on the
332/// HTTP query, so the server pushes it down rather than the client paging the
333/// whole set.
334#[derive(Clone, Debug, Serialize, Deserialize)]
335#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
336pub struct ListSchemas {
337    pub v: u32,
338    #[serde(default, skip_serializing_if = "Option::is_none")]
339    pub name_contains: Option<String>,
340    /// The stream whose registry is listed. Absent for the deployment-wide
341    /// registry.
342    #[serde(default, skip_serializing_if = "Option::is_none")]
343    pub stream: Option<String>,
344    /// The 1-based page. Zero reads the first page.
345    #[serde(default, skip_serializing_if = "is_zero")]
346    pub page: u32,
347    /// The schemas per page. Zero leaves it to the server.
348    #[serde(default, skip_serializing_if = "is_zero")]
349    pub results: u32,
350}
351
352/// One page of a writer-schema listing, ordered by id. `page` counts from 1.
353#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
354#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
355pub struct SchemaPage {
356    pub items: Vec<SchemaInfo>,
357    pub page: u32,
358    pub total_pages: u32,
359    pub total_results: u32,
360}
361
362/// The synchronous register request: no id, LaserData Cloud validates the
363/// definition, allocates the next free id, durably appends the control
364/// event, and replies `SchemaRegistered(id)`. Distinct from
365/// `ControlCommand::RegisterSchema`, the durable log form that carries the
366/// allocated id.
367#[derive(Clone, Debug, Serialize, Deserialize)]
368#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
369pub struct RegisterSchema {
370    pub v: u32,
371    pub source: SchemaSource,
372    #[serde(default, skip_serializing_if = "Option::is_none")]
373    pub name: Option<String>,
374    #[serde(default, skip_serializing_if = "Option::is_none")]
375    pub version: Option<u32>,
376    /// The stream whose registry allocates the id. Absent for the
377    /// deployment-wide registry.
378    #[serde(default, skip_serializing_if = "Option::is_none")]
379    pub stream: Option<String>,
380}
381
382/// Request to decode one record body under the schema registered for `id`,
383/// the same decode the projector runs on `agdx.sid`-stamped records. Read-only
384/// convenience for consoles and tools that hold a schema-first (Avro/Protobuf)
385/// payload and want its JSON form without re-implementing the codecs.
386#[derive(Clone, Debug, Serialize, Deserialize)]
387#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
388pub struct DecodeRecord {
389    pub v: u32,
390    pub id: u32,
391    #[cfg_attr(
392        feature = "schemars",
393        schemars(schema_with = "crate::encoding::bytes_schema")
394    )]
395    #[serde(with = "crate::encoding::bin_bytes")]
396    pub payload: Vec<u8>,
397    /// The stream the record was read from: `id` resolves in its registry,
398    /// then in the deployment-wide one. Absent for the deployment-wide
399    /// registry alone.
400    #[serde(default, skip_serializing_if = "Option::is_none")]
401    pub stream: Option<String>,
402}
403
404/// Reply to a registry browse: `Ok` with the result, or `Err`.
405#[derive(Clone, Debug, Serialize, Deserialize)]
406#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
407#[non_exhaustive]
408pub enum BrowseReply {
409    Ok(BrowseOutcome),
410    Err(QueryError),
411}
412
413/// The result of a registry browse, shaped per request.
414#[derive(Clone, Debug, Serialize, Deserialize)]
415#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
416#[non_exhaustive]
417pub enum BrowseOutcome {
418    /// `list_projections`: one page of the matching projections.
419    Projections(ProjectionPage),
420    /// `get projection`: the projection with the requested id, or `None`.
421    Projection(Option<Box<ProjectionInfo>>),
422    /// `list schemas`: one page of writer schemas, active and tombstoned.
423    Schemas(SchemaPage),
424    /// `get schema`: the schema occupying the requested id, or `None`.
425    Schema(Option<SchemaInfo>),
426    /// `register schema`: the LaserData-Cloud-allocated id, already durably appended
427    /// to the control topic (visibility follows within the apply latency).
428    SchemaRegistered(u32),
429    /// `decode record`: the payload's JSON form under the requested schema,
430    /// or `None` when the body does not decode under it. A `serde_json::Value`
431    /// because the decoded shape is arbitrary (object, array, scalar) and the
432    /// LaserData Cloud encodes exactly that value into the reply.
433    Decoded(Option<serde_json::Value>),
434}
435
436fn is_zero(value: &u32) -> bool {
437    *value == 0
438}
439
440#[cfg(all(test, feature = "cbor"))]
441mod tests {
442    use super::*;
443    use crate::codes::QUERY_OP_VERSION;
444    use crate::content::ContentType;
445    use crate::control::ProjectionBinding;
446    use crate::framing::{decode_named, encode_named};
447
448    fn status(
449        realization: RealizationState,
450        partitions: &[(u32, Option<u64>, Option<u64>)],
451    ) -> BindingStatus {
452        BindingStatus {
453            history: ProjectionHistory::Append,
454            source: SourceSelector::new("fleet", "readings"),
455            index: "readings_rows".to_owned(),
456            realization,
457            realization_reason: None,
458            failure: None,
459            stall: None,
460            source_incarnation: Some(7),
461            partitions: partitions
462                .iter()
463                .map(
464                    |(partition_id, head_offset, applied_offset)| PartitionProgress {
465                        partition_id: *partition_id,
466                        head_offset: *head_offset,
467                        applied_offset: *applied_offset,
468                        first_offset: applied_offset.map(|_| 0),
469                    },
470                )
471                .collect(),
472            holds: Vec::new(),
473            accepted_gaps: Vec::new(),
474            skipped_records: 0,
475        }
476    }
477
478    #[test]
479    fn given_a_missing_incarnation_or_a_hold_when_checking_catch_up_then_should_refuse() {
480        let target = status(RealizationState::Realized, &[(0, Some(10), Some(10))]);
481        let mut unknown = target.clone();
482        unknown.source_incarnation = None;
483        assert!(!unknown.caught_up_to(&unknown));
484        let mut blocked = target.clone();
485        blocked.holds.push(Hold {
486            partition_id: 0,
487            offset: 11,
488            cause: HoldCause::Schema,
489            reason: "invalid".to_owned(),
490        });
491        assert!(!blocked.caught_up_to(&target));
492    }
493
494    #[test]
495    fn given_a_captured_target_when_the_destination_reaches_it_then_should_be_caught_up() {
496        let target = status(
497            RealizationState::Realized,
498            &[(0, Some(10), Some(4)), (1, None, None)],
499        );
500        let behind = status(RealizationState::Realized, &[(0, Some(12), Some(9))]);
501        assert!(!behind.caught_up_to(&target));
502        let reached = status(RealizationState::Realized, &[(0, Some(15), Some(10))]);
503        assert!(
504            reached.caught_up_to(&target),
505            "a newer head does not move the target"
506        );
507        let unrealized = status(RealizationState::AwaitingOwner, &[(0, Some(15), Some(10))]);
508        assert!(!unrealized.caught_up_to(&target));
509        let mut recreated = reached.clone();
510        recreated.source_incarnation = Some(8);
511        assert!(
512            !recreated.caught_up_to(&target),
513            "offsets of another incarnation never compare"
514        );
515        assert_eq!(reached.readiness(), MaterializationReadiness::Realized);
516        assert_eq!(unrealized.readiness(), MaterializationReadiness::Applied);
517    }
518
519    #[test]
520    fn given_a_late_start_a_gap_a_skip_or_references_when_checked_then_should_not_claim_complete_history()
521     {
522        let complete = status(RealizationState::Realized, &[(0, Some(3), Some(3))]);
523        assert!(complete.history_complete(OversizePolicy::Block));
524        assert!(!complete.history_complete(OversizePolicy::Reference));
525        let mut late = complete.clone();
526        late.partitions[0].first_offset = Some(5);
527        assert!(!late.history_complete(OversizePolicy::Block));
528        let mut unknown = complete.clone();
529        unknown.partitions[0].first_offset = None;
530        assert!(
531            !unknown.history_complete(OversizePolicy::Block),
532            "unknown is never complete"
533        );
534        let mut skipped = complete.clone();
535        skipped.skipped_records = 1;
536        assert!(!skipped.history_complete(OversizePolicy::Block));
537        let mut held = complete.clone();
538        held.holds.push(Hold {
539            partition_id: 0,
540            offset: 4,
541            cause: HoldCause::Oversize,
542            reason: "too large".to_owned(),
543        });
544        assert!(held.is_blocked());
545    }
546
547    #[test]
548    fn given_a_partition_whose_records_expired_unread_when_checked_then_should_not_claim_complete_history()
549     {
550        let mut expired = status(RealizationState::Realized, &[(0, Some(3), Some(3))]);
551        expired.partitions.push(PartitionProgress {
552            partition_id: 1,
553            head_offset: None,
554            applied_offset: None,
555            first_offset: Some(5),
556        });
557        assert!(
558            !expired.history_complete(OversizePolicy::Block),
559            "records 0 to 4 of partition 1 expired before the binding read them"
560        );
561        let mut never_written = status(RealizationState::Realized, &[(0, Some(3), Some(3))]);
562        never_written.partitions.push(PartitionProgress {
563            partition_id: 1,
564            head_offset: None,
565            applied_offset: None,
566            first_offset: None,
567        });
568        assert!(never_written.history_complete(OversizePolicy::Block));
569    }
570
571    #[test]
572    fn given_realization_failures_when_checked_then_should_fail_only_on_a_permanent_class() {
573        let mut failed = status(RealizationState::Pending, &[]);
574        assert!(!failed.is_failed());
575        for (class, permanent) in [
576            (FailureClass::Configuration, true),
577            (FailureClass::Schema, true),
578            (FailureClass::Poison, true),
579            (FailureClass::Fatal, true),
580            (FailureClass::Transient, false),
581            (FailureClass::Capacity, false),
582            (FailureClass::ReadOnly, false),
583            (FailureClass::Unknown, false),
584        ] {
585            failed.failure = Some(class);
586            assert_eq!(failed.is_failed(), permanent, "{class:?}");
587        }
588    }
589
590    #[test]
591    fn given_a_failure_a_stall_and_a_retired_hold_when_round_tripped_then_should_preserve_them() {
592        let mut stalled = status(RealizationState::Pending, &[(0, Some(3), None)]);
593        stalled.failure = Some(FailureClass::ReadOnly);
594        stalled.stall = Some(StallReason::Backpressure);
595        stalled.holds.push(Hold {
596            partition_id: 0,
597            offset: 0,
598            cause: HoldCause::RetiredIncarnation,
599            reason: "applied for an earlier stream".to_owned(),
600        });
601        let back: BindingStatus =
602            decode_named(&encode_named(&stalled).expect("serializes")).expect("deserializes");
603        assert_eq!(back, stalled);
604        let json = serde_json::to_value(&stalled).expect("serializes");
605        assert_eq!(
606            (&json["failure"], &json["stall"], &json["holds"][0]["cause"]),
607            (
608                &serde_json::json!("read_only"),
609                &serde_json::json!("backpressure"),
610                &serde_json::json!("retired_incarnation")
611            )
612        );
613        let newer: BindingStatus = serde_json::from_value(serde_json::json!({
614            "source": {"stream": "fleet", "topic": "readings"},
615            "index": "readings_rows",
616            "realization": "pending",
617            "failure": "quota",
618            "stall": "paused",
619        }))
620        .expect("a newer class decodes");
621        assert_eq!(
622            (newer.failure, newer.stall),
623            (Some(FailureClass::Unknown), Some(StallReason::Unknown))
624        );
625        let quiet =
626            serde_json::to_value(status(RealizationState::Realized, &[])).expect("serializes");
627        assert!(
628            quiet.get("failure").is_none() && quiet.get("stall").is_none(),
629            "absent fields are omitted: {quiet}"
630        );
631    }
632
633    #[test]
634    fn given_a_projection_listing_when_encoded_then_should_send_its_page_only_when_set() {
635        let first = ListProjections {
636            v: QUERY_OP_VERSION,
637            ..ListProjections::default()
638        };
639        let json = serde_json::to_value(&first).expect("serializes");
640        assert!(
641            json.get("page").is_none()
642                && json.get("results").is_none()
643                && json.get("kinds").is_none(),
644            "{json}"
645        );
646        let third = ListProjections {
647            v: QUERY_OP_VERSION,
648            kinds: vec![ProjectionKind::Row, ProjectionKind::Record],
649            page: 3,
650            results: 20,
651            ..ListProjections::default()
652        };
653        let back: ListProjections =
654            decode_named(&encode_named(&third).expect("serializes")).expect("deserializes");
655        assert_eq!(
656            (back.kinds, back.page, back.results),
657            (vec![ProjectionKind::Row, ProjectionKind::Record], 3, 20)
658        );
659    }
660
661    #[test]
662    fn given_a_browse_reply_when_round_tripped_then_should_preserve_projection_details() {
663        let info = ProjectionInfo {
664            projection: Projection::builder("reading.v1")
665                .name("reading")
666                .version(1)
667                .content_type(ContentType::Json)
668                .fields(["reading_id", "cpu"])
669                .build(),
670            bindings: vec![
671                ProjectionBinding::builder()
672                    .source("fleet", "readings")
673                    .allow("reading.v1")
674                    .default_projection("reading.v1")
675                    .index("readings_rows")
676                    .build(),
677            ],
678            status: Vec::new(),
679        };
680        let reply = BrowseReply::Ok(BrowseOutcome::Projections(ProjectionPage {
681            items: vec![info],
682            page: 1,
683            total_pages: 1,
684            total_results: 1,
685        }));
686        let bytes = encode_named(&reply).expect("the reply serializes");
687        let back: BrowseReply = decode_named(&bytes).expect("the reply deserializes");
688        let BrowseReply::Ok(BrowseOutcome::Projections(page)) = back else {
689            panic!("expected an Ok(Projections) browse reply");
690        };
691        assert_eq!((page.page, page.total_pages, page.total_results), (1, 1, 1));
692        let list = page.items;
693        assert_eq!(list.len(), 1);
694        assert_eq!(list[0].projection.id.as_str(), "reading.v1");
695        assert_eq!(list[0].projection.extraction.fields.len(), 2);
696        assert_eq!(list[0].bindings[0].index, "readings_rows");
697    }
698
699    #[test]
700    fn given_a_decode_record_when_round_tripped_then_should_preserve_payload_bytes() {
701        let request = DecodeRecord {
702            v: QUERY_OP_VERSION,
703            id: 7,
704            payload: vec![0xff, 0x00, 0x10],
705            stream: None,
706        };
707        let bytes = encode_named(&request).expect("serializes");
708        let back: DecodeRecord = decode_named(&bytes).expect("deserializes");
709        assert_eq!(back.id, 7);
710        assert_eq!(back.payload, vec![0xff, 0x00, 0x10]);
711        assert_eq!(back.stream, None);
712    }
713
714    #[test]
715    fn given_schema_requests_with_a_stream_when_round_tripped_then_should_preserve_it() {
716        let get = GetSchema {
717            v: QUERY_OP_VERSION,
718            id: 7,
719            stream: Some("acme".to_owned()),
720        };
721        let back: GetSchema =
722            decode_named(&encode_named(&get).expect("serializes")).expect("deserializes");
723        assert_eq!((back.id, back.stream.as_deref()), (7, Some("acme")));
724        let list = ListSchemas {
725            v: QUERY_OP_VERSION,
726            name_contains: None,
727            stream: Some("acme".to_owned()),
728            page: 0,
729            results: 0,
730        };
731        let back: ListSchemas =
732            decode_named(&encode_named(&list).expect("serializes")).expect("deserializes");
733        assert_eq!(back.stream.as_deref(), Some("acme"));
734        let register = RegisterSchema {
735            v: QUERY_OP_VERSION,
736            source: SchemaSource::JsonSchema {
737                schema: "{}".to_owned(),
738            },
739            name: None,
740            version: None,
741            stream: Some("acme".to_owned()),
742        };
743        let back: RegisterSchema =
744            decode_named(&encode_named(&register).expect("serializes")).expect("deserializes");
745        assert_eq!(back.stream.as_deref(), Some("acme"));
746        let decode = DecodeRecord {
747            v: QUERY_OP_VERSION,
748            id: 7,
749            payload: vec![1],
750            stream: Some("acme".to_owned()),
751        };
752        let back: DecodeRecord =
753            decode_named(&encode_named(&decode).expect("serializes")).expect("deserializes");
754        assert_eq!(back.stream.as_deref(), Some("acme"));
755    }
756
757    #[test]
758    fn given_schema_requests_without_a_stream_when_encoded_then_should_omit_it() {
759        let get = GetSchema {
760            v: QUERY_OP_VERSION,
761            id: 7,
762            stream: None,
763        };
764        let list = ListSchemas {
765            v: QUERY_OP_VERSION,
766            name_contains: None,
767            stream: None,
768            page: 0,
769            results: 0,
770        };
771        for json in [
772            serde_json::to_string(&get).expect("serializes"),
773            serde_json::to_string(&list).expect("serializes"),
774        ] {
775            assert!(
776                !json.contains("stream"),
777                "an unset stream is omitted: {json}"
778            );
779        }
780    }
781}