@wazootech/worlds-cloudflare 0.0.0-stage → 0.15.6
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 +21 -0
- package/README.md +359 -2
- package/dist/d1-connection-driver-DfBsnVwn.d.ts +71 -0
- package/dist/d1-provenance-sql-jn_cwWxX.js +99 -0
- package/dist/d1-quad-insert-sql-B4ZiZZe8.js +313 -0
- package/dist/d1-rdfjs-store-read-2QTEEe_a.js +64 -0
- package/dist/d1-schema-builder-DmrQfhKJ.js +86 -0
- package/dist/d1-schema-builder-sx3v-XjI.d.ts +42 -0
- package/dist/index.d.ts +205 -0
- package/dist/index.js +354 -0
- package/dist/mod-BRtbH8pa.d.ts +52 -0
- package/dist/mod-Do_hSIzo.d.ts +452 -0
- package/dist/mod-L9cQ_Ztm.d.ts +192 -0
- package/dist/project-search-chunks-options-qI9m5FWz.js +166 -0
- package/dist/quad-store-DX7Nqyjw.js +398 -0
- package/dist/quad-store.d.ts +2 -0
- package/dist/quad-store.js +1 -0
- package/dist/rdfjs-store-B3w5noFV.js +668 -0
- package/dist/rdfjs-store.d.ts +2 -0
- package/dist/rdfjs-store.js +1 -0
- package/dist/schema.d.ts +2 -0
- package/dist/schema.js +1 -0
- package/dist/search-index-DVbbsc3z.js +609 -0
- package/dist/search-index.d.ts +2 -0
- package/dist/search-index.js +1 -0
- package/package.json +84 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Wazoo Technologies
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,360 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @wazootech/worlds-cloudflare
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Durable backend for the Worlds client
|
|
4
|
+
([`@wazootech/worlds-sdk`](https://www.npmjs.com/package/@wazootech/worlds-sdk)) targeting Cloudflare-native
|
|
5
|
+
deployments: **D1** first, with optional **Vectorize** (semantic search) and
|
|
6
|
+
**Workers AI** (embeddings) integrations.
|
|
7
|
+
|
|
8
|
+
Part of the Worlds durable-backend family alongside
|
|
9
|
+
[`@wazootech/worlds-libsql`](https://github.com/wazootech/worlds-libsql) and
|
|
10
|
+
[`@wazootech/worlds-postgres`](https://github.com/wazootech/worlds-postgres). The
|
|
11
|
+
provider-strategy vocabulary is backend-internal (per the de-escalated seam
|
|
12
|
+
decision,
|
|
13
|
+
[worlds-sdk-ts#170](https://github.com/wazootech/worlds-sdk-ts/issues/170));
|
|
14
|
+
cross-backend interchangeability lives at the `@wazootech/worlds-sdk` `WorldsSdk` seam.
|
|
15
|
+
|
|
16
|
+
## Status
|
|
17
|
+
|
|
18
|
+
Active development. The D1 quad store layer ([`D1RdfjsStore`](#exports) +
|
|
19
|
+
`D1SchemaBuilder` + miniflare substrate), the keyword search index
|
|
20
|
+
(`CloudflareSearchIndex`, FTS5), the SDK factory (`createCloudflareWorldsSdk`),
|
|
21
|
+
and the shared parity suite (against `@wazootech/worlds-sdk/memory`'s
|
|
22
|
+
`createMemoryWorldsSdk`) are implemented and tested. So is semantic search with
|
|
23
|
+
Vectorize: pass `vectorize` and an `embeddingService`. An embedding service for
|
|
24
|
+
Workers AI remains planned. The phased plan is
|
|
25
|
+
tracked in
|
|
26
|
+
[worlds-cloudflare#7](https://github.com/wazootech/worlds-cloudflare/issues/7).
|
|
27
|
+
|
|
28
|
+
**World scoping with Vectorize.** One Vectorize index is shared by every world,
|
|
29
|
+
so `createCloudflareWorldsSdk` requires `worldId` whenever `vectorize` is set
|
|
30
|
+
and throws otherwise. Every vector is stored with `world_id` metadata, every
|
|
31
|
+
vector query is filtered on it, and vector ids are namespaced per world, so
|
|
32
|
+
identical triple text in two worlds never shares a vector
|
|
33
|
+
([worlds-cloudflare#41](https://github.com/wazootech/worlds-cloudflare/issues/41)).
|
|
34
|
+
|
|
35
|
+
**Vector sync is reported, not swallowed.** A failed vector upsert or
|
|
36
|
+
stale-vector delete never fails an import (D1 is the source of truth and keyword
|
|
37
|
+
search keeps serving), but it is logged as a structured `[vector-sync]` error
|
|
38
|
+
and counted. `CloudflareSearchIndex.reindex()` returns `vectorSync`
|
|
39
|
+
(`attempted`, `upserted`, `failedUpserts`, `staleDeleteFailures`, `errors`;
|
|
40
|
+
`embeddingFailures` is always 0, kept so report schemas keep parsing), and
|
|
41
|
+
rerunning reindex repairs the drift
|
|
42
|
+
([worlds-cloudflare#40](https://github.com/wazootech/worlds-cloudflare/issues/40)).
|
|
43
|
+
|
|
44
|
+
**An embedding failure throws.** Like every `worlds-*` backend, a commit or
|
|
45
|
+
reindex whose embedding service fails (or returns vectors of the wrong length)
|
|
46
|
+
rejects before anything is written, so the caller can retry. Writes therefore
|
|
47
|
+
fail while the embedding service is down; there is no keyword-only fallback and
|
|
48
|
+
no stale marker.
|
|
49
|
+
|
|
50
|
+
**Commit path.** Commits run through the shared `commitSqlPatch` and reindex
|
|
51
|
+
through `rebuildSqlSearchIndex` from `@wazootech/worlds-sqlite/sql-core`; this package
|
|
52
|
+
only supplies a D1 driver and dialect (`src/cloudflare/commit/`). Differences
|
|
53
|
+
from the shared behavior, each forced by the platform or kept for hosted
|
|
54
|
+
consumers:
|
|
55
|
+
|
|
56
|
+
- **Atomicity is bounded by one `batch()` call.** D1's atomic unit is a single
|
|
57
|
+
`batch()`. A commit that fits in one batch under both limits, at most
|
|
58
|
+
`maxWriteBatchSize` statements (default 2,000) and at most `maxBatchWeight`
|
|
59
|
+
estimated serialized bytes (default 16 MiB, `DEFAULT_D1_MAX_BATCH_WEIGHT`), is
|
|
60
|
+
one atomic batch, including its chunk rows, and a failed replace import keeps
|
|
61
|
+
the old graph. A larger commit takes the core's chunked fallback, which fills
|
|
62
|
+
each batch up to both limits: not atomic, a failure removes the quads written
|
|
63
|
+
so far, and a replace import that fails after its wipe leaves an empty graph.
|
|
64
|
+
Each quad costs about two statements (a quad row and a chunk row). By the
|
|
65
|
+
estimate below, an import stays atomic up to about 1,000 quads with 384-dim
|
|
66
|
+
vectors (the count limit binds) and about 640 quads with 1,536-dim vectors
|
|
67
|
+
(the byte budget binds); beyond that it takes the chunked fallback. Raise or
|
|
68
|
+
lower either limit through the `maxWriteBatchSize` and `maxBatchWeight`
|
|
69
|
+
options, mindful of the payload limit below. The default was 100 before the
|
|
70
|
+
first real-D1 measurement (imports of 50 or more quads took the non-atomic
|
|
71
|
+
fallback) and 750 in an unreleased build; this release replaces it with the
|
|
72
|
+
2,000 count plus the byte guard. Cloudflare documents no per-batch statement
|
|
73
|
+
cap (read 2026-11-22,
|
|
74
|
+
<https://developers.cloudflare.com/d1/platform/limits/>): a `db.batch()`
|
|
75
|
+
"counts as a single query" against the 1000 (paid) / 50 (free) queries per
|
|
76
|
+
invocation, the 30 second query duration "also applies to the entire batch
|
|
77
|
+
call", and the 100 bound parameters and 100,000 byte statement length are
|
|
78
|
+
per-statement limits that still apply inside a batch (the lookup chunk size
|
|
79
|
+
stays 100). The binding has one more limit, found by measurement: **the
|
|
80
|
+
Worker-to-D1 RPC rejects a `batch()` whose serialized arguments exceed 32
|
|
81
|
+
MiB**
|
|
82
|
+
(`D1_ERROR: Serialized RPC arguments or return values are limited to
|
|
83
|
+
32MiB`).
|
|
84
|
+
It is a byte limit, so the safe statement count depends on row size.
|
|
85
|
+
- **Measured on a real D1 throwaway database, 2026-11-22** (Worker binding,
|
|
86
|
+
`wrangler dev --remote`, the repo's `quads`/`chunks` schema with the 7 quad
|
|
87
|
+
indexes, the chunk index, the FTS5 table and its triggers; one run each, so
|
|
88
|
+
timings are indicative, not statistical). "Mixed" alternates a quad row and
|
|
89
|
+
a chunk row, as an import does; "chunks" is chunk rows only (a reindex).
|
|
90
|
+
Chunk rows carry a float32 BLOB vector and about 200 characters of text.
|
|
91
|
+
|
|
92
|
+
| statements | row kind | payload (raw) | wall ms (Worker) | result |
|
|
93
|
+
| ---------- | ------------------------- | ------------- | ---------------- | ------------------------------------- |
|
|
94
|
+
| 100 | mixed, 384-dim | 0.11 MB | 99 (87 on rerun) | ok |
|
|
95
|
+
| 500 | mixed, 384-dim | 0.57 MB | 268 | ok |
|
|
96
|
+
| 1,000 | mixed, 384-dim | 1.1 MB | 387 | ok |
|
|
97
|
+
| 2,000 | mixed, 384-dim | 2.3 MB | 710 | ok |
|
|
98
|
+
| 4,000 | mixed, 384-dim | 4.6 MB | 1,411 | ok |
|
|
99
|
+
| 2,000 | chunks, 384-dim | 4.0 MB | 1,034 | ok |
|
|
100
|
+
| 3,000 | chunks, 384-dim | 6.0 MB | 2,044 | ok |
|
|
101
|
+
| 4,000 | chunks, 384-dim | 8.0 MB | 3,243 | ok |
|
|
102
|
+
| 100 | mixed, 1,536-dim | 0.34 MB | 121 | ok |
|
|
103
|
+
| 500 | mixed, 1,536-dim | 1.7 MB | 391 | ok |
|
|
104
|
+
| 1,000 | mixed, 1,536-dim | 3.4 MB | 870 | ok |
|
|
105
|
+
| 2,000 | mixed, 1,536-dim | 6.9 MB | 1,425 | ok (about 22.7 MB serialized) |
|
|
106
|
+
| 4,000 | mixed, 1,536-dim | 13.8 MB | n/a | rejected, 45.3 MB serialized > 32 MiB |
|
|
107
|
+
| 1,000 | chunks, 1,536-dim | 6.6 MB | 1,511 | ok |
|
|
108
|
+
| 1,400 | chunks, 1,536-dim | 9.2 MB | 1,707 | ok |
|
|
109
|
+
| 1,500 | chunks, 1,536-dim | 9.9 MB | 2,584 | ok |
|
|
110
|
+
| 1,510 | chunks, 1,536-dim | 10.0 MB | n/a | rejected, 33.6 MB serialized > 32 MiB |
|
|
111
|
+
| 2,000 | chunks, 1,536-dim (heavy) | 13.2 MB | n/a | rejected, 44.5 MB serialized > 32 MiB |
|
|
112
|
+
|
|
113
|
+
A 1,536-dim chunk row serializes to about 22 KB (3.6x its raw BLOB bytes),
|
|
114
|
+
so pure heavy-chunk batches top out near 1,500 statements, while 2,000
|
|
115
|
+
statements were accepted at every other measured shape. Time was never the
|
|
116
|
+
constraint: every accepted batch finished in under 3 s against the
|
|
117
|
+
documented 30 s, and D1 reported under 0.6 s of summed SQL time for every
|
|
118
|
+
batch up to 2,000 statements (1.7 s at 4,000 chunk rows). **Atomic
|
|
119
|
+
rollback** was verified on real D1: a batch whose last statement duplicated
|
|
120
|
+
an earlier primary key (after 500, then 2,000 statements, 384-dim and
|
|
121
|
+
1,536-dim) failed with `UNIQUE constraint failed` and left zero rows in
|
|
122
|
+
`quads` and `chunks`; a last statement against a missing table did the same
|
|
123
|
+
(rejected before any row was written).
|
|
124
|
+
|
|
125
|
+
- **The byte estimate is an ESTIMATE, calibrated from those points.** The
|
|
126
|
+
commit driver weighs each statement as its SQL text length, 64 bytes of
|
|
127
|
+
overhead, and its bound parameters: strings by UTF-16 code units, BLOBs (the
|
|
128
|
+
float32 vector) at 4 bytes per raw byte (measured about 3.6, rounded up to
|
|
129
|
+
err high), numbers, booleans and null at 8 bytes. It puts a 1,536-dim chunk
|
|
130
|
+
row near 25 KB, a 768-dim one near 13 KB and a 384-dim one near 7 KB, so
|
|
131
|
+
2,000 heavy chunk rows estimate well over 16 MiB and 2,000 mixed 384-dim
|
|
132
|
+
rows do not. The unit tests check that the estimate is not below the
|
|
133
|
+
serialized sizes measured above, using the repo's own statement builders; no
|
|
134
|
+
real D1 call checked the estimator itself. The 16 MiB budget leaves 2x
|
|
135
|
+
headroom under 32 MiB for its error. Both are exported and overridable
|
|
136
|
+
(`d1StatementWeight`, `DEFAULT_D1_MAX_BATCH_WEIGHT`, the `maxBatchWeight`
|
|
137
|
+
option).
|
|
138
|
+
- **This change was not re-verified on a real D1.** The measurements above
|
|
139
|
+
predate the byte budget; the budget, the 2,000 default and the estimator are
|
|
140
|
+
tested on miniflare and with fakes only, and miniflare enforces no 32 MiB
|
|
141
|
+
limit.
|
|
142
|
+
- **Not measured:** the estimator and the 16 MiB budget on a real D1 after
|
|
143
|
+
this change, concurrent writers or load, production latency under realistic
|
|
144
|
+
contention (this was an idle new database from one location, WNAM), batches
|
|
145
|
+
above 4,000 statements of 384-dim rows (the 32 MiB bound suggests about
|
|
146
|
+
6,000 chunk rows of 384 dimensions), chunk text far longer than 200
|
|
147
|
+
characters (a larger `value`/`fts_value` shrinks the safe count), and
|
|
148
|
+
databases with large existing tables. Production batch timing and the
|
|
149
|
+
`Too many API requests by single Worker invocation` limit were not
|
|
150
|
+
exercised.
|
|
151
|
+
- **Vectorize is outside D1.** Vectors sync after the D1 write lands, so a
|
|
152
|
+
Vectorize failure is logged drift (above), never a rollback.
|
|
153
|
+
- **Deleting a quad leaves its chunk rows** until a reindex or the hosted API's
|
|
154
|
+
orphan cleanup, because those rows are the only record of the Vectorize ids to
|
|
155
|
+
remove.
|
|
156
|
+
- **`searchIndexOnImport` defaults to `"incremental"`**, the shared default: an
|
|
157
|
+
import projects chunks and embeds only the quads it writes, so a failed
|
|
158
|
+
embedding throws before anything is written. `"deferred"` (persist quads, then
|
|
159
|
+
rebuild the whole world's index) is an option, not the default. Measured on
|
|
160
|
+
miniflare (worlds-cloudflare#92), `incremental` issues the same number of
|
|
161
|
+
statements and about the same number of `batch()` calls as `deferred`, embeds
|
|
162
|
+
fewer texts when merging into a populated world, and leaves nothing behind
|
|
163
|
+
when embedding fails; `deferred` leaves quads without chunk rows.
|
|
164
|
+
|
|
165
|
+
This package consumes the shared, driver-free SQL plan layer from
|
|
166
|
+
[`@wazootech/worlds-sqlite/sql-core`](https://www.npmjs.com/package/@wazootech/worlds-sqlite) — the FTS5
|
|
167
|
+
sanitizer/stopwords, `buildChunkFtsValue`, `buildSearchResultId`, the
|
|
168
|
+
`chunks_fts` DDL/triggers emitters, filter-clause helpers, and the keyword
|
|
169
|
+
branch plan. The D1-specific pieces stay local: the `chunks` table's `F32_BLOB`
|
|
170
|
+
vector column reserved for Vectorize sync, the blob-bind chunk insert, and the
|
|
171
|
+
empty-query fallback statement.
|
|
172
|
+
|
|
173
|
+
## D1 schema rollout
|
|
174
|
+
|
|
175
|
+
The D1 store creates its canonical schema on an empty database and verifies an
|
|
176
|
+
existing canonical schema before serving traffic. It does not migrate older
|
|
177
|
+
UID-era tables or preserve their rows. Reset only a D1 that still has those tables;
|
|
178
|
+
startup rejects an incompatible schema instead of changing it in place.
|
|
179
|
+
|
|
180
|
+
## Inference (opt-in, experimental)
|
|
181
|
+
|
|
182
|
+
A world can opt in to OWL 2 RL materialization with
|
|
183
|
+
[`@wazootech/reasoner`](https://www.npmjs.com/package/@wazootech/reasoner). It is off by default; a
|
|
184
|
+
world that does not set `inference` behaves exactly as before.
|
|
185
|
+
|
|
186
|
+
```ts
|
|
187
|
+
const sdk = await createCloudflareWorldsSdk({
|
|
188
|
+
database: env.DB,
|
|
189
|
+
worldId,
|
|
190
|
+
inference: { enabled: true }, // graphs: "per-graph" (default) | "union"
|
|
191
|
+
});
|
|
192
|
+
```
|
|
193
|
+
|
|
194
|
+
- **Storage.** Inferred quads are stored in `quads` with `derived = 1`; asserted
|
|
195
|
+
quads have `derived = 0`. A quad that is both is stored once, as asserted.
|
|
196
|
+
Inferred quads are visible to SPARQL and export like any other. They are not
|
|
197
|
+
chunked for search on commit.
|
|
198
|
+
- **Write path.** Each commit loads the world's asserted quads, rebuilds a
|
|
199
|
+
`Reasoner`, then uses `retract` for deletions and `extend` for insertions to
|
|
200
|
+
get exactly the inferred rows to remove and add. Removal only ever deletes
|
|
201
|
+
`derived = 1` rows. Retracting an asserted quad that is still entailed keeps
|
|
202
|
+
it as a derived row.
|
|
203
|
+
- **Named graphs.** Default `"per-graph"`: entailment sees every graph; an
|
|
204
|
+
inferred quad is listed in the graph(s) that entail it alone, else in
|
|
205
|
+
`https://wazoo.dev/ns/reasoner#derived`. `"union"` lists everything in the
|
|
206
|
+
default graph.
|
|
207
|
+
- **Limits.** The reasoner has no serialize/restore, so every commit costs a
|
|
208
|
+
read and run over all asserted quads. `maxAssertedQuads` (default 100000)
|
|
209
|
+
fails a commit with `InferenceSizeGuardError`, before any write, when the
|
|
210
|
+
world is larger. Commits that go through `D1RdfjsStore` directly (not the SDK
|
|
211
|
+
or SPARQL update) do not infer. `include`/`exclude` filters narrow the patch,
|
|
212
|
+
not the reasoning input.
|
|
213
|
+
- **Shared databases.** Before 0.12.0 a world-scoped `quads` table keyed rows by
|
|
214
|
+
`quad_id` alone, so two worlds holding the same triple shared one row (#60).
|
|
215
|
+
Existing databases need `migrations/0002-quads-world-scoped-key.sql`, run
|
|
216
|
+
after `0001`; new databases get the `(world_id, quad_id)` key.
|
|
217
|
+
- **Enabling on an existing world.** Add the column with
|
|
218
|
+
`migrations/0001-quads-derived-column.sql` (or start from an empty database).
|
|
219
|
+
Enabling alone does not back-fill: inferred rows appear only for later
|
|
220
|
+
changes. To materialize inference for data already stored, call
|
|
221
|
+
`backfillInference({ database, worldId, inference })`. It runs the reasoner
|
|
222
|
+
once over the asserted quads, clears the world's inferred rows, writes the
|
|
223
|
+
closure, and reports counts and inconsistencies. It is idempotent, honors
|
|
224
|
+
`maxAssertedQuads` before any write, and never touches asserted rows. The
|
|
225
|
+
clear and the writes are separate batches, so after a failure run it again.
|
|
226
|
+
- **Inconsistencies.** `backfillInference` returns the reasoner's
|
|
227
|
+
`inconsistencies`; a commit does not report them and they do not block the
|
|
228
|
+
write. SHACL validation does not exist in this package; if added, it must run
|
|
229
|
+
after inference.
|
|
230
|
+
|
|
231
|
+
## Provenance (opt-in)
|
|
232
|
+
|
|
233
|
+
A world can keep a record of when each quad was written or removed, by what, from
|
|
234
|
+
what source, and what it replaced. It is off by default.
|
|
235
|
+
|
|
236
|
+
```ts
|
|
237
|
+
const sdk = await createCloudflareWorldsSdk({
|
|
238
|
+
database: env.DB,
|
|
239
|
+
worldId,
|
|
240
|
+
provenance: { enabled: true },
|
|
241
|
+
});
|
|
242
|
+
await sdk.import({ source, provenance: { writer: "agent-1", source: "feed" } });
|
|
243
|
+
const { results } = await sdk.provenance({ subject });
|
|
244
|
+
```
|
|
245
|
+
|
|
246
|
+
- **Storage.** Records live in a `provenance` table beside `quads`, keyed by quad
|
|
247
|
+
hash. They hold no quad content, so they show that a quad was removed, not what
|
|
248
|
+
it said. Opening a world with the option on creates the table if it is missing;
|
|
249
|
+
no migration is needed.
|
|
250
|
+
- **What is recorded.** Only real changes. Importing quads the world already holds
|
|
251
|
+
adds nothing, where the SDK's in-memory store records every insertion again.
|
|
252
|
+
Quads written before the option was on have no records, and none are made up.
|
|
253
|
+
- **Atomicity.** Records are written in the same D1 batch as their quads. A commit
|
|
254
|
+
too large for one batch is not atomic, with or without provenance; if it fails
|
|
255
|
+
partway, its cleanup corrects the records too.
|
|
256
|
+
- **Writers.** Imports and SPARQL updates both take `provenance`:
|
|
257
|
+
`sdk.sparql({ query, provenance: { writer } })`. Without it they are recorded
|
|
258
|
+
with a time only. Inferred quads have no records. Writes that go
|
|
259
|
+
through `D1RdfjsStore` directly, or through an SDK without the option, are not
|
|
260
|
+
recorded.
|
|
261
|
+
- **Cost.** Measured on miniflare with 1,000 and 10,000 short quads: 2 more rows
|
|
262
|
+
written per new quad (11 instead of 9) and about 230 bytes per record. A
|
|
263
|
+
replace import also reads the whole world first.
|
|
264
|
+
- **Deletion.** `purgeWorld` removes a world's records. A replace import keeps
|
|
265
|
+
them.
|
|
266
|
+
|
|
267
|
+
## Install
|
|
268
|
+
|
|
269
|
+
```sh
|
|
270
|
+
npm install @wazootech/worlds-cloudflare
|
|
271
|
+
```
|
|
272
|
+
|
|
273
|
+
Use it in a Worker that has a [D1](https://developers.cloudflare.com/d1/) database
|
|
274
|
+
bound as `DB` and the `nodejs_compat` flag, because the SDK uses `node:events`:
|
|
275
|
+
|
|
276
|
+
```jsonc
|
|
277
|
+
// wrangler.jsonc
|
|
278
|
+
{
|
|
279
|
+
"name": "my-worker",
|
|
280
|
+
"main": "src/index.ts",
|
|
281
|
+
"compatibility_date": "2026-07-01",
|
|
282
|
+
"compatibility_flags": ["nodejs_compat"],
|
|
283
|
+
"d1_databases": [
|
|
284
|
+
{ "binding": "DB", "database_name": "my-worlds", "database_id": "<id>" },
|
|
285
|
+
],
|
|
286
|
+
}
|
|
287
|
+
```
|
|
288
|
+
|
|
289
|
+
```ts
|
|
290
|
+
// src/index.ts
|
|
291
|
+
import { createCloudflareWorldsSdk } from "@wazootech/worlds-cloudflare";
|
|
292
|
+
|
|
293
|
+
export default {
|
|
294
|
+
async fetch(_request: Request, env: { DB: D1Database }): Promise<Response> {
|
|
295
|
+
const sdk = await createCloudflareWorldsSdk({
|
|
296
|
+
database: env.DB,
|
|
297
|
+
worldId: "world-1",
|
|
298
|
+
});
|
|
299
|
+
await sdk.import({
|
|
300
|
+
source: {
|
|
301
|
+
kind: "serialized",
|
|
302
|
+
contentType: "text/turtle",
|
|
303
|
+
data: `<http://example.com/alice> <http://example.com/bio> "Explores caves" .`,
|
|
304
|
+
},
|
|
305
|
+
});
|
|
306
|
+
return Response.json(await sdk.search({ query: "caves" }));
|
|
307
|
+
},
|
|
308
|
+
};
|
|
309
|
+
```
|
|
310
|
+
|
|
311
|
+
It also works in a Durable Object. The package imports nothing that only Workers
|
|
312
|
+
have, so it loads on Node.js 22.13 or newer, Bun and Deno too, for tests with a D1
|
|
313
|
+
database from [miniflare](https://developers.cloudflare.com/workers/testing/miniflare/).
|
|
314
|
+
|
|
315
|
+
Versions up to 0.15.5 were published on JSR as `@worlds/cloudflare`. Only the name,
|
|
316
|
+
the registry and the license changed: every import path and export is the same, and
|
|
317
|
+
so is the database. Move every Wazoo package in an app at once, because an app that
|
|
318
|
+
mixes old and new names loads two copies of the SPARQL engine, and two copies can
|
|
319
|
+
merge unrelated blank nodes in stored data.
|
|
320
|
+
|
|
321
|
+
## Exports
|
|
322
|
+
|
|
323
|
+
| Export | Role |
|
|
324
|
+
| ---------------- | ------------------------------------------------------------------------- |
|
|
325
|
+
| `.` | Root barrel: `createCloudflareWorldsSdk`, `D1RdfjsStore`, `D1QuadStore` |
|
|
326
|
+
| `./quad-store` | `D1QuadStore` (import/export/transaction over D1) |
|
|
327
|
+
| `./search-index` | `CloudflareSearchIndex`, `D1SearchIndexProjector`, `D1SearchQueryBuilder` |
|
|
328
|
+
| `./rdfjs-store` | `D1RdfjsStore` (RDF/JS Store over D1), `D1QuadStream` |
|
|
329
|
+
| `./schema` | `D1SchemaBuilder` (idempotent D1 DDL: quads, chunks, FTS5 + triggers) |
|
|
330
|
+
|
|
331
|
+
## Development
|
|
332
|
+
|
|
333
|
+
`bun install` sets up, `bun run ci` runs every check on the source, and
|
|
334
|
+
`bun run build && bun run check:package` builds the npm package, installs it in an
|
|
335
|
+
empty project, and uses it on Node.js, Bun and Deno, which must all be on your
|
|
336
|
+
PATH, and in a Worker. Everything runs on your machine, without a Cloudflare
|
|
337
|
+
account. CI runs both on Linux, and the package check on Windows too.
|
|
338
|
+
|
|
339
|
+
## Releases
|
|
340
|
+
|
|
341
|
+
Every push to `main` runs the [Publish workflow](.github/workflows/publish.yml),
|
|
342
|
+
which publishes only when `package.json`'s `version` is not yet on npm:
|
|
343
|
+
|
|
344
|
+
- **Release PR** (bumps `version`): merging it publishes the new version of
|
|
345
|
+
`@wazootech/worlds-cloudflare`.
|
|
346
|
+
- **Routine PR** (no bump): the Publish job skips green with a notice. That is
|
|
347
|
+
expected, not a failure.
|
|
348
|
+
|
|
349
|
+
To release, bump `version` in `package.json` (a patch, unless the change breaks
|
|
350
|
+
callers) in the PR that should ship. A version with a suffix, such as
|
|
351
|
+
`0.16.0-rc.0`, goes to the `next` tag instead of `latest`.
|
|
352
|
+
|
|
353
|
+
npm accepts the publish because this repository's `publish.yml` is the package's
|
|
354
|
+
trusted publisher, so there is no npm token to store or rotate. After publishing,
|
|
355
|
+
a second job installs the new version from npm and checks it. If only that job
|
|
356
|
+
fails, re-run it on its own.
|
|
357
|
+
|
|
358
|
+
## License
|
|
359
|
+
|
|
360
|
+
[MIT](LICENSE). Versions up to 0.15.5, on JSR, are WTFPL.
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* D1PreparedStatementLike is the minimal D1 prepared-statement surface the
|
|
3
|
+
* driver uses (prepare → bind → all/first/run). Miniflare's real D1 binding
|
|
4
|
+
* satisfies it structurally, so tests run against the actual binding.
|
|
5
|
+
*/
|
|
6
|
+
interface D1PreparedStatementLike {
|
|
7
|
+
bind(...values: unknown[]): D1PreparedStatementLike;
|
|
8
|
+
all<T = Record<string, unknown>>(): Promise<{
|
|
9
|
+
results: T[];
|
|
10
|
+
}>;
|
|
11
|
+
first<T = Record<string, unknown>>(): Promise<T | null>;
|
|
12
|
+
run(): Promise<{
|
|
13
|
+
success: boolean;
|
|
14
|
+
}>;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* D1DatabaseLike is the minimal D1 binding surface the driver uses:
|
|
18
|
+
* prepare, batch (atomic multi-statement transaction), and exec (DDL).
|
|
19
|
+
*/
|
|
20
|
+
interface D1DatabaseLike {
|
|
21
|
+
prepare(sql: string): D1PreparedStatementLike;
|
|
22
|
+
batch(statements: D1PreparedStatementLike[]): Promise<unknown[]>;
|
|
23
|
+
/** D1 reports a count and duration here; nothing reads them. */
|
|
24
|
+
exec(sql: string): Promise<unknown>;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* D1Statement is a single parameterized SQL statement with `?` placeholders.
|
|
28
|
+
*/
|
|
29
|
+
interface D1Statement {
|
|
30
|
+
sql: string;
|
|
31
|
+
args?: unknown[];
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* D1Result is the outcome of executing a single statement.
|
|
35
|
+
*/
|
|
36
|
+
interface D1Result<Row = Record<string, unknown>> {
|
|
37
|
+
rows: Row[];
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* D1ConnectionDriver adapts a D1 binding (miniflare or a real Worker binding)
|
|
41
|
+
* to the uniform execute/batch/exec surface used by the D1 stores. D1 has no
|
|
42
|
+
* interactive transactions: the atomic unit is one `db.batch()` call, which
|
|
43
|
+
* runs its statements sequentially in a transaction and rolls back the whole
|
|
44
|
+
* sequence on any failure.
|
|
45
|
+
*/
|
|
46
|
+
interface D1ConnectionDriverOptions {
|
|
47
|
+
worldId?: string;
|
|
48
|
+
}
|
|
49
|
+
declare class D1ConnectionDriver {
|
|
50
|
+
private readonly database;
|
|
51
|
+
readonly worldId?: string;
|
|
52
|
+
constructor(database: D1DatabaseLike, options?: D1ConnectionDriverOptions);
|
|
53
|
+
/**
|
|
54
|
+
* execute runs a single parameterized statement and returns its rows.
|
|
55
|
+
*/
|
|
56
|
+
execute<Row = Record<string, unknown>>(statement: D1Statement): Promise<D1Result<Row>>;
|
|
57
|
+
/**
|
|
58
|
+
* batch runs multiple statements atomically in one D1 batch transaction.
|
|
59
|
+
*/
|
|
60
|
+
batch(statements: readonly D1Statement[]): Promise<void>;
|
|
61
|
+
/**
|
|
62
|
+
* exec runs a multi-statement DDL/migration string (no bound parameters).
|
|
63
|
+
*
|
|
64
|
+
* D1's script executor splits the input on newlines — each statement must
|
|
65
|
+
* therefore be single-line, and statements are separated by newlines. For
|
|
66
|
+
* individual statements with internal formatting (e.g. shared sql-core DDL),
|
|
67
|
+
* prefer execute() instead.
|
|
68
|
+
*/
|
|
69
|
+
exec(sql: string): Promise<void>;
|
|
70
|
+
}
|
|
71
|
+
export { D1Statement as a, D1Result as i, D1DatabaseLike as n, D1PreparedStatementLike as r, D1ConnectionDriver as t };
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
// src/cloudflare/provenance/d1-provenance-sql.ts
|
|
2
|
+
/**
|
|
3
|
+
* PROVENANCE_IDS_PER_STATEMENT is how many quads one provenance statement
|
|
4
|
+
* carries. Ids travel as one JSON parameter instead of one parameter each, so a
|
|
5
|
+
* commit gains about one statement per 5,000 quads and stays inside D1's
|
|
6
|
+
* 100-parameter, 2 MB-per-value, and batch limits.
|
|
7
|
+
*/
|
|
8
|
+
const PROVENANCE_IDS_PER_STATEMENT = 5e3;
|
|
9
|
+
/** buildProvenanceTable returns the DDL of the sidecar table and its two lookup indexes. */
|
|
10
|
+
function buildProvenanceTable(worldId) {
|
|
11
|
+
const scope = worldId ? "world_id, " : "";
|
|
12
|
+
return [
|
|
13
|
+
`CREATE TABLE IF NOT EXISTS provenance (record_id INTEGER PRIMARY KEY, quad_id TEXT NOT NULL, type TEXT NOT NULL, recorded_at TEXT NOT NULL, writer TEXT, source TEXT, supersedes_quad_id TEXT${worldId ? ", world_id TEXT NOT NULL" : ""})`,
|
|
14
|
+
`CREATE INDEX IF NOT EXISTS idx_provenance_quad ON provenance(${scope}quad_id)`,
|
|
15
|
+
`CREATE INDEX IF NOT EXISTS idx_provenance_supersedes ON provenance(${scope}supersedes_quad_id) WHERE supersedes_quad_id IS NOT NULL`
|
|
16
|
+
];
|
|
17
|
+
}
|
|
18
|
+
/** chunk slices `items` into groups one provenance statement can carry. */
|
|
19
|
+
function chunk(items) {
|
|
20
|
+
const groups = [];
|
|
21
|
+
for (let i = 0; i < items.length; i += PROVENANCE_IDS_PER_STATEMENT) groups.push(items.slice(i, i + PROVENANCE_IDS_PER_STATEMENT));
|
|
22
|
+
return groups;
|
|
23
|
+
}
|
|
24
|
+
/** buildInsertProvenance appends one record per entry, in order. */
|
|
25
|
+
function buildInsertProvenance(type, entries, stamp, worldId) {
|
|
26
|
+
return chunk(entries).map((group) => ({
|
|
27
|
+
sql: `INSERT INTO provenance (quad_id, supersedes_quad_id, type, recorded_at, writer, source${worldId ? ", world_id" : ""}) SELECT json_extract(value, '$[0]'), json_extract(value, '$[1]'), ?, ?, ?, ?${worldId ? ", ?" : ""} FROM json_each(?) ORDER BY key`,
|
|
28
|
+
args: [
|
|
29
|
+
type,
|
|
30
|
+
stamp.recordedAt,
|
|
31
|
+
stamp.writer ?? null,
|
|
32
|
+
stamp.source ?? null,
|
|
33
|
+
...worldId ? [worldId] : [],
|
|
34
|
+
JSON.stringify(group)
|
|
35
|
+
]
|
|
36
|
+
}));
|
|
37
|
+
}
|
|
38
|
+
/** buildDeleteWriteRecords takes back one commit's write records for quads it could not keep. */
|
|
39
|
+
function buildDeleteWriteRecords(quadIds, recordedAt, worldId) {
|
|
40
|
+
return chunk(quadIds).map((group) => ({
|
|
41
|
+
sql: `DELETE FROM provenance WHERE type = 'write' AND recorded_at = ? AND quad_id IN (SELECT value FROM json_each(?))${worldId ? " AND world_id = ?" : ""}`,
|
|
42
|
+
args: [
|
|
43
|
+
recordedAt,
|
|
44
|
+
JSON.stringify(group),
|
|
45
|
+
...worldId ? [worldId] : []
|
|
46
|
+
]
|
|
47
|
+
}));
|
|
48
|
+
}
|
|
49
|
+
/** buildSelectProvenance lists records oldest first, narrowed by quad and type. */
|
|
50
|
+
function buildSelectProvenance(query, worldId) {
|
|
51
|
+
const filters = Object.entries({
|
|
52
|
+
world_id: worldId,
|
|
53
|
+
quad_id: query.quadId,
|
|
54
|
+
type: query.type
|
|
55
|
+
}).filter(([, value]) => value !== void 0);
|
|
56
|
+
const where = filters.map(([column]) => `${column} = ?`).join(" AND ");
|
|
57
|
+
return {
|
|
58
|
+
sql: `SELECT * FROM provenance${where && ` WHERE ${where}`} ORDER BY record_id`,
|
|
59
|
+
args: filters.map(([, value]) => value)
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* buildSelectQuadRecords reads the records of the given quads, oldest first. D1
|
|
64
|
+
* has no table statistics and would read every record in the world, so this and
|
|
65
|
+
* the chain query below fix the join order and the index.
|
|
66
|
+
*/
|
|
67
|
+
function buildSelectQuadRecords(quadIds, worldId) {
|
|
68
|
+
return {
|
|
69
|
+
sql: `SELECT p.* FROM json_each(?) ids CROSS JOIN provenance p INDEXED BY idx_provenance_quad ON p.quad_id = ids.value${worldId ? " AND p.world_id = ?" : ""} ORDER BY p.record_id`,
|
|
70
|
+
args: [JSON.stringify(quadIds), ...worldId ? [worldId] : []]
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* buildSelectProvenanceChains reads every record of the given quads and of the
|
|
75
|
+
* quads they replaced or were replaced by, transitively. UNION drops repeats, so
|
|
76
|
+
* a value that flips back and forth still terminates.
|
|
77
|
+
*/
|
|
78
|
+
function buildSelectProvenanceChains(quadIds, worldId) {
|
|
79
|
+
const scope = worldId ? " AND p.world_id = ?" : "";
|
|
80
|
+
const byQuad = (from) => `${from} CROSS JOIN provenance p INDEXED BY idx_provenance_quad ON p.quad_id = ${from}.id${scope}`;
|
|
81
|
+
const byReplaced = (from) => `${from} CROSS JOIN provenance p INDEXED BY idx_provenance_supersedes ON p.supersedes_quad_id = ${from}.id AND p.supersedes_quad_id IS NOT NULL${scope}`;
|
|
82
|
+
const ids = JSON.stringify(quadIds);
|
|
83
|
+
const world = worldId ? [worldId] : [];
|
|
84
|
+
return {
|
|
85
|
+
sql: `WITH RECURSIVE
|
|
86
|
+
up(id) AS (SELECT value FROM json_each(?) UNION SELECT p.supersedes_quad_id FROM ${byQuad("up")} WHERE p.supersedes_quad_id IS NOT NULL),
|
|
87
|
+
down(id) AS (SELECT value FROM json_each(?) UNION SELECT p.quad_id FROM ${byReplaced("down")})
|
|
88
|
+
SELECT p.* FROM ${byQuad("up")} UNION SELECT p.* FROM ${byReplaced("down")} ORDER BY record_id`,
|
|
89
|
+
args: [
|
|
90
|
+
ids,
|
|
91
|
+
...world,
|
|
92
|
+
ids,
|
|
93
|
+
...world,
|
|
94
|
+
...world,
|
|
95
|
+
...world
|
|
96
|
+
]
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
export { buildSelectProvenance as a, chunk as c, buildProvenanceTable as i, buildDeleteWriteRecords as n, buildSelectProvenanceChains as o, buildInsertProvenance as r, buildSelectQuadRecords as s, PROVENANCE_IDS_PER_STATEMENT as t };
|