Skip to main content

zero_client/protocol/
inspect.rs

1//! The `inspect` messages (`inspect-up.ts`, `inspect-down.ts`, and
2//! `analyze-query-result.ts`), kept as JSON, checked and stripped as valita
3//! does: the client has no inspector yet.
4
5use super::valita::{Field, Schema as S};
6use super::*;
7use crate::ast::{Ast, Condition, strict};
8use std::sync::LazyLock;
9
10/// An `inspect` request from the client (`inspectUpBodySchema`).
11#[derive(Clone, Debug, PartialEq)]
12pub struct InspectUpBody(pub Value);
13
14/// An `inspect` response from zero-cache (`inspectDownBodySchema`).
15#[derive(Clone, Debug, PartialEq)]
16pub struct InspectDownBody(pub Value);
17
18impl JsonCodable for InspectUpBody {
19    fn from_json(v: &Value) -> Result<Self> {
20        UP.parse(v).map(InspectUpBody)
21    }
22
23    fn to_json(&self) -> Value {
24        self.0.clone()
25    }
26}
27
28impl JsonCodable for InspectDownBody {
29    fn from_json(v: &Value) -> Result<Self> {
30        DOWN.parse(v).map(InspectDownBody)
31    }
32
33    fn to_json(&self) -> Value {
34        self.0.clone()
35    }
36}
37
38fn b(s: S) -> Box<S> {
39    Box::new(s)
40}
41
42fn req(key: &'static str, s: S) -> (&'static str, Field) {
43    (key, Field::Required(s))
44}
45
46fn opt(key: &'static str, s: S) -> (&'static str, Field) {
47    (key, Field::Optional(s))
48}
49
50fn op(name: &'static str, mut fields: Vec<(&'static str, Field)>) -> S {
51    fields.push(req("id", S::String));
52    fields.push(req("op", S::Literal(name)));
53    S::Object(fields)
54}
55
56fn event(ty: &'static str, mut fields: Vec<(&'static str, Field)>) -> S {
57    fields.push(req("type", S::Literal(ty)));
58    S::Object(fields)
59}
60
61fn ast(v: &Value) -> Result<Value> {
62    Ast::from_json(v).map(|a| a.to_json())
63}
64
65fn strict_ast(v: &Value) -> Result<Value> {
66    strict::decode(v).map(|a| a.to_json())
67}
68
69fn condition(v: &Value) -> Result<Value> {
70    Condition::from_json(v).map(|c| c.to_json())
71}
72
73static UP: LazyLock<S> = LazyLock::new(|| {
74    S::Union(vec![
75        op("queries", vec![opt("clientID", S::String)]),
76        op("metrics", vec![]),
77        op("version", vec![]),
78        op("authenticate", vec![req("value", S::String)]),
79        op(
80            "analyze-query",
81            vec![
82                opt("value", S::Custom(strict_ast)),
83                opt(
84                    "options",
85                    S::Object(vec![
86                        opt("vendedRows", S::Boolean),
87                        opt("syncedRows", S::Boolean),
88                        opt("joinPlans", S::Boolean),
89                    ]),
90                ),
91                opt("ast", S::Custom(strict_ast)),
92                opt("name", S::String),
93                opt("args", S::Array(b(S::Any))),
94            ],
95        ),
96    ])
97});
98
99static DOWN: LazyLock<S> = LazyLock::new(|| {
100    // `tdigestSchema` (`packages/shared/src/tdigest-schema.ts`).
101    let tdigest = S::NonEmptyArray(b(S::Number));
102    let row = S::Record(b(S::Any));
103    let ordering = S::Array(b(S::Tuple(vec![
104        S::String,
105        S::Union(vec![S::Literal("asc"), S::Literal("desc")]),
106    ])));
107    let query_server_metrics = S::Object(vec![
108        opt("query-hydration-server-ms", S::Number),
109        req("query-update-server", tdigest.clone()),
110    ]);
111    let inspect_query_row = S::Object(vec![
112        req("clientID", S::String),
113        req("queryID", S::String),
114        req("ast", S::Nullable(b(S::Custom(ast)))),
115        req("name", S::Nullable(b(S::String))),
116        req("args", S::Nullable(b(S::Array(b(S::Any))))),
117        req("got", S::Boolean),
118        req("deleted", S::Boolean),
119        req("ttl", S::Number),
120        req("inactivatedAt", S::Nullable(b(S::Number))),
121        req("rowCount", S::Number),
122        opt("metrics", S::Nullable(b(query_server_metrics))),
123    ]);
124    let server_metrics = S::Object(vec![
125        req("query-materialization-server", tdigest.clone()),
126        req("query-update-server", tdigest),
127    ]);
128    let row_counts_by_source = S::Record(b(S::Record(b(S::Number))));
129    let rows_by_source = S::Record(b(S::Record(b(S::Array(b(row.clone()))))));
130    let cost_estimate = S::Object(vec![
131        req("startupCost", S::Number),
132        req("scanEst", S::Number),
133        req("cost", S::Number),
134        req("returnedRows", S::Number),
135        req("selectivity", S::Number),
136        opt("limit", S::Number),
137    ]);
138    // `plannerConstraintSchema`, a record of `v.union(v.unknown(), v.null())`.
139    let planner_constraint = S::Record(b(S::Any));
140    let constraints = S::Record(b(S::Nullable(b(planner_constraint.clone()))));
141    let join_states = S::Array(b(S::Object(vec![
142        req("join", S::String),
143        req("type", S::String),
144    ])));
145    let plan_debug_event = S::Union(vec![
146        event(
147            "attempt-start",
148            vec![
149                req("attemptNumber", S::Number),
150                req("totalAttempts", S::Number),
151            ],
152        ),
153        event(
154            "connection-costs",
155            vec![
156                req("attemptNumber", S::Number),
157                req(
158                    "costs",
159                    S::Array(b(S::Object(vec![
160                        req("connection", S::String),
161                        req("cost", S::Number),
162                        req("costEstimate", cost_estimate.clone()),
163                        req("pinned", S::Boolean),
164                        req("constraints", constraints.clone()),
165                        req("constraintCosts", S::Record(b(cost_estimate.clone()))),
166                    ]))),
167                ),
168            ],
169        ),
170        event(
171            "connection-selected",
172            vec![
173                req("attemptNumber", S::Number),
174                req("connection", S::String),
175                req("cost", S::Number),
176                req("isRoot", S::Boolean),
177            ],
178        ),
179        event(
180            "constraints-propagated",
181            vec![
182                req("attemptNumber", S::Number),
183                req(
184                    "connectionConstraints",
185                    S::Array(b(S::Object(vec![
186                        req("connection", S::String),
187                        req("constraints", constraints),
188                        req("constraintCosts", S::Record(b(cost_estimate.clone()))),
189                    ]))),
190                ),
191            ],
192        ),
193        event(
194            "plan-complete",
195            vec![
196                req("attemptNumber", S::Number),
197                req("totalCost", S::Number),
198                req("flipPattern", S::Number),
199                req("joinStates", join_states.clone()),
200            ],
201        ),
202        event(
203            "plan-failed",
204            vec![req("attemptNumber", S::Number), req("reason", S::String)],
205        ),
206        event(
207            "best-plan-selected",
208            vec![
209                req("bestAttemptNumber", S::Number),
210                req("totalCost", S::Number),
211                req("flipPattern", S::Number),
212                req("joinStates", join_states),
213            ],
214        ),
215        event(
216            "node-cost",
217            vec![
218                opt("attemptNumber", S::Number),
219                req("nodeType", S::String),
220                req("node", S::String),
221                req("branchPattern", S::Array(b(S::Number))),
222                req("downstreamChildSelectivity", S::Number),
223                req("costEstimate", cost_estimate),
224                opt("filters", S::Custom(condition)),
225                opt("ordering", ordering),
226                opt("joinType", S::String),
227            ],
228        ),
229        event(
230            "node-constraint",
231            vec![
232                opt("attemptNumber", S::Number),
233                req("nodeType", S::String),
234                req("node", S::String),
235                req("branchPattern", S::Array(b(S::Number))),
236                opt("constraint", S::Nullable(b(planner_constraint))),
237                req("from", S::String),
238            ],
239        ),
240    ]);
241    // `analyzeQueryResultSchema`.
242    let analyze_query_result = S::Object(vec![
243        req("warnings", S::Array(b(S::String))),
244        opt("syncedRows", S::Record(b(S::Array(b(row))))),
245        req("syncedRowCount", S::Number),
246        req("start", S::Number),
247        req("end", S::Number),
248        opt("elapsed", S::Number),
249        opt("afterPermissions", S::String),
250        opt("vendedRowCounts", row_counts_by_source.clone()),
251        opt("vendedRows", rows_by_source.clone()),
252        opt("sqlitePlans", S::Record(b(S::Array(b(S::String))))),
253        opt("readRows", rows_by_source),
254        opt("readRowCountsByQuery", row_counts_by_source.clone()),
255        opt("readRowCount", S::Number),
256        opt("dbScansByQuery", row_counts_by_source),
257        opt("joinPlans", S::Array(b(plan_debug_event))),
258    ]);
259    S::Union(vec![
260        op(
261            "queries",
262            vec![req("value", S::Array(b(inspect_query_row)))],
263        ),
264        op("metrics", vec![req("value", server_metrics)]),
265        op("version", vec![req("value", S::String)]),
266        op("authenticated", vec![req("value", S::Boolean)]),
267        op("analyze-query", vec![req("value", analyze_query_result)]),
268        op("error", vec![req("value", S::String)]),
269    ])
270});