bot-polling-retry-backoff.test.ts 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  1. import assert from "node:assert/strict";
  2. import type { BotRuntimeInfo, BotsConfigFile } from "@zcode/shared";
  3. import {
  4. createFeishuConfig,
  5. readBotSyntheticFixture,
  6. } from "#e2e/bots/helpers/bots-service-harness";
  7. import { createTelegramChannelRuntime } from "../../../../../services/src/bots/telegramChannelRuntime.js";
  8. import { createWeixinChannelRuntime } from "../../../../../services/src/bots/weixinChannelRuntime.js";
  9. type CredentialService = Parameters<typeof createWeixinChannelRuntime>[0]["credentialService"];
  10. function createRuntimeDeps(provider: "weixin" | "telegram") {
  11. const config: BotsConfigFile = createFeishuConfig();
  12. config.bots = [{ ...config.bots[0]!, id: `${provider}-retry-e2e`, provider }];
  13. const statuses = new Map<string, BotRuntimeInfo>();
  14. const warnings: string[] = [];
  15. return {
  16. bot: config.bots[0]!,
  17. warnings,
  18. deps: {
  19. // runtime 只读取 token;其余凭据能力与本用例无关。
  20. credentialService: { load: async () => "token-e2e" } as unknown as CredentialService,
  21. logger: {
  22. debug: () => undefined,
  23. info: () => undefined,
  24. warn: (_traceId: string | undefined, message: string) => warnings.push(message),
  25. },
  26. statusSink: {
  27. getRuntimeStatus: (botId: string) => statuses.get(botId),
  28. setRuntimeStatus: (status: BotRuntimeInfo) => statuses.set(status.botId, status),
  29. },
  30. ensureBotStorageMigrated: async () => undefined,
  31. readConfig: async () => config,
  32. acquirePollingLock: async () => ({ release: async () => undefined }),
  33. },
  34. };
  35. }
  36. /** 等到第 3 次拉取,返回相邻两次重试的间隔。 */
  37. async function waitForTwoRetryGaps(calls: number[], label: string): Promise<[number, number]> {
  38. await browser.waitUntil(async () => calls.length >= 3, {
  39. timeout: 30_000,
  40. timeoutMsg: `${label} 没有在退避后继续重试`,
  41. });
  42. return [calls[1]! - calls[0]!, calls[2]! - calls[1]!];
  43. }
  44. function assertBackoff(label: string, gaps: [number, number], warnings: string[], marker: string) {
  45. // 第 1 次失败等 5 秒,第 2 次等 10 秒;修复前两次都是 5 秒且没有日志。
  46. assert.ok(gaps[0] >= 4_500, `${label} 第 1 次重试间隔过短:${gaps[0]}ms`);
  47. assert.ok(gaps[1] >= 9_500, `${label} 第 2 次重试没有退避:${gaps[1]}ms`);
  48. assert.ok(
  49. warnings.some((line) => line.includes("failures=1 retryInMs=5000") && line.includes(marker)),
  50. `${label} 第 1 次失败没有 warn 日志:${JSON.stringify(warnings)}`,
  51. );
  52. assert.ok(
  53. warnings.some((line) => line.includes("failures=2 retryInMs=10000") && line.includes(marker)),
  54. `${label} 第 2 次失败没有 warn 日志:${JSON.stringify(warnings)}`,
  55. );
  56. }
  57. describe("BOT-E2E-RD-02 polling failure log and backoff", () => {
  58. const originalFetch = globalThis.fetch;
  59. afterEach(() => {
  60. globalThis.fetch = originalFetch;
  61. });
  62. it("weixin: logs each failed poll and doubles the retry delay without moving the cursor", async () => {
  63. const fixture = await readBotSyntheticFixture("polling-retry-backoff.json");
  64. assert.equal(fixture.caseId, "BOT-E2E-RD-02");
  65. const marker = `${fixture.promptMarker}_WEIXIN_DOWN`;
  66. const { bot, deps, warnings } = createRuntimeDeps("weixin");
  67. const calls: number[] = [];
  68. const bufs: Array<string | undefined> = [];
  69. const writtenBufs: string[] = [];
  70. const runtime = createWeixinChannelRuntime({
  71. ...deps,
  72. readWeixinGetUpdatesBuf: async () => "e2e-buf-before-failure",
  73. writeWeixinGetUpdatesBuf: async (_botId, buf) => {
  74. writtenBufs.push(buf);
  75. },
  76. processProviderCallback: async () => ({ ok: true, replies: [] }),
  77. getUpdates: async (params) => {
  78. calls.push(Date.now());
  79. bufs.push(params.buf);
  80. throw new Error(marker);
  81. },
  82. });
  83. try {
  84. await runtime.refresh();
  85. const gaps = await waitForTwoRetryGaps(calls, "weixin");
  86. assertBackoff("weixin", gaps, warnings, marker);
  87. assert.ok(warnings.every((line) => line.includes(`bot=${bot.id}`)));
  88. assert.deepEqual(
  89. new Set(bufs),
  90. new Set(["e2e-buf-before-failure"]),
  91. "失败后必须用原游标重试",
  92. );
  93. assert.deepEqual(writtenBufs, [], "失败的批次不能提交游标");
  94. } finally {
  95. await runtime.dispose();
  96. }
  97. });
  98. it("weixin: a committed batch resets the backoff, and dispose ends the wait at once", async () => {
  99. const fixture = await readBotSyntheticFixture("polling-retry-backoff.json");
  100. const marker = `${fixture.promptMarker}_WEIXIN_FLAKY`;
  101. const { deps, warnings } = createRuntimeDeps("weixin");
  102. let call = 0;
  103. const writtenBufs: string[] = [];
  104. const runtime = createWeixinChannelRuntime({
  105. ...deps,
  106. readWeixinGetUpdatesBuf: async () => "e2e-buf-before-failure",
  107. writeWeixinGetUpdatesBuf: async (_botId, buf) => {
  108. writtenBufs.push(buf);
  109. },
  110. processProviderCallback: async () => ({ ok: true, replies: [] }),
  111. // 失败、失败、成功提交、之后再失败。
  112. getUpdates: async () => {
  113. call += 1;
  114. if (call === 3) return { messages: [], buf: "e2e-buf-after-success" };
  115. throw new Error(marker);
  116. },
  117. });
  118. const firstFailureLogs = () =>
  119. warnings.filter(
  120. (line) => line.includes("failures=1 retryInMs=5000") && line.includes(marker),
  121. );
  122. try {
  123. await runtime.refresh();
  124. await browser.waitUntil(async () => firstFailureLogs().length >= 2, {
  125. timeout: 30_000,
  126. timeoutMsg: `成功提交后没有从 5 秒重新退避:${JSON.stringify(warnings)}`,
  127. });
  128. assert.deepEqual(writtenBufs, ["e2e-buf-after-success"], "只有完整成功的批次提交游标");
  129. assert.ok(
  130. warnings.some((line) => line.includes("failures=2 retryInMs=10000")),
  131. "成功前应已退避到 10 秒",
  132. );
  133. } finally {
  134. // 此时 runtime 正在 5 秒退避中;dispose 必须中止等待并释放轮询锁,不能等退避结束。
  135. const startedAt = Date.now();
  136. await runtime.dispose();
  137. assert.ok(
  138. Date.now() - startedAt < 2_000,
  139. `dispose 被退避等待阻塞:${Date.now() - startedAt}ms`,
  140. );
  141. }
  142. });
  143. it("telegram: logs each failed callback and doubles the retry delay without moving the offset", async () => {
  144. const fixture = await readBotSyntheticFixture("polling-retry-backoff.json");
  145. const marker = "Telegram callback failed: status=503";
  146. const { bot, deps, warnings } = createRuntimeDeps("telegram");
  147. const calls: number[] = [];
  148. const offsets: Array<number | undefined> = [];
  149. const writtenOffsets: number[] = [];
  150. globalThis.fetch = async (input, init) => {
  151. const url = String(input);
  152. if (url.endsWith("/getUpdates")) {
  153. calls.push(Date.now());
  154. offsets.push((JSON.parse(String(init?.body ?? "{}")) as { offset?: number }).offset);
  155. return Response.json({
  156. ok: true,
  157. result: [
  158. {
  159. update_id: 41,
  160. message: {
  161. message_id: 1,
  162. chat: { id: 1, type: "private" },
  163. from: { id: 1 },
  164. text: `${fixture.promptMarker} telegram`,
  165. },
  166. },
  167. ],
  168. });
  169. }
  170. return Response.json({ ok: true, result: true });
  171. };
  172. const runtime = createTelegramChannelRuntime({
  173. ...deps,
  174. telegramProvider: null,
  175. readTelegramOffset: async () => 41,
  176. writeTelegramOffset: async (_botId, offset) => {
  177. writtenOffsets.push(offset);
  178. },
  179. // 业务回调返回可恢复失败,offset 不能提交。
  180. processProviderCallback: async () => ({ ok: false, replies: [], status: 503 }),
  181. });
  182. try {
  183. await runtime.refresh();
  184. const gaps = await waitForTwoRetryGaps(calls, "telegram");
  185. assertBackoff("telegram", gaps, warnings, marker);
  186. assert.ok(warnings.every((line) => line.includes(`bot=${bot.id}`)));
  187. assert.deepEqual(new Set(offsets), new Set([41]), "失败后必须用原 offset 重试");
  188. assert.deepEqual(writtenOffsets, [], "失败的 update 不能提交 offset");
  189. } finally {
  190. await runtime.dispose();
  191. }
  192. });
  193. });