deploy-cloud-fn.mjs 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. #!/usr/bin/env node
  2. /**
  3. * 云函数热更脚本(本地使用,不部署、不上传)
  4. *
  5. * ## 用途
  6. *
  7. * 把 `cloud/functions/*.js` 的最新源码推到线上 Parse 的 `Function` 表。
  8. * 热更免重启(`PUT /parse/classes/Function/<objectId>`)。
  9. *
  10. * ## 为什么需要 Master-Key
  11. *
  12. * 写 `Function` 表属于平台管理操作,只有 Master-Key 有权限。
  13. * 🔴 **Master-Key 绝不能写进代码或提交进 git**,只能通过环境变量传入:
  14. *
  15. * ```bash
  16. * PARSE_MASTER_KEY=xxx node scripts/deploy-cloud-fn.mjs
  17. * PARSE_MASTER_KEY=xxx node scripts/deploy-cloud-fn.mjs --dry-run
  18. * ```
  19. *
  20. * ## 安全
  21. *
  22. * · 默认 **dry-run**:只打印将要更新什么,不发请求
  23. * · `--apply` 才真正 PUT
  24. * · 不发请求前先 GET 一次,对比线上版本,避免误覆盖别人改过的代码
  25. *
  26. * ## 频率限制
  27. *
  28. * 实测:`PUT` 连续请求会返回 403,需退避重试(见操作追踪 :3125)。
  29. */
  30. import { readFileSync } from 'node:fs';
  31. import { dirname, resolve } from 'node:path';
  32. import { fileURLToPath } from 'node:url';
  33. const here = dirname(fileURLToPath(import.meta.url));
  34. const root = resolve(here, '..');
  35. const APP_ID = 'ncloudmaster';
  36. const BASE = 'https://server.fmode.cn/parse';
  37. const MK = process.env.PARSE_MASTER_KEY;
  38. const APPLY = process.argv.includes('--apply');
  39. /**
  40. * 只部署指定函数(2026-11-12 新增)。
  41. *
  42. * 背景:本地保存的是各函数的源码副本,但不保证与线上随时同步 ——
  43. * 别人可能在控制台改过线上版本。批量 `--apply` 会把本地较旧的副本推上去,
  44. * 覆盖掉那些改动。
  45. *
  46. * 用法:`--only=fmodeagent-matrix-provision`(按 name 或 id 精确匹配)
  47. */
  48. const ONLY = (process.argv.find((a) => a.startsWith('--only=')) ?? '').slice('--only='.length);
  49. /** 要部署的函数清单
  50. *
  51. * `create: true` 表示「线上还没这条就新建」——新建后会在控制台打印 objectId,
  52. * 需要把它写回 `src/app/core/api/parse-api.ts` 的 `FN` 常量。
  53. */
  54. const TARGETS = [
  55. {
  56. /*
  57. * 2026-11-23 新建:App 版本更新检查。
  58. * 老接口 app_update 在当前集群已 404,导致更新功能整体失效 —— 本函数接管。
  59. * 调用方式用函数 id(按 path 调用实测返回「云函数不存在」)。
  60. */
  61. file: 'cloud/functions/fmode-app-update-db.js',
  62. id: 'kTPtIM9YTQ',
  63. name: 'fmode-app-update',
  64. version: '1.0.0',
  65. },
  66. {
  67. file: 'cloud/functions/fmodeagent-chatthreads.js',
  68. id: 'oR5O67i1Cm',
  69. name: 'fmodeagent-chatthreads',
  70. version: '0.1.9',
  71. },
  72. {
  73. file: 'cloud/functions/fmodeagent-matrix-provision.js',
  74. id: 'RP5Ht55NeX',
  75. name: 'fmodeagent-matrix-provision',
  76. version: '0.1.6',
  77. },
  78. {
  79. file: 'cloud/functions/fmode-file-hub.js',
  80. id: null, // 新建前未知,部署时按 name 查
  81. name: 'fmode-file-hub',
  82. /* v0.3.0(2026-11-13):归属主键切 roomId + 新增 listByUrl */
  83. version: '0.3.0',
  84. create: true,
  85. },
  86. {
  87. /* 2026-11-21:v0.2.0 修复「无鉴权」—— 初版不带任何身份即可给任意用户发推送 */
  88. file: 'cloud/functions/fmodeagent-push.js',
  89. id: 'oCRJCCdiAx',
  90. name: 'fmodeagent-push',
  91. version: '0.2.0',
  92. },
  93. {
  94. /* 2026-11-21:新建。Matrix 新消息 → 调极光(服务端触发链路,此前完全缺失) */
  95. file: 'cloud/functions/fmodeagent-push-watch.js',
  96. id: null,
  97. name: 'fmodeagent-push-watch',
  98. version: '0.1.0',
  99. create: true,
  100. },
  101. {
  102. /* 2026-11-25:新建。容器开通(start/status/retry/list)
  103. *
  104. * 🔴 这是「App 点一下 → 平台建容器」的服务端实现:
  105. * 建 FmodeAgent 记录 → Matrix 身份 → **新建任务房间** → 发技能工单 → 服务端核验。
  106. * ready 只由服务端事实推导,不信任主容器的自然语言回报。
  107. *
  108. * v0.3.0(2026-11-26):主容器「技能工单 + 一任务一房间」
  109. * · 指令从 200 行长文改为 JSON 工单,步骤移到 `container-provision-job` 技能
  110. * · 每个任务新建 Matrix 房间(新 roomId = 新 Hermes session = 干净上下文)
  111. * · 从任务房间回读 ===PROVISION-RESULT=== 作为诊断(不参与 ready 判定)
  112. */
  113. file: 'cloud/functions/fmode-provisioning.js',
  114. id: 'VtW1GT93Ax',
  115. name: 'fmode-provisioning',
  116. version: '0.8.0',
  117. create: true,
  118. },
  119. ];
  120. function authHeaders() {
  121. return {
  122. 'X-Parse-Application-Id': APP_ID,
  123. 'X-Parse-Master-Key': MK,
  124. 'Content-Type': 'application/json',
  125. };
  126. }
  127. async function getRemote(id) {
  128. const res = await fetch(`${BASE}/classes/Function/${id}`, { headers: authHeaders() });
  129. if (!res.ok) throw new Error(`读取失败 HTTP ${res.status}`);
  130. return res.json();
  131. }
  132. /** 按函数名查 objectId(新建前用于判断「线上是否已存在」) */
  133. async function findByName(name) {
  134. const where = encodeURIComponent(JSON.stringify({ name }));
  135. const res = await fetch(`${BASE}/classes/Function?where=${where}&limit=1`, {
  136. headers: authHeaders(),
  137. });
  138. if (!res.ok) throw new Error(`按名查询失败 HTTP ${res.status}`);
  139. const j = await res.json();
  140. return (j.results ?? [])[0] ?? null;
  141. }
  142. /** 新建云函数(POST /classes/Function),返回新 objectId */
  143. async function createRemote(name, code, version) {
  144. const res = await fetch(`${BASE}/classes/Function`, {
  145. method: 'POST',
  146. headers: authHeaders(),
  147. body: JSON.stringify({ name, code, version, enabled: true }),
  148. });
  149. const text = await res.text();
  150. if (!res.ok) throw new Error(`新建失败 HTTP ${res.status}: ${text.slice(0, 200)}`);
  151. const j = JSON.parse(text);
  152. return j.objectId;
  153. }
  154. /** PUT 有频率限制,403 时退避重试 */
  155. async function putRemote(id, body, attempt = 1) {
  156. const res = await fetch(`${BASE}/classes/Function/${id}`, {
  157. method: 'PUT',
  158. headers: authHeaders(),
  159. body: JSON.stringify(body),
  160. });
  161. if (res.status === 403 && attempt <= 4) {
  162. const wait = 1000 * attempt;
  163. console.log(` ⚠️ 403(频率限制),${wait}ms 后重试 ${attempt}/4`);
  164. await new Promise((r) => setTimeout(r, wait));
  165. return putRemote(id, body, attempt + 1);
  166. }
  167. const text = await res.text();
  168. if (!res.ok) throw new Error(`PUT 失败 HTTP ${res.status}: ${text.slice(0, 200)}`);
  169. try {
  170. return JSON.parse(text);
  171. } catch {
  172. return { raw: text.slice(0, 200) };
  173. }
  174. }
  175. async function main() {
  176. if (!MK) {
  177. console.error('❌ 缺少 PARSE_MASTER_KEY 环境变量');
  178. console.error(' 用法:PARSE_MASTER_KEY=xxx node scripts/deploy-cloud-fn.mjs [--apply]');
  179. process.exit(2);
  180. }
  181. console.log(APPLY ? '🔴 APPLY:将热更线上云函数' : '🟡 DRY-RUN:只对比,不写入');
  182. if (ONLY) console.log(`🎯 只处理:${ONLY}`);
  183. for (const t of TARGETS) {
  184. /* `--only=` 指定时,跳过不匹配的(按 name 或 id) */
  185. if (ONLY && t.name !== ONLY && t.id !== ONLY) continue;
  186. const code = readFileSync(resolve(root, t.file), 'utf8');
  187. console.log(`\n=== ${t.name} (${t.id ?? '待新建'}) ===`);
  188. console.log(` 本地源码:${t.file},${code.length} 字符,v${t.version}`);
  189. /* 新建分支:线上还没有这条 Function 记录 */
  190. if (t.create) {
  191. let existing = null;
  192. try {
  193. existing = await findByName(t.name);
  194. } catch (e) {
  195. console.log(` ⚠️ 按名查询失败:${e.message}`);
  196. }
  197. if (!existing) {
  198. console.log(' → 线上不存在,将新建');
  199. if (!APPLY) {
  200. console.log(' → 加 --apply 才会真正新建');
  201. continue;
  202. }
  203. const id = await createRemote(t.name, code, t.version);
  204. console.log(` ✅ 已新建,objectId = ${id}`);
  205. console.log(` 🔴 请把它写进 src/app/core/api/parse-api.ts 的 FN 常量`);
  206. continue;
  207. }
  208. t.id = existing.objectId;
  209. console.log(` → 线上已存在,objectId = ${t.id},转为更新`);
  210. }
  211. let remote;
  212. try {
  213. remote = await getRemote(t.id);
  214. } catch (e) {
  215. console.log(` ⚠️ 读取线上失败:${e.message}(跳过对比)`);
  216. remote = null;
  217. }
  218. if (remote) {
  219. const rc = remote.code || '';
  220. console.log(` 线上源码:${rc.length} 字符,v${remote.version ?? '?'}`);
  221. if (rc === code) {
  222. console.log(' ✅ 与线上完全一致,无需部署');
  223. continue;
  224. }
  225. if (rc.length && code.length < rc.length * 0.7) {
  226. console.log(' 🔴 警告:本地源码明显小于线上,可能回退功能,已跳过');
  227. continue;
  228. }
  229. }
  230. if (!APPLY) {
  231. console.log(' → 加 --apply 才会真正热更');
  232. continue;
  233. }
  234. const r = await putRemote(t.id, { code, version: t.version, enabled: true });
  235. console.log(` ✅ 已热更:${JSON.stringify(r).slice(0, 120)}(免重启,立即生效)`);
  236. }
  237. }
  238. main().catch((e) => {
  239. console.error('❌ 执行失败:', e.message);
  240. process.exit(1);
  241. });