Skip to content

Commit 1c93766

Browse files
ampagenttmm
andcommitted
zero-swift: sync aggregates, distinct and groupBy from zero-cache
Named queries read the aggregate rows zero-cache sends under the a/ key prefix instead of dropping them. Relationship aggregates and grouped counts move optimistically with local mutations (crud-impl's deltas), and a mutator's tx.run reads synced rows for an answered query. Pending mutations are rebased once a synced aggregate's query first materializes after launch, since Swift replays them before any query registers. Client scenarios in packages/zero-conformance compute the server's rows with JS's pipeline (server-rows.ts), and a new E2E test runs the same queries against zero-cache. Co-authored-by: tmm <tmm@tmm.dev> Amp-Thread-ID: https://ampcode.com/threads/T-01a19a37-5aa9-7256-bff5-cdc47c01a1fe
1 parent c5a9c02 commit 1c93766

17 files changed

Lines changed: 1416 additions & 36 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'zero-swift': patch
3+
---
4+
5+
Aggregates, `distinct()` and `groupBy()` sync from zero-cache: a named query's view reads the rows the server computes, stored under `a/`, instead of dropping them from pokes. Until the server answers, a view computes nothing and shows the empty value (`0` for a count). A local mutation moves a synced relationship aggregate or grouped count at once, as the JS client's optimistic deltas do, and the server's rows replace them when it confirms. A mutator's `tx.run` reads the synced rows for a query the server has answered, and computes them otherwise. Pending mutations are rebased when a synced aggregate's query first materializes after launch, so a relaunched client keeps their moves.

‎packages/zero-conformance/src/client/app.ts‎

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import {defineMutators} from '../../../zql/src/mutate/mutator-registry.ts';
99
import {defineMutator} from '../../../zql/src/mutate/mutator.ts';
1010
import {createBuilder} from '../../../zql/src/query/create-builder.ts';
1111
import {
12+
addContextToQuery,
1213
defineQueries,
1314
defineQuery,
1415
} from '../../../zql/src/query/query-registry.ts';
@@ -60,6 +61,29 @@ export const queries = defineQueries({
6061
users: {
6162
all: defineQuery(() => zql.user.orderBy('id', 'asc')),
6263
},
64+
// Aggregates, distinct and groupBy, which the server computes.
65+
aggregates: {
66+
issueCount: defineQuery(() => zql.issue.count()),
67+
openIssueCount: defineQuery(() => zql.issue.where('closed', false).count()),
68+
commentCounts: defineQuery(() =>
69+
zql.issue.related('comments', q => q.count()).orderBy('id', 'asc'),
70+
),
71+
commentTimes: defineQuery(() =>
72+
zql.issue
73+
.related('comments', q =>
74+
q.where('authorId', '!=', 'u9').avg('createdAt'),
75+
)
76+
.orderBy('id', 'asc'),
77+
),
78+
labelCounts: defineQuery(() =>
79+
zql.issue.related('labels', q => q.count()).orderBy('id', 'asc'),
80+
),
81+
owners: defineQuery(() => zql.issue.distinct('ownerId')),
82+
commentsByIssue: defineQuery(() => zql.comment.groupBy('issueId').count()),
83+
timeByAuthor: defineQuery(() =>
84+
zql.comment.groupBy('authorId').sum('createdAt'),
85+
),
86+
},
6387
// A table with a compound primary key.
6488
issueLabels: {
6589
all: defineQuery(() =>
@@ -177,9 +201,40 @@ const harden = {
177201
}),
178202
};
179203

204+
/**
205+
* Runs `ops` (CRUD operations, as `harden.ops` does), then each of the named
206+
* `queries` through the transaction, and returns what they read: a query the
207+
* server has answered reads its synced aggregates, any other computes them.
208+
*/
209+
const aggregates = {
210+
read: defineMutator(async ({tx, args}: {tx: Tx; args: JSONObject}) => {
211+
for (const o of (args['ops'] ?? []) as CRUDOp[]) {
212+
await tx.mutate[o.table][o.op](o.value);
213+
}
214+
const out: ReadonlyJSONValue[] = [];
215+
for (const {name, args: queryArgs} of (args['queries'] ?? []) as {
216+
name: string;
217+
args?: ReadonlyJSONValue;
218+
}[]) {
219+
let v: unknown = queries;
220+
for (const part of name.split('.')) {
221+
v = (v as Record<string, unknown>)[part];
222+
}
223+
const request = (v as (...a: unknown[]) => unknown)(
224+
...(queryArgs === undefined ? [] : [queryArgs]),
225+
);
226+
// oxlint-disable-next-line @typescript-eslint/no-explicit-any
227+
const result = await tx.run(addContextToQuery(request as any, undefined));
228+
out.push(JSON.parse(JSON.stringify(result ?? null)));
229+
}
230+
return out;
231+
}),
232+
};
233+
180234
export const mutators = defineMutators({
181235
issue,
182236
harden,
237+
aggregates,
183238
comment: {
184239
add: defineMutator(async ({tx, args}: {tx: Tx; args: JSONObject}) => {
185240
await tx.mutate.comment.insert({

‎packages/zero-conformance/src/client/scenarios.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import type {Scenario} from './harness.ts';
2+
import {aggregateScenarios} from './scenarios/aggregates.ts';
23
import {connectionScenarios} from './scenarios/connection.ts';
34
import {errorScenarios} from './scenarios/errors.ts';
45
import {mutationScenarios} from './scenarios/mutations.ts';
@@ -12,6 +13,7 @@ export const scenarios: Scenario[] = [
1213
...errorScenarios,
1314
...pokeScenarios,
1415
...queryScenarios,
16+
...aggregateScenarios,
1517
...mutationScenarios,
1618
...persistenceScenarios,
1719
...visibilityScenarios,

0 commit comments

Comments
 (0)