Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions sdk/typescript/src/client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -338,7 +338,7 @@ describe("ZyncBaseClient", () => {
);
const handle = await pendingListen;
await new Promise((r) => setTimeout(r, 0));
expect(values).toEqual([]);
expect(values).toEqual([null]);

// A namespace switch re-runs the replay path without dropping the socket.
const switching = client.setStoreNamespace("other");
Expand Down Expand Up @@ -375,6 +375,7 @@ describe("ZyncBaseClient", () => {

// The remapped document listen receives its snapshot again.
expect(values).toEqual([
null,
{
id: userId,
namespace_id: 1,
Expand Down Expand Up @@ -442,8 +443,9 @@ describe("ZyncBaseClient", () => {
],
}),
);
await waitFor(() => values.length === 1);
expect(values[0]).toMatchObject({ name: "Ada" });
await waitFor(() => values.length === 2);
expect(values[0]).toBeNull();
expect(values[1]).toMatchObject({ name: "Ada" });

client.disconnect();
restoreWebSocket();
Expand Down
59 changes: 59 additions & 0 deletions sdk/typescript/src/filter_eval.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import { describe, expect, test } from "bun:test";
import { compileWhere } from "./filter_eval.js";
import {
FILTER_VECTOR_DOC_ID_FIELDS,
FILTER_VECTOR_RECORDS,
FILTER_VECTORS,
} from "./filter_eval.vectors.js";
import { encodeQueryOptions } from "./store_wire.js";

const isDocIdField = (field: string) => FILTER_VECTOR_DOC_ID_FIELDS.has(field);

describe("compileWhere", () => {
for (const vector of FILTER_VECTORS) {
test(vector.name, () => {
const matches = compileWhere(
encodeQueryOptions({ where: vector.where }),
isDocIdField,
);
const ids = FILTER_VECTOR_RECORDS.filter(matches).map((r) => r.id);
expect(ids.sort()).toEqual([...vector.expected].sort());
});
}

test("a missing field reads as null", () => {
const matches = compileWhere(
encodeQueryOptions({ where: { score: { isNull: true } } }),
isDocIdField,
);
expect(matches({ id: "x" })).toBe(true);
expect(matches({ id: "x", score: 1 })).toBe(false);
});

test("array equality ignores order and duplicates on the record side", () => {
const matches = compileWhere(
encodeQueryOptions({ where: { tags: ["a", "b"] } }),
isDocIdField,
);
expect(matches({ tags: ["b", "a", "b"] })).toBe(true);
});

test("binary operands are snapshotted when the predicate is compiled", () => {
const bytes = new Uint8Array([1, 2, 3]);
const eq = compileWhere(
encodeQueryOptions({ where: { coordinates: bytes } }),
isDocIdField,
);
const ne = compileWhere(
encodeQueryOptions({ where: { coordinates: { ne: bytes } } }),
isDocIdField,
);

bytes[0] = 9;

expect(eq({ coordinates: new Uint8Array([1, 2, 3]) })).toBe(true);
expect(eq({ coordinates: new Uint8Array([9, 2, 3]) })).toBe(false);
expect(ne({ coordinates: new Uint8Array([1, 2, 3]) })).toBe(false);
expect(ne({ coordinates: new Uint8Array([9, 2, 3]) })).toBe(true);
});
});
156 changes: 156 additions & 0 deletions sdk/typescript/src/filter_eval.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
import { getDeepProperty, splitFieldPath } from "./path.js";
import { OP_CODES, type WireCondition } from "./store_wire.js";
import type { JsonValue } from "./types.js";
import { compareScalars, scalarsEqual, sortedSet } from "./value_order.js";

/** Whether a record belongs in a view; the server's delta matching, client side. */
export type RecordMatcher = (record: JsonValue) => boolean;

type Condition = WireCondition | [string, number, JsonValue?];

/** A wire `where`, as `encodeQueryOptions` builds it. */
export interface WireWhere {
conditions?: readonly Condition[];
orConditions?: readonly Condition[];
}

type ValueTest = (value: JsonValue) => boolean;

const ORDERINGS: Record<number, (order: number) => boolean> = {
[OP_CODES.gt]: (order) => order > 0,
[OP_CODES.lt]: (order) => order < 0,
[OP_CODES.gte]: (order) => order >= 0,
[OP_CODES.lte]: (order) => order <= 0,
};

/**
* Compiles a wire `where` into a matcher: every condition holds, and when
* `orConditions` is present at least one of them holds. `isDocIdField`
* reports whether a flat field name holds document ids.
*/
export function compileWhere(
where: WireWhere,
isDocIdField: (field: string) => boolean,
): RecordMatcher {
const all = (where.conditions ?? []).map((c) =>
compileCondition(c, isDocIdField),
);
const any = (where.orConditions ?? []).map((c) =>
compileCondition(c, isDocIdField),
);
return (record) =>
all.every((matches) => matches(record)) &&
(any.length === 0 || any.some((matches) => matches(record)));
}

function compileCondition(
[field, op, operand = null]: Condition,
isDocIdField: (field: string) => boolean,
): RecordMatcher {
const parts = splitFieldPath(field);
const test = compileTest(op, operand, isDocIdField(field));
return (record) => test(getDeepProperty(record, parts) ?? null);
}

function compileTest(
op: number,
operand: JsonValue,
docId: boolean,
): ValueTest {
switch (op) {
case OP_CODES.isNull:
return (value) => value === null;
case OP_CODES.isNotNull:
return (value) => value !== null;
case OP_CODES.eq:
return compileEquality(operand, docId, false);
case OP_CODES.ne:
return compileEquality(operand, docId, true);
case OP_CODES.in:
return compileMembership(operand as JsonValue[], false);
case OP_CODES.notIn:
return compileMembership(operand as JsonValue[], true);
case OP_CODES.contains:
return compileContains(operand);
case OP_CODES.startsWith:
return compileText(operand, (value, needle) => value.startsWith(needle));
case OP_CODES.endsWith:
return compileText(operand, (value, needle) => value.endsWith(needle));
default:
return compileOrdering(ORDERINGS[op], operand, docId);
}
}

/** Null fails both `eq` and `ne`; arrays compare as sorted sets. */
function compileEquality(
operand: JsonValue,
docId: boolean,
negate: boolean,
): ValueTest {
const expected = snapshotBinary(operand);
const equals: ValueTest = Array.isArray(expected)
? setEquals(sortedSet(expected, docId), docId)
: (value) => scalarsEqual(value, expected);
return (value) => value !== null && equals(value) !== negate;
}

/** Snapshot bytes so later caller mutations cannot change a compiled predicate. */
function snapshotBinary(value: JsonValue): JsonValue {
if (value instanceof Uint8Array) return value.slice();
if (Array.isArray(value)) return value.map(snapshotBinary);
return value;
}

function setEquals(expected: JsonValue[], docId: boolean): ValueTest {
return (value) => {
if (!Array.isArray(value)) return false;
const actual = sortedSet(value, docId);
return (
actual.length === expected.length &&
actual.every((item, i) => scalarsEqual(item, expected[i]))
);
};
}

/** `in []` matches nothing and `notIn []` everything, null included; otherwise null fails both. */
function compileMembership(members: JsonValue[], negate: boolean): ValueTest {
if (members.length === 0) return () => negate;
const set = new Set(members);
return (value) => value !== null && set.has(value) !== negate;
}

/** Exact element membership on arrays; ASCII case-insensitive substring on text. */
function compileContains(operand: JsonValue): ValueTest {
const text = compileText(operand, (value, needle) => value.includes(needle));
return (value) =>
Array.isArray(value)
? value.some((item) => scalarsEqual(item, operand))
: text(value);
}

function compileText(
operand: JsonValue,
matches: (value: string, needle: string) => boolean,
): ValueTest {
const needle = typeof operand === "string" ? foldAscii(operand) : null;
return (value) =>
typeof value === "string" &&
needle !== null &&
matches(foldAscii(value), needle);
}

function compileOrdering(
accepts: (order: number) => boolean,
operand: JsonValue,
docId: boolean,
): ValueTest {
return (value) =>
value !== null &&
typeof value === typeof operand &&
accepts(compareScalars(value, operand, docId));
}

/** Lowercases A-Z only, like the server's ASCII case-insensitive matching. */
function foldAscii(value: string): string {
return value.replace(/[A-Z]/g, (char) => char.toLowerCase());
}
Loading
Loading