zero_client/define.rs
1//! Typed named queries and mutators, behind the `serde` feature:
2//! [`define_query`] and [`define_mutator`] (`defineQuery` in
3//! `packages/zql/src/query/query-registry.ts` and `defineMutator` in
4//! `packages/zql/src/mutate/mutator.ts`, shaped like the Swift client's).
5//!
6//! Each is defined once, by its name in the TS registry the server runs and
7//! a serde argument type, and called with a value of that type: the client
8//! sends the name and the arguments as JSON, as JS does, and reads them back
9//! as the type before a mutator's body runs. The context comes from the
10//! [`Zero`](crate::client::Zero) the request goes to.
11//!
12//! ```
13//! # use zero_client::define::{MutatorDefinition, QueryDefinition, define_mutator, define_query};
14//! # use zero_client::client::{Error, Transaction};
15//! # use zero_client::typed::Query;
16//! # struct Label;
17//! # fn labels_query(project: &str) -> Query<Label> { unimplemented!() }
18//! #[derive(serde::Serialize, serde::Deserialize)]
19//! #[serde(rename_all = "camelCase")]
20//! struct ProjectArgs { project_name: String }
21//!
22//! /// The logged-in user, which `Zero::new` was given.
23//! type Context = Option<String>;
24//!
25//! const LABELS: QueryDefinition<ProjectArgs, Context, Label> =
26//! define_query("labels", |args, _ctx| labels_query(&args.project_name));
27//! const RENAME: MutatorDefinition<ProjectArgs, Context> =
28//! define_mutator("project.rename", |tx, args, ctx| Ok(()));
29//!
30//! // zero.materialize(&LABELS.with(ProjectArgs { project_name: "Zero".into() }), &ttl)?;
31//! // zero.mutate_request(RENAME.with(ProjectArgs { project_name: "Zero".into() }));
32//! // Zero::new(schema, context, vec![RENAME.mutator()], ...);
33//! ```
34//!
35//! A definition that takes no arguments takes `()` (or another type with
36//! no fields), which sends none, as JS's `undefined` does.
37
38use crate::client::{ApplicationError, Error, MutateRequest, Mutator, Transaction};
39use crate::ivm::ViewValue;
40use crate::json::{self, Value};
41use crate::query::{AnyQuery, ZeroQuery};
42use crate::typed::{Query, QueryValue, TypedQuery, ZeroValueError};
43use serde::Serialize;
44use serde::de::DeserializeOwned;
45use std::borrow::Cow;
46use std::sync::Arc;
47
48/// `args` as sent: `None` for a type without fields that writes `null`,
49/// such as `()`, which stands for no arguments.
50fn encode_args<A: Serialize>(args: &A) -> Option<Value> {
51 let value = json::to_value(args).expect("arguments must encode as JSON");
52 (size_of::<A>() != 0 || !value.is_null()).then_some(value)
53}
54
55/// `args` (none, or one JSON value) read as `A`.
56fn decode_args<A: DeserializeOwned>(args: Option<&Value>) -> Result<A, String> {
57 json::from_value(args.unwrap_or(&Value::Null)).map_err(|e| e.to_string())
58}
59
60/// A named query (`defineQuery`): `A` is its arguments, `C` the client's
61/// context, and `Query<R, T>` what it builds. Make one with
62/// [`define_query`].
63///
64/// The name must match the TS registry entry the server runs: the client
65/// builds the query here for optimistic results, and the server builds its
66/// own from the name and arguments.
67pub struct QueryDefinition<A, C, R, T = Vec<R>> {
68 /// Its name in the TS query registry.
69 pub name: &'static str,
70 body: fn(&A, &C) -> Query<R, T>,
71}
72
73impl<A, C, R, T> Clone for QueryDefinition<A, C, R, T> {
74 fn clone(&self) -> Self {
75 *self
76 }
77}
78
79impl<A, C, R, T> Copy for QueryDefinition<A, C, R, T> {}
80
81/// A named query: `name` in the TS registry, and the query `body` builds
82/// from the arguments and the client's context.
83pub const fn define_query<A, C, R, T>(
84 name: &'static str,
85 body: fn(&A, &C) -> Query<R, T>,
86) -> QueryDefinition<A, C, R, T> {
87 QueryDefinition { name, body }
88}
89
90impl<A, C, R, T> QueryDefinition<A, C, R, T>
91where
92 A: Serialize + Send + Sync + 'static,
93 C: 'static,
94 R: 'static,
95 T: 'static,
96{
97 /// The query with `args`, ready to materialize, run, or preload.
98 pub fn with(&self, args: A) -> QueryRequest<C, R, T> {
99 let encoded = encode_args(&args).into_iter().collect();
100 let body = self.body;
101 QueryRequest {
102 name: self.name,
103 args: encoded,
104 build: Arc::new(move |context| body(&args, context)),
105 }
106 }
107}
108
109/// Builds a request's query from the client's context.
110type BuildQuery<C, R, T> = Arc<dyn Fn(&C) -> Query<R, T> + Send + Sync>;
111
112/// A [`QueryDefinition`] applied to its arguments: what
113/// [`Zero::materialize`](crate::client::Zero::materialize), `run`, and
114/// `preload` take, which build it with the client's context. It is `Send`,
115/// so an app can make one on one thread for a client on another.
116pub struct QueryRequest<C, R, T = Vec<R>> {
117 name: &'static str,
118 args: Vec<Value>,
119 build: BuildQuery<C, R, T>,
120}
121
122impl<C, R, T> Clone for QueryRequest<C, R, T> {
123 fn clone(&self) -> Self {
124 QueryRequest {
125 name: self.name,
126 args: self.args.clone(),
127 build: self.build.clone(),
128 }
129 }
130}
131
132impl<C, R, T> QueryRequest<C, R, T> {
133 /// The query's name.
134 pub fn name(&self) -> &'static str {
135 self.name
136 }
137
138 /// The arguments as sent: none, or one JSON value.
139 pub fn args(&self) -> &[Value] {
140 &self.args
141 }
142
143 /// The query as `context` sees it, named so the server knows it.
144 pub fn query(&self, context: &C) -> Query<R, T> {
145 let any = (self.build)(context).into_any();
146 Query::from_any(any.name_and_args(self.name, self.args.clone()))
147 }
148}
149
150impl<C, R, T: QueryValue> QueryRequest<C, R, T> {
151 /// Reads a view of this query as its result, as `Query::read` does.
152 pub fn read(&self, view: &ViewValue) -> Result<T, ZeroValueError> {
153 T::from_view(view)
154 }
155}
156
157impl<C, R, T> ZeroQuery<C> for QueryRequest<C, R, T> {
158 fn any_query(&self, context: &C) -> Cow<'_, AnyQuery> {
159 Cow::Owned(self.query(context).into_any())
160 }
161}
162
163impl<C, R, T: QueryValue> TypedQuery<C> for QueryRequest<C, R, T> {
164 type Value = T;
165}
166
167/// A named query whose arguments come as JSON, as the server gets them,
168/// whatever its types: for a list of an app's queries, such as a test that
169/// checks them against the TS definitions.
170pub trait NamedQuery<C> {
171 /// Its name in the TS query registry.
172 fn name(&self) -> &'static str;
173
174 /// The query for `args` (none, or one JSON value) read as the
175 /// definition's argument type, as `context` sees it, with the arguments
176 /// as this side sends them.
177 fn query_from_json(
178 &self,
179 args: &[Value],
180 context: &C,
181 ) -> Result<(AnyQuery, Vec<Value>), String>;
182}
183
184impl<A, C, R, T> NamedQuery<C> for QueryDefinition<A, C, R, T>
185where
186 A: Serialize + DeserializeOwned + Send + Sync + 'static,
187 C: 'static,
188 R: 'static,
189 T: 'static,
190{
191 fn name(&self) -> &'static str {
192 self.name
193 }
194
195 fn query_from_json(
196 &self,
197 args: &[Value],
198 context: &C,
199 ) -> Result<(AnyQuery, Vec<Value>), String> {
200 let decoded: A = match args {
201 [] => decode_args(None)?,
202 [a] => decode_args(Some(a))?,
203 _ => return Err(format!("expected at most one argument, got {}", args.len())),
204 };
205 let request = self.with(decoded);
206 Ok((request.query(context).into_any(), request.args))
207 }
208}
209
210type MutatorBody<A, C, O> = fn(&Transaction, A, &C) -> Result<O, Error>;
211
212/// A named mutator (`defineMutator`): `A` is its arguments, `C` the
213/// client's context, and `O` what its optimistic run returns to the
214/// caller's `client` outcome (`()` for nothing). Make one with
215/// [`define_mutator`].
216///
217/// The name must match the TS registry entry the API server runs. The body
218/// runs once optimistically and again on every rebase while the mutation is
219/// pending, so it must only depend on `tx`, the arguments, and the context.
220pub struct MutatorDefinition<A, C, O = ()> {
221 /// Its name in the TS mutator registry.
222 pub name: &'static str,
223 body: MutatorBody<A, C, O>,
224}
225
226impl<A, C, O> Clone for MutatorDefinition<A, C, O> {
227 fn clone(&self) -> Self {
228 *self
229 }
230}
231
232impl<A, C, O> Copy for MutatorDefinition<A, C, O> {}
233
234/// A named mutator: `name` in the TS registry, and its `body`.
235pub const fn define_mutator<A, C, O>(
236 name: &'static str,
237 body: MutatorBody<A, C, O>,
238) -> MutatorDefinition<A, C, O> {
239 MutatorDefinition { name, body }
240}
241
242impl<A, C, O> MutatorDefinition<A, C, O>
243where
244 A: Serialize + DeserializeOwned + 'static,
245 C: 'static,
246 O: Serialize + 'static,
247{
248 /// The mutation of this mutator with `args`, for
249 /// [`Zero::mutate_request`](crate::client::Zero::mutate_request).
250 pub fn with(&self, args: A) -> MutateRequest {
251 MutateRequest::new(self.name, encode_args(&args))
252 }
253
254 /// The mutator to register with `Zero::new`, so the client runs it and
255 /// replays it by name. Arguments that don't read as `A` fail it with
256 /// an [`ApplicationError`].
257 pub fn mutator(&self) -> Mutator<C> {
258 let body = self.body;
259 Mutator::new(self.name, move |tx, args, context: &C| {
260 let args: A = decode_args(args).map_err(ApplicationError::new)?;
261 Ok(encode_args(&body(tx, args, context)?))
262 })
263 }
264
265 /// `args` read as `A` and encoded again: what this side would send for
266 /// them.
267 pub fn reencode(&self, args: Option<&Value>) -> Result<Option<Value>, String> {
268 Ok(encode_args(&decode_args::<A>(args)?))
269 }
270}
271
272/// A named mutator whatever its types: for a list of an app's mutators,
273/// to register them all and to check them against the TS definitions.
274pub trait NamedMutator<C> {
275 /// Its name in the TS mutator registry.
276 fn name(&self) -> &'static str;
277 /// [`MutatorDefinition::mutator`].
278 fn mutator(&self) -> Mutator<C>;
279 /// [`MutatorDefinition::reencode`].
280 fn reencode(&self, args: Option<&Value>) -> Result<Option<Value>, String>;
281}
282
283impl<A, C, O> NamedMutator<C> for MutatorDefinition<A, C, O>
284where
285 A: Serialize + DeserializeOwned + 'static,
286 C: 'static,
287 O: Serialize + 'static,
288{
289 fn name(&self) -> &'static str {
290 self.name
291 }
292 fn mutator(&self) -> Mutator<C> {
293 MutatorDefinition::mutator(self)
294 }
295 fn reencode(&self, args: Option<&Value>) -> Result<Option<Value>, String> {
296 MutatorDefinition::reencode(self, args)
297 }
298}