recycle-expired.mjs 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. #!/usr/bin/env node
  2. /**
  3. * 过期容器回收(2026-12-04)—— 默认只读,`--apply` 才执行。
  4. *
  5. * ## 规则(用户裁决)
  6. *
  7. * 到期 → 能力立刻失效(各接口读时判定,不靠本脚本)
  8. * 到期满 7 天未续费 → 本脚本回收:
  9. * ① R730 上 docker stop + docker rm(容器消失)
  10. * ② 会话数据软删(FmodeChatThread 按 agentId)—— 用户再开通时不串旧数据
  11. * ③ 平台记录软删 + accessState=revoked;绑定 revoked
  12. * ④ 数据目录默认**保留**并打印路径,`--purge-data` 才删除
  13. *
  14. * 用法:
  15. * node scripts/recycle-expired.mjs # 干跑,列出清单
  16. * node scripts/recycle-expired.mjs --apply # 执行
  17. * node scripts/recycle-expired.mjs --apply --days=7 # 自定义宽限天数
  18. * node scripts/recycle-expired.mjs --apply --purge-data # 连数据目录一起删
  19. */
  20. import fs from 'node:fs';
  21. import { execFileSync } from 'node:child_process';
  22. import { resolve } from 'node:path';
  23. const ROOT = process.cwd();
  24. const argv = process.argv.slice(2);
  25. const has = (f) => argv.includes(f);
  26. const arg = (f, d) => argv.find((a) => a.startsWith(`--${f}=`))?.split('=')[1] ?? d;
  27. const APPLY = has('--apply');
  28. const PURGE = has('--purge-data');
  29. const DAYS = Number(arg('days', '7'));
  30. const R730 = resolve(ROOT, '.local-backup/skill-lock-20261201/r730.py');
  31. const cfg = JSON.parse(fs.readFileSync(resolve(ROOT, '.claude/dev-login.json'), 'utf8'));
  32. const H = { 'Content-Type': 'application/json', 'X-Parse-Application-Id': 'ncloudmaster', 'X-Parse-Master-Key': cfg.masterKey };
  33. const B = 'https://server.fmode.cn/parse/classes';
  34. const now = Date.now();
  35. const GRACE_MS = DAYS * 86400_000;
  36. const list = async (cls, where, keys) =>
  37. (await (await fetch(`${B}/${cls}?where=${encodeURIComponent(JSON.stringify(where))}&limit=500${keys ? '&keys=' + keys : ''}`, { headers: H })).json()).results ?? [];
  38. const put = async (cls, id, body) => (await fetch(`${B}/${cls}/${id}`, { method: 'PUT', headers: H, body: JSON.stringify(body) })).status;
  39. /* 1. 找候选:已过期且超过宽限期 */
  40. const agents = await list('FmodeAgent', { isDeleted: { $ne: true } }, 'objectId,name,agentId,planCode,user,accessExpiresAt,trialEndsAt,accessState');
  41. const due = [];
  42. for (const a of agents) {
  43. const raw = a.accessExpiresAt?.iso || a.trialEndsAt?.iso;
  44. const exp = raw ? Date.parse(raw) : 0;
  45. if (!exp || now - exp <= GRACE_MS) continue;
  46. due.push({ ...a, exp, overDays: Math.floor((now - exp) / 86400_000) });
  47. }
  48. console.log(`候选 ${due.length} 条(宽限 ${DAYS} 天,当前时间 ${new Date(now).toISOString()})\n`);
  49. if (!due.length) {
  50. console.log('没有需要回收的容器。');
  51. process.exit(0);
  52. }
  53. /* 2. 附带信息:会话数 */
  54. for (const a of due) {
  55. const threads = await list('FmodeChatThread', { agentId: a.agentId, isDeleted: { $ne: true } }, 'objectId');
  56. a.threadCount = threads.length;
  57. const isPlatform = (a.planCode === 'advanced' || a.planCode === 'enterprise');
  58. console.log(
  59. ` ${a.name || a.objectId} | ${a.agentId} | ${a.planCode} | 超期 ${a.overDays} 天 | 会话 ${a.threadCount} 条 | ${isPlatform ? '平台容器' : '本地容器(无容器可停)'}`,
  60. );
  61. }
  62. if (!APPLY) {
  63. console.log('\n[干跑] 未加 --apply,未做任何修改。');
  64. process.exit(0);
  65. }
  66. /* 3. 执行 */
  67. const platformAgents = due.filter((a) => a.planCode === 'advanced' || a.planCode === 'enterprise' || a.agentId);
  68. if (platformAgents.length) {
  69. const lines = ['set -e'];
  70. for (const a of platformAgents) {
  71. lines.push(`echo "[RECYCLE] ${a.agentId}"`);
  72. lines.push(`docker stop ${a.agentId} >/dev/null 2>&1 || true`);
  73. lines.push(`docker rm ${a.agentId} >/dev/null 2>&1 || echo " (容器已不在)"`);
  74. if (PURGE) lines.push(`[ -d /opt/fmode-containers/${a.agentId} ] && rm -rf /opt/fmode-containers/${a.agentId} && echo " [PURGE] 数据目录已删" || true`);
  75. else lines.push(`[ -d /opt/fmode-containers/${a.agentId} ] && echo " [KEEP] 数据目录保留: /opt/fmode-containers/${a.agentId}" || true`);
  76. }
  77. const f = resolve(ROOT, `.local-release/recycle-${Date.now()}.sh`);
  78. fs.mkdirSync(resolve(ROOT, '.local-release'), { recursive: true });
  79. fs.writeFileSync(f, lines.join('\n'));
  80. const out = execFileSync('python', [R730, f, '180'], { encoding: 'utf8', cwd: ROOT });
  81. console.log(out.split('\n').filter((l) => l.includes('[') || l.includes('已不在') || l.includes('KEEP') || l.includes('PURGE')).join('\n'));
  82. }
  83. for (const a of due) {
  84. /* 会话数据软删:用户再开通时不串旧数据 */
  85. const threads = await list('FmodeChatThread', { agentId: a.agentId, isDeleted: { $ne: true } }, 'objectId');
  86. for (const t of threads) await put('FmodeChatThread', t.objectId, { isDeleted: true });
  87. /* 平台记录与绑定 */
  88. await put('FmodeAgent', a.objectId, { isDeleted: true, accessState: 'revoked' });
  89. const binds = await list('FmodeMatrixBinding', { agentId: a.agentId }, 'objectId,status');
  90. for (const b of binds) await put('FmodeMatrixBinding', b.objectId, { status: 'revoked' });
  91. console.log(`[DONE] ${a.name || a.objectId}:会话软删 ${threads.length} 条,记录 revoked,绑定 ${binds.length} 条`);
  92. }
  93. console.log('\n回收完成。审计记录已打印在终端,按规范需补写操作追踪。');