@vultro/docstore-d1 0.0.0-stage → 0.0.1

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.
@@ -0,0 +1,7 @@
1
+ import { type DocStoreBackend } from "@vultro/core/docstore";
2
+ /**
3
+ * D1 文档存储选择器(纯配置)。
4
+ *
5
+ * 实现由 `@vultro/docstore-d1/runtime` 注册。
6
+ */
7
+ export declare function d1Store(): DocStoreBackend;
package/dist/index.js ADDED
@@ -0,0 +1,19 @@
1
+ import { resolveDocStoreCreator } from "@vultro/core/docstore";
2
+ // src/index.ts
3
+ /**
4
+ * D1 文档存储选择器(纯配置)。
5
+ *
6
+ * 实现由 `@vultro/docstore-d1/runtime` 注册。
7
+ */
8
+ function d1Store() {
9
+ return {
10
+ name: "d1",
11
+ runtimes: ["cloudflare", "cloud"],
12
+ module: "@vultro/docstore-d1",
13
+ exportName: "d1Store",
14
+ create(runtime, context) {
15
+ return resolveDocStoreCreator("d1")(runtime, context);
16
+ }
17
+ };
18
+ }
19
+ export { d1Store };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,8 @@
1
+ import { registerDocStore } from "@vultro/core/docstore";
2
+ import { AsyncCachedDocumentStore } from "@vultro/core";
3
+ // src/runtime.ts
4
+ /** D1 文档存储实现:内存读缓存 + 异步批量写。 */
5
+ registerDocStore("d1", (_runtime, context) => {
6
+ if (!context.d1) throw new Error("d1Store requires a D1 database");
7
+ return new AsyncCachedDocumentStore(context.schema, context.d1);
8
+ });
@@ -0,0 +1,67 @@
1
+ /**
2
+ * ============================================================================
3
+ * Sharded D1 文档存储
4
+ * ============================================================================
5
+ *
6
+ * `runtime-cf` 支持 sharded docstore;这里实现一个与 `AsyncCachedDocumentStore`
7
+ * 兼容的分片层:
8
+ *
9
+ * - 每个 shard 是独立的 D1 database;
10
+ * - 文档按 ID 的稳定哈希路由到某个 shard;
11
+ * - 单文档 get / 写入只命中一个 shard;
12
+ * - 全表 scan / search / vector 查询合并所有 shard;
13
+ * - 跨 shard 的 mutation 不是原子事务(分片存储的固有限制),提交按 shard
14
+ * 并行执行;需要强原子的写入应留在单个 shard。
15
+ *
16
+ * schema 会为每个 shard 克隆一份,保证每个 D1 独立完成建表和编号。
17
+ */
18
+ import type { D1DatabaseLike } from "@vultro/core/d1";
19
+ import { AsyncCachedDocumentStore } from "@vultro/core";
20
+ import type { Doc, HistoryEntry, PendingWrite } from "@vultro/core";
21
+ import type { IndexInfo, SchemaInfo, SearchIndexInfo, TableInfo, VectorIndexInfo } from "@vultro/core/schema-info";
22
+ /** 与 D1AsyncStoreLike 对齐的分片文档存储。 */
23
+ export declare class ShardedAsyncDocumentStore {
24
+ readonly isAsync = true;
25
+ private readonly stores;
26
+ constructor(schema: SchemaInfo, databases: D1DatabaseLike[]);
27
+ /** shard 数量,供 dashboard / 测试观察。 */
28
+ get shardCount(): number;
29
+ /** 某个 shard 的文档数量。 */
30
+ shardSize(shard: number): number;
31
+ /** 根据文档 ID 选择 shard。 */
32
+ shardForId(id: string): number;
33
+ get commitTs(): number;
34
+ nextCommitTs(): number;
35
+ getTable(name: string): TableInfo;
36
+ findTable(name: string): TableInfo | undefined;
37
+ getTableByNumber(number: number): TableInfo | undefined;
38
+ get(table: TableInfo, id: string): Doc | null;
39
+ scan(table: TableInfo): Doc[];
40
+ /** 当前所有 shard 中某张表的文档数。 */
41
+ count(table: TableInfo): number;
42
+ getAsync(table: TableInfo, id: string): Promise<Doc | null>;
43
+ scanAsync(table: TableInfo): Promise<Doc[]>;
44
+ commitAsync(writes: Iterable<PendingWrite>, timestamp: number): Promise<void>;
45
+ searchDocIds(table: TableInfo, index: SearchIndexInfo, tokens: string[], filters: Array<{
46
+ field: string;
47
+ valueJson: string;
48
+ }>): Promise<Set<string> | null>;
49
+ vectorEntries(table: TableInfo, index: VectorIndexInfo): Promise<Array<{
50
+ docId: string;
51
+ vector: number[];
52
+ bytes: number;
53
+ }> | null>;
54
+ findIndexDocIds(table: TableInfo, index: IndexInfo, field: string, value: unknown): Set<string>;
55
+ allIndexDocIds(table: TableInfo, index: IndexInfo): Set<string>;
56
+ createTable(name: string): TableInfo;
57
+ load(): Promise<void>;
58
+ flush(): Promise<void>;
59
+ listHistoryAsync(options?: Parameters<AsyncCachedDocumentStore["listHistoryAsync"]>[0]): Promise<{
60
+ entries: HistoryEntry[];
61
+ total: number;
62
+ limit: number;
63
+ offset: number;
64
+ }>;
65
+ countHistory(): number;
66
+ documentCount(): number;
67
+ }
@@ -0,0 +1,134 @@
1
+ import { AsyncCachedDocumentStore } from "@vultro/core";
2
+ // src/sharded.ts
3
+ /** 稳定 FNV-1a 哈希;同一文档 ID 永远落到同一 shard。 */
4
+ function hashShard(id, shards) {
5
+ let hash = 0x811c9dc5;
6
+ for (let i = 0; i < id.length; i++) {
7
+ hash ^= id.charCodeAt(i);
8
+ hash = Math.imul(hash, 16777619) >>> 0;
9
+ }
10
+ return hash % shards;
11
+ }
12
+ /** 深拷贝 schema 的索引 Map,避免各 shard 共享可变元数据。 */
13
+ function cloneSchema(schema) {
14
+ const tables = /* @__PURE__ */ new Map();
15
+ for (const [name, table] of schema.tables) tables.set(name, {
16
+ ...table,
17
+ indexes: new Map(table.indexes),
18
+ searchIndexes: table.searchIndexes ? new Map(table.searchIndexes) : void 0,
19
+ vectorIndexes: table.vectorIndexes ? new Map(table.vectorIndexes) : void 0
20
+ });
21
+ return {
22
+ tables,
23
+ order: [...schema.order]
24
+ };
25
+ }
26
+ /** 与 D1AsyncStoreLike 对齐的分片文档存储。 */
27
+ var ShardedAsyncDocumentStore = class {
28
+ isAsync = true;
29
+ stores;
30
+ constructor(schema, databases) {
31
+ if (databases.length === 0) throw new Error("Sharded docstore requires at least one D1 database");
32
+ this.stores = databases.map((database) => new AsyncCachedDocumentStore(cloneSchema(schema), database));
33
+ }
34
+ /** shard 数量,供 dashboard / 测试观察。 */
35
+ get shardCount() {
36
+ return this.stores.length;
37
+ }
38
+ /** 某个 shard 的文档数量。 */
39
+ shardSize(shard) {
40
+ return this.stores[shard]?.documentCount() ?? 0;
41
+ }
42
+ /** 根据文档 ID 选择 shard。 */
43
+ shardForId(id) {
44
+ return hashShard(id, this.stores.length);
45
+ }
46
+ get commitTs() {
47
+ return this.stores[0].commitTs;
48
+ }
49
+ nextCommitTs() {
50
+ return this.stores[0].nextCommitTs();
51
+ }
52
+ getTable(name) {
53
+ return this.stores[0].getTable(name);
54
+ }
55
+ findTable(name) {
56
+ return this.stores[0].findTable(name);
57
+ }
58
+ getTableByNumber(number) {
59
+ return this.stores[0].getTableByNumber(number);
60
+ }
61
+ get(table, id) {
62
+ return this.stores[this.shardForId(id)].get(table, id);
63
+ }
64
+ scan(table) {
65
+ return this.stores.flatMap((store) => store.scan(table));
66
+ }
67
+ /** 当前所有 shard 中某张表的文档数。 */
68
+ count(table) {
69
+ return this.stores.reduce((sum, store) => sum + store.count(table), 0);
70
+ }
71
+ async getAsync(table, id) {
72
+ return this.stores[this.shardForId(id)].getAsync(table, id);
73
+ }
74
+ async scanAsync(table) {
75
+ return (await Promise.all(this.stores.map((store) => store.scanAsync(table)))).flat();
76
+ }
77
+ async commitAsync(writes, timestamp) {
78
+ const groups = /* @__PURE__ */ new Map();
79
+ for (const write of writes) {
80
+ const shard = this.shardForId(write.id);
81
+ const group = groups.get(shard) ?? [];
82
+ group.push(write);
83
+ groups.set(shard, group);
84
+ }
85
+ await Promise.all([...groups].map(([shard, group]) => this.stores[shard].commitAsync(group, timestamp)));
86
+ }
87
+ async searchDocIds(table, index, tokens, filters) {
88
+ const results = await Promise.all(this.stores.map((store) => store.searchDocIds(table, index, tokens, filters)));
89
+ if (results.some((result) => result === null)) return null;
90
+ const union = /* @__PURE__ */ new Set();
91
+ for (const result of results) for (const id of result) union.add(id);
92
+ return union;
93
+ }
94
+ async vectorEntries(table, index) {
95
+ const results = await Promise.all(this.stores.map((store) => store.vectorEntries(table, index)));
96
+ if (results.some((result) => result === null)) return null;
97
+ return results.flatMap((result) => result);
98
+ }
99
+ findIndexDocIds(table, index, field, value) {
100
+ const union = /* @__PURE__ */ new Set();
101
+ for (const store of this.stores) for (const id of store.findIndexDocIds(table, index, field, value)) union.add(id);
102
+ return union;
103
+ }
104
+ allIndexDocIds(table, index) {
105
+ const union = /* @__PURE__ */ new Set();
106
+ for (const store of this.stores) for (const id of store.allIndexDocIds(table, index)) union.add(id);
107
+ return union;
108
+ }
109
+ createTable(name) {
110
+ return this.stores.map((store) => store.createTable(name))[0];
111
+ }
112
+ async load() {
113
+ await Promise.all(this.stores.map((store) => store.load()));
114
+ }
115
+ async flush() {
116
+ await Promise.all(this.stores.map((store) => store.flush()));
117
+ }
118
+ async listHistoryAsync(options = {}) {
119
+ const results = await Promise.all(this.stores.map((store) => store.listHistoryAsync(options)));
120
+ return {
121
+ entries: results.flatMap((result) => result.entries).sort((a, b) => b.commitTs - a.commitTs || b.seq - a.seq).slice(options.offset ?? 0, (options.offset ?? 0) + (options.limit ?? 50)),
122
+ total: results.reduce((sum, result) => sum + result.total, 0),
123
+ limit: options.limit ?? 50,
124
+ offset: options.offset ?? 0
125
+ };
126
+ }
127
+ countHistory() {
128
+ return this.stores.reduce((sum, store) => sum + store.countHistory(), 0);
129
+ }
130
+ documentCount() {
131
+ return this.stores.reduce((sum, store) => sum + store.documentCount(), 0);
132
+ }
133
+ };
134
+ export { ShardedAsyncDocumentStore };
package/package.json CHANGED
@@ -1,6 +1,30 @@
1
1
  {
2
2
  "name": "@vultro/docstore-d1",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.0.1",
4
+ "type": "module",
5
+ "description": "D1 document store backend for Vultro",
6
+ "exports": {
7
+ ".": {
8
+ "types": "./dist/index.d.ts",
9
+ "import": "./dist/index.js",
10
+ "default": "./dist/index.js"
11
+ },
12
+ "./runtime": {
13
+ "types": "./dist/runtime.d.ts",
14
+ "import": "./dist/runtime.js",
15
+ "default": "./dist/runtime.js"
16
+ },
17
+ "./sharded": {
18
+ "types": "./dist/sharded.d.ts",
19
+ "import": "./dist/sharded.js",
20
+ "default": "./dist/sharded.js"
21
+ }
22
+ },
23
+ "dependencies": {
24
+ "@vultro/core": "0.0.1"
25
+ },
26
+ "publishConfig": {
27
+ "access": "public"
28
+ },
29
+ "types": "./dist/index.d.ts"
30
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.