@vultro/runtime-cf 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,101 @@
1
+ /**
2
+ * ============================================================================
3
+ * Isolated UDF executor
4
+ * ============================================================================
5
+ *
6
+ * 隔离执行时,UDF 代码运行在独立 Worker entrypoint(`UdfExecutorRpc`),
7
+ * 不能直接访问 RuntimeDO 的 SQLite。这里提供一个远程 DocumentStore:
8
+ *
9
+ * - `getAsync` / `scanAsync` → DATA_SERVICE.storeGet / storeScan;
10
+ * - `commitAsync` → DATA_SERVICE.storeCommit;
11
+ * - search / vector → DATA_SERVICE.storeSearch / storeVector。
12
+ *
13
+ * Runtime 仍然使用真实的 QueryBuilder / Transaction / schema 校验,只是底层
14
+ * 存储通过网络访问。内部服务(scheduler/cron/storage)在隔离执行中暂不持久化。
15
+ */
16
+ import type { Doc, PendingWrite } from "@vultro/core";
17
+ import type { D1AsyncStoreLike } from "@vultro/core";
18
+ import type { SchemaInfo, SearchIndexInfo, TableInfo, VectorIndexInfo } from "@vultro/core";
19
+ import type { RuntimeEnv } from "./platform.js";
20
+ import { type RpcEntrypointBase } from "./rpc.js";
21
+ /** DATA_SERVICE 暴露给 isolated UDF worker 的数据接口。 */
22
+ export interface IsolatedDataServiceLike {
23
+ storeGet(table: string, id: string): Promise<Doc | null>;
24
+ storeScan(table: string): Promise<Doc[]>;
25
+ storeCommit(writes: PendingWrite[], timestamp: number): Promise<{
26
+ version?: number;
27
+ } | void>;
28
+ storeSearch(table: string, index: string, tokens: string[], filters: Array<{
29
+ field: string;
30
+ valueJson: string;
31
+ }>): Promise<string[] | null>;
32
+ storeVector(table: string, index: string): Promise<Array<{
33
+ docId: string;
34
+ vector: number[];
35
+ bytes: number;
36
+ }> | null>;
37
+ storageStore(data: string, contentType?: string): Promise<string>;
38
+ storageGet(storageId: string): Promise<string | null>;
39
+ storageGetMetadata(storageId: string): Promise<{
40
+ size: number;
41
+ contentType?: string;
42
+ } | null>;
43
+ storageGetUrl(storageId: string): Promise<string | null>;
44
+ storageDelete(storageId: string): Promise<void>;
45
+ storageGenerateUploadUrl(): Promise<string>;
46
+ schedulerRunAt(runAt: number, path: string, argsJson: string, kind: "mutation" | "action", id?: string): Promise<string>;
47
+ schedulerCancel(id: string): Promise<void>;
48
+ }
49
+ /** 通过 DATA_SERVICE 访问 RuntimeDO 的异步文档存储。 */
50
+ export declare class RemoteDocumentStore implements D1AsyncStoreLike {
51
+ private readonly schema;
52
+ private readonly service;
53
+ readonly isAsync = true;
54
+ private commitTimestamp;
55
+ constructor(schema: SchemaInfo, service: IsolatedDataServiceLike);
56
+ get commitTs(): number;
57
+ nextCommitTs(): number;
58
+ getTable(name: string): TableInfo;
59
+ findTable(name: string): TableInfo | undefined;
60
+ getTableByNumber(number: number): TableInfo | undefined;
61
+ getAsync(table: TableInfo, id: string): Promise<Doc | null>;
62
+ scanAsync(table: TableInfo): Promise<Doc[]>;
63
+ commitAsync(writes: Iterable<PendingWrite>, timestamp: number): Promise<void>;
64
+ searchDocIds(table: TableInfo, index: SearchIndexInfo, tokens: string[], filters: Array<{
65
+ field: string;
66
+ valueJson: string;
67
+ }>): Promise<Set<string> | null>;
68
+ vectorEntries(table: TableInfo, index: VectorIndexInfo): Promise<Array<{
69
+ docId: string;
70
+ vector: number[];
71
+ bytes: number;
72
+ }> | null>;
73
+ load(): Promise<void>;
74
+ flush(): Promise<void>;
75
+ documentCount(): number;
76
+ }
77
+ export interface IsolatedUdfExecutorOptions {
78
+ schema: SchemaInfo;
79
+ modules: Record<string, unknown>;
80
+ /** Service binding name;默认 DATA_SERVICE。 */
81
+ dataServiceBinding?: string;
82
+ /** 生产环境传 WorkerEntrypoint。 */
83
+ workerEntrypointBase?: RpcEntrypointBase;
84
+ }
85
+ /**
86
+ * IsolatedUdfExecutor 对外的公开契约。
87
+ *
88
+ * 工厂返回匿名 class;显式声明公开方法,避免声明生成阶段把私有字段带进
89
+ * `.d.ts`(TS4094),同时固定发布包只暴露执行入口。
90
+ */
91
+ export interface IsolatedUdfExecutorInstance {
92
+ /** 自定义 WorkerEntrypoint 基类可能暴露的字段。 */
93
+ ctx?: unknown;
94
+ env?: unknown;
95
+ query(path: string, argsJson?: string, identityJson?: string): Promise<unknown>;
96
+ mutation(path: string, argsJson?: string, identityJson?: string): Promise<unknown>;
97
+ action(path: string, argsJson?: string, identityJson?: string): Promise<unknown>;
98
+ execute(kind: "query" | "mutation" | "action", path: string, argsJson?: string, identityJson?: string): Promise<unknown>;
99
+ }
100
+ /** 在 isolated Worker entrypoint 中执行 query / mutation / action。 */
101
+ export declare function createIsolatedUdfExecutor(options: IsolatedUdfExecutorOptions): new (ctx: unknown, env: RuntimeEnv) => IsolatedUdfExecutorInstance;
@@ -0,0 +1,175 @@
1
+ import { Runtime } from "@vultro/core";
2
+ import { PlainRpcEntrypoint } from "./rpc.js";
3
+ // src/isolated.ts
4
+ var noopSql = {
5
+ exec: (sql) => {
6
+ const head = sql.trimStart().slice(0, 6).toLowerCase();
7
+ if ([
8
+ "insert",
9
+ "update",
10
+ "delete"
11
+ ].includes(head) && !sql.includes("_vultro_execution_logs")) throw new Error("Local SQLite writes are not available in isolated UDF execution; use DATA_SERVICE");
12
+ return [];
13
+ },
14
+ transactionSync: (fn) => fn()
15
+ };
16
+ /** 通过 DATA_SERVICE 访问 RuntimeDO 的异步文档存储。 */
17
+ var RemoteDocumentStore = class {
18
+ schema;
19
+ service;
20
+ isAsync = true;
21
+ commitTimestamp = Date.now();
22
+ constructor(schema, service) {
23
+ this.schema = schema;
24
+ this.service = service;
25
+ schema.order.forEach((name, index) => {
26
+ const table = schema.tables.get(name);
27
+ if (table && table.number === 0) table.number = index + 1;
28
+ });
29
+ }
30
+ get commitTs() {
31
+ return this.commitTimestamp;
32
+ }
33
+ nextCommitTs() {
34
+ this.commitTimestamp = Math.max(this.commitTimestamp + 1, Date.now());
35
+ return this.commitTimestamp;
36
+ }
37
+ getTable(name) {
38
+ const table = this.schema.tables.get(name);
39
+ if (!table) throw new Error(`Table "${name}" is not in this schema`);
40
+ return table;
41
+ }
42
+ findTable(name) {
43
+ return this.schema.tables.get(name);
44
+ }
45
+ getTableByNumber(number) {
46
+ for (const table of this.schema.tables.values()) if (table.number === number) return table;
47
+ }
48
+ async getAsync(table, id) {
49
+ return this.service.storeGet(table.name, id);
50
+ }
51
+ async scanAsync(table) {
52
+ return this.service.storeScan(table.name);
53
+ }
54
+ async commitAsync(writes, timestamp) {
55
+ const version = (await this.service.storeCommit([...writes], timestamp))?.version;
56
+ this.commitTimestamp = Math.max(this.commitTimestamp, Number(version ?? timestamp));
57
+ }
58
+ async searchDocIds(table, index, tokens, filters) {
59
+ const ids = await this.service.storeSearch(table.name, index.name, tokens, filters);
60
+ return ids === null ? null : new Set(ids);
61
+ }
62
+ async vectorEntries(table, index) {
63
+ return this.service.storeVector(table.name, index.name);
64
+ }
65
+ async load() {}
66
+ async flush() {}
67
+ documentCount() {
68
+ return 0;
69
+ }
70
+ };
71
+ /** 在 isolated Worker entrypoint 中执行 query / mutation / action。 */
72
+ function createIsolatedUdfExecutor(options) {
73
+ const dataServiceBinding = options.dataServiceBinding ?? "DATA_SERVICE";
74
+ const base = options.workerEntrypointBase ?? PlainRpcEntrypoint;
75
+ return class IsolatedUdfExecutor extends base {
76
+ runtime;
77
+ getRuntime() {
78
+ if (this.runtime) return this.runtime;
79
+ const service = this.env[dataServiceBinding];
80
+ if (!service) throw new Error(`Missing isolated data service binding "${dataServiceBinding}"`);
81
+ const store = new RemoteDocumentStore(options.schema, service);
82
+ this.runtime = new Runtime({
83
+ sql: noopSql,
84
+ schema: options.schema,
85
+ modules: options.modules,
86
+ store,
87
+ backend: "d1",
88
+ remote: {
89
+ storage: {
90
+ get: async (storageId) => {
91
+ const data = await service.storageGet(storageId);
92
+ return data === null ? null : decodeBase64(data);
93
+ },
94
+ getUrl: (storageId) => service.storageGetUrl(storageId),
95
+ getMetadata: (storageId) => service.storageGetMetadata(storageId),
96
+ generateUploadUrl: () => service.storageGenerateUploadUrl(),
97
+ delete: (storageId) => service.storageDelete(storageId),
98
+ store: (bytes, options) => service.storageStore(encodeBase64(bytes), options?.contentType)
99
+ },
100
+ scheduler: {
101
+ runAt: (runAt, path, args, kind, id) => service.schedulerRunAt(runAt, path, JSON.stringify(args), kind, id),
102
+ cancel: (id) => service.schedulerCancel(id)
103
+ }
104
+ }
105
+ });
106
+ return this.runtime;
107
+ }
108
+ async run(kind, path, args, identity) {
109
+ const runtime = this.getRuntime();
110
+ if (kind === "query") {
111
+ const result = await runtime.runPublicQuery(path, args, { identity });
112
+ return {
113
+ status: "success",
114
+ value: result.result,
115
+ logLines: result.logLines
116
+ };
117
+ }
118
+ if (kind === "mutation") {
119
+ const result = await runtime.runPublicMutation(path, args, { identity });
120
+ return {
121
+ status: "success",
122
+ value: result.result,
123
+ version: result.version,
124
+ logLines: result.logLines
125
+ };
126
+ }
127
+ const result = await runtime.runPublicAction(path, args, { identity });
128
+ return {
129
+ status: "success",
130
+ value: result.result,
131
+ logLines: result.logLines
132
+ };
133
+ }
134
+ async query(path, argsJson = "{}", identityJson) {
135
+ return this.run("query", path, parseArgs(argsJson), parseIdentity(identityJson));
136
+ }
137
+ async mutation(path, argsJson = "{}", identityJson) {
138
+ return this.run("mutation", path, parseArgs(argsJson), parseIdentity(identityJson));
139
+ }
140
+ async action(path, argsJson = "{}", identityJson) {
141
+ return this.run("action", path, parseArgs(argsJson), parseIdentity(identityJson));
142
+ }
143
+ async execute(kind, path, argsJson = "{}", identityJson) {
144
+ return this.run(kind, path, parseArgs(argsJson), parseIdentity(identityJson));
145
+ }
146
+ };
147
+ }
148
+ function parseArgs(value) {
149
+ try {
150
+ const parsed = JSON.parse(value);
151
+ return parsed && typeof parsed === "object" ? parsed : {};
152
+ } catch {
153
+ return {};
154
+ }
155
+ }
156
+ function parseIdentity(value) {
157
+ if (!value) return void 0;
158
+ try {
159
+ return JSON.parse(value);
160
+ } catch {
161
+ return;
162
+ }
163
+ }
164
+ function encodeBase64(bytes) {
165
+ let binary = "";
166
+ for (const byte of bytes) binary += String.fromCharCode(byte);
167
+ return btoa(binary);
168
+ }
169
+ function decodeBase64(value) {
170
+ const binary = atob(value);
171
+ const bytes = new Uint8Array(binary.length);
172
+ for (let index = 0; index < binary.length; index++) bytes[index] = binary.charCodeAt(index);
173
+ return bytes;
174
+ }
175
+ export { RemoteDocumentStore, createIsolatedUdfExecutor };
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Cloudflare Durable Object 的最小平台类型。
3
+ *
4
+ * 不直接依赖 `@cloudflare/workers-types` 有两个好处:
5
+ * 1. 本包可以在 Bun 里做单元测试;
6
+ * 2. 运行时只使用真正需要的 API,避免平台类型污染核心逻辑。
7
+ *
8
+ * 这些接口是结构化类型,Cloudflare 运行时传入的真实对象天然满足它们。
9
+ */
10
+ import type { SqlStorageLike } from "@vultro/core";
11
+ export interface DurableObjectStorageLike {
12
+ /** SQLite 存储(`storage: "sqlite"` 的 DO 才有)。 */
13
+ sql?: SqlStorageLike;
14
+ /** 同步事务包装器,用于原子提交。 */
15
+ transactionSync?<T>(fn: () => T): T;
16
+ /** 分布式 alarm,用于 WebSocket 保活等定时任务。 */
17
+ setAlarm?(scheduledTime: number): Promise<void>;
18
+ getAlarm?(): Promise<number | null>;
19
+ deleteAlarm?(): Promise<void>;
20
+ }
21
+ export interface DurableObjectStateLike {
22
+ storage: DurableObjectStorageLike;
23
+ /** 允许在请求结束后继续执行后台任务。 */
24
+ waitUntil?(promise: Promise<unknown>): void;
25
+ blockConcurrencyWhile?<T>(fn: () => Promise<T>): Promise<T>;
26
+ }
27
+ export interface DurableObjectStubLike {
28
+ fetch(request: Request | string, init?: RequestInit): Promise<Response>;
29
+ }
30
+ export interface DurableObjectGetOptions {
31
+ /** Cloudflare location hint,例如 enam / weur / apac / eeur。 */
32
+ locationHint?: string;
33
+ }
34
+ export interface DurableObjectNamespaceLike {
35
+ idFromName(name: string): unknown;
36
+ get(id: unknown, options?: DurableObjectGetOptions): DurableObjectStubLike;
37
+ }
38
+ /** Worker / Durable Object 的 env 形状。 */
39
+ export interface RuntimeEnv {
40
+ VULTRO_DO?: DurableObjectNamespaceLike;
41
+ VULTRO_SYNC_DO?: DurableObjectNamespaceLike;
42
+ [key: string]: unknown;
43
+ }
File without changes
package/dist/rpc.d.ts ADDED
@@ -0,0 +1,101 @@
1
+ /**
2
+ * ============================================================================
3
+ * Worker RPC entrypoints
4
+ * ============================================================================
5
+ *
6
+ * Cloudflare Workers RPC 要求 entrypoint 类继承 `WorkerEntrypoint`。核心包不能
7
+ * 直接 import `cloudflare:workers`(Bun 测试环境没有该模块),因此 RPC 类由
8
+ * 工厂创建,并允许调用方传入 WorkerEntrypoint 基类:
9
+ *
10
+ * ```ts
11
+ * import { WorkerEntrypoint } from "cloudflare:workers";
12
+ * const composition = defineWorker({
13
+ * modules,
14
+ * workerEntrypointBase: WorkerEntrypoint,
15
+ * });
16
+ * ```
17
+ *
18
+ * 未传入基类时使用普通类,便于单元测试和非 Worker 环境使用。
19
+ *
20
+ * 这三个 entrypoint 的职责:
21
+ * - DataService:让 isolated UDF 通过 service binding 读写数据;
22
+ * - UdfExecutorRpc:执行 query / mutation / action 的 RPC 入口;
23
+ * - SyncTransportRpc:把提交版本广播到 SyncDO。
24
+ */
25
+ import type { RuntimeEnv } from "./platform.js";
26
+ /** 默认 RPC 基类;生产环境应由调用方传入 WorkerEntrypoint。 */
27
+ export declare class PlainRpcEntrypoint {
28
+ readonly ctx: unknown;
29
+ readonly env: RuntimeEnv;
30
+ constructor(ctx: unknown, env: RuntimeEnv);
31
+ }
32
+ export type RpcEntrypointBase = abstract new (ctx: any, env: any) => {
33
+ env?: RuntimeEnv;
34
+ } | unknown;
35
+ export interface RpcBindingNames {
36
+ runtimeDO?: string;
37
+ syncDO?: string;
38
+ }
39
+ export interface RpcEntrypointOptions {
40
+ workerEntrypointBase?: RpcEntrypointBase;
41
+ bindings?: RpcBindingNames;
42
+ }
43
+ /**
44
+ * DataService RPC entrypoint 对外的公开契约。
45
+ *
46
+ * 工厂返回的是匿名 class,直接推导返回类型会把 `private` 字段带进 `.d.ts`,
47
+ * TypeScript 会报 TS4094(无法为含私有成员的匿名类型生成声明)。这里显式
48
+ * 声明公开方法,既解决声明生成,也让发布包的类型只暴露稳定接口。
49
+ */
50
+ export interface DataServiceRpcInstance {
51
+ /** 自定义 WorkerEntrypoint 基类可能暴露的字段。 */
52
+ ctx?: unknown;
53
+ env?: unknown;
54
+ query(path: string, argsJson?: string, identityJson?: string): Promise<unknown>;
55
+ mutation(path: string, argsJson?: string, identityJson?: string): Promise<unknown>;
56
+ action(path: string, argsJson?: string, identityJson?: string): Promise<unknown>;
57
+ storeGet(table: string, id: string): Promise<unknown>;
58
+ storeScan(table: string): Promise<unknown>;
59
+ storeCommit(writes: unknown[], timestamp: number): Promise<unknown>;
60
+ storeSearch(table: string, index: string, tokens: string[], filters: Array<{
61
+ field: string;
62
+ valueJson: string;
63
+ }>): Promise<unknown>;
64
+ storeVector(table: string, index: string): Promise<unknown>;
65
+ storeNextCommit(): Promise<unknown>;
66
+ storageStore(data: string, contentType?: string): Promise<unknown>;
67
+ storageGet(storageId: string): Promise<unknown>;
68
+ storageGetMetadata(storageId: string): Promise<unknown>;
69
+ storageGetUrl(storageId: string): Promise<unknown>;
70
+ storageDelete(storageId: string): Promise<unknown>;
71
+ storageGenerateUploadUrl(): Promise<unknown>;
72
+ schedulerRunAt(runAt: number, path: string, argsJson: string, kind: "mutation" | "action", id?: string): Promise<unknown>;
73
+ schedulerCancel(id: string): Promise<unknown>;
74
+ runQuery(path: string, argsJson?: string, identityJson?: string): Promise<unknown>;
75
+ runMutation(path: string, argsJson?: string, identityJson?: string): Promise<unknown>;
76
+ runAction(path: string, argsJson?: string, identityJson?: string): Promise<unknown>;
77
+ }
78
+ /** UdfExecutorRpc 对外的公开契约(见 `DataServiceRpcInstance` 的声明说明)。 */
79
+ export interface UdfExecutorRpcInstance {
80
+ /** 自定义 WorkerEntrypoint 基类可能暴露的字段。 */
81
+ ctx?: unknown;
82
+ env?: unknown;
83
+ query(path: string, argsJson?: string, identityJson?: string): Promise<unknown>;
84
+ mutation(path: string, argsJson?: string, identityJson?: string): Promise<unknown>;
85
+ action(path: string, argsJson?: string, identityJson?: string): Promise<unknown>;
86
+ execute(kind: "query" | "mutation" | "action", path: string, argsJson?: string, identityJson?: string): Promise<unknown>;
87
+ }
88
+ /** SyncTransportRpc 对外的公开契约(见 `DataServiceRpcInstance` 的声明说明)。 */
89
+ export interface SyncTransportRpcInstance {
90
+ /** 自定义 WorkerEntrypoint 基类可能暴露的字段。 */
91
+ ctx?: unknown;
92
+ env?: unknown;
93
+ notify(version: number, shard?: number): Promise<unknown>;
94
+ broadcast(version: number): Promise<unknown>;
95
+ }
96
+ /** 创建 DataService RPC entrypoint。 */
97
+ export declare function createDataServiceRpc(options?: RpcEntrypointOptions): new (ctx: unknown, env: RuntimeEnv) => DataServiceRpcInstance;
98
+ /** 创建 UdfExecutorRpc RPC entrypoint。 */
99
+ export declare function createUdfExecutorRpc(options?: RpcEntrypointOptions): new (ctx: unknown, env: RuntimeEnv) => UdfExecutorRpcInstance;
100
+ /** 创建 SyncTransportRpc RPC entrypoint。 */
101
+ export declare function createSyncTransportRpc(options?: RpcEntrypointOptions): new (ctx: unknown, env: RuntimeEnv) => SyncTransportRpcInstance;
package/dist/rpc.js ADDED
@@ -0,0 +1,193 @@
1
+ import { syncShardNames } from "@vultro/core";
2
+ // src/rpc.ts
3
+ /** 默认 RPC 基类;生产环境应由调用方传入 WorkerEntrypoint。 */
4
+ var PlainRpcEntrypoint = class {
5
+ ctx;
6
+ env;
7
+ constructor(ctx, env) {
8
+ this.ctx = ctx;
9
+ this.env = env;
10
+ }
11
+ };
12
+ function readEnv(instance, fallback) {
13
+ const env = instance?.env ?? fallback;
14
+ if (!env) throw new Error("RPC entrypoint is missing Workers env");
15
+ return env;
16
+ }
17
+ function parseJson(value) {
18
+ if (value === void 0 || value === "") return void 0;
19
+ try {
20
+ return JSON.parse(value);
21
+ } catch {
22
+ return value;
23
+ }
24
+ }
25
+ async function fetchBinding(env, bindingName, instanceName, path, body) {
26
+ const namespace = env[bindingName];
27
+ if (!namespace || typeof namespace.get !== "function") throw new Error(`Missing Durable Object binding "${bindingName}"`);
28
+ const text = await (await namespace.get(namespace.idFromName(instanceName)).fetch(new Request(`https://rpc.internal${path}`, {
29
+ method: "POST",
30
+ headers: { "content-type": "application/json" },
31
+ body: JSON.stringify(body)
32
+ }))).text();
33
+ if (text === "") return null;
34
+ try {
35
+ return JSON.parse(text);
36
+ } catch {
37
+ return text;
38
+ }
39
+ }
40
+ function dataRequestBody(path, argsJson, identityJson) {
41
+ return {
42
+ path,
43
+ args: parseJson(argsJson) ?? {},
44
+ ...identityJson ? { identity: parseJson(identityJson) } : {}
45
+ };
46
+ }
47
+ /** 创建 DataService RPC entrypoint。 */
48
+ function createDataServiceRpc(options = {}) {
49
+ const base = options.workerEntrypointBase ?? PlainRpcEntrypoint;
50
+ const binding = options.bindings?.runtimeDO ?? "VULTRO_DO";
51
+ return class DataService extends base {
52
+ get runtimeEnv() {
53
+ return readEnv(this);
54
+ }
55
+ async query(path, argsJson = "{}", identityJson) {
56
+ return fetchBinding(this.runtimeEnv, binding, "global", "/internal/query", dataRequestBody(path, argsJson, identityJson));
57
+ }
58
+ async mutation(path, argsJson = "{}", identityJson) {
59
+ return fetchBinding(this.runtimeEnv, binding, "global", "/internal/mutation", dataRequestBody(path, argsJson, identityJson));
60
+ }
61
+ async action(path, argsJson = "{}", identityJson) {
62
+ return fetchBinding(this.runtimeEnv, binding, "global", "/internal/action", dataRequestBody(path, argsJson, identityJson));
63
+ }
64
+ /** isolated UDF worker 的远程存储接口。 */
65
+ async storeGet(table, id) {
66
+ return (await fetchBinding(this.runtimeEnv, binding, "global", "/internal/store/get", {
67
+ table,
68
+ id
69
+ }))?.doc ?? null;
70
+ }
71
+ async storeScan(table) {
72
+ return (await fetchBinding(this.runtimeEnv, binding, "global", "/internal/store/scan", { table }))?.docs ?? [];
73
+ }
74
+ async storeCommit(writes, timestamp) {
75
+ return fetchBinding(this.runtimeEnv, binding, "global", "/internal/store/commit", {
76
+ writes,
77
+ timestamp
78
+ });
79
+ }
80
+ async storeSearch(table, index, tokens, filters) {
81
+ return (await fetchBinding(this.runtimeEnv, binding, "global", "/internal/store/search", {
82
+ table,
83
+ index,
84
+ tokens,
85
+ filters
86
+ }))?.ids ?? null;
87
+ }
88
+ async storeVector(table, index) {
89
+ return (await fetchBinding(this.runtimeEnv, binding, "global", "/internal/store/vector", {
90
+ table,
91
+ index
92
+ }))?.entries ?? null;
93
+ }
94
+ async storeNextCommit() {
95
+ const body = await fetchBinding(this.runtimeEnv, binding, "global", "/internal/store/next-commit", {});
96
+ return Number(body?.version ?? 0);
97
+ }
98
+ async storageStore(data, contentType) {
99
+ const body = await fetchBinding(this.runtimeEnv, binding, "global", "/internal/storage/store", {
100
+ data,
101
+ contentType
102
+ });
103
+ return String(body?.storageId ?? "");
104
+ }
105
+ async storageGet(storageId) {
106
+ return (await fetchBinding(this.runtimeEnv, binding, "global", "/internal/storage/get", { storageId }))?.data ?? null;
107
+ }
108
+ async storageGetMetadata(storageId) {
109
+ return (await fetchBinding(this.runtimeEnv, binding, "global", "/internal/storage/metadata", { storageId }))?.metadata ?? null;
110
+ }
111
+ async storageGetUrl(storageId) {
112
+ return (await fetchBinding(this.runtimeEnv, binding, "global", "/internal/storage/url", { storageId }))?.url ?? null;
113
+ }
114
+ async storageDelete(storageId) {
115
+ await fetchBinding(this.runtimeEnv, binding, "global", "/internal/storage/delete", { storageId });
116
+ }
117
+ async storageGenerateUploadUrl() {
118
+ const body = await fetchBinding(this.runtimeEnv, binding, "global", "/internal/storage/upload-url", {});
119
+ return String(body?.url ?? "");
120
+ }
121
+ async schedulerRunAt(runAt, path, argsJson, kind, id) {
122
+ const body = await fetchBinding(this.runtimeEnv, binding, "global", "/internal/scheduler/run-at", {
123
+ path,
124
+ args: parseJson(argsJson) ?? {},
125
+ runAt,
126
+ kind,
127
+ id
128
+ });
129
+ return String(body?.id ?? "");
130
+ }
131
+ async schedulerCancel(id) {
132
+ await fetchBinding(this.runtimeEnv, binding, "global", "/internal/scheduler/cancel", { id });
133
+ }
134
+ async runQuery(path, argsJson = "{}", identityJson) {
135
+ return this.query(path, argsJson, identityJson);
136
+ }
137
+ async runMutation(path, argsJson = "{}", identityJson) {
138
+ return this.mutation(path, argsJson, identityJson);
139
+ }
140
+ async runAction(path, argsJson = "{}", identityJson) {
141
+ return this.action(path, argsJson, identityJson);
142
+ }
143
+ };
144
+ }
145
+ /** 创建 UdfExecutorRpc RPC entrypoint。 */
146
+ function createUdfExecutorRpc(options = {}) {
147
+ const base = options.workerEntrypointBase ?? PlainRpcEntrypoint;
148
+ const binding = options.bindings?.runtimeDO ?? "VULTRO_DO";
149
+ return class UdfExecutorRpc extends base {
150
+ get runtimeEnv() {
151
+ return readEnv(this);
152
+ }
153
+ async query(path, argsJson = "{}", identityJson) {
154
+ return fetchBinding(this.runtimeEnv, binding, "global", "/internal/query", dataRequestBody(path, argsJson, identityJson));
155
+ }
156
+ async mutation(path, argsJson = "{}", identityJson) {
157
+ return fetchBinding(this.runtimeEnv, binding, "global", "/internal/mutation", dataRequestBody(path, argsJson, identityJson));
158
+ }
159
+ async action(path, argsJson = "{}", identityJson) {
160
+ return fetchBinding(this.runtimeEnv, binding, "global", "/internal/action", dataRequestBody(path, argsJson, identityJson));
161
+ }
162
+ /** 统一入口;kind 决定调用 query / mutation / action。 */
163
+ async execute(kind, path, argsJson = "{}", identityJson) {
164
+ return this[kind](path, argsJson, identityJson);
165
+ }
166
+ };
167
+ }
168
+ /** 创建 SyncTransportRpc RPC entrypoint。 */
169
+ function createSyncTransportRpc(options = {}) {
170
+ const base = options.workerEntrypointBase ?? PlainRpcEntrypoint;
171
+ const binding = options.bindings?.syncDO ?? "VULTRO_SYNC_DO";
172
+ return class SyncTransportRpc extends base {
173
+ get runtimeEnv() {
174
+ return readEnv(this);
175
+ }
176
+ /** 通知单个 shard;默认第一个 shard。 */
177
+ async notify(version, shard = 0) {
178
+ const env = this.runtimeEnv;
179
+ const shardCount = Number(env.VULTRO_SYNC_SHARDS ?? 1) || 1;
180
+ const names = syncShardNames(shardCount);
181
+ const name = names[shard] ?? names[0];
182
+ return fetchBinding(env, binding, name, "/notify", { version });
183
+ }
184
+ /** 向所有 shard 广播同一个提交版本。 */
185
+ async broadcast(version) {
186
+ const env = this.runtimeEnv;
187
+ const shardCount = Number(env.VULTRO_SYNC_SHARDS ?? 1) || 1;
188
+ const names = syncShardNames(shardCount);
189
+ return Promise.all(names.map((name) => fetchBinding(env, binding, name, "/notify", { version })));
190
+ }
191
+ };
192
+ }
193
+ export { PlainRpcEntrypoint, createDataServiceRpc, createSyncTransportRpc, createUdfExecutorRpc };
@@ -0,0 +1,36 @@
1
+ import type { SchedulerDriver, SchedulerDriverContext } from "@vultro/core";
2
+ import type { DurableObjectStorageLike } from "./platform.js";
3
+ /**
4
+ * ============================================================================
5
+ * Cloudflare Durable Object alarm 驱动器
6
+ * ============================================================================
7
+ *
8
+ * core 的 cron / scheduled job 只关心「下一次执行时间」;Cloudflare 上真正
9
+ * 的持久化定时器是 DO `storage.setAlarm()`。这个驱动器把两者接起来:
10
+ *
11
+ * - `schedule(runAt)`:设置 alarm,已有更早的 alarm 时不推迟;
12
+ * - `fire()`:DO `alarm()` 到点后执行 `runtime.runDueScheduledJobs()`;
13
+ * - `start()`:DO 冷启动时根据数据库里的 `next_run` 恢复 alarm;
14
+ * - `dispose()`:只标记停止,**不删除 alarm**——DO 被回收后 alarm 仍然
15
+ * 需要保留,平台下次会继续唤醒。
16
+ *
17
+ * 与 Bun / Node 的 `setTimeout` 驱动器不同,alarm 由 Cloudflare 持久化,
18
+ * 进程 / DO 重启不会丢失。
19
+ */
20
+ /** 创建 alarm 驱动器时的 DO 侧选项。 */
21
+ export interface AlarmSchedulerOptions {
22
+ /**
23
+ * 把设置 alarm 的 Promise 交给 `state.waitUntil()`。
24
+ *
25
+ * `constructor` / `scheduleAlarm` 不在请求上下文里,Cloudflare 要求通过
26
+ * `waitUntil` 延后异步工作,否则可能在 alarm 写入前进入空闲。
27
+ */
28
+ waitUntil?(promise: Promise<unknown>): void;
29
+ }
30
+ /**
31
+ * 创建 DO alarm 定时任务驱动器。
32
+ *
33
+ * `context` 由 `createRuntimeGraph` 所在适配层提供;`storage` 是 DO 的
34
+ * `state.storage`(只用到 alarm 相关 API)。
35
+ */
36
+ export declare function createAlarmSchedulerDriver(context: SchedulerDriverContext, storage: DurableObjectStorageLike, options?: AlarmSchedulerOptions): SchedulerDriver;