@vultro/runtime-cf 0.0.0-stage → 0.0.2
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/README.md +28 -2
- package/dist/config.d.ts +14 -0
- package/dist/config.js +1 -0
- package/dist/define.d.ts +119 -0
- package/dist/define.js +218 -0
- package/dist/durable-objects.d.ts +175 -0
- package/dist/durable-objects.js +583 -0
- package/dist/index.d.ts +27 -0
- package/dist/index.js +9 -0
- package/dist/isolated.d.ts +101 -0
- package/dist/isolated.js +175 -0
- package/dist/platform.d.ts +43 -0
- package/dist/platform.js +0 -0
- package/dist/rpc.d.ts +101 -0
- package/dist/rpc.js +193 -0
- package/dist/scheduler.d.ts +36 -0
- package/dist/scheduler.js +49 -0
- package/dist/storage.d.ts +22 -0
- package/dist/storage.js +9 -0
- package/dist/sync-coordinator.d.ts +30 -0
- package/dist/sync-coordinator.js +107 -0
- package/dist/worker.d.ts +24 -0
- package/dist/worker.js +149 -0
- package/package.json +26 -4
|
@@ -0,0 +1,583 @@
|
|
|
1
|
+
import { AsyncCachedDocumentStore, D1DeploymentStore, HttpVectorizeIndex, SyncEngine, createDurableObjectSqlExecutor, createHttpApi, createJwksVerifier, createRuntimeGraph, resolveSyncRegions, resolveSyncShardCount, resolveSyncShardMapFromEnv, syncShardNames, syncShardRegion } from "@vultro/core";
|
|
2
|
+
import { createRuntimeWorker } from "./worker.js";
|
|
3
|
+
import { ShardedAsyncDocumentStore } from "@vultro/docstore-d1/sharded";
|
|
4
|
+
import { sqliteStore } from "@vultro/docstore-sqlite";
|
|
5
|
+
import "@vultro/docstore-sqlite/runtime";
|
|
6
|
+
import { createCloudflareStorage } from "./storage.js";
|
|
7
|
+
import { createAlarmSchedulerDriver } from "./scheduler.js";
|
|
8
|
+
// src/durable-objects.ts
|
|
9
|
+
var TRANSACTOR_INSTANCE_NAME = "global";
|
|
10
|
+
/**
|
|
11
|
+
* 创建一个完整的 Cloudflare 运行时组合。
|
|
12
|
+
*
|
|
13
|
+
* 返回值可以直接用于 Worker 入口:
|
|
14
|
+
*
|
|
15
|
+
* ```ts
|
|
16
|
+
* const runtime = createRuntime({ schema, modules: { messages } });
|
|
17
|
+
* export const { VultroDO, VultroSyncDO } = runtime;
|
|
18
|
+
* export default runtime.worker;
|
|
19
|
+
* ```
|
|
20
|
+
*/
|
|
21
|
+
function createRuntime(options) {
|
|
22
|
+
/**
|
|
23
|
+
* 事务 Durable Object。
|
|
24
|
+
*
|
|
25
|
+
* 每个 DO 实例拥有独立的 SQLite 存储,但当前 play 应用只使用一个
|
|
26
|
+
* 名为 "global" 的实例,以获得全局有序的事务提交。
|
|
27
|
+
*/
|
|
28
|
+
class VultroDO {
|
|
29
|
+
runtime;
|
|
30
|
+
scheduler;
|
|
31
|
+
http;
|
|
32
|
+
state;
|
|
33
|
+
env;
|
|
34
|
+
d1;
|
|
35
|
+
d1Direct;
|
|
36
|
+
d1Mode;
|
|
37
|
+
externalSqlMode;
|
|
38
|
+
/** 当前 deployment 的 SyncDO shard 数量。 */
|
|
39
|
+
syncShardCount;
|
|
40
|
+
/** shard 索引对应的 Cloudflare locationHint。 */
|
|
41
|
+
syncRegions;
|
|
42
|
+
/**
|
|
43
|
+
* 是否把进入本 DO 的 HTTP 请求都当作「本机受信」。
|
|
44
|
+
*
|
|
45
|
+
* DO 收到的请求是 Worker 转发来的,`request.url` 的 hostname 来自
|
|
46
|
+
* 客户端可伪造的 Host 头,**不能**用它判断来源(实测伪造
|
|
47
|
+
* `Host: localhost` 即可绕过 admin token 读取 `/api/json_schemas`)。
|
|
48
|
+
*
|
|
49
|
+
* 默认不受信;本地 dev 由 vite 插件注入该变量(生产构建不含)
|
|
50
|
+
* (本地开发)才放开。
|
|
51
|
+
*/
|
|
52
|
+
trustLocalhost;
|
|
53
|
+
/** 最近一次 fan-out 的 shard 状态;dashboard 展示用。 */
|
|
54
|
+
syncShardStatus = [];
|
|
55
|
+
/** D1 初始化 / 冷启动恢复完成的 Promise;fetch 前必须等待。 */
|
|
56
|
+
ready;
|
|
57
|
+
persistQueue = Promise.resolve();
|
|
58
|
+
d1Summary = null;
|
|
59
|
+
constructor(state, env) {
|
|
60
|
+
this.state = state;
|
|
61
|
+
this.env = env;
|
|
62
|
+
this.syncShardCount = resolveSyncShardCount(options.sync?.shards ?? env.VULTRO_SYNC_SHARDS);
|
|
63
|
+
this.syncRegions = resolveSyncRegions(env.VULTRO_SYNC_REGIONS, options.sync?.regions ?? []);
|
|
64
|
+
this.trustLocalhost = env.VULTRO_TRUST_LOCALHOST === "true";
|
|
65
|
+
if (!state.storage.sql) throw new Error("VultroDO requires a SQLite-backed Durable Object. Configure the export with storage: \"sqlite\".");
|
|
66
|
+
const storage = state.storage;
|
|
67
|
+
const transactionSync = storage.transactionSync ? (fn) => storage.transactionSync(fn) : void 0;
|
|
68
|
+
const sql = createDurableObjectSqlExecutor(state.storage.sql, transactionSync);
|
|
69
|
+
const deploymentUrl = appendPrefix(options.deploymentUrl ?? (typeof env.VULTRO_DEPLOYMENT_URL === "string" && env.VULTRO_DEPLOYMENT_URL.trim() ? env.VULTRO_DEPLOYMENT_URL : void 0), options.prefix);
|
|
70
|
+
const r2 = options.r2 ?? (env.VULTRO_R2 && typeof env.VULTRO_R2 === "object" ? {
|
|
71
|
+
bucket: env.VULTRO_R2,
|
|
72
|
+
prefix: typeof env.VULTRO_R2_PREFIX === "string" ? env.VULTRO_R2_PREFIX : void 0
|
|
73
|
+
} : void 0);
|
|
74
|
+
const authConfig = options.auth ?? (typeof env.VULTRO_AUTH_JWKS_URI === "string" && env.VULTRO_AUTH_JWKS_URI.trim() !== "" || typeof env.VULTRO_AUTH_DOMAIN === "string" && env.VULTRO_AUTH_DOMAIN.trim() !== "" ? {
|
|
75
|
+
jwksUri: typeof env.VULTRO_AUTH_JWKS_URI === "string" && env.VULTRO_AUTH_JWKS_URI.trim() !== "" ? env.VULTRO_AUTH_JWKS_URI : void 0,
|
|
76
|
+
domain: typeof env.VULTRO_AUTH_DOMAIN === "string" && env.VULTRO_AUTH_DOMAIN.trim() !== "" ? env.VULTRO_AUTH_DOMAIN : void 0,
|
|
77
|
+
issuer: typeof env.VULTRO_AUTH_ISSUER === "string" ? env.VULTRO_AUTH_ISSUER : void 0,
|
|
78
|
+
audience: typeof env.VULTRO_AUTH_AUDIENCE === "string" ? env.VULTRO_AUTH_AUDIENCE : void 0
|
|
79
|
+
} : void 0);
|
|
80
|
+
const verifyToken = authConfig ? createJwksVerifier(authConfig) : void 0;
|
|
81
|
+
const d1Config = options.d1 ?? (env.VULTRO_D1 && typeof env.VULTRO_D1 === "object" ? {
|
|
82
|
+
database: env.VULTRO_D1,
|
|
83
|
+
key: typeof env.VULTRO_D1_KEY === "string" ? env.VULTRO_D1_KEY : void 0
|
|
84
|
+
} : void 0);
|
|
85
|
+
const docstoreMode = options.docstore ?? (typeof env.VULTRO_DOCSTORE === "string" ? env.VULTRO_DOCSTORE : void 0);
|
|
86
|
+
const d1ShardCount = options.d1ShardCount ?? (typeof env.VULTRO_D1_SHARD_COUNT === "string" ? Number(env.VULTRO_D1_SHARD_COUNT) : 0);
|
|
87
|
+
const d1Shards = options.d1Shards ?? Array.from({ length: Math.max(0, d1ShardCount) }, (_, index) => {
|
|
88
|
+
const binding = env[`VULTRO_D1_${index}`];
|
|
89
|
+
return binding && typeof binding === "object" ? binding : void 0;
|
|
90
|
+
}).filter((database) => Boolean(database));
|
|
91
|
+
const shardedD1 = docstoreMode === "sharded" && d1Shards.length > 0;
|
|
92
|
+
const postgresClient = options.postgres?.client ?? options.postgres?.createClient?.(env);
|
|
93
|
+
const mysqlClient = options.mysql?.client ?? options.mysql?.createClient?.(env);
|
|
94
|
+
const directD1 = (d1Config !== void 0 || shardedD1) && (docstoreMode === "d1" || shardedD1);
|
|
95
|
+
const storageFactory = options.storage ?? createCloudflareStorage({
|
|
96
|
+
...options.blobs ? { blobs: options.blobs } : {},
|
|
97
|
+
...r2 ? {
|
|
98
|
+
bucket: r2.bucket,
|
|
99
|
+
...r2.prefix ? { prefix: r2.prefix } : {}
|
|
100
|
+
} : {}
|
|
101
|
+
});
|
|
102
|
+
const wantsPostgres = docstoreMode === "postgres";
|
|
103
|
+
const wantsMysql = docstoreMode === "mysql";
|
|
104
|
+
if (wantsPostgres && !postgresClient || wantsMysql && !mysqlClient) throw new Error(`docstore: "${docstoreMode}" 需要注入 client;请在自定义 Worker 入口用 createRuntime({ postgres: { createClient: (env) => new Client(...) } }) 或 mysql: { createClient } 提供,并在该 app 安装 pg / mysql2。`);
|
|
105
|
+
const mysqlMode = wantsMysql && mysqlClient !== void 0;
|
|
106
|
+
this.externalSqlMode = wantsPostgres || mysqlMode;
|
|
107
|
+
const docStore = options.docStore ?? (docstoreMode === void 0 || docstoreMode === "sqlite" ? sqliteStore() : void 0);
|
|
108
|
+
const vectorize = options.vectorize ?? (env.VULTRO_VECTORIZE && typeof env.VULTRO_VECTORIZE === "object" ? {
|
|
109
|
+
index: env.VULTRO_VECTORIZE,
|
|
110
|
+
namespace: typeof env.VULTRO_VECTORIZE_NAMESPACE === "string" ? env.VULTRO_VECTORIZE_NAMESPACE : void 0
|
|
111
|
+
} : typeof env.VULTRO_VECTORIZE_INDEX_NAME === "string" && env.VULTRO_VECTORIZE_INDEX_NAME !== "" && typeof (env.VULTRO_VECTORIZE_API_TOKEN ?? env.VULTRO_CLOUDFLARE_API_TOKEN) === "string" && typeof (env.VULTRO_VECTORIZE_ACCOUNT_ID ?? env.VULTRO_CLOUDFLARE_ACCOUNT_ID) === "string" ? {
|
|
112
|
+
index: new HttpVectorizeIndex({
|
|
113
|
+
indexName: env.VULTRO_VECTORIZE_INDEX_NAME,
|
|
114
|
+
apiToken: env.VULTRO_VECTORIZE_API_TOKEN ?? env.VULTRO_CLOUDFLARE_API_TOKEN,
|
|
115
|
+
accountId: env.VULTRO_VECTORIZE_ACCOUNT_ID ?? env.VULTRO_CLOUDFLARE_ACCOUNT_ID,
|
|
116
|
+
apiBase: typeof env.VULTRO_VECTORIZE_API_BASE === "string" ? env.VULTRO_VECTORIZE_API_BASE : void 0
|
|
117
|
+
}),
|
|
118
|
+
namespace: typeof env.VULTRO_VECTORIZE_NAMESPACE === "string" ? env.VULTRO_VECTORIZE_NAMESPACE : void 0
|
|
119
|
+
} : void 0);
|
|
120
|
+
let alarmScheduler;
|
|
121
|
+
this.runtime = createRuntimeGraph({
|
|
122
|
+
sql,
|
|
123
|
+
schema: options.schema,
|
|
124
|
+
modules: options.modules,
|
|
125
|
+
components: options.components,
|
|
126
|
+
...docStore ? { docStore } : directD1 ? { storeFactory: (schema) => {
|
|
127
|
+
if (shardedD1) {
|
|
128
|
+
const store = new ShardedAsyncDocumentStore(schema, d1Shards);
|
|
129
|
+
this.d1Direct = store;
|
|
130
|
+
return store;
|
|
131
|
+
}
|
|
132
|
+
const store = new AsyncCachedDocumentStore(schema, d1Config.database);
|
|
133
|
+
this.d1Direct = store;
|
|
134
|
+
return store;
|
|
135
|
+
} } : {},
|
|
136
|
+
onCommit: (version) => {
|
|
137
|
+
this.notifySync(version);
|
|
138
|
+
if (!directD1) this.scheduleD1Persist();
|
|
139
|
+
},
|
|
140
|
+
onSchedule: (runAt) => {
|
|
141
|
+
alarmScheduler?.schedule(runAt);
|
|
142
|
+
},
|
|
143
|
+
deploymentUrl,
|
|
144
|
+
prefix: options.prefix,
|
|
145
|
+
env,
|
|
146
|
+
storage: storageFactory,
|
|
147
|
+
verifyToken,
|
|
148
|
+
backend: directD1 ? "d1" : "sqlite",
|
|
149
|
+
d1: directD1 ? shardedD1 ? d1Shards[0] : d1Config.database : void 0,
|
|
150
|
+
vectorize,
|
|
151
|
+
postgres: docstoreMode === "postgres" && postgresClient ? { client: postgresClient } : void 0,
|
|
152
|
+
mysql: docstoreMode === "mysql" && mysqlClient ? { client: mysqlClient } : void 0,
|
|
153
|
+
cloudAccount: {
|
|
154
|
+
teamName: options.cloudAccount?.teamName ?? (typeof env.VULTRO_CLOUD_TEAM_NAME === "string" ? env.VULTRO_CLOUD_TEAM_NAME : void 0),
|
|
155
|
+
projectName: options.cloudAccount?.projectName ?? (typeof env.VULTRO_CLOUD_PROJECT_NAME === "string" ? env.VULTRO_CLOUD_PROJECT_NAME : void 0),
|
|
156
|
+
billingUrl: options.cloudAccount?.billingUrl ?? (typeof env.VULTRO_CLOUD_BILLING_URL === "string" ? env.VULTRO_CLOUD_BILLING_URL : void 0),
|
|
157
|
+
apiToken: options.cloudAccount?.apiToken ?? (typeof env.VULTRO_CLOUD_BILLING_TOKEN === "string" ? env.VULTRO_CLOUD_BILLING_TOKEN : void 0)
|
|
158
|
+
},
|
|
159
|
+
cloudflare: {
|
|
160
|
+
apiToken: options.cloudflare?.apiToken ?? (typeof env.VULTRO_CLOUDFLARE_API_TOKEN === "string" ? env.VULTRO_CLOUDFLARE_API_TOKEN : void 0),
|
|
161
|
+
accountId: options.cloudflare?.accountId ?? (typeof env.VULTRO_CLOUDFLARE_ACCOUNT_ID === "string" ? env.VULTRO_CLOUDFLARE_ACCOUNT_ID : void 0),
|
|
162
|
+
zoneId: options.cloudflare?.zoneId ?? (typeof env.VULTRO_CLOUDFLARE_ZONE_ID === "string" ? env.VULTRO_CLOUDFLARE_ZONE_ID : void 0),
|
|
163
|
+
workerName: options.cloudflare?.workerName ?? (typeof env.VULTRO_CLOUDFLARE_WORKER_NAME === "string" ? env.VULTRO_CLOUDFLARE_WORKER_NAME : typeof env.VULTRO_DEPLOYMENT_URL === "string" ? new URL(env.VULTRO_DEPLOYMENT_URL).hostname.split(".")[0] : void 0),
|
|
164
|
+
databaseId: options.cloudflare?.databaseId ?? (typeof env.VULTRO_CLOUDFLARE_D1_DATABASE_ID === "string" ? env.VULTRO_CLOUDFLARE_D1_DATABASE_ID : void 0),
|
|
165
|
+
aiGatewayId: options.cloudflare?.aiGatewayId ?? (typeof env.VULTRO_CLOUDFLARE_AI_GATEWAY_ID === "string" ? env.VULTRO_CLOUDFLARE_AI_GATEWAY_ID : void 0),
|
|
166
|
+
apiBase: options.cloudflare?.apiBase ?? (typeof env.VULTRO_CLOUDFLARE_API_BASE === "string" ? env.VULTRO_CLOUDFLARE_API_BASE : void 0)
|
|
167
|
+
}
|
|
168
|
+
});
|
|
169
|
+
alarmScheduler = createAlarmSchedulerDriver({
|
|
170
|
+
nextRun: () => this.runtime.nextScheduledRun(),
|
|
171
|
+
runDue: () => this.runtime.runDueScheduledJobs()
|
|
172
|
+
}, this.state.storage, { waitUntil: (promise) => this.state.waitUntil?.(promise) });
|
|
173
|
+
this.scheduler = alarmScheduler;
|
|
174
|
+
if (directD1 || this.externalSqlMode || mysqlMode) {
|
|
175
|
+
this.d1Mode = "document";
|
|
176
|
+
const hydrate = () => this.hydrateFromD1();
|
|
177
|
+
this.ready = this.state.blockConcurrencyWhile ? this.state.blockConcurrencyWhile(hydrate) : hydrate();
|
|
178
|
+
} else if (d1Config) {
|
|
179
|
+
this.d1Mode = "snapshot";
|
|
180
|
+
this.d1 = new D1DeploymentStore(d1Config.database, d1Config.key ?? "global");
|
|
181
|
+
const hydrate = () => this.hydrateFromD1();
|
|
182
|
+
this.ready = this.state.blockConcurrencyWhile ? this.state.blockConcurrencyWhile(hydrate) : hydrate();
|
|
183
|
+
} else {
|
|
184
|
+
this.d1Mode = "none";
|
|
185
|
+
const hydrateSqlite = async () => {
|
|
186
|
+
try {
|
|
187
|
+
await this.runtime.loadBackends();
|
|
188
|
+
} catch (error) {
|
|
189
|
+
console.error("[vultro] SQLite backend load failed:", error);
|
|
190
|
+
}
|
|
191
|
+
};
|
|
192
|
+
this.ready = this.state.blockConcurrencyWhile ? this.state.blockConcurrencyWhile(hydrateSqlite) : hydrateSqlite();
|
|
193
|
+
}
|
|
194
|
+
this.ready.then(() => {
|
|
195
|
+
this.scheduler.start();
|
|
196
|
+
}).catch((error) => {
|
|
197
|
+
console.error("[vultro] failed to restore scheduler alarm:", error);
|
|
198
|
+
});
|
|
199
|
+
const adminToken = typeof env.VULTRO_ADMIN_TOKEN === "string" && env.VULTRO_ADMIN_TOKEN ? env.VULTRO_ADMIN_TOKEN : void 0;
|
|
200
|
+
this.http = createHttpApi(this.runtime, { adminToken });
|
|
201
|
+
}
|
|
202
|
+
/**
|
|
203
|
+
* 所有 HTTP 请求都交给 http API 处理。
|
|
204
|
+
*
|
|
205
|
+
* 这里同时承载公开路由与 `/internal/*` 路由:
|
|
206
|
+
* - 公开路由由 Worker 转发而来;
|
|
207
|
+
* - 内部路由只由 VultroSyncDO 通过 Service Binding / DO stub 调用。
|
|
208
|
+
*/
|
|
209
|
+
async fetch(request) {
|
|
210
|
+
await this.ready;
|
|
211
|
+
const response = await this.http(request, { local: this.trustLocalhost });
|
|
212
|
+
await this.runtime.flushExecutionLogs();
|
|
213
|
+
return response;
|
|
214
|
+
}
|
|
215
|
+
/**
|
|
216
|
+
* DO alarm:执行到点的计划任务,并设置下一个 alarm。
|
|
217
|
+
*
|
|
218
|
+
* Cloudflare 会在 alarm() resolve 后按 setAlarm 的设置继续调度;这里必须
|
|
219
|
+
* 显式等待 setAlarm 完成,否则可能在任务还没写回前就进入空闲。
|
|
220
|
+
*/
|
|
221
|
+
async alarm() {
|
|
222
|
+
await this.ready;
|
|
223
|
+
await this.scheduler.fire();
|
|
224
|
+
await this.runtime.flushExecutionLogs();
|
|
225
|
+
}
|
|
226
|
+
/**
|
|
227
|
+
* D1 冷启动恢复:只有本地 DO SQLite 没有任何文档时才覆盖,
|
|
228
|
+
* 避免旧快照回滚已经更新的本地事务。
|
|
229
|
+
*/
|
|
230
|
+
async hydrateFromD1() {
|
|
231
|
+
if (this.d1Direct || this.externalSqlMode) {
|
|
232
|
+
try {
|
|
233
|
+
await this.runtime.loadBackends();
|
|
234
|
+
} catch (error) {
|
|
235
|
+
console.error("[vultro] D1 backend load failed:", error);
|
|
236
|
+
}
|
|
237
|
+
return;
|
|
238
|
+
}
|
|
239
|
+
if (!this.d1) return;
|
|
240
|
+
try {
|
|
241
|
+
await this.d1.initialize();
|
|
242
|
+
this.d1Summary = await this.d1.summary();
|
|
243
|
+
if (this.runtime.documentCount() > 0) return;
|
|
244
|
+
const snapshot = await this.d1.load();
|
|
245
|
+
if (!snapshot) return;
|
|
246
|
+
await this.runtime.snapshots.restore(snapshot);
|
|
247
|
+
} catch (error) {
|
|
248
|
+
console.error("[vultro] D1 hydrate failed:", error);
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
/** 每次提交后把最新快照写穿到 D1,串行执行避免旧快照覆盖新快照。 */
|
|
252
|
+
scheduleD1Persist() {
|
|
253
|
+
if (!this.d1) return;
|
|
254
|
+
const task = this.persistQueue.then(async () => {
|
|
255
|
+
const snapshot = await this.runtime.snapshots.export("d1");
|
|
256
|
+
this.d1Summary = await this.d1.save(snapshot);
|
|
257
|
+
});
|
|
258
|
+
this.persistQueue = task.catch(() => void 0);
|
|
259
|
+
this.state.waitUntil?.(task);
|
|
260
|
+
}
|
|
261
|
+
/** Dashboard / 运维脚本调用:立即写一次 D1。 */
|
|
262
|
+
async persistD1Now() {
|
|
263
|
+
await this.ready;
|
|
264
|
+
if (this.d1Direct) {
|
|
265
|
+
await this.d1Direct.flush();
|
|
266
|
+
return {
|
|
267
|
+
mode: "document-store",
|
|
268
|
+
commitTs: this.runtime.version
|
|
269
|
+
};
|
|
270
|
+
}
|
|
271
|
+
if (!this.d1) return null;
|
|
272
|
+
const snapshot = await this.runtime.snapshots.export("d1-manual");
|
|
273
|
+
this.d1Summary = await this.d1.save(snapshot);
|
|
274
|
+
return this.d1Summary;
|
|
275
|
+
}
|
|
276
|
+
/** 从 D1 恢复当前 deployment(破坏性,仅 dashboard 写模式开放)。 */
|
|
277
|
+
async restoreD1Now() {
|
|
278
|
+
await this.ready;
|
|
279
|
+
if (this.d1Direct) {
|
|
280
|
+
await this.d1Direct.load();
|
|
281
|
+
return {
|
|
282
|
+
restored: true,
|
|
283
|
+
summary: null,
|
|
284
|
+
mode: "document-store"
|
|
285
|
+
};
|
|
286
|
+
}
|
|
287
|
+
if (!this.d1) return {
|
|
288
|
+
restored: false,
|
|
289
|
+
summary: null
|
|
290
|
+
};
|
|
291
|
+
const snapshot = await this.d1.load();
|
|
292
|
+
if (!snapshot) return {
|
|
293
|
+
restored: false,
|
|
294
|
+
summary: this.d1Summary
|
|
295
|
+
};
|
|
296
|
+
const result = await this.runtime.snapshots.restore(snapshot);
|
|
297
|
+
return {
|
|
298
|
+
restored: true,
|
|
299
|
+
summary: this.d1Summary,
|
|
300
|
+
documents: result.documents
|
|
301
|
+
};
|
|
302
|
+
}
|
|
303
|
+
/** Dashboard backend 状态:SQLite 永远可用,字节后端 / D1 取决于配置。 */
|
|
304
|
+
async backendStatus() {
|
|
305
|
+
await this.ready;
|
|
306
|
+
this.d1Summary = this.d1 ? await this.d1.summary() : null;
|
|
307
|
+
const blobstore = this.runtime.storage.blobstore;
|
|
308
|
+
return {
|
|
309
|
+
sql: {
|
|
310
|
+
kind: "durable-object-sqlite",
|
|
311
|
+
configured: true
|
|
312
|
+
},
|
|
313
|
+
blobstore,
|
|
314
|
+
r2: {
|
|
315
|
+
configured: blobstore !== false,
|
|
316
|
+
kind: blobstore
|
|
317
|
+
},
|
|
318
|
+
d1: {
|
|
319
|
+
configured: this.d1Mode !== "none",
|
|
320
|
+
mode: this.d1Mode,
|
|
321
|
+
summary: this.d1Summary
|
|
322
|
+
}
|
|
323
|
+
};
|
|
324
|
+
}
|
|
325
|
+
/**
|
|
326
|
+
* 提交后通知同步层。
|
|
327
|
+
*
|
|
328
|
+
* 使用 `waitUntil` 让通知在响应返回后继续执行,避免 mutation 的
|
|
329
|
+
* 延迟受到 WebSocket 广播影响;同时避免 SyncDO 与 VultroDO 之间
|
|
330
|
+
* 因为同步等待而产生循环依赖。
|
|
331
|
+
*/
|
|
332
|
+
notifySync(version) {
|
|
333
|
+
const namespace = this.env.VULTRO_SYNC_DO;
|
|
334
|
+
if (!namespace) return;
|
|
335
|
+
const promise = (async () => {
|
|
336
|
+
const targets = (await resolveSyncShardMapFromEnv(this.env))?.shards ?? syncShardNames(this.syncShardCount).map((name, shard) => ({
|
|
337
|
+
shard,
|
|
338
|
+
name,
|
|
339
|
+
region: syncShardRegion(this.syncRegions, shard)
|
|
340
|
+
}));
|
|
341
|
+
const items = await Promise.all(targets.map(async ({ shard, name, region }) => {
|
|
342
|
+
try {
|
|
343
|
+
const response = await namespace.get(namespace.idFromName(name), { ...region ? { locationHint: region } : {} }).fetch(new Request("https://sync.internal/notify", {
|
|
344
|
+
method: "POST",
|
|
345
|
+
headers: {
|
|
346
|
+
"content-type": "application/json",
|
|
347
|
+
...region ? { "x-vultro-sync-region": region } : {}
|
|
348
|
+
},
|
|
349
|
+
body: JSON.stringify({
|
|
350
|
+
version,
|
|
351
|
+
shard,
|
|
352
|
+
region
|
|
353
|
+
})
|
|
354
|
+
}));
|
|
355
|
+
const body = await response.json().catch(() => ({}));
|
|
356
|
+
return {
|
|
357
|
+
shard,
|
|
358
|
+
name,
|
|
359
|
+
region: region ?? null,
|
|
360
|
+
ok: response.ok,
|
|
361
|
+
latestVersion: Number(body.latestVersion ?? version),
|
|
362
|
+
connections: Number(body.connections ?? 0)
|
|
363
|
+
};
|
|
364
|
+
} catch (error) {
|
|
365
|
+
return {
|
|
366
|
+
shard,
|
|
367
|
+
name,
|
|
368
|
+
region: region ?? null,
|
|
369
|
+
ok: false,
|
|
370
|
+
latestVersion: version,
|
|
371
|
+
connections: 0,
|
|
372
|
+
error: error instanceof Error ? error.message : String(error)
|
|
373
|
+
};
|
|
374
|
+
}
|
|
375
|
+
}));
|
|
376
|
+
this.syncShardStatus = items;
|
|
377
|
+
await this.reportSyncToCoordinator(items);
|
|
378
|
+
})();
|
|
379
|
+
this.state.waitUntil?.(promise);
|
|
380
|
+
}
|
|
381
|
+
/**
|
|
382
|
+
* 把每个 shard 的连接数上报给 global-auto Coordinator。
|
|
383
|
+
*
|
|
384
|
+
* Coordinator 会写入 KV shard map;Worker 下一次同步请求就会使用新 map。
|
|
385
|
+
*/
|
|
386
|
+
async reportSyncToCoordinator(items) {
|
|
387
|
+
const namespace = this.env.VULTRO_SYNC_COORDINATOR;
|
|
388
|
+
if (!namespace) return;
|
|
389
|
+
await Promise.all(items.map(async (item) => {
|
|
390
|
+
try {
|
|
391
|
+
await namespace.get(namespace.idFromName("global")).fetch(new Request("https://sync-coordinator.internal/report", {
|
|
392
|
+
method: "POST",
|
|
393
|
+
headers: { "content-type": "application/json" },
|
|
394
|
+
body: JSON.stringify({
|
|
395
|
+
shard: item.shard,
|
|
396
|
+
name: item.name,
|
|
397
|
+
region: item.region ?? void 0,
|
|
398
|
+
connections: item.connections
|
|
399
|
+
})
|
|
400
|
+
}));
|
|
401
|
+
} catch (error) {
|
|
402
|
+
console.error("Failed to report sync shard:", error);
|
|
403
|
+
}
|
|
404
|
+
}));
|
|
405
|
+
}
|
|
406
|
+
/** Dashboard:查询每个 shard 的 /health,确认版本是否已经传播。 */
|
|
407
|
+
async syncShardsStatus() {
|
|
408
|
+
const namespace = this.env.VULTRO_SYNC_DO;
|
|
409
|
+
const targets = (await resolveSyncShardMapFromEnv(this.env))?.shards ?? syncShardNames(this.syncShardCount).map((name, shard) => ({
|
|
410
|
+
shard,
|
|
411
|
+
name,
|
|
412
|
+
region: syncShardRegion(this.syncRegions, shard)
|
|
413
|
+
}));
|
|
414
|
+
if (!namespace) return {
|
|
415
|
+
shards: targets.length,
|
|
416
|
+
configured: false,
|
|
417
|
+
items: []
|
|
418
|
+
};
|
|
419
|
+
const items = await Promise.all(targets.map(async ({ shard, name, region }) => {
|
|
420
|
+
try {
|
|
421
|
+
const response = await namespace.get(namespace.idFromName(name), { ...region ? { locationHint: region } : {} }).fetch(new Request("https://sync.internal/health", { headers: {
|
|
422
|
+
"x-vultro-sync-shard": String(shard),
|
|
423
|
+
...region ? { "x-vultro-sync-region": region } : {}
|
|
424
|
+
} }));
|
|
425
|
+
const body = await response.json();
|
|
426
|
+
return {
|
|
427
|
+
shard,
|
|
428
|
+
name,
|
|
429
|
+
ok: response.ok,
|
|
430
|
+
latestVersion: Number(body.latestVersion ?? 0),
|
|
431
|
+
connections: Number(body.connections ?? 0),
|
|
432
|
+
region: body.region ?? null
|
|
433
|
+
};
|
|
434
|
+
} catch (error) {
|
|
435
|
+
return {
|
|
436
|
+
shard,
|
|
437
|
+
name,
|
|
438
|
+
ok: false,
|
|
439
|
+
error: error instanceof Error ? error.message : String(error)
|
|
440
|
+
};
|
|
441
|
+
}
|
|
442
|
+
}));
|
|
443
|
+
return {
|
|
444
|
+
shards: targets.length,
|
|
445
|
+
configured: true,
|
|
446
|
+
items
|
|
447
|
+
};
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
/**
|
|
451
|
+
* 同步 Durable Object。
|
|
452
|
+
*
|
|
453
|
+
* 负责保存每个 WebSocket 连接的订阅集合,并在数据变更后重新执行 query。
|
|
454
|
+
* 连接状态保存在内存中:标准 WebSocket API 下 DO 会随连接保持存活;
|
|
455
|
+
* 如果未来需要 Hibernation,需要把连接状态持久化到 storage。
|
|
456
|
+
*/
|
|
457
|
+
/**
|
|
458
|
+
* 同步 Durable Object。
|
|
459
|
+
*
|
|
460
|
+
* 这里只保留 Cloudflare 专属的部分:WebSocket 握手(`WebSocketPair`)、
|
|
461
|
+
* DO alarm 调度、以及通过 DO binding 调用事务器。订阅 / 广播 / 认证的
|
|
462
|
+
* 协议逻辑全部在 `SyncEngine` 里,与 Bun 运行时共用同一份实现。
|
|
463
|
+
*/
|
|
464
|
+
class VultroSyncDO {
|
|
465
|
+
state;
|
|
466
|
+
env;
|
|
467
|
+
engine;
|
|
468
|
+
/** 连接 id -> 引擎里的连接对象,用于收到 message / close 时定位。 */
|
|
469
|
+
connections = /* @__PURE__ */ new Map();
|
|
470
|
+
adminToken;
|
|
471
|
+
/**
|
|
472
|
+
* 是否把本 DO 的所有连接都当作「本机受信」。
|
|
473
|
+
*
|
|
474
|
+
* 仅供本地开发:DO 内部无法区分公网来源(请求的 hostname 可被伪造),
|
|
475
|
+
* 所以生产环境必须靠 `VULTRO_ADMIN_TOKEN`。这里要求显式设置
|
|
476
|
+
* `VULTRO_TRUST_LOCALHOST=true` 才放开(dev 由 vite 插件自动注入),避免误判成「反正 localhost 安全」。
|
|
477
|
+
*/
|
|
478
|
+
trustLocalhost;
|
|
479
|
+
constructor(state, env) {
|
|
480
|
+
this.state = state;
|
|
481
|
+
this.env = env;
|
|
482
|
+
this.adminToken = typeof env.VULTRO_ADMIN_TOKEN === "string" && env.VULTRO_ADMIN_TOKEN ? env.VULTRO_ADMIN_TOKEN : void 0;
|
|
483
|
+
this.trustLocalhost = env.VULTRO_TRUST_LOCALHOST === "true";
|
|
484
|
+
const namespace = env.VULTRO_DO;
|
|
485
|
+
this.engine = new SyncEngine({
|
|
486
|
+
transactor: { fetch: async (request) => {
|
|
487
|
+
if (!namespace) throw new Error("VULTRO_DO binding is missing; cannot execute functions");
|
|
488
|
+
return namespace.get(namespace.idFromName(TRANSACTOR_INSTANCE_NAME)).fetch(request);
|
|
489
|
+
} },
|
|
490
|
+
adminToken: this.adminToken,
|
|
491
|
+
schedulePing: (runAt) => {
|
|
492
|
+
const setAlarm = this.state.storage.setAlarm;
|
|
493
|
+
if (!setAlarm) return;
|
|
494
|
+
setAlarm.call(this.state.storage, runAt).catch(() => {});
|
|
495
|
+
}
|
|
496
|
+
});
|
|
497
|
+
}
|
|
498
|
+
async fetch(request) {
|
|
499
|
+
const url = new URL(request.url);
|
|
500
|
+
if (request.headers.get("upgrade")?.toLowerCase() === "websocket") return this.acceptWebSocket(request);
|
|
501
|
+
if (url.pathname === "/notify") {
|
|
502
|
+
const body = await request.json();
|
|
503
|
+
const version = Number(body.version ?? 0);
|
|
504
|
+
await this.engine.notify(version);
|
|
505
|
+
return Response.json({
|
|
506
|
+
ok: true,
|
|
507
|
+
connections: this.engine.connectionCount,
|
|
508
|
+
latestVersion: this.engine.version
|
|
509
|
+
});
|
|
510
|
+
}
|
|
511
|
+
if (url.pathname === "/health") {
|
|
512
|
+
const shardHeader = request.headers.get("x-vultro-sync-shard");
|
|
513
|
+
return Response.json({
|
|
514
|
+
ok: true,
|
|
515
|
+
shard: shardHeader === null ? null : Number(shardHeader),
|
|
516
|
+
region: request.headers.get("x-vultro-sync-region") ?? (typeof this.env.VULTRO_REGION === "string" ? this.env.VULTRO_REGION : null),
|
|
517
|
+
connections: this.engine.connectionCount,
|
|
518
|
+
latestVersion: this.engine.version
|
|
519
|
+
});
|
|
520
|
+
}
|
|
521
|
+
return new Response("Not found", { status: 404 });
|
|
522
|
+
}
|
|
523
|
+
/** DO 的 alarm:定期给客户端发送 Ping,避免连接因 60 秒无消息被断开。 */
|
|
524
|
+
async alarm() {
|
|
525
|
+
this.engine.ping();
|
|
526
|
+
}
|
|
527
|
+
acceptWebSocket(request) {
|
|
528
|
+
const pair = new globalThis.WebSocketPair();
|
|
529
|
+
const client = pair[0];
|
|
530
|
+
const server = pair[1];
|
|
531
|
+
server.accept();
|
|
532
|
+
const connection = this.engine.attach(server, { local: this.trustLocalhost });
|
|
533
|
+
this.connections.set(connection.id, connection);
|
|
534
|
+
server.addEventListener("message", (event) => {
|
|
535
|
+
this.engine.receive(connection, dataToString(event.data));
|
|
536
|
+
});
|
|
537
|
+
server.addEventListener("close", () => {
|
|
538
|
+
this.connections.delete(connection.id);
|
|
539
|
+
this.engine.detach(connection);
|
|
540
|
+
});
|
|
541
|
+
server.addEventListener("error", () => {
|
|
542
|
+
this.connections.delete(connection.id);
|
|
543
|
+
this.engine.detach(connection);
|
|
544
|
+
});
|
|
545
|
+
return new Response(null, {
|
|
546
|
+
status: 101,
|
|
547
|
+
webSocket: client
|
|
548
|
+
});
|
|
549
|
+
}
|
|
550
|
+
}
|
|
551
|
+
return {
|
|
552
|
+
VultroDO,
|
|
553
|
+
VultroSyncDO,
|
|
554
|
+
/** Worker 默认导出,见 worker.ts。 */
|
|
555
|
+
worker: createRuntimeWorker(resolveSyncShardCount(options.sync?.shards, 1), options.sync?.regions ?? [], {
|
|
556
|
+
countryMap: options.sync?.countryMap,
|
|
557
|
+
regionMap: options.sync?.regionMap,
|
|
558
|
+
defaultRegion: options.sync?.defaultRegion,
|
|
559
|
+
useColoAsRegion: options.sync?.useColoAsRegion
|
|
560
|
+
}, options.prefix)
|
|
561
|
+
};
|
|
562
|
+
}
|
|
563
|
+
/**
|
|
564
|
+
* 给 deploymentUrl 加上路由前缀(幂等)。
|
|
565
|
+
*
|
|
566
|
+
* 已经带前缀时原样返回,避免重复配置时拼成 `/v/v`。
|
|
567
|
+
*/
|
|
568
|
+
function appendPrefix(deploymentUrl, prefix) {
|
|
569
|
+
if (!deploymentUrl || !prefix) return deploymentUrl;
|
|
570
|
+
const normalized = `/${prefix.trim().replace(/^\/+|\/+$/g, "")}`;
|
|
571
|
+
if (normalized === "/") return deploymentUrl;
|
|
572
|
+
const base = deploymentUrl.replace(/\/+$/, "");
|
|
573
|
+
if (base.endsWith(normalized)) return base;
|
|
574
|
+
return `${base}${normalized}`;
|
|
575
|
+
}
|
|
576
|
+
/** WebSocket 事件数据可能是 string / ArrayBuffer / TypedArray。 */
|
|
577
|
+
function dataToString(data) {
|
|
578
|
+
if (typeof data === "string") return data;
|
|
579
|
+
if (data instanceof ArrayBuffer) return new TextDecoder().decode(data);
|
|
580
|
+
if (ArrayBuffer.isView(data)) return new TextDecoder().decode(new Uint8Array(data.buffer, data.byteOffset, data.byteLength));
|
|
581
|
+
return String(data);
|
|
582
|
+
}
|
|
583
|
+
export { createRuntime };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ============================================================================
|
|
3
|
+
* @vultro/runtime-cf
|
|
4
|
+
* ============================================================================
|
|
5
|
+
*
|
|
6
|
+
* `@vultro/core` 的 Cloudflare 适配层。
|
|
7
|
+
*
|
|
8
|
+
* core 本身是平台无关的(运行时 / 事务 / 查询引擎 / HTTP API / 同步协议),
|
|
9
|
+
* 本包只负责把 core 装配到 Cloudflare Workers + Durable Objects 上:
|
|
10
|
+
*
|
|
11
|
+
* - `createRuntime` / `defineWorker`:组合 DO、RPC entrypoint 与 Worker;
|
|
12
|
+
* - `createRuntimeWorker`:Worker 路由(HTTP API + WebSocket 转发);
|
|
13
|
+
* - RPC entrypoint 工厂:UDF 执行、数据服务、同步传输;
|
|
14
|
+
* - 同步拓扑与协调器:多 shard / 区域亲和。
|
|
15
|
+
*
|
|
16
|
+
* 这样 core 不 import 任何 `cloudflare:*` 模块,Bun 运行时(`@vultro/runtime-bun`)
|
|
17
|
+
* 可以复用同一套内核。
|
|
18
|
+
*/
|
|
19
|
+
export { createRuntime } from "./durable-objects.js";
|
|
20
|
+
export { createCloudflareStorage, type CloudflareStorageOptions } from "./storage.js";
|
|
21
|
+
export { createAlarmSchedulerDriver, type AlarmSchedulerOptions } from "./scheduler.js";
|
|
22
|
+
export { defineWorker, type WorkerComposition, type RequiredBinding, type WranglerFragment, type DefineWorkerOptions, } from "./define.js";
|
|
23
|
+
export { createDataServiceRpc, createSyncTransportRpc, createUdfExecutorRpc, PlainRpcEntrypoint, type RpcBindingNames, type RpcEntrypointOptions, } from "./rpc.js";
|
|
24
|
+
export { createRuntimeWorker } from "./worker.js";
|
|
25
|
+
export { createIsolatedUdfExecutor, RemoteDocumentStore, type IsolatedDataServiceLike, type IsolatedUdfExecutorOptions, } from "./isolated.js";
|
|
26
|
+
export { createSyncCoordinatorDO, type SyncCoordinatorOptions, } from "./sync-coordinator.js";
|
|
27
|
+
export type { DurableObjectGetOptions, DurableObjectNamespaceLike, DurableObjectStateLike, DurableObjectStorageLike, DurableObjectStubLike, RuntimeEnv, } from "./platform.js";
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { createRuntime } from "./durable-objects.js";
|
|
2
|
+
import { createCloudflareStorage } from "./storage.js";
|
|
3
|
+
import { createAlarmSchedulerDriver } from "./scheduler.js";
|
|
4
|
+
import { defineWorker } from "./define.js";
|
|
5
|
+
import { PlainRpcEntrypoint, createDataServiceRpc, createSyncTransportRpc, createUdfExecutorRpc } from "./rpc.js";
|
|
6
|
+
import { createRuntimeWorker } from "./worker.js";
|
|
7
|
+
import { RemoteDocumentStore, createIsolatedUdfExecutor } from "./isolated.js";
|
|
8
|
+
import { createSyncCoordinatorDO } from "./sync-coordinator.js";
|
|
9
|
+
export { PlainRpcEntrypoint, RemoteDocumentStore, createAlarmSchedulerDriver, createCloudflareStorage, createDataServiceRpc, createIsolatedUdfExecutor, createRuntime, createRuntimeWorker, createSyncCoordinatorDO, createSyncTransportRpc, createUdfExecutorRpc, defineWorker };
|