@rindle/wasm 0.1.0-rc.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,82 @@
1
+ # @rindle/wasm — local (in-process) IVM backend
2
+
3
+ The WASM backend for [`@rindle/client`](../client): the Rust IVM engine (a port of Zero's ZQL
4
+ dataflow engine) compiled to WebAssembly, running queries **in-process**. It re-exports
5
+ `@rindle/client`, so a local app can import everything from here.
6
+
7
+ ## Quick start
8
+
9
+ ```ts
10
+ import { table, string, number, boolean, createSchema, createWasmStore } from "@rindle/wasm";
11
+
12
+ const issue = table("issue")
13
+ .columns({ id: number(), title: string(), closed: boolean() })
14
+ .primaryKey("id");
15
+ const comment = table("comment")
16
+ .columns({ id: number(), issueID: number(), body: string() })
17
+ .primaryKey("id");
18
+ const schema = createSchema({ tables: [issue, comment] });
19
+
20
+ const store = await createWasmStore(schema); // inits the wasm + wires the local backend
21
+
22
+ const view = store.query.issue
23
+ .where.closed(false)
24
+ .sub("comments", comment, { parent: ["id"], child: ["issueID"] }, (c) => c.orderBy("id", "asc"))
25
+ .materialize();
26
+
27
+ view.subscribe((data) => render(data)); // typed, nested, reference-stable tree
28
+ await store.write((tx) => tx.add("comment", { id: 1, issueID: 1, body: "hi" }));
29
+
30
+ // `.one()` materializes a single row (`data` is the row or `null`, not an array):
31
+ const top = store.query.issue.orderBy("priority", "desc").one().materialize();
32
+ top.subscribe((row) => render(row)); // row: Issue | null
33
+
34
+ // `.start(cursor, { exclusive })` pages from a cursor over the sort columns:
35
+ const page2 = store.query.issue.orderBy("id", "asc").start({ id: lastId }, { exclusive: true }).limit(20).materialize();
36
+ ```
37
+
38
+ ## How it works
39
+
40
+ `store.query.<table>…materialize()` registers the query with the in-process engine and folds
41
+ its **flat change** stream into a live `ArrayView`. `store.write(...)` applies row mutations and
42
+ the affected views update. The engine derives true incremental changes — `view.data` always
43
+ equals a freshly-run query.
44
+
45
+ ## Building & publishing
46
+
47
+ Two build steps. The Rust → wasm artifact (`pkg/`), needed once (and whenever the engine changes):
48
+
49
+ ```sh
50
+ pnpm --filter @rindle/wasm build:wasm # or: packages/wasm/build.sh [dev|release|wasm-release]
51
+ ```
52
+
53
+ Requires the Rust toolchain + `wasm-bindgen` (`cargo install wasm-bindgen-cli`). The output is a
54
+ `--target web` ESM bundle that runs in browsers, bundlers, and Node.
55
+
56
+ Then the TypeScript → `dist/` compile that produces the published, runnable `.js` + `.d.ts`:
57
+
58
+ ```sh
59
+ pnpm run build # builds @rindle/client then @rindle/wasm dist/ (run from the repo root)
60
+ ```
61
+
62
+ The published package ships `dist/` (compiled) + `pkg/` (the wasm). In-repo the test suite resolves
63
+ the TS source directly (via the `@rindle/source` export condition), so `pnpm test` needs no build.
64
+
65
+ ### Browser smoke test
66
+
67
+ `pnpm test:browser` builds `dist/`, then loads the package in **headless Chrome** (taking the real
68
+ browser `fetch` + `WebAssembly.instantiateStreaming` init path) and runs a query. Needs system
69
+ Chrome/Chromium (`CHROME_BIN` to override); skipped with a message when none is installed.
70
+
71
+ ## Initialization
72
+
73
+ `createWasmStore(schema)` calls `initWasm()` for you. If you build a `WasmBackend` directly,
74
+ `await initWasm()` first:
75
+
76
+ ```ts
77
+ import { initWasm, WasmBackend, Store } from "@rindle/wasm";
78
+ await initWasm(); // browser: fetches the wasm; Node: reads it
79
+ const store = new Store(schema, new WasmBackend(schema));
80
+ ```
81
+
82
+ Pass `initWasm(moduleOrPath)` to supply the wasm yourself (a `WebAssembly.Module`, URL, or bytes).
package/build.sh ADDED
@@ -0,0 +1,39 @@
1
+ #!/usr/bin/env bash
2
+ # Build the rindle wasm engine into this package as a portable ESM artifact (--target web):
3
+ # works in browsers/bundlers (await init()) and Node (await init(bytes)) — see src/index.ts.
4
+ #
5
+ # ./build.sh [profile] # wasm-release (default) | release | dev
6
+ #
7
+ # Produces packages/wasm/pkg/{rindle.js, rindle_bg.wasm, rindle.d.ts}.
8
+ set -euo pipefail
9
+
10
+ PROFILE="${1:-wasm-release}"
11
+ TARGET=wasm32-unknown-unknown
12
+ FEATURES=wasm
13
+ ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
14
+ OUT="$ROOT/packages/wasm/pkg"
15
+ export PATH="$HOME/.cargo/bin:$PATH"
16
+
17
+ cd "$ROOT"
18
+
19
+ # `-p rindle`: build ONLY the C-toolchain-free core crate for wasm32 — not the whole workspace
20
+ # (the SQLite members `rindle-sqlite`/`rindle-replica` and `rindle-fuzz`'s `getrandom` don't compile to
21
+ # `wasm32-unknown-unknown`, and a bare `cargo build` would try to).
22
+ #
23
+ # `cargo rustc … --crate-type cdylib`: the lib's default crate-type is `rlib` (so native builds
24
+ # don't emit a colliding `librindle.so`, cargo#6313); the `.wasm` artifact needs `cdylib`, requested
25
+ # here just for this wasm32 build. Produces `target/$TARGET/<profile>/rindle.wasm` either way.
26
+ case "$PROFILE" in
27
+ dev) cargo rustc -p rindle --target "$TARGET" --no-default-features --features "$FEATURES" --crate-type cdylib; WASM="$ROOT/target/$TARGET/debug/rindle.wasm" ;;
28
+ release) cargo rustc -p rindle --release --target "$TARGET" --no-default-features --features "$FEATURES" --crate-type cdylib; WASM="$ROOT/target/$TARGET/release/rindle.wasm" ;;
29
+ *) cargo rustc -p rindle --profile "$PROFILE" --target "$TARGET" --no-default-features --features "$FEATURES" --crate-type cdylib; WASM="$ROOT/target/$TARGET/$PROFILE/rindle.wasm" ;;
30
+ esac
31
+
32
+ wasm-bindgen --target web --out-dir "$OUT" --out-name rindle "$WASM"
33
+
34
+ if command -v wasm-opt >/dev/null 2>&1 && [ "$PROFILE" != "dev" ]; then
35
+ wasm-opt -Oz "$OUT/rindle_bg.wasm" -o "$OUT/rindle_bg.wasm"
36
+ echo "wasm-opt -Oz applied"
37
+ fi
38
+
39
+ echo "built $OUT (target=web, profile=$PROFILE, $(wc -c < "$OUT/rindle_bg.wasm") bytes)"
@@ -0,0 +1,85 @@
1
+ import { Store } from "@rindle/client";
2
+ import type { Ast, Backend, ChangeEvent, ColsMap, Mutation, QueryId, Schema } from "@rindle/client";
3
+ export * from "@rindle/client";
4
+ /** A raw staged write transaction over the wasm engine — the surface an optimistic client
5
+ * mutator runs against (`get` reads the live state under this txn's staged overlay, so a
6
+ * read-dependent mutator sees its own writes; OPTIMISTIC-WRITES-DESIGN.md §4.1). */
7
+ export interface WasmWriteTxn {
8
+ add(table: string, row: unknown[]): void;
9
+ remove(table: string, row: unknown[]): void;
10
+ edit(table: string, oldRow: unknown[], newRow: unknown[]): void;
11
+ get(table: string, pk: unknown[]): unknown[] | undefined;
12
+ commit(): Array<{
13
+ queryId: number;
14
+ events: unknown[];
15
+ }>;
16
+ rollback(): void;
17
+ }
18
+ /** One base-table row op of a coherent server delta (the §1.3 `D`), bare cells. */
19
+ export type ServerDeltaOp = {
20
+ table: string;
21
+ type: "add";
22
+ row: unknown[];
23
+ } | {
24
+ table: string;
25
+ type: "remove";
26
+ row: unknown[];
27
+ } | {
28
+ table: string;
29
+ type: "edit";
30
+ row: unknown[];
31
+ old: unknown[];
32
+ };
33
+ /** Initialize the wasm module (idempotent). Call once at startup before `new WasmBackend`
34
+ * / `createWasmStore`. Browser/bundler: no args (the wasm is fetched). Node: the bytes are
35
+ * read from the package. Pass `moduleOrPath` to override (a `WebAssembly.Module`, URL, or bytes). */
36
+ export declare function initWasm(moduleOrPath?: unknown): Promise<void>;
37
+ export declare class WasmBackend<S extends ColsMap> implements Backend {
38
+ private readonly db;
39
+ private handler;
40
+ private readonly dispatchQueue;
41
+ private draining;
42
+ constructor(schema: Schema<S>);
43
+ /** Register an additional base table after construction — for a SYNTHETIC aggregate table
44
+ * (`AGGREGATE-SYNC-DESIGN.md` §3.3) that is not in the typed schema. The
45
+ * `NormalizedBackend` registers each such `__agg_*` table once, before a query that reads
46
+ * it, so the local engine can join to it (the relationship `count` it backs is shipped by
47
+ * the server, never recomputed). */
48
+ registerTable(name: string, spec: {
49
+ columns: string[];
50
+ primaryKey: number[];
51
+ }): void;
52
+ /** Remove a synthetic aggregate table registered by {@link registerTable}, once the last
53
+ * query reading it has been unregistered (`AGGREGATE-SYNC-DESIGN.md` §4): frees the engine
54
+ * source + its optimistic baseline so aggregate state is reclaimed, not permanent. Throws
55
+ * if a query still reads it (the backend refcounts readers, so it calls this only at 0). */
56
+ unregisterTable(name: string): void;
57
+ registerQuery(qid: QueryId, ast: Ast): void;
58
+ unregisterQuery(qid: QueryId): void;
59
+ mutate(mutations: Mutation[]): Promise<void>;
60
+ onEvent(handler: (qid: QueryId, ev: ChangeEvent) => void): void;
61
+ /** Deliver one commit's per-query batches. Non-reentrant (#15): if a delivery is already in
62
+ * progress (a subscriber re-entered via write()), enqueue and let the active drain pick it
63
+ * up FIFO, so each query folds commits in order. Per-query isolated (#11): a view's fold or
64
+ * subscriber throwing does NOT drop sibling queries' batches — the first error is re-raised
65
+ * only after every query has been delivered. */
66
+ private dispatch;
67
+ /** Run `f` against a raw staged write txn (with the §4.1 `get` read path), commit, and
68
+ * dispatch the resulting batches on the ordinary event stream. Inside an open server
69
+ * batch the engine buffers the events into the cycle instead (commit returns `[]`),
70
+ * so re-invocations dispatch nothing here — delivery is `serverBatchEnd`'s. */
71
+ writeWith(f: (tx: WasmWriteTxn) => void): void;
72
+ /** Open a §1.3 reconcile cycle against the coherent server delta: the engine rewinds
73
+ * (optimistic layer un-applied, delta folded in, `sync` re-forked) and starts
74
+ * buffering. Re-invoke the still-pending mutators via {@link writeWith}, then call
75
+ * {@link serverBatchEnd}. On error the optimistic state is poisoned — discard the
76
+ * backend and re-hydrate. */
77
+ serverBatchBegin(deltas: ServerDeltaOp[]): void;
78
+ /** Close the cycle: the whole buffered stream (rewind + re-invocations) coalesces to
79
+ * the minimal net per query (§3 — a confirmed-correct prediction delivers nothing)
80
+ * and dispatches as ONE batch per affected query on the ordinary event stream. */
81
+ serverBatchEnd(): void;
82
+ }
83
+ /** Convenience: init the wasm + return a ready local {@link Store}. */
84
+ export declare function createWasmStore<S extends ColsMap>(schema: Schema<S>): Promise<Store<S>>;
85
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AASA,OAAO,EAAE,KAAK,EAAa,MAAM,gBAAgB,CAAC;AAClD,OAAO,KAAK,EACV,GAAG,EACH,OAAO,EACP,WAAW,EACX,OAAO,EACP,QAAQ,EACR,OAAO,EACP,MAAM,EACP,MAAM,gBAAgB,CAAC;AAExB,cAAc,gBAAgB,CAAC;AAa/B;;qFAEqF;AACrF,MAAM,WAAW,YAAY;IAC3B,GAAG,CAAC,KAAK,EAAE,MAAM,EAAE,GAAG,EAAE,OAAO,EAAE,GAAG,IAAI,CAAC;IACzC,MAAM,CAAC,KAAK,EAAE,MAAM,EAAE,GAAG,EAAE,OAAO,EAAE,GAAG,IAAI,CAAC;IAC5C,IAAI,CAAC,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,EAAE,MAAM,EAAE,OAAO,EAAE,GAAG,IAAI,CAAC;IAChE,GAAG,CAAC,KAAK,EAAE,MAAM,EAAE,EAAE,EAAE,OAAO,EAAE,GAAG,OAAO,EAAE,GAAG,SAAS,CAAC;IACzD,MAAM,IAAI,KAAK,CAAC;QAAE,OAAO,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,OAAO,EAAE,CAAA;KAAE,CAAC,CAAC;IACxD,QAAQ,IAAI,IAAI,CAAC;CAClB;AAED,mFAAmF;AACnF,MAAM,MAAM,aAAa,GACrB;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,KAAK,CAAC;IAAC,GAAG,EAAE,OAAO,EAAE,CAAA;CAAE,GAC9C;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,QAAQ,CAAC;IAAC,GAAG,EAAE,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C9B,gBAAgB,CAAC,MAAM,EAAE,aAAa,EAAE,GAAG,IAAI;IAI/C;;uFAEmF;IACnF,cAAc,IAAI,IAAI;CAGvB;AAED,uEAAuE;AACvE,wBAAsB,eAAe,CAAC,CAAC,SAAS,OAAO,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAG7F"}
package/dist/index.js ADDED
@@ -0,0 +1,154 @@
1
+ // @rindle/wasm — the WASM backend: the in-process IVM engine (src/wasm/db.rs) behind the
2
+ // @rindle/client `Backend` seam (WASM-CLIENT-DESIGN.md §2.1). Also re-exports @rindle/client so a
3
+ // local app can import everything from here.
4
+ //
5
+ // The wasm is a `--target web` ESM artifact (packages/wasm/pkg, built by ./build.sh): it
6
+ // needs an explicit, one-time init — `await initWasm()` — before constructing a backend.
7
+ // In Node the bytes are read from the package; in a browser/bundler the wasm is fetched.
8
+ import init, { Db } from "../pkg/rindle.js";
9
+ import { Store, tableSpec } from "@rindle/client";
10
+ export * from "@rindle/client";
11
+ let initialized = null;
12
+ /** Initialize the wasm module (idempotent). Call once at startup before `new WasmBackend`
13
+ * / `createWasmStore`. Browser/bundler: no args (the wasm is fetched). Node: the bytes are
14
+ * read from the package. Pass `moduleOrPath` to override (a `WebAssembly.Module`, URL, or bytes). */
15
+ export function initWasm(moduleOrPath) {
16
+ if (!initialized) {
17
+ initialized = (async () => {
18
+ if (moduleOrPath !== undefined) {
19
+ await init({ module_or_path: moduleOrPath });
20
+ }
21
+ else if (globalThis.process?.versions?.node) {
22
+ const { readFile } = await import("node:fs/promises");
23
+ const bytes = await readFile(new URL("../pkg/rindle_bg.wasm", import.meta.url));
24
+ await init({ module_or_path: bytes });
25
+ }
26
+ else {
27
+ await init();
28
+ }
29
+ })();
30
+ }
31
+ return initialized;
32
+ }
33
+ export class WasmBackend {
34
+ db;
35
+ handler = () => { };
36
+ // Non-reentrant delivery (#15): commits dispatch through a FIFO queue. A subscriber that
37
+ // synchronously triggers another write enqueues that commit's batches; they drain only after
38
+ // the in-flight commit's batches finish, preserving per-query commit order regardless of what
39
+ // subscribers do.
40
+ dispatchQueue = [];
41
+ draining = false;
42
+ constructor(schema) {
43
+ this.db = new Db();
44
+ for (const name of Object.keys(schema.tables)) {
45
+ this.db.registerTable(name, tableSpec(schema.tables[name]));
46
+ }
47
+ }
48
+ /** Register an additional base table after construction — for a SYNTHETIC aggregate table
49
+ * (`AGGREGATE-SYNC-DESIGN.md` §3.3) that is not in the typed schema. The
50
+ * `NormalizedBackend` registers each such `__agg_*` table once, before a query that reads
51
+ * it, so the local engine can join to it (the relationship `count` it backs is shipped by
52
+ * the server, never recomputed). */
53
+ registerTable(name, spec) {
54
+ this.db.registerTable(name, spec);
55
+ }
56
+ /** Remove a synthetic aggregate table registered by {@link registerTable}, once the last
57
+ * query reading it has been unregistered (`AGGREGATE-SYNC-DESIGN.md` §4): frees the engine
58
+ * source + its optimistic baseline so aggregate state is reclaimed, not permanent. Throws
59
+ * if a query still reads it (the backend refcounts readers, so it calls this only at 0). */
60
+ unregisterTable(name) {
61
+ this.db.unregisterTable(name);
62
+ }
63
+ registerQuery(qid, ast) {
64
+ const r = this.db.query(qid, ast);
65
+ this.handler(qid, { type: "hello", schema: r.schema, comparatorVersion: r.comparatorVersion });
66
+ this.handler(qid, { type: "snapshot", adds: r.snapshot, last: true });
67
+ }
68
+ unregisterQuery(qid) {
69
+ this.db.destroyQuery(qid);
70
+ }
71
+ mutate(mutations) {
72
+ const tx = this.db.write();
73
+ for (const m of mutations) {
74
+ if (m.op === "add")
75
+ tx.add(m.table, m.row);
76
+ else if (m.op === "remove")
77
+ tx.remove(m.table, m.row);
78
+ else
79
+ tx.edit(m.table, m.old, m.new);
80
+ }
81
+ this.dispatch(tx.commit());
82
+ return Promise.resolve();
83
+ }
84
+ onEvent(handler) {
85
+ this.handler = handler;
86
+ }
87
+ /** Deliver one commit's per-query batches. Non-reentrant (#15): if a delivery is already in
88
+ * progress (a subscriber re-entered via write()), enqueue and let the active drain pick it
89
+ * up FIFO, so each query folds commits in order. Per-query isolated (#11): a view's fold or
90
+ * subscriber throwing does NOT drop sibling queries' batches — the first error is re-raised
91
+ * only after every query has been delivered. */
92
+ dispatch(batches) {
93
+ this.dispatchQueue.push(batches);
94
+ if (this.draining)
95
+ return; // an outer drain is running; it will deliver this set
96
+ this.draining = true;
97
+ let firstError;
98
+ let hasError = false;
99
+ try {
100
+ while (this.dispatchQueue.length) {
101
+ const next = this.dispatchQueue.shift();
102
+ for (const b of next) {
103
+ try {
104
+ this.handler(b.queryId, { type: "batch", events: b.events });
105
+ }
106
+ catch (err) {
107
+ if (!hasError) {
108
+ hasError = true;
109
+ firstError = err;
110
+ }
111
+ }
112
+ }
113
+ }
114
+ }
115
+ finally {
116
+ this.draining = false;
117
+ }
118
+ if (hasError)
119
+ throw firstError;
120
+ }
121
+ // --- the optimistic-cycle surface (OPTIMISTIC-WRITES-DESIGN.md §1/§3/§9) ----------
122
+ //
123
+ // `@rindle/optimistic` drives the engine's fork/rebase loop through these three; the
124
+ // plain local path never calls them.
125
+ /** Run `f` against a raw staged write txn (with the §4.1 `get` read path), commit, and
126
+ * dispatch the resulting batches on the ordinary event stream. Inside an open server
127
+ * batch the engine buffers the events into the cycle instead (commit returns `[]`),
128
+ * so re-invocations dispatch nothing here — delivery is `serverBatchEnd`'s. */
129
+ writeWith(f) {
130
+ const tx = this.db.write();
131
+ f(tx);
132
+ this.dispatch(tx.commit());
133
+ }
134
+ /** Open a §1.3 reconcile cycle against the coherent server delta: the engine rewinds
135
+ * (optimistic layer un-applied, delta folded in, `sync` re-forked) and starts
136
+ * buffering. Re-invoke the still-pending mutators via {@link writeWith}, then call
137
+ * {@link serverBatchEnd}. On error the optimistic state is poisoned — discard the
138
+ * backend and re-hydrate. */
139
+ serverBatchBegin(deltas) {
140
+ this.db.serverBatchBegin(deltas);
141
+ }
142
+ /** Close the cycle: the whole buffered stream (rewind + re-invocations) coalesces to
143
+ * the minimal net per query (§3 — a confirmed-correct prediction delivers nothing)
144
+ * and dispatches as ONE batch per affected query on the ordinary event stream. */
145
+ serverBatchEnd() {
146
+ this.dispatch(this.db.serverBatchEnd());
147
+ }
148
+ }
149
+ /** Convenience: init the wasm + return a ready local {@link Store}. */
150
+ export async function createWasmStore(schema) {
151
+ await initWasm();
152
+ return new Store(schema, new WasmBackend(schema));
153
+ }
154
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,yFAAyF;AACzF,kGAAkG;AAClG,6CAA6C;AAC7C,EAAE;AACF,yFAAyF;AACzF,yFAAyF;AACzF,yFAAyF;AAEzF,OAAO,IAAI,EAAE,EAAE,EAAE,EAAE,MAAM,kBAAkB,CAAC;AAC5C,OAAO,EAAE,KAAK,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAWlD,cAAc,gBAAgB,CAAC;AA+B/B,IAAI,WAAW,GAAyB,IAAI,CAAC;AAE7C;;sGAEsG;AACtG,MAAM,UAAU,QAAQ,CAAC,YAAsB;IAC7C,IAAI,CAAC,WAAW,EAAE,CAAC;QACjB,WAAW,GAAG,CAAC,KAAK,IAAI,EAAE;YACxB,IAAI,YAAY,KAAK,SAAS,EAAE,CAAC;gBAC/B,MAAM,IAAI,CAAC,EAAE,cAAc,EAAE,YAAY,EAAE,CAAC,CAAC;YAC/C,CAAC;iBAAM,IAAK,UAA6D,CAAC,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,CAAC;gBAClG,MAAM,EAAE,QAAQ,EAAE,GAAG,MAAM,MAAM,CAAC,kBAAkB,CAAC,CAAC;gBACtD,MAAM,KAAK,GAAG,MAAM,QAAQ,CAAC,IAAI,GAAG,CAAC,uBAAuB,EAAE,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC;gBAChF,MAAM,IAAI,CAAC,EAAE,cAAc,EAAE,KAAK,EA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Ae,CAAoB,MAAiB;IACxE,MAAM,QAAQ,EAAE,CAAC;IACjB,OAAO,IAAI,KAAK,CAAC,MAAM,EAAE,IAAI,WAAW,CAAC,MAAM,CAAC,CAAC,CAAC;AACpD,CAAC"}
package/package.json ADDED
@@ -0,0 +1,43 @@
1
+ {
2
+ "name": "@rindle/wasm",
3
+ "version": "0.1.0-rc.5",
4
+ "license": "Apache-2.0",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "git+https://github.com/rindle-sh/rindle.git",
8
+ "directory": "packages/wasm"
9
+ },
10
+ "type": "module",
11
+ "description": "WASM backend for @rindle/client — the in-process IVM engine behind the Backend seam.",
12
+ "main": "./dist/index.js",
13
+ "types": "./dist/index.d.ts",
14
+ "sideEffects": false,
15
+ "exports": {
16
+ ".": {
17
+ "@rindle/source": "./src/index.ts",
18
+ "types": "./dist/index.d.ts",
19
+ "default": "./dist/index.js"
20
+ }
21
+ },
22
+ "files": [
23
+ "dist",
24
+ "src",
25
+ "pkg",
26
+ "build.sh",
27
+ "README.md"
28
+ ],
29
+ "dependencies": {
30
+ "@rindle/client": "0.1.0-rc.5"
31
+ },
32
+ "devDependencies": {
33
+ "@types/node": "^22.10.0",
34
+ "typescript": "^5.7.0"
35
+ },
36
+ "scripts": {
37
+ "build": "tsc -p tsconfig.build.json",
38
+ "build:wasm": "./build.sh",
39
+ "typecheck": "tsc --noEmit",
40
+ "test": "node test/bundle-size.mjs && node --conditions=@rindle/source test/e2e.mjs && node --conditions=@rindle/source test/one-start.e2e.mjs && node --conditions=@rindle/source test/repro-high.e2e.mjs && node --conditions=@rindle/source test/partial-write.e2e.mjs",
41
+ "test:browser": "node test/browser-smoke.mjs"
42
+ }
43
+ }