deploy-cloud-fn.mjs 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  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. const TARGETS = [
  41. {
  42. file: 'cloud/functions/fmodeagent-chatthreads.js',
  43. id: 'oR5O67i1Cm',
  44. name: 'fmodeagent-chatthreads',
  45. version: '0.1.9',
  46. },
  47. ];
  48. function authHeaders() {
  49. return {
  50. 'X-Parse-Application-Id': APP_ID,
  51. 'X-Parse-Master-Key': MK,
  52. 'Content-Type': 'application/json',
  53. };
  54. }
  55. async function getRemote(id) {
  56. const res = await fetch(`${BASE}/classes/Function/${id}`, { headers: authHeaders() });
  57. if (!res.ok) throw new Error(`读取失败 HTTP ${res.status}`);
  58. return res.json();
  59. }
  60. /** PUT 有频率限制,403 时退避重试 */
  61. async function putRemote(id, body, attempt = 1) {
  62. const res = await fetch(`${BASE}/classes/Function/${id}`, {
  63. method: 'PUT',
  64. headers: authHeaders(),
  65. body: JSON.stringify(body),
  66. });
  67. if (res.status === 403 && attempt <= 4) {
  68. const wait = 1000 * attempt;
  69. console.log(` ⚠️ 403(频率限制),${wait}ms 后重试 ${attempt}/4`);
  70. await new Promise((r) => setTimeout(r, wait));
  71. return putRemote(id, body, attempt + 1);
  72. }
  73. const text = await res.text();
  74. if (!res.ok) throw new Error(`PUT 失败 HTTP ${res.status}: ${text.slice(0, 200)}`);
  75. try {
  76. return JSON.parse(text);
  77. } catch {
  78. return { raw: text.slice(0, 200) };
  79. }
  80. }
  81. async function main() {
  82. if (!MK) {
  83. console.error('❌ 缺少 PARSE_MASTER_KEY 环境变量');
  84. console.error(' 用法:PARSE_MASTER_KEY=xxx node scripts/deploy-cloud-fn.mjs [--apply]');
  85. process.exit(2);
  86. }
  87. console.log(APPLY ? '🔴 APPLY:将热更线上云函数' : '🟡 DRY-RUN:只对比,不写入');
  88. for (const t of TARGETS) {
  89. const code = readFileSync(resolve(root, t.file), 'utf8');
  90. console.log(`\n=== ${t.name} (${t.id}) ===`);
  91. console.log(` 本地源码:${t.file},${code.length} 字符,v${t.version}`);
  92. let remote;
  93. try {
  94. remote = await getRemote(t.id);
  95. } catch (e) {
  96. console.log(` ⚠️ 读取线上失败:${e.message}(跳过对比)`);
  97. remote = null;
  98. }
  99. if (remote) {
  100. const rc = remote.code || '';
  101. console.log(` 线上源码:${rc.length} 字符,v${remote.version ?? '?'}`);
  102. if (rc === code) {
  103. console.log(' ✅ 与线上完全一致,无需部署');
  104. continue;
  105. }
  106. if (rc.length && code.length < rc.length * 0.7) {
  107. console.log(' 🔴 警告:本地源码明显小于线上,可能回退功能,已跳过');
  108. continue;
  109. }
  110. }
  111. if (!APPLY) {
  112. console.log(' → 加 --apply 才会真正热更');
  113. continue;
  114. }
  115. const r = await putRemote(t.id, { code, version: t.version, enabled: true });
  116. console.log(` ✅ 已热更:${JSON.stringify(r).slice(0, 120)}(免重启,立即生效)`);
  117. }
  118. }
  119. main().catch((e) => {
  120. console.error('❌ 执行失败:', e.message);
  121. process.exit(1);
  122. });