Skip to main content

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, 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
163/// A named query whose arguments come as JSON, as the server gets them,
164/// whatever its types: for a list of an app's queries, such as a test that
165/// checks them against the TS definitions.
166pub trait NamedQuery<C> {
167    /// Its name in the TS query registry.
168    fn name(&self) -> &'static str;
169
170    /// The query for `args` (none, or one JSON value) read as the
171    /// definition's argument type, as `context` sees it, with the arguments
172    /// as this side sends them.
173    fn query_from_json(
174        &self,
175        args: &[Value],
176        context: &C,
177    ) -> Result<(AnyQuery, Vec<Value>), String>;
178}
179
180impl<A, C, R, T> NamedQuery<C> for QueryDefinition<A, C, R, T>
181where
182    A: Serialize + DeserializeOwned + Send + Sync + 'static,
183    C: 'static,
184    R: 'static,
185    T: 'static,
186{
187    fn name(&self) -> &'static str {
188        self.name
189    }
190
191    fn query_from_json(
192        &self,
193        args: &[Value],
194        context: &C,
195    ) -> Result<(AnyQuery, Vec<Value>), String> {
196        let decoded: A = match args {
197            [] => decode_args(None)?,
198            [a] => decode_args(Some(a))?,
199            _ => return Err(format!("expected at most one argument, got {}", args.len())),
200        };
201        let request = self.with(decoded);
202        Ok((request.query(context).into_any(), request.args))
203    }
204}
205
206type MutatorBody<A, C, O> = fn(&Transaction, A, &C) -> Result<O, Error>;
207
208/// A named mutator (`defineMutator`): `A` is its arguments, `C` the
209/// client's context, and `O` what its optimistic run returns to the
210/// caller's `client` outcome (`()` for nothing). Make one with
211/// [`define_mutator`].
212///
213/// The name must match the TS registry entry the API server runs. The body
214/// runs once optimistically and again on every rebase while the mutation is
215/// pending, so it must only depend on `tx`, the arguments, and the context.
216pub struct MutatorDefinition<A, C, O = ()> {
217    /// Its name in the TS mutator registry.
218    pub name: &'static str,
219    body: MutatorBody<A, C, O>,
220}
221
222impl<A, C, O> Clone for MutatorDefinition<A, C, O> {
223    fn clone(&self) -> Self {
224        *self
225    }
226}
227
228impl<A, C, O> Copy for MutatorDefinition<A, C, O> {}
229
230/// A named mutator: `name` in the TS registry, and its `body`.
231pub const fn define_mutator<A, C, O>(
232    name: &'static str,
233    body: MutatorBody<A, C, O>,
234) -> MutatorDefinition<A, C, O> {
235    MutatorDefinition { name, body }
236}
237
238impl<A, C, O> MutatorDefinition<A, C, O>
239where
240    A: Serialize + DeserializeOwned + 'static,
241    C: 'static,
242    O: Serialize + 'static,
243{
244    /// The mutation of this mutator with `args`, for
245    /// [`Zero::mutate_request`](crate::client::Zero::mutate_request).
246    pub fn with(&self, args: A) -> MutateRequest {
247        MutateRequest::new(self.name, encode_args(&args))
248    }
249
250    /// The mutator to register with `Zero::new`, so the client runs it and
251    /// replays it by name. Arguments that don't read as `A` fail it with
252    /// an [`ApplicationError`].
253    pub fn mutator(&self) -> Mutator<C> {
254        let body = self.body;
255        Mutator::new(self.name, move |tx, args, context: &C| {
256            let args: A = decode_args(args).map_err(ApplicationError::new)?;
257            Ok(encode_args(&body(tx, args, context)?))
258        })
259    }
260
261    /// `args` read as `A` and encoded again: what this side would send for
262    /// them.
263    pub fn reencode(&self, args: Option<&Value>) -> Result<Option<Value>, String> {
264        Ok(encode_args(&decode_args::<A>(args)?))
265    }
266}
267
268/// A named mutator whatever its types: for a list of an app's mutators,
269/// to register them all and to check them against the TS definitions.
270pub trait NamedMutator<C> {
271    /// Its name in the TS mutator registry.
272    fn name(&self) -> &'static str;
273    /// [`MutatorDefinition::mutator`].
274    fn mutator(&self) -> Mutator<C>;
275    /// [`MutatorDefinition::reencode`].
276    fn reencode(&self, args: Option<&Value>) -> Result<Option<Value>, String>;
277}
278
279impl<A, C, O> NamedMutator<C> for MutatorDefinition<A, C, O>
280where
281    A: Serialize + DeserializeOwned + 'static,
282    C: 'static,
283    O: Serialize + 'static,
284{
285    fn name(&self) -> &'static str {
286        self.name
287    }
288    fn mutator(&self) -> Mutator<C> {
289        MutatorDefinition::mutator(self)
290    }
291    fn reencode(&self, args: Option<&Value>) -> Result<Option<Value>, String> {
292        MutatorDefinition::reencode(self, args)
293    }
294}