@nexcraft-dev/r2d1 0.0.0-stage → 0.1.0
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 +201 -0
- package/README.md +165 -2
- package/dist/core/codec.d.ts +7 -0
- package/dist/core/codec.js +16 -0
- package/dist/core/codec.js.map +1 -0
- package/dist/core/collection.d.ts +32 -0
- package/dist/core/collection.js +193 -0
- package/dist/core/collection.js.map +1 -0
- package/dist/core/cursor.d.ts +5 -0
- package/dist/core/cursor.js +139 -0
- package/dist/core/cursor.js.map +1 -0
- package/dist/core/errors.d.ts +27 -0
- package/dist/core/errors.js +42 -0
- package/dist/core/errors.js.map +1 -0
- package/dist/core/model.d.ts +91 -0
- package/dist/core/model.js +54 -0
- package/dist/core/model.js.map +1 -0
- package/dist/core/query.d.ts +29 -0
- package/dist/core/query.js +65 -0
- package/dist/core/query.js.map +1 -0
- package/dist/core/schema.d.ts +21 -0
- package/dist/core/schema.js +61 -0
- package/dist/core/schema.js.map +1 -0
- package/dist/index.d.ts +12 -0
- package/dist/index.js +8 -0
- package/dist/index.js.map +1 -0
- package/dist/node/d1.d.ts +10 -0
- package/dist/node/d1.js +57 -0
- package/dist/node/d1.js.map +1 -0
- package/dist/node/index.d.ts +4 -0
- package/dist/node/index.js +3 -0
- package/dist/node/index.js.map +1 -0
- package/dist/node/r2.d.ts +23 -0
- package/dist/node/r2.js +115 -0
- package/dist/node/r2.js.map +1 -0
- package/dist/storage/d1.d.ts +28 -0
- package/dist/storage/d1.js +301 -0
- package/dist/storage/d1.js.map +1 -0
- package/dist/storage/r2-key.d.ts +4 -0
- package/dist/storage/r2-key.js +36 -0
- package/dist/storage/r2-key.js.map +1 -0
- package/dist/workers/index.d.ts +47 -0
- package/dist/workers/index.js +93 -0
- package/dist/workers/index.js.map +1 -0
- package/examples/common.ts +54 -0
- package/examples/node.ts +36 -0
- package/examples/workers.ts +22 -0
- package/package.json +61 -4
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
CHANGED
|
@@ -1,3 +1,166 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @nexcraft-dev/r2d1
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
An ESM TypeScript document library for Node.js 22+ and Cloudflare Workers. R2 stores authoritative document bytes. D1 stores a rebuildable index.
|
|
4
|
+
|
|
5
|
+
This port preserves Java R2D1 storage contracts at commit `5afb4f97635ff8ff533e09b715232be13318b4b9`. It has not been published. Before release, use `npm pack` and install the resulting tarball. After release, install with `npm install @nexcraft-dev/r2d1`.
|
|
6
|
+
|
|
7
|
+
## Node.js
|
|
8
|
+
|
|
9
|
+
```ts
|
|
10
|
+
import { R2D1, defineSchema, jsonCodec } from '@nexcraft-dev/r2d1';
|
|
11
|
+
import { NodeR2DocumentStore, NodeD1IndexStore } from '@nexcraft-dev/r2d1/node';
|
|
12
|
+
|
|
13
|
+
interface User {
|
|
14
|
+
id: string;
|
|
15
|
+
country: string;
|
|
16
|
+
score: number;
|
|
17
|
+
}
|
|
18
|
+
const schema = defineSchema<User>({
|
|
19
|
+
collection: 'users',
|
|
20
|
+
id: 'id',
|
|
21
|
+
indexes: { country: 'string', score: 'double' },
|
|
22
|
+
});
|
|
23
|
+
const codec = jsonCodec<User>((value) => {
|
|
24
|
+
if (!value || typeof value !== 'object') throw new TypeError('Invalid user');
|
|
25
|
+
const user = value as Record<string, unknown>;
|
|
26
|
+
if (
|
|
27
|
+
typeof user.id !== 'string' ||
|
|
28
|
+
typeof user.country !== 'string' ||
|
|
29
|
+
typeof user.score !== 'number' ||
|
|
30
|
+
!Number.isFinite(user.score)
|
|
31
|
+
) {
|
|
32
|
+
throw new TypeError('Invalid user');
|
|
33
|
+
}
|
|
34
|
+
return { id: user.id, country: user.country, score: user.score };
|
|
35
|
+
});
|
|
36
|
+
const documents = new NodeR2DocumentStore({
|
|
37
|
+
endpoint: 'https://<account-id>.r2.cloudflarestorage.com',
|
|
38
|
+
bucket: '<bucket>',
|
|
39
|
+
accessKeyId: '<access-key-id>',
|
|
40
|
+
secretAccessKey: '<secret-access-key>',
|
|
41
|
+
});
|
|
42
|
+
const indexes = new NodeD1IndexStore({
|
|
43
|
+
accountId: '<account-id>',
|
|
44
|
+
databaseId: '<database-id>',
|
|
45
|
+
apiToken: '<api-token>',
|
|
46
|
+
});
|
|
47
|
+
const users = await new R2D1(documents, indexes).collection(schema, codec, {
|
|
48
|
+
hydrationConcurrency: 16,
|
|
49
|
+
maxConcurrentOperations: 32,
|
|
50
|
+
});
|
|
51
|
+
try {
|
|
52
|
+
await users.put({ id: 'user-1', country: 'NZ', score: 4.5 });
|
|
53
|
+
const user = await users.get('user-1'); // undefined only when absent
|
|
54
|
+
const page = await users
|
|
55
|
+
.query()
|
|
56
|
+
.where('country')
|
|
57
|
+
.eq('NZ')
|
|
58
|
+
.sortBy('score', 'DESC')
|
|
59
|
+
.limit(20)
|
|
60
|
+
.fetch();
|
|
61
|
+
if (page.nextCursor) {
|
|
62
|
+
console.log(
|
|
63
|
+
await users
|
|
64
|
+
.query()
|
|
65
|
+
.where('country')
|
|
66
|
+
.eq('NZ')
|
|
67
|
+
.sortBy('score', 'DESC')
|
|
68
|
+
.limit(20)
|
|
69
|
+
.after(page.nextCursor)
|
|
70
|
+
.fetch(),
|
|
71
|
+
);
|
|
72
|
+
}
|
|
73
|
+
console.log(user, page.items);
|
|
74
|
+
await users.delete('user-1');
|
|
75
|
+
} finally {
|
|
76
|
+
documents.close();
|
|
77
|
+
}
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
Supply credentials from application secret configuration. The library does not read environment variables or log credentials. R2 uses the AWS S3 SDK, region `auto` by default, and no library-configured retries. To borrow a client, supply `{ client, bucket }`. `close()` destroys only an internally created client. A borrowed client's configuration belongs to the caller. D1 uses the Cloudflare REST query endpoint.
|
|
81
|
+
|
|
82
|
+
## Cloudflare Workers
|
|
83
|
+
|
|
84
|
+
```ts
|
|
85
|
+
import { R2D1 } from '@nexcraft-dev/r2d1';
|
|
86
|
+
import { WorkersR2DocumentStore, WorkersD1IndexStore } from '@nexcraft-dev/r2d1/workers';
|
|
87
|
+
|
|
88
|
+
// Inside your Worker, using the same schema and codec:
|
|
89
|
+
const users = await new R2D1(
|
|
90
|
+
new WorkersR2DocumentStore(env.DOCUMENTS),
|
|
91
|
+
new WorkersD1IndexStore(env.INDEXES),
|
|
92
|
+
).collection(schema, codec);
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
Bind an R2 bucket as `DOCUMENTS` and a D1 database as `INDEXES`. The library does not provision or deploy resources. Core and the Workers adapters need no `nodejs_compat` flag. Their subpaths import no AWS SDK or Node built-ins. The npm package includes the Node dependency, but a Workers bundle includes only reachable modules.
|
|
96
|
+
|
|
97
|
+
See the [Node example](examples/node.ts), [Workers example](examples/workers.ts), and [shared codec example](examples/common.ts). Examples are TypeScript source for your build tool.
|
|
98
|
+
|
|
99
|
+
## Schema and queries
|
|
100
|
+
|
|
101
|
+
- Collection and indexed-field names must match `[A-Za-z_][A-Za-z0-9_]*`.
|
|
102
|
+
- IDs are nonblank strings. Values are not trimmed or normalized.
|
|
103
|
+
- Each collection has at most five indexed fields. `document_id` is reserved.
|
|
104
|
+
- Index types: `string` (TEXT), `long` (INTEGER), `double` (REAL), `boolean` (INTEGER 0/1).
|
|
105
|
+
- Use signed 64-bit `bigint` for `long`. A JavaScript `number` is rejected for this type.
|
|
106
|
+
- Indexed values must be present and non-null. Double values must be finite.
|
|
107
|
+
- `where(field).eq/notEq/gt/gte/lt/lte(value)` adds an AND filter. Boolean fields support only `eq` and `notEq`.
|
|
108
|
+
- Every indexed field can be sorted. One sort and a positive integer limit are supported. Default order is document ID ascending.
|
|
109
|
+
- Sorted queries use ID as a tie-breaker in the same direction. Continuation uses Java-compatible opaque v1 cursors.
|
|
110
|
+
- Repeat the same collection, filters and sort when continuing. Java cursors do not encode the filter or sort field. They are not signed authorization tokens.
|
|
111
|
+
- Builders are immutable. Repeated sort, limit or cursor configuration fails.
|
|
112
|
+
|
|
113
|
+
Core exports `DocumentStore`, `IndexStore`, `DocumentCodec<T>`, and their model types for custom integrations. SPI methods return Promises. `DocumentStore.get` rejects with `DocumentNotFoundError` when absent. Collection `get` maps only that failure to `undefined`.
|
|
114
|
+
|
|
115
|
+
## Java data compatibility
|
|
116
|
+
|
|
117
|
+
R2 keys use uppercase percent encoding of each UTF-8 collection and ID segment, separated by `/`. There is no file suffix or added envelope. D1 uses the collection name, `document_id TEXT PRIMARY KEY NOT NULL`, required typed columns, and `idx_<collection>_<field>` indexes.
|
|
118
|
+
|
|
119
|
+
**Java supplies no default document format.** Use a TypeScript codec that matches your application's Java codec. `jsonCodec` is an explicit helper. It uses ordinary JSON and cannot serialize `bigint`. Supply a custom codec for Long values or custom formats. The shared example matches the Java integration-test codec's dot-separated base64url fields and decimal Long.
|
|
120
|
+
|
|
121
|
+
Long bindings use decimal text with `CAST(... AS INTEGER)`. Sorted Long values are selected as text and converted to `bigint`. Stored columns and numeric query order remain compatible. No data rewrite is needed.
|
|
122
|
+
|
|
123
|
+
D1 initialization inspects actual schema. Same-schema initialization shares I/O. Conflicting schemas fail. Initialization failures remain failed for that store instance. Missing columns can be added to an empty table. Required additions to populated tables fail. Extra columns and indexes remain intact. Incompatible columns/index names require application-managed migration. Extra required columns without defaults can prevent insertion and are not removed automatically.
|
|
124
|
+
|
|
125
|
+
## Consistency and recovery
|
|
126
|
+
|
|
127
|
+
PUT and DELETE mutate the authoritative store first, then the index. No transaction spans both stores. An index failure after authoritative success raises `PartialFailureError`, retaining `documentKey` and `cause`. No rollback occurs. GET reflects authoritative existence.
|
|
128
|
+
|
|
129
|
+
Hydration preserves index order. Missing documents raise `InconsistentStateError` for the whole page. Stale rows are not skipped.
|
|
130
|
+
|
|
131
|
+
Pause all application writes to the collection, including other processes, before calling `await users.rebuildIndex()`. Rebuild prepares the first page before clearing rows. It scans 100 keys per page and preserves schema. First-page preparation failure leaves existing rows intact. Later failure can leave an incomplete index. Resolve the cause and rebuild again. Rebuild is not atomic and has no distributed lock.
|
|
132
|
+
|
|
133
|
+
Hydration defaults to 16 concurrent reads per operation. Optional `maxConcurrentOperations` rejects excess operations on that collection instance with `AdmissionRejectedError`. There is no queue, timer, or cross-instance cap. Caller timeouts do not guarantee cancellation of storage requests.
|
|
134
|
+
|
|
135
|
+
Storage errors use `StorageError`, `StorageAccessError`, `StorageUnavailableError`, and `StorageOperationError`. Native failures without reliable status use `StorageOperationError`. Codec errors propagate unchanged. Library-generated transport errors exclude response bodies and raw SDK errors. There are no automatic retries, background jobs, or automatic recovery.
|
|
136
|
+
|
|
137
|
+
## Development and validation
|
|
138
|
+
|
|
139
|
+
```sh
|
|
140
|
+
npm ci
|
|
141
|
+
npm run typecheck
|
|
142
|
+
npm test
|
|
143
|
+
npm run verify:java
|
|
144
|
+
npm run check:package
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
Tests cover SQLite execution, failure paths, rebuilds, concurrency and local Miniflare/Workerd R2/D1 bindings. `verify:java` requires Java 21+ and the Java checkout at `../r2d1`, or set `R2D1_JAVA_ROOT`. It compiles original source copies in a temporary directory and checks source hashes, fixtures and bidirectional cursors. It never builds or modifies the Java checkout. Normal tests use checked-in fixtures without Java.
|
|
148
|
+
|
|
149
|
+
The `Publish npm package` workflow is manually dispatched from `main` with the exact stable `package.json` version. It verifies Node 22 and 24, inspects package contents, tests the release tarball, and passes that artifact to a separate GitHub-hosted OIDC publish job. The `npm` GitHub environment and npm trusted publisher must be configured first. The workflow does not create commits, tags, or GitHub releases. It needs no long-lived npm write token after trusted publishing is configured. A new npm package may need a separately authorized initial registration before package-level trusted publishing settings are available.
|
|
150
|
+
|
|
151
|
+
Live testing is opt-in and writes to dedicated resources. Set these variables:
|
|
152
|
+
|
|
153
|
+
```text
|
|
154
|
+
R2D1_IT_ALLOW_MUTATIONS=true
|
|
155
|
+
R2D1_IT_R2_ENDPOINT
|
|
156
|
+
R2D1_IT_R2_BUCKET_NAME
|
|
157
|
+
R2D1_IT_R2_ACCESS_KEY_ID
|
|
158
|
+
R2D1_IT_R2_SECRET_ACCESS_KEY
|
|
159
|
+
R2D1_IT_D1_ACCOUNT_ID
|
|
160
|
+
R2D1_IT_D1_DATABASE_ID
|
|
161
|
+
R2D1_IT_D1_API_TOKEN
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
Run `npm run test:live`. Without opt-in, it is skipped. Do not use production resources. It uses a unique collection, removes its document and rows, and prints its retained table name for manual removal. Local tests do not verify remote permissions, quotas, latency, or sustained load.
|
|
165
|
+
|
|
166
|
+
JDBC, filesystem storage, Java framework integrations, annotation processing, deployment automation, async indexing queues and distributed transactions are outside this package's scope.
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { StoredDocument } from './model.js';
|
|
2
|
+
export interface DocumentCodec<T> {
|
|
3
|
+
serialize(document: T): StoredDocument;
|
|
4
|
+
deserialize(document: StoredDocument): T;
|
|
5
|
+
}
|
|
6
|
+
/** Opt-in JSON only. Supply a decoder to validate untrusted data and restore domain types. */
|
|
7
|
+
export declare function jsonCodec<T>(decode: (value: unknown) => T): DocumentCodec<T>;
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { StoredDocument } from './model.js';
|
|
2
|
+
/** Opt-in JSON only. Supply a decoder to validate untrusted data and restore domain types. */
|
|
3
|
+
export function jsonCodec(decode) {
|
|
4
|
+
return Object.freeze({
|
|
5
|
+
serialize(document) {
|
|
6
|
+
const json = JSON.stringify(document);
|
|
7
|
+
if (json === undefined)
|
|
8
|
+
throw new TypeError('document is not JSON serializable');
|
|
9
|
+
return new StoredDocument(new TextEncoder().encode(json));
|
|
10
|
+
},
|
|
11
|
+
deserialize(document) {
|
|
12
|
+
return decode(JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(document.content())));
|
|
13
|
+
},
|
|
14
|
+
});
|
|
15
|
+
}
|
|
16
|
+
//# sourceMappingURL=codec.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"codec.js","sourceRoot":"","sources":["../../src/core/codec.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAM5C,8FAA8F;AAC9F,MAAM,UAAU,SAAS,CAAI,MAA6B;IACxD,OAAO,MAAM,CAAC,MAAM,CAAC;QACnB,SAAS,CAAC,QAAW;YACnB,MAAM,IAAI,GAAG,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,CAAC;YACtC,IAAI,IAAI,KAAK,SAAS;gBAAE,MAAM,IAAI,SAAS,CAAC,mCAAmC,CAAC,CAAC;YACjF,OAAO,IAAI,cAAc,CAAC,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC;QAC5D,CAAC;QACD,WAAW,CAAC,QAAwB;YAClC,OAAO,MAAM,CACX,IAAI,CAAC,KAAK,CAAC,IAAI,WAAW,CAAC,OAAO,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC,MAAM,CAAC,QAAQ,CAAC,OAAO,EAAE,CAAC,CAAY,CAC5F,CAAC;QACJ,CAAC;KACF,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { StoredDocument } from './model.js';\n\nexport interface DocumentCodec<T> {\n serialize(document: T): StoredDocument;\n deserialize(document: StoredDocument): T;\n}\n/** Opt-in JSON only. Supply a decoder to validate untrusted data and restore domain types. */\nexport function jsonCodec<T>(decode: (value: unknown) => T): DocumentCodec<T> {\n return Object.freeze({\n serialize(document: T): StoredDocument {\n const json = JSON.stringify(document);\n if (json === undefined) throw new TypeError('document is not JSON serializable');\n return new StoredDocument(new TextEncoder().encode(json));\n },\n deserialize(document: StoredDocument): T {\n return decode(\n JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(document.content())) as unknown,\n );\n },\n });\n}\n"]}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import type { DocumentStore, IndexStore } from './model.js';
|
|
2
|
+
import type { DocumentCodec } from './codec.js';
|
|
3
|
+
import type { CollectionSchema } from './schema.js';
|
|
4
|
+
import { Query } from './query.js';
|
|
5
|
+
export interface CollectionOptions {
|
|
6
|
+
readonly hydrationConcurrency?: number;
|
|
7
|
+
readonly maxConcurrentOperations?: number;
|
|
8
|
+
}
|
|
9
|
+
export declare class R2D1Collection<T extends object> {
|
|
10
|
+
#private;
|
|
11
|
+
readonly schema: CollectionSchema<T>;
|
|
12
|
+
private readonly documents;
|
|
13
|
+
private readonly indexes;
|
|
14
|
+
private readonly codec;
|
|
15
|
+
constructor(schema: CollectionSchema<T>, documents: DocumentStore, indexes: IndexStore, codec: DocumentCodec<T>, options?: CollectionOptions);
|
|
16
|
+
put(document: T): Promise<void>;
|
|
17
|
+
get(id: string): Promise<T | undefined>;
|
|
18
|
+
delete(id: string): Promise<void>;
|
|
19
|
+
query(): Query<T>;
|
|
20
|
+
rebuildIndex(): Promise<void>;
|
|
21
|
+
private fetch;
|
|
22
|
+
private validateKey;
|
|
23
|
+
private hydrate;
|
|
24
|
+
private deserialize;
|
|
25
|
+
private run;
|
|
26
|
+
}
|
|
27
|
+
export declare class R2D1 {
|
|
28
|
+
private readonly documents;
|
|
29
|
+
private readonly indexes;
|
|
30
|
+
constructor(documents: DocumentStore, indexes: IndexStore);
|
|
31
|
+
collection<T extends object>(schema: CollectionSchema<T>, codec: DocumentCodec<T>, options?: CollectionOptions): Promise<R2D1Collection<T>>;
|
|
32
|
+
}
|
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
import { encodeCursor } from './cursor.js';
|
|
2
|
+
import { AdmissionRejectedError, DocumentNotFoundError, InconsistentStateError, PartialFailureError, PersistenceError, } from './errors.js';
|
|
3
|
+
import { key, positive, StoredDocument } from './model.js';
|
|
4
|
+
import { Query } from './query.js';
|
|
5
|
+
async function mapBounded(items, concurrency, map) {
|
|
6
|
+
const output = new Array(items.length);
|
|
7
|
+
let next = 0;
|
|
8
|
+
let failed = false;
|
|
9
|
+
let failure;
|
|
10
|
+
await Promise.all(Array.from({ length: Math.min(items.length, concurrency) }, async () => {
|
|
11
|
+
while (!failed && next < items.length) {
|
|
12
|
+
const index = next++;
|
|
13
|
+
try {
|
|
14
|
+
output[index] = await map(items[index]);
|
|
15
|
+
}
|
|
16
|
+
catch (cause) {
|
|
17
|
+
if (!failed) {
|
|
18
|
+
failed = true;
|
|
19
|
+
failure = cause;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
}));
|
|
24
|
+
// Drain in-flight reads before releasing the admission slot.
|
|
25
|
+
if (failed)
|
|
26
|
+
throw failure;
|
|
27
|
+
return output;
|
|
28
|
+
}
|
|
29
|
+
export class R2D1Collection {
|
|
30
|
+
schema;
|
|
31
|
+
documents;
|
|
32
|
+
indexes;
|
|
33
|
+
codec;
|
|
34
|
+
#concurrency;
|
|
35
|
+
#maxOperations;
|
|
36
|
+
#active = 0;
|
|
37
|
+
constructor(schema, documents, indexes, codec, options = {}) {
|
|
38
|
+
this.schema = schema;
|
|
39
|
+
this.documents = documents;
|
|
40
|
+
this.indexes = indexes;
|
|
41
|
+
this.codec = codec;
|
|
42
|
+
this.#concurrency = positive(options.hydrationConcurrency ?? 16, 'hydrationConcurrency');
|
|
43
|
+
this.#maxOperations =
|
|
44
|
+
options.maxConcurrentOperations === undefined
|
|
45
|
+
? Infinity
|
|
46
|
+
: positive(options.maxConcurrentOperations, 'maxConcurrentOperations');
|
|
47
|
+
}
|
|
48
|
+
async put(document) {
|
|
49
|
+
return this.run(async () => {
|
|
50
|
+
const entry = this.schema.entry(document);
|
|
51
|
+
const stored = this.codec.serialize(document);
|
|
52
|
+
if (!(stored instanceof StoredDocument))
|
|
53
|
+
throw new TypeError('codec must return StoredDocument');
|
|
54
|
+
await this.documents.put(entry.documentKey, stored);
|
|
55
|
+
try {
|
|
56
|
+
await this.indexes.upsert(entry);
|
|
57
|
+
}
|
|
58
|
+
catch (cause) {
|
|
59
|
+
throw new PartialFailureError('Document write succeeded but index upsert failed', entry.documentKey, cause);
|
|
60
|
+
}
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
async get(id) {
|
|
64
|
+
return this.run(async () => {
|
|
65
|
+
let stored;
|
|
66
|
+
try {
|
|
67
|
+
stored = await this.documents.get(key(this.schema.metadata.collection, id));
|
|
68
|
+
}
|
|
69
|
+
catch (cause) {
|
|
70
|
+
if (cause instanceof DocumentNotFoundError)
|
|
71
|
+
return undefined;
|
|
72
|
+
throw cause;
|
|
73
|
+
}
|
|
74
|
+
return this.deserialize(stored);
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
async delete(id) {
|
|
78
|
+
return this.run(async () => {
|
|
79
|
+
const documentKey = key(this.schema.metadata.collection, id);
|
|
80
|
+
await this.documents.delete(documentKey);
|
|
81
|
+
try {
|
|
82
|
+
await this.indexes.delete(documentKey);
|
|
83
|
+
}
|
|
84
|
+
catch (cause) {
|
|
85
|
+
throw new PartialFailureError('Document delete succeeded but index cleanup failed', documentKey, cause);
|
|
86
|
+
}
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
query() {
|
|
90
|
+
return new Query(this.schema, (query) => this.fetch(query));
|
|
91
|
+
}
|
|
92
|
+
async rebuildIndex() {
|
|
93
|
+
return this.run(async () => {
|
|
94
|
+
const prepare = async (cursor) => {
|
|
95
|
+
const page = await this.documents.list(this.schema.metadata.collection, cursor, 100);
|
|
96
|
+
if (page.documentKeys.length > 100)
|
|
97
|
+
throw new PersistenceError('Document listing exceeded page limit');
|
|
98
|
+
const entries = await mapBounded(page.documentKeys, this.#concurrency, async (documentKey) => {
|
|
99
|
+
this.validateKey(documentKey);
|
|
100
|
+
const entry = this.schema.entry(await this.hydrate(documentKey));
|
|
101
|
+
if (entry.documentKey.id !== documentKey.id)
|
|
102
|
+
throw new InconsistentStateError('Document key does not match its content', documentKey);
|
|
103
|
+
return entry;
|
|
104
|
+
});
|
|
105
|
+
return {
|
|
106
|
+
entries,
|
|
107
|
+
...(page.nextCursor !== undefined ? { nextCursor: page.nextCursor } : {}),
|
|
108
|
+
};
|
|
109
|
+
};
|
|
110
|
+
let page = await prepare();
|
|
111
|
+
await this.indexes.clear(this.schema.metadata.collection);
|
|
112
|
+
let cursor;
|
|
113
|
+
while (true) {
|
|
114
|
+
for (const entry of page.entries)
|
|
115
|
+
await this.indexes.upsert(entry);
|
|
116
|
+
if (page.nextCursor === undefined)
|
|
117
|
+
break;
|
|
118
|
+
if (!page.nextCursor || page.nextCursor === cursor)
|
|
119
|
+
throw new PersistenceError('Document listing did not advance');
|
|
120
|
+
cursor = page.nextCursor;
|
|
121
|
+
page = await prepare(cursor);
|
|
122
|
+
}
|
|
123
|
+
});
|
|
124
|
+
}
|
|
125
|
+
async fetch(query) {
|
|
126
|
+
return this.run(async () => {
|
|
127
|
+
const page = await this.indexes.query(query);
|
|
128
|
+
if (page.documentKeys.length > query.limit)
|
|
129
|
+
throw new PersistenceError('Index exceeded page limit');
|
|
130
|
+
const items = await mapBounded(page.documentKeys, this.#concurrency, (documentKey) => {
|
|
131
|
+
this.validateKey(documentKey);
|
|
132
|
+
return this.hydrate(documentKey);
|
|
133
|
+
});
|
|
134
|
+
if (page.nextCursor)
|
|
135
|
+
this.validateKey(page.nextCursor.lastDocumentKey);
|
|
136
|
+
return Object.freeze({
|
|
137
|
+
items: Object.freeze(items),
|
|
138
|
+
...(page.nextCursor ? { nextCursor: encodeCursor(page.nextCursor) } : {}),
|
|
139
|
+
});
|
|
140
|
+
});
|
|
141
|
+
}
|
|
142
|
+
validateKey(documentKey) {
|
|
143
|
+
key(documentKey.collection, documentKey.id);
|
|
144
|
+
if (documentKey.collection !== this.schema.metadata.collection)
|
|
145
|
+
throw new PersistenceError('Storage returned a key outside the collection');
|
|
146
|
+
}
|
|
147
|
+
async hydrate(documentKey) {
|
|
148
|
+
let stored;
|
|
149
|
+
try {
|
|
150
|
+
stored = await this.documents.get(documentKey);
|
|
151
|
+
}
|
|
152
|
+
catch (cause) {
|
|
153
|
+
if (cause instanceof DocumentNotFoundError)
|
|
154
|
+
throw new InconsistentStateError('Index or listing references a missing document', documentKey, cause);
|
|
155
|
+
throw cause;
|
|
156
|
+
}
|
|
157
|
+
return this.deserialize(stored);
|
|
158
|
+
}
|
|
159
|
+
deserialize(stored) {
|
|
160
|
+
const value = this.codec.deserialize(stored);
|
|
161
|
+
if (value === null || value === undefined)
|
|
162
|
+
throw new TypeError('codec returned no document');
|
|
163
|
+
return value;
|
|
164
|
+
}
|
|
165
|
+
async run(operation) {
|
|
166
|
+
if (this.#active >= this.#maxOperations)
|
|
167
|
+
throw new AdmissionRejectedError('Collection operation limit reached');
|
|
168
|
+
this.#active++;
|
|
169
|
+
try {
|
|
170
|
+
return await operation();
|
|
171
|
+
}
|
|
172
|
+
finally {
|
|
173
|
+
this.#active--;
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
export class R2D1 {
|
|
178
|
+
documents;
|
|
179
|
+
indexes;
|
|
180
|
+
constructor(documents, indexes) {
|
|
181
|
+
this.documents = documents;
|
|
182
|
+
this.indexes = indexes;
|
|
183
|
+
}
|
|
184
|
+
async collection(schema, codec, options) {
|
|
185
|
+
if (!schema || !codec)
|
|
186
|
+
throw new TypeError('schema and codec are required');
|
|
187
|
+
// Validate options before any schema I/O.
|
|
188
|
+
const collection = new R2D1Collection(schema, this.documents, this.indexes, codec, options);
|
|
189
|
+
await this.indexes.initialize(schema.metadata);
|
|
190
|
+
return collection;
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
//# sourceMappingURL=collection.js.map
|
|
@@ -0,0 +1 @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;QACzE,IAAI,CAAC,OAAO,EAAE,CAAC;QACf,IAAI,CAAC;YACH,OAAO,MAAM,SAAS,EAAE,CAAC;QAC3B,CAAC;gBAAS,CAAC;YACT,IAAI,CAAC,OAAO,EAAE,CAAC;QACjB,CAAC;IACH,CAAC;CACF;AAED,MAAM,OAAO,IAAI;IAEI,SAAS;IACT,OAAO;IAF1B,YACmB,SAAwB,EACxB,OAAmB;yBADnB,SAAS;uBACT,OAAO;IACvB,CAAC;IACJ,KAAK,CAAC,UAAU,CACd,MAA2B,EAC3B,KAAuB,EACvB,OAA2B;QAE3B,IAAI,CAAC,MAAM,IAAI,CAAC,KAAK;YAAE,MAAM,IAAI,SAAS,CAAC,+BAA+B,CAAC,CAAC;QAC5E,0CAA0C;QAC1C,MAAM,UAAU,GAAG,IAAI,cAAc,CAAC,MAAM,EAAE,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,OAAO,EAAE,KAAK,EAAE,OAAO,CAAC,CAAC;QAC5F,MAAM,IAAI,CAAC,OAAO,CAAC,UAAU,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;QAC/C,OAAO,UAAU,CAAC;IACpB,CAAC;CACF","sourcesContent":["import { encodeCursor } from './cursor.js';\nimport {\n AdmissionRejectedError,\n DocumentNotFoundError,\n InconsistentStateError,\n PartialFailureError,\n PersistenceError,\n} from './errors.js';\nimport { key, positive, StoredDocument } from './model.js';\nimport type {\n DocumentKey,\n DocumentStore,\n IndexEntry,\n IndexQuery,\n IndexStore,\n Page,\n} from './model.js';\nimport type { DocumentCodec } from './codec.js';\nimport type { CollectionSchema } from './schema.js';\nimport { Query } from './query.js';\n\nexport interface CollectionOptions {\n readonly hydrationConcurrency?: number;\n readonly maxConcurrentOperations?: number;\n}\n\nasync function mapBounded<A, B>(\n items: readonly A[],\n concurrency: number,\n map: (value: A) => Promise<B>,\n): Promise<B[]> {\n const output = new Array<B>(items.length);\n let next = 0;\n let failed = false;\n let failure: unknown;\n await Promise.all(\n Array.from({ length: Math.min(items.length, concurrency) }, async () => {\n while (!failed && next < items.length) {\n const index = next++;\n try {\n output[index] = await map(items[index]!);\n } catch (cause) {\n if (!failed) {\n failed = true;\n failure = cause;\n }\n }\n }\n }),\n );\n // Drain in-flight reads before releasing the admission slot.\n if (failed) throw failure;\n return output;\n}\n\nexport class R2D1Collection<T extends object> {\n readonly #concurrency: number;\n readonly #maxOperations: number;\n #active = 0;\n constructor(\n readonly schema: CollectionSchema<T>,\n private readonly documents: DocumentStore,\n private readonly indexes: IndexStore,\n private readonly codec: DocumentCodec<T>,\n options: CollectionOptions = {},\n ) {\n this.#concurrency = positive(options.hydrationConcurrency ?? 16, 'hydrationConcurrency');\n this.#maxOperations =\n options.maxConcurrentOperations === undefined\n ? Infinity\n : positive(options.maxConcurrentOperations, 'maxConcurrentOperations');\n }\n async put(document: T): Promise<void> {\n return this.run(async () => {\n const entry = this.schema.entry(document);\n const stored = this.codec.serialize(document);\n if (!(stored instanceof StoredDocument))\n throw new TypeError('codec must return StoredDocument');\n await this.documents.put(entry.documentKey, stored);\n try {\n await this.indexes.upsert(entry);\n } catch (cause) {\n throw new PartialFailureError(\n 'Document write succeeded but index upsert failed',\n entry.documentKey,\n cause,\n );\n }\n });\n }\n async get(id: string): Promise<T | undefined> {\n return this.run(async () => {\n let stored: StoredDocument;\n try {\n stored = await this.documents.get(key(this.schema.metadata.collection, id));\n } catch (cause) {\n if (cause instanceof DocumentNotFoundError) return undefined;\n throw cause;\n }\n return this.deserialize(stored);\n });\n }\n async delete(id: string): Promise<void> {\n return this.run(async () => {\n const documentKey = key(this.schema.metadata.collection, id);\n await this.documents.delete(documentKey);\n try {\n await this.indexes.delete(documentKey);\n } catch (cause) {\n throw new PartialFailureError(\n 'Document delete succeeded but index cleanup failed',\n documentKey,\n cause,\n );\n }\n });\n }\n query(): Query<T> {\n return new Query(this.schema, (query) => this.fetch(query));\n }\n async rebuildIndex(): Promise<void> {\n return this.run(async () => {\n const prepare = async (\n cursor?: string,\n ): Promise<{ entries: IndexEntry[]; nextCursor?: string }> => {\n const page = await this.documents.list(this.schema.metadata.collection, cursor, 100);\n if (page.documentKeys.length > 100)\n throw new PersistenceError('Document listing exceeded page limit');\n const entries = await mapBounded(\n page.documentKeys,\n this.#concurrency,\n async (documentKey) => {\n this.validateKey(documentKey);\n const entry = this.schema.entry(await this.hydrate(documentKey));\n if (entry.documentKey.id !== documentKey.id)\n throw new InconsistentStateError(\n 'Document key does not match its content',\n documentKey,\n );\n return entry;\n },\n );\n return {\n entries,\n ...(page.nextCursor !== undefined ? { nextCursor: page.nextCursor } : {}),\n };\n };\n let page = await prepare();\n await this.indexes.clear(this.schema.metadata.collection);\n let cursor: string | undefined;\n while (true) {\n for (const entry of page.entries) await this.indexes.upsert(entry);\n if (page.nextCursor === undefined) break;\n if (!page.nextCursor || page.nextCursor === cursor)\n throw new PersistenceError('Document listing did not advance');\n cursor = page.nextCursor;\n page = await prepare(cursor);\n }\n });\n }\n private async fetch(query: IndexQuery): Promise<Page<T>> {\n return this.run(async () => {\n const page = await this.indexes.query(query);\n if (page.documentKeys.length > query.limit)\n throw new PersistenceError('Index exceeded page limit');\n const items = await mapBounded(page.documentKeys, this.#concurrency, (documentKey) => {\n this.validateKey(documentKey);\n return this.hydrate(documentKey);\n });\n if (page.nextCursor) this.validateKey(page.nextCursor.lastDocumentKey);\n return Object.freeze({\n items: Object.freeze(items),\n ...(page.nextCursor ? { nextCursor: encodeCursor(page.nextCursor) } : {}),\n });\n });\n }\n private validateKey(documentKey: DocumentKey): void {\n key(documentKey.collection, documentKey.id);\n if (documentKey.collection !== this.schema.metadata.collection)\n throw new PersistenceError('Storage returned a key outside the collection');\n }\n private async hydrate(documentKey: DocumentKey): Promise<T> {\n let stored: StoredDocument;\n try {\n stored = await this.documents.get(documentKey);\n } catch (cause) {\n if (cause instanceof DocumentNotFoundError)\n throw new InconsistentStateError(\n 'Index or listing references a missing document',\n documentKey,\n cause,\n );\n throw cause;\n }\n return this.deserialize(stored);\n }\n private deserialize(stored: StoredDocument): T {\n const value = this.codec.deserialize(stored);\n if (value === null || value === undefined) throw new TypeError('codec returned no document');\n return value;\n }\n private async run<R>(operation: () => Promise<R>): Promise<R> {\n if (this.#active >= this.#maxOperations)\n throw new AdmissionRejectedError('Collection operation limit reached');\n this.#active++;\n try {\n return await operation();\n } finally {\n this.#active--;\n }\n }\n}\n\nexport class R2D1 {\n constructor(\n private readonly documents: DocumentStore,\n private readonly indexes: IndexStore,\n ) {}\n async collection<T extends object>(\n schema: CollectionSchema<T>,\n codec: DocumentCodec<T>,\n options?: CollectionOptions,\n ): Promise<R2D1Collection<T>> {\n if (!schema || !codec) throw new TypeError('schema and codec are required');\n // Validate options before any schema I/O.\n const collection = new R2D1Collection(schema, this.documents, this.indexes, codec, options);\n await this.indexes.initialize(schema.metadata);\n return collection;\n }\n}\n"]}
|