@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.
@@ -0,0 +1,49 @@
1
+ // src/scheduler.ts
2
+ /**
3
+ * 创建 DO alarm 定时任务驱动器。
4
+ *
5
+ * `context` 由 `createRuntimeGraph` 所在适配层提供;`storage` 是 DO 的
6
+ * `state.storage`(只用到 alarm 相关 API)。
7
+ */
8
+ function createAlarmSchedulerDriver(context, storage, options = {}) {
9
+ let disposed = false;
10
+ /** 最近一次 setAlarm 的 Promise;DO alarm 返回前要等它写完。 */
11
+ let pendingAlarm;
12
+ /** 实际写 alarm;失败只记录日志,不能影响 mutation / DO 启动。 */
13
+ async function setAlarmAt(runAt) {
14
+ if (!storage.setAlarm) return;
15
+ try {
16
+ if (storage.getAlarm) {
17
+ const existing = await storage.getAlarm();
18
+ if (existing !== null && existing <= runAt) return;
19
+ }
20
+ await storage.setAlarm(Math.max(runAt, Date.now()));
21
+ } catch (error) {
22
+ console.error("Failed to schedule VultroDO alarm:", error);
23
+ }
24
+ }
25
+ function schedule(runAt) {
26
+ if (disposed) return;
27
+ const promise = setAlarmAt(runAt);
28
+ pendingAlarm = promise;
29
+ options.waitUntil?.(promise);
30
+ }
31
+ return {
32
+ start() {
33
+ const next = context.nextRun();
34
+ if (next !== null) schedule(next);
35
+ },
36
+ schedule,
37
+ async fire() {
38
+ if (disposed) return;
39
+ await context.runDue();
40
+ const pending = pendingAlarm;
41
+ pendingAlarm = void 0;
42
+ if (pending) await pending;
43
+ },
44
+ dispose() {
45
+ disposed = true;
46
+ }
47
+ };
48
+ }
49
+ export { createAlarmSchedulerDriver };
@@ -0,0 +1,22 @@
1
+ import { type BlobStore, type StorageFactory } from "@vultro/core/storage";
2
+ import { type CreateR2StorageOptions } from "@vultro/storage-r2";
3
+ /**
4
+ * ============================================================================
5
+ * Cloudflare 默认 Storage
6
+ * ============================================================================
7
+ *
8
+ * Cloudflare 运行时的 `ctx.storage` 默认组合:
9
+ *
10
+ * - 元数据:DO SQLite(默认)或 D1 直连模式下的 D1,由 Runtime 通过
11
+ * `StorageContext` 注入;
12
+ * - 字节:R2 绑定(`VULTRO_R2` / `cloudflare.r2`)。
13
+ *
14
+ * R2 未配置时字节回退到 DO SQLite 的 base64 副本,本地开发仍然零配置。
15
+ * 自定义 S3 / 其他后端通过 `blobs` 覆盖。
16
+ */
17
+ export interface CloudflareStorageOptions extends CreateR2StorageOptions {
18
+ /** 自定义字节后端;优先于 R2。 */
19
+ blobs?: BlobStore;
20
+ }
21
+ /** 创建 Cloudflare 运行时的默认 Storage 工厂。 */
22
+ export declare function createCloudflareStorage(options?: CloudflareStorageOptions): StorageFactory;
@@ -0,0 +1,9 @@
1
+ import { createStorageFactory } from "@vultro/core/storage";
2
+ import { createR2Storage } from "@vultro/storage-r2";
3
+ // src/storage.ts
4
+ /** 创建 Cloudflare 运行时的默认 Storage 工厂。 */
5
+ function createCloudflareStorage(options = {}) {
6
+ if (options.blobs) return createStorageFactory({ blobs: options.blobs });
7
+ return createR2Storage(options);
8
+ }
9
+ export { createCloudflareStorage };
@@ -0,0 +1,30 @@
1
+ /**
2
+ * ============================================================================
3
+ * global-auto SyncCoordinator
4
+ * ============================================================================
5
+ *
6
+ * `global-auto` 拓扑由一个独立的 Durable Object 汇总各 SyncDO shard 的
7
+ * 连接数,并生成持久化 shard map:
8
+ *
9
+ * - SyncDO / 运维脚本通过 `POST /report` 上报 `{ shard, connections, region }`;
10
+ * - Coordinator 把报告写入自己的 SQLite;
11
+ * - 重新计算 shard map,写入 `VULTRO_SYNC_SHARD_MAP` KV;
12
+ * - Worker 每个请求优先读 KV;没有 KV 时通过 `GET /map` 读取 Coordinator。
13
+ *
14
+ * 连接数超过阈值时自动增加 shard;报告是幂等的,重复上报不会重复扩容。
15
+ */
16
+ import type { DurableObjectStateLike, RuntimeEnv } from "./platform.js";
17
+ import { type SyncRegionHint } from "@vultro/core";
18
+ export interface SyncCoordinatorOptions {
19
+ instance?: string;
20
+ regions?: readonly SyncRegionHint[];
21
+ shardsPerRegion?: number;
22
+ targetConnectionsPerShard?: number;
23
+ kvBinding?: string;
24
+ }
25
+ /** SyncCoordinatorDO 对外的公开契约(只暴露 fetch)。 */
26
+ export interface SyncCoordinatorInstance {
27
+ fetch(request: Request): Promise<Response>;
28
+ }
29
+ /** 创建 SyncCoordinatorDO 类;测试可传入 fake state / env。 */
30
+ export declare function createSyncCoordinatorDO(options?: SyncCoordinatorOptions): new (state: DurableObjectStateLike, env: RuntimeEnv) => SyncCoordinatorInstance;
@@ -0,0 +1,107 @@
1
+ import { buildSyncShardMap, createDurableObjectSqlExecutor, resolveSyncRegions, syncShardMapKey } from "@vultro/core";
2
+ // src/sync-coordinator.ts
3
+ var REPORTS_TABLE = "_vultro_sync_reports";
4
+ /** 创建 SyncCoordinatorDO 类;测试可传入 fake state / env。 */
5
+ function createSyncCoordinatorDO(options = {}) {
6
+ const instance = options.instance ?? "global";
7
+ const kvBinding = options.kvBinding ?? "VULTRO_SYNC_SHARD_MAP";
8
+ return class VultroSyncCoordinatorDO {
9
+ state;
10
+ env;
11
+ reports = /* @__PURE__ */ new Map();
12
+ sql;
13
+ constructor(state, env) {
14
+ this.state = state;
15
+ this.env = env;
16
+ if (state.storage.sql) {
17
+ this.sql = createDurableObjectSqlExecutor(state.storage.sql, state.storage.transactionSync);
18
+ this.sql.exec(`
19
+ CREATE TABLE IF NOT EXISTS ${REPORTS_TABLE} (
20
+ shard INTEGER PRIMARY KEY,
21
+ name TEXT NOT NULL,
22
+ region TEXT,
23
+ connections INTEGER NOT NULL,
24
+ version REAL,
25
+ updated_at REAL NOT NULL
26
+ )
27
+ `);
28
+ for (const row of this.sql.exec(`SELECT * FROM ${REPORTS_TABLE}`)) this.reports.set(Number(row.shard), {
29
+ shard: Number(row.shard),
30
+ name: row.name,
31
+ ...row.region ? { region: row.region } : {},
32
+ connections: Number(row.connections),
33
+ ...row.version !== null ? { version: Number(row.version) } : {},
34
+ updatedAt: Number(row.updated_at)
35
+ });
36
+ }
37
+ }
38
+ async fetch(request) {
39
+ const url = new URL(request.url);
40
+ if (url.pathname === "/report" && request.method === "POST") {
41
+ const body = await request.json();
42
+ const shard = Number(body.shard);
43
+ if (!Number.isInteger(shard) || shard < 0) return Response.json({ error: "Invalid shard" }, { status: 400 });
44
+ const report = {
45
+ shard,
46
+ name: typeof body.name === "string" && body.name !== "" ? body.name : shard === 0 ? "global" : `sync-${shard}`,
47
+ ...typeof body.region === "string" ? { region: body.region } : {},
48
+ connections: Math.max(0, Number(body.connections ?? 0)),
49
+ ...body.version !== void 0 ? { version: Number(body.version) } : {},
50
+ updatedAt: Date.now()
51
+ };
52
+ this.persist(report);
53
+ const map = this.rebuild();
54
+ await this.publish(map);
55
+ return Response.json({
56
+ ok: true,
57
+ map
58
+ });
59
+ }
60
+ if (url.pathname === "/map" && request.method === "GET") {
61
+ const map = this.rebuild();
62
+ return Response.json(map);
63
+ }
64
+ if (url.pathname === "/rebalance" && request.method === "POST") {
65
+ const map = this.rebuild();
66
+ await this.publish(map);
67
+ return Response.json({
68
+ ok: true,
69
+ map
70
+ });
71
+ }
72
+ if (url.pathname === "/health") return Response.json({
73
+ ok: true,
74
+ reports: this.reports.size,
75
+ map: this.rebuild()
76
+ });
77
+ return new Response("Not found", { status: 404 });
78
+ }
79
+ persist(report) {
80
+ this.reports.set(report.shard, report);
81
+ if (!this.sql) return;
82
+ this.sql.exec(`INSERT INTO ${REPORTS_TABLE}
83
+ (shard, name, region, connections, version, updated_at)
84
+ VALUES (?, ?, ?, ?, ?, ?)
85
+ ON CONFLICT(shard) DO UPDATE SET
86
+ name = excluded.name,
87
+ region = excluded.region,
88
+ connections = excluded.connections,
89
+ version = excluded.version,
90
+ updated_at = excluded.updated_at`, report.shard, report.name ?? "", report.region ?? null, report.connections, report.version ?? null, report.updatedAt ?? Date.now());
91
+ }
92
+ rebuild() {
93
+ return buildSyncShardMap({
94
+ regions: resolveSyncRegions(this.env.VULTRO_SYNC_REGIONS, options.regions ?? []),
95
+ shardsPerRegion: options.shardsPerRegion ?? Number(this.env.VULTRO_SYNC_SHARDS_PER_REGION ?? 1),
96
+ targetConnectionsPerShard: options.targetConnectionsPerShard ?? Number(this.env.VULTRO_SYNC_TARGET_CONNECTIONS ?? 500),
97
+ reports: [...this.reports.values()]
98
+ });
99
+ }
100
+ async publish(map) {
101
+ const kv = this.env[kvBinding];
102
+ if (!kv || typeof kv.put !== "function") return;
103
+ await kv.put(syncShardMapKey(instance), JSON.stringify(map));
104
+ }
105
+ };
106
+ }
107
+ export { createSyncCoordinatorDO };
@@ -0,0 +1,24 @@
1
+ import type { RuntimeEnv } from "./platform.js";
2
+ import { type SyncRegionHint, type SyncRoutingConfig } from "@vultro/core";
3
+ /**
4
+ * ============================================================================
5
+ * Worker 入口
6
+ * ============================================================================
7
+ *
8
+ * 路由规则:
9
+ * - `WS /api/<clientVersion>/sync` -> VultroSyncDO(按 `?shard=` 或客户端哈希选 shard)
10
+ * - `POST /api/query|mutation|action|function` -> VultroDO
11
+ * - `GET /health` -> VultroDO(诊断用)
12
+ * - `GET /` -> 静态资源缺失时的兜底页(正常由 Cloudflare Assets 服务 React)
13
+ *
14
+ * 注意:
15
+ * - `VultroDO` 的 `/internal/*` 路由只允许 `VultroSyncDO` 通过 DO binding
16
+ * 直接调用,**不会**在 Worker 层暴露,避免客户端绕过 public/internal 检查。
17
+ * - Worker 本身不持有数据库,所有状态都在 Durable Object 中,
18
+ * 因此 Worker 可以水平扩展,事务仍然由单个 VultroDO 串行化。
19
+ */
20
+ export declare function createRuntimeWorker(defaultShards?: number, defaultRegions?: readonly SyncRegionHint[], defaultRouting?: SyncRoutingConfig,
21
+ /** 路由前缀,例如 `"/v"`;空串表示不加前缀。 */
22
+ prefix?: string): {
23
+ fetch(request: Request, env: RuntimeEnv, _ctx?: unknown): Promise<Response>;
24
+ };
package/dist/worker.js ADDED
@@ -0,0 +1,149 @@
1
+ import { DEFAULT_SYNC_SHARDS, resolveSyncRegions, resolveSyncRouting, resolveSyncShardCount, resolveSyncShardMapFromEnv, selectSyncShard, selectSyncShardFromMap, syncShardName, syncShardRegion } from "@vultro/core";
2
+ // src/worker.ts
3
+ /**
4
+ * ============================================================================
5
+ * Worker 入口
6
+ * ============================================================================
7
+ *
8
+ * 路由规则:
9
+ * - `WS /api/<clientVersion>/sync` -> VultroSyncDO(按 `?shard=` 或客户端哈希选 shard)
10
+ * - `POST /api/query|mutation|action|function` -> VultroDO
11
+ * - `GET /health` -> VultroDO(诊断用)
12
+ * - `GET /` -> 静态资源缺失时的兜底页(正常由 Cloudflare Assets 服务 React)
13
+ *
14
+ * 注意:
15
+ * - `VultroDO` 的 `/internal/*` 路由只允许 `VultroSyncDO` 通过 DO binding
16
+ * 直接调用,**不会**在 Worker 层暴露,避免客户端绕过 public/internal 检查。
17
+ * - Worker 本身不持有数据库,所有状态都在 Durable Object 中,
18
+ * 因此 Worker 可以水平扩展,事务仍然由单个 VultroDO 串行化。
19
+ */
20
+ function createRuntimeWorker(defaultShards = DEFAULT_SYNC_SHARDS, defaultRegions = [], defaultRouting = {}, prefix = "") {
21
+ const routePrefix = normalizePrefix(prefix);
22
+ return { async fetch(request, env, _ctx) {
23
+ if (routePrefix) {
24
+ const prefixed = stripPrefix(request, routePrefix);
25
+ if (!prefixed) return new Response("Not found", { status: 404 });
26
+ request = prefixed;
27
+ }
28
+ {
29
+ const probe = new URL(request.url);
30
+ if (probe.pathname.startsWith("//")) {
31
+ probe.pathname = probe.pathname.replace(/^\/{2,}/, "/");
32
+ request = new Request(probe, request);
33
+ }
34
+ }
35
+ const url = new URL(request.url);
36
+ const shardCount = resolveSyncShardCount(env.VULTRO_SYNC_SHARDS, defaultShards);
37
+ const regions = resolveSyncRegions(env.VULTRO_SYNC_REGIONS, defaultRegions);
38
+ const routing = resolveSyncRouting(env, defaultRouting);
39
+ if (url.pathname === "/sync" || url.pathname.endsWith("/sync")) {
40
+ const namespace = env.VULTRO_SYNC_DO;
41
+ if (!namespace) return jsonError("VULTRO_SYNC_DO binding is missing", 500);
42
+ const target = await resolveSyncTarget(request, env, shardCount, regions, routing);
43
+ const headers = new Headers(request.headers);
44
+ headers.set("x-vultro-sync-shard", String(target.shard));
45
+ if (target.region) headers.set("x-vultro-sync-region", target.region);
46
+ const routed = new Request(request, { headers });
47
+ return namespace.get(namespace.idFromName(target.name), { ...target.region ? { locationHint: target.region } : {} }).fetch(routed);
48
+ }
49
+ if (url.pathname === "/_sync/health") {
50
+ const namespace = env.VULTRO_SYNC_DO;
51
+ if (!namespace) return jsonError("VULTRO_SYNC_DO binding is missing", 500);
52
+ const target = await resolveSyncTarget(request, env, shardCount, regions, routing);
53
+ const headers = new Headers(request.headers);
54
+ headers.set("x-vultro-sync-shard", String(target.shard));
55
+ if (target.region) headers.set("x-vultro-sync-region", target.region);
56
+ return namespace.get(namespace.idFromName(target.name), { ...target.region ? { locationHint: target.region } : {} }).fetch(new Request("https://sync.internal/health", { headers }));
57
+ }
58
+ if (url.pathname.startsWith("/api/") || url.pathname === "/_dashboard" || url.pathname.startsWith("/_dashboard/") || url.pathname.startsWith("/_storage/") || url.pathname.startsWith("/_http/") || url.pathname === "/_http" || url.pathname.startsWith("/.well-known/") || isSettingsApiPath(url.pathname) || url.pathname === "/health") {
59
+ const namespace = env.VULTRO_DO;
60
+ if (!namespace) return jsonError("VULTRO_DO binding is missing", 500);
61
+ return namespace.get(namespace.idFromName("global")).fetch(request);
62
+ }
63
+ if (url.pathname === "/" || url.pathname === "/index.html") return new Response(FALLBACK_HTML, { headers: { "content-type": "text/html; charset=utf-8" } });
64
+ if (url.pathname === "/favicon.ico") return new Response(null, { status: 204 });
65
+ return new Response("Not found", { status: 404 });
66
+ } };
67
+ }
68
+ /**
69
+ * 把前缀规范成 `/xxx` 形式。
70
+ *
71
+ * 接受 `"v"` / `"/v"` / `"/v/"` 三种写法,统一成 `/v`;空串原样返回。
72
+ */
73
+ function normalizePrefix(prefix) {
74
+ const trimmed = prefix.trim().replace(/^\/+|\/+$/g, "");
75
+ return trimmed ? `/${trimmed}` : "";
76
+ }
77
+ /**
78
+ * 从请求路径里剥掉前缀,返回**新路径**的 Request。
79
+ *
80
+ * 前缀不匹配时返回 `null`,由调用方决定怎么处理(当前是 404)。
81
+ * 只改 pathname,保留 method / headers / body,DO 那边看到的与直接访问
82
+ * 原始路径完全一致。
83
+ */
84
+ function stripPrefix(request, prefix) {
85
+ const url = new URL(request.url);
86
+ if (url.pathname !== prefix && !url.pathname.startsWith(`${prefix}/`)) return null;
87
+ url.pathname = url.pathname.slice(prefix.length) || "/";
88
+ return new Request(url, request);
89
+ }
90
+ /** 解析 global-auto map 或静态拓扑,返回最终路由目标。 */
91
+ async function resolveSyncTarget(request, env, shardCount, regions, routing) {
92
+ const map = await resolveSyncShardMapFromEnv(env);
93
+ if (map) {
94
+ const entry = selectSyncShardFromMap(request, map, routing);
95
+ return {
96
+ shard: entry.shard,
97
+ name: entry.name,
98
+ ...entry.region ? { region: entry.region } : {}
99
+ };
100
+ }
101
+ const shard = selectSyncShard(request, shardCount, regions, routing);
102
+ const region = syncShardRegion(regions, shard);
103
+ return {
104
+ shard,
105
+ name: syncShardName(shard),
106
+ ...region ? { region } : {}
107
+ };
108
+ }
109
+ /** 与 http.ts 保持一致:官方 dashboard 根路径 API 转发给 VultroDO。 */
110
+ function isSettingsApiPath(pathname) {
111
+ const path = pathname.replace(/^\/api\/v1(?=\/|$)/, "");
112
+ return path === "/pause_deployment" || path === "/unpause_deployment" || path === "/list_usage_limits" || path === "/get_current_usage" || path === "/create_usage_limit" || path.startsWith("/update_usage_limit/") || path.startsWith("/delete_usage_limit/") || path === "/create_log_stream" || path.startsWith("/update_log_stream/") || path.startsWith("/delete_log_stream/") || path.startsWith("/data/");
113
+ }
114
+ function jsonError(message, status) {
115
+ return new Response(JSON.stringify({ error: message }), {
116
+ status,
117
+ headers: { "content-type": "application/json" }
118
+ });
119
+ }
120
+ /**
121
+ * 静态资源兜底页。
122
+ *
123
+ * 正常部署时 `/` 由 Cloudflare Assets 提供 React 前端(apps/play/index.html)。
124
+ * 这个页面只在 Worker 直接运行、没有绑定静态资源时出现,用于提示配置问题;
125
+ * 后端的 `/api/*` 与 WebSocket 仍然可用。
126
+ */
127
+ var FALLBACK_HTML = `<!doctype html>
128
+ <html lang="zh-CN">
129
+ <head>
130
+ <meta charset="utf-8" />
131
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
132
+ <title>Vultro</title>
133
+ <style>
134
+ body { margin: 0; min-height: 100vh; display: grid; place-items: center; background: #080a0d; color: #eef3f8; font: 15px/1.7 system-ui, sans-serif; }
135
+ main { max-width: 560px; padding: 32px; border: 1px solid #262d36; border-radius: 16px; background: #14181d; }
136
+ h1 { margin: 0 0 12px; font-size: 22px; }
137
+ p { margin: 0 0 12px; color: #8b98a5; }
138
+ code { color: #fdba74; }
139
+ </style>
140
+ </head>
141
+ <body>
142
+ <main>
143
+ <h1>Vultro</h1>
144
+ <p>前端静态资源没有正确绑定。请确认 <code>apps/play/index.html</code> 已构建,并在 <code>cloudflare.config.ts</code> 中启用 Assets。</p>
145
+ <p>后端 API 仍然可用:<code>POST /api/query</code>、<code>POST /api/mutation</code>、<code>WS /api/&lt;version&gt;/sync</code>。</p>
146
+ </main>
147
+ </body>
148
+ </html>`;
149
+ export { createRuntimeWorker };
package/package.json CHANGED
@@ -1,6 +1,28 @@
1
1
  {
2
2
  "name": "@vultro/runtime-cf",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.0.2",
4
+ "type": "module",
5
+ "description": "Cloudflare Workers / Durable Objects adapter for the @vultro/core runtime",
6
+ "exports": {
7
+ ".": {
8
+ "types": "./dist/index.d.ts",
9
+ "import": "./dist/index.js",
10
+ "default": "./dist/index.js"
11
+ },
12
+ "./config": {
13
+ "types": "./dist/config.d.ts",
14
+ "import": "./dist/config.js",
15
+ "default": "./dist/config.js"
16
+ }
17
+ },
18
+ "dependencies": {
19
+ "@vultro/core": "0.0.2",
20
+ "@vultro/docstore-d1": "0.0.2",
21
+ "@vultro/docstore-sqlite": "0.0.2",
22
+ "@vultro/storage-r2": "0.0.2"
23
+ },
24
+ "publishConfig": {
25
+ "access": "public"
26
+ },
27
+ "types": "./dist/index.d.ts"
28
+ }