deploy-cloud-fn.mjs 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  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. *
  41. * `create: true` 表示「线上还没这条就新建」——新建后会在控制台打印 objectId,
  42. * 需要把它写回 `src/app/core/api/parse-api.ts` 的 `FN` 常量。
  43. */
  44. const TARGETS = [
  45. {
  46. file: 'cloud/functions/fmodeagent-chatthreads.js',
  47. id: 'oR5O67i1Cm',
  48. name: 'fmodeagent-chatthreads',
  49. version: '0.1.9',
  50. },
  51. {
  52. file: 'cloud/functions/fmode-file-hub.js',
  53. id: null, // 新建前未知,部署时按 name 查
  54. name: 'fmode-file-hub',
  55. version: '0.1.0',
  56. create: true,
  57. },
  58. ];
  59. function authHeaders() {
  60. return {
  61. 'X-Parse-Application-Id': APP_ID,
  62. 'X-Parse-Master-Key': MK,
  63. 'Content-Type': 'application/json',
  64. };
  65. }
  66. async function getRemote(id) {
  67. const res = await fetch(`${BASE}/classes/Function/${id}`, { headers: authHeaders() });
  68. if (!res.ok) throw new Error(`读取失败 HTTP ${res.status}`);
  69. return res.json();
  70. }
  71. /** 按函数名查 objectId(新建前用于判断「线上是否已存在」) */
  72. async function findByName(name) {
  73. const where = encodeURIComponent(JSON.stringify({ name }));
  74. const res = await fetch(`${BASE}/classes/Function?where=${where}&limit=1`, {
  75. headers: authHeaders(),
  76. });
  77. if (!res.ok) throw new Error(`按名查询失败 HTTP ${res.status}`);
  78. const j = await res.json();
  79. return (j.results ?? [])[0] ?? null;
  80. }
  81. /** 新建云函数(POST /classes/Function),返回新 objectId */
  82. async function createRemote(name, code, version) {
  83. const res = await fetch(`${BASE}/classes/Function`, {
  84. method: 'POST',
  85. headers: authHeaders(),
  86. body: JSON.stringify({ name, code, version, enabled: true }),
  87. });
  88. const text = await res.text();
  89. if (!res.ok) throw new Error(`新建失败 HTTP ${res.status}: ${text.slice(0, 200)}`);
  90. const j = JSON.parse(text);
  91. return j.objectId;
  92. }
  93. /** PUT 有频率限制,403 时退避重试 */
  94. async function putRemote(id, body, attempt = 1) {
  95. const res = await fetch(`${BASE}/classes/Function/${id}`, {
  96. method: 'PUT',
  97. headers: authHeaders(),
  98. body: JSON.stringify(body),
  99. });
  100. if (res.status === 403 && attempt <= 4) {
  101. const wait = 1000 * attempt;
  102. console.log(` ⚠️ 403(频率限制),${wait}ms 后重试 ${attempt}/4`);
  103. await new Promise((r) => setTimeout(r, wait));
  104. return putRemote(id, body, attempt + 1);
  105. }
  106. const text = await res.text();
  107. if (!res.ok) throw new Error(`PUT 失败 HTTP ${res.status}: ${text.slice(0, 200)}`);
  108. try {
  109. return JSON.parse(text);
  110. } catch {
  111. return { raw: text.slice(0, 200) };
  112. }
  113. }
  114. async function main() {
  115. if (!MK) {
  116. console.error('❌ 缺少 PARSE_MASTER_KEY 环境变量');
  117. console.error(' 用法:PARSE_MASTER_KEY=xxx node scripts/deploy-cloud-fn.mjs [--apply]');
  118. process.exit(2);
  119. }
  120. console.log(APPLY ? '🔴 APPLY:将热更线上云函数' : '🟡 DRY-RUN:只对比,不写入');
  121. for (const t of TARGETS) {
  122. const code = readFileSync(resolve(root, t.file), 'utf8');
  123. console.log(`\n=== ${t.name} (${t.id ?? '待新建'}) ===`);
  124. console.log(` 本地源码:${t.file},${code.length} 字符,v${t.version}`);
  125. /* 新建分支:线上还没有这条 Function 记录 */
  126. if (t.create) {
  127. let existing = null;
  128. try {
  129. existing = await findByName(t.name);
  130. } catch (e) {
  131. console.log(` ⚠️ 按名查询失败:${e.message}`);
  132. }
  133. if (!existing) {
  134. console.log(' → 线上不存在,将新建');
  135. if (!APPLY) {
  136. console.log(' → 加 --apply 才会真正新建');
  137. continue;
  138. }
  139. const id = await createRemote(t.name, code, t.version);
  140. console.log(` ✅ 已新建,objectId = ${id}`);
  141. console.log(` 🔴 请把它写进 src/app/core/api/parse-api.ts 的 FN 常量`);
  142. continue;
  143. }
  144. t.id = existing.objectId;
  145. console.log(` → 线上已存在,objectId = ${t.id},转为更新`);
  146. }
  147. let remote;
  148. try {
  149. remote = await getRemote(t.id);
  150. } catch (e) {
  151. console.log(` ⚠️ 读取线上失败:${e.message}(跳过对比)`);
  152. remote = null;
  153. }
  154. if (remote) {
  155. const rc = remote.code || '';
  156. console.log(` 线上源码:${rc.length} 字符,v${remote.version ?? '?'}`);
  157. if (rc === code) {
  158. console.log(' ✅ 与线上完全一致,无需部署');
  159. continue;
  160. }
  161. if (rc.length && code.length < rc.length * 0.7) {
  162. console.log(' 🔴 警告:本地源码明显小于线上,可能回退功能,已跳过');
  163. continue;
  164. }
  165. }
  166. if (!APPLY) {
  167. console.log(' → 加 --apply 才会真正热更');
  168. continue;
  169. }
  170. const r = await putRemote(t.id, { code, version: t.version, enabled: true });
  171. console.log(` ✅ 已热更:${JSON.stringify(r).slice(0, 120)}(免重启,立即生效)`);
  172. }
  173. }
  174. main().catch((e) => {
  175. console.error('❌ 执行失败:', e.message);
  176. process.exit(1);
  177. });