test-provision-entry.mjs 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  1. /** 本地云函数契约回归;全部使用内存数据,不访问远程。 */
  2. import { readFileSync } from 'node:fs';
  3. import vm from 'node:vm';
  4. import assert from 'node:assert/strict';
  5. import { test } from 'node:test';
  6. const scope = vm.createContext({});
  7. vm.runInContext(readFileSync(new URL('../cloud/functions/fmodeagent-status.js', import.meta.url), 'utf8'), scope);
  8. const record = (id, fields) => ({ id, get: key => fields[key] });
  9. const owner = { id: 'owner' };
  10. const agent = (fields = {}) => record('a1', { user: owner, agentId: 'agent-node-app-a1', ...fields });
  11. const binding = () => record('b1', { agentMxId: '@a1:fmode.cn', roomId: '!room', accessToken: 'never-return-this' });
  12. const index = (status = 'ready') => ({
  13. bindings: { 'owner:agent-node-app-a1': binding() },
  14. jobs: { 'owner:a1': record('j1', { status }) },
  15. });
  16. test('真实心跳过期时,重命名改 updatedAt 不能把离线容器判在线', () => {
  17. const fields = { heartbeatAt: new Date(Date.now() - 86400000) };
  18. const a = { ...record('a1', fields), updatedAt: new Date(), toJSON: () => ({ status: 'offline' }) };
  19. const out = scope._agentJSON(a, {});
  20. assert.ok(out.heartbeatAgeSec >= 86400);
  21. const projected = scope._withAppReadiness(agent({ channels: { matrixConfig: { channelState: 'connected' } } }), out, index());
  22. assert.equal(projected.status, 'offline');
  23. });
  24. test('已完成交付与接入绑定独立于原始 offline;不泄漏绑定凭据', () => {
  25. const out = scope._withAppReadiness(agent(), { status: 'offline', heartbeatAgeSec: 10 }, index());
  26. assert.equal(out.provisioned, true);
  27. assert.equal(out.matrixReady, true);
  28. assert.equal(out.channels.matrixConfig.userId, '@a1:fmode.cn');
  29. assert.equal(out.status, 'offline'); // 只有绑定不能宣称实时在线
  30. assert.equal(out.channels.matrixConfig.channelState, undefined);
  31. assert.equal(JSON.stringify(out).includes('never-return-this'), false);
  32. assert.equal(JSON.stringify(out).includes('!room'), false);
  33. });
  34. test('有绑定、正在开通不等于已交付', () => {
  35. assert.equal(scope._withAppReadiness(agent(), {}, index('provisioning')).provisioned, false);
  36. });
  37. test('其他用户的相同容器标识不能提供准入', () => {
  38. const out = scope._withAppReadiness(agent({ user: { id: 'other' } }), {}, index());
  39. assert.equal(out.matrixReady, false);
  40. assert.equal(out.provisioned, false);
  41. });
  42. test('初始 offline 只有真实 connected 上报及新鲜心跳才能投影 idle', () => {
  43. const a = agent({ channels: { matrixConfig: { channelState: 'connected' } } });
  44. assert.equal(scope._withAppReadiness(a, { status: 'offline', heartbeatAgeSec: 30 }, index()).status, 'idle');
  45. assert.equal(scope._withAppReadiness(a, { status: 'offline', heartbeatAgeSec: 5000 }, index()).status, 'offline');
  46. assert.equal(scope._withAppReadiness(a, { status: 'stopped', heartbeatAgeSec: 30 }, index()).status, 'stopped');
  47. });
  48. test('没有新任务的历史接入兼容;只有空记录不能准入', () => {
  49. const emptyIndex = { bindings: {}, jobs: {} };
  50. assert.equal(scope._withAppReadiness(agent({ channels: { matrix: true } }), {}, emptyIndex).provisioned, true);
  51. assert.equal(scope._withAppReadiness(agent(), {}, emptyIndex).provisioned, false);
  52. });
  53. const provisionScope = vm.createContext({});
  54. vm.runInContext(readFileSync(new URL('../cloud/functions/fmode-provisioning.js', import.meta.url), 'utf8'), provisionScope);
  55. test('阶段已完成后不再把该阶段旧 running 当作当前进度', () => {
  56. const steps = [
  57. { stage: 'prepare', status: 'running' }, { stage: 'prepare', status: 'ok' },
  58. { stage: 'copy', status: 'running' }, { stage: 'copy', status: 'ok' },
  59. ];
  60. assert.equal(provisionScope._currentStep(steps).status, 'ok');
  61. assert.equal(provisionScope._currentStep(steps).stage, 'copy');
  62. steps.push({ stage: 'configure', status: 'running' });
  63. assert.equal(provisionScope._currentStep(steps).stage, 'configure');
  64. });
  65. test('延迟到达的 running 不能覆盖同次尝试已确认完成的阶段', () => {
  66. const steps = [{ stage: 'verify', status: 'ok' }, { stage: 'verify', status: 'running' }];
  67. assert.equal(provisionScope._currentStep(steps).status, 'ok');
  68. });
  69. function probeFixture() {
  70. let sent = 0;
  71. let events = [{ event_id: '$probe', type: 'm.room.message', sender: '@owner:fmode.cn' }];
  72. const fields = { attempts: 1 };
  73. const job = { ...record('job-1', fields), set: (k, v) => { fields[k] = v; }, save: async () => {} };
  74. const prov = { roomId: '!bound', userMxId: '@owner:fmode.cn', agentMxId: '@a1:fmode.cn', accessToken: 'fixture' };
  75. provisionScope.fetch = async (url, init) => {
  76. if (init?.method === 'PUT') {
  77. sent++;
  78. assert.match(url, /fmode-ready-job-1-1$/);
  79. assert.equal(JSON.parse(init.body)['m.mentions'].user_ids[0], prov.agentMxId);
  80. return { ok: true, json: async () => ({ event_id: '$probe' }) };
  81. }
  82. return { ok: true, json: async () => ({ chunk: events }) };
  83. };
  84. return { job, prov, sent: () => sent, events: value => { events = value; } };
  85. }
  86. test('只有建号、房间和心跳,尚无真实回复不能通过收发核验;轮询不重复发探针', async () => {
  87. const f = probeFixture();
  88. assert.equal(await provisionScope._probeRoundtrip(f.job, f.prov), false);
  89. assert.equal(await provisionScope._probeRoundtrip(f.job, f.prov), false);
  90. assert.equal(f.sent(), 1);
  91. });
  92. test('目标 sender 的实际回复与对应结束反应才通过,历史消息及其他 sender 不算', async () => {
  93. const f = probeFixture();
  94. await provisionScope._probeRoundtrip(f.job, f.prov);
  95. const reply = { event_id: '$reply', type: 'm.room.message', sender: f.prov.agentMxId,
  96. content: { msgtype: 'm.text', body: '在线' } };
  97. const done = { event_id: '$done', type: 'm.reaction', sender: f.prov.agentMxId,
  98. content: { 'm.relates_to': { rel_type: 'm.annotation', key: '✅', event_id: '$probe' } } };
  99. const root = { event_id: '$probe' };
  100. f.events([done, reply, root]);
  101. assert.equal(await provisionScope._probeRoundtrip(f.job, f.prov), true);
  102. f.events([{ ...done, sender: '@other:fmode.cn' }, reply, root]);
  103. assert.equal(await provisionScope._probeRoundtrip(f.job, f.prov), false);
  104. f.events([done, root, reply]);
  105. assert.equal(await provisionScope._probeRoundtrip(f.job, f.prov), false);
  106. });
  107. test('探针超过最近消息窗口时按事件上下文恢复验证', async () => {
  108. const f = probeFixture();
  109. await provisionScope._probeRoundtrip(f.job, f.prov);
  110. f.events([]);
  111. const original = provisionScope.fetch;
  112. provisionScope.fetch = async (url, init) => url.includes('/context/') ? {
  113. ok: true,
  114. json: async () => ({ event: { event_id: '$probe' }, events_after: [
  115. { event_id: '$reply', type: 'm.room.message', sender: f.prov.agentMxId, content: { msgtype: 'm.text', body: '在线' } },
  116. { event_id: '$done', type: 'm.reaction', sender: f.prov.agentMxId,
  117. content: { 'm.relates_to': { rel_type: 'm.annotation', key: '✅', event_id: '$probe' } } },
  118. ] }),
  119. } : original(url, init);
  120. assert.equal(await provisionScope._probeRoundtrip(f.job, f.prov), true);
  121. });