mobileLogPull.test.ts 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  1. import { gzipSync } from "node:zlib";
  2. import { describe, expect, it, vi } from "vitest";
  3. import type { WebRemoteControlMobileLogPullRequestPayload } from "@zcode/shared";
  4. import {
  5. createMobileLogPullCoordinator,
  6. decodeCompressedMobileLogShard,
  7. type MobileLogPullShard,
  8. } from "#src/main/web-remote-relay/index.js";
  9. function gzipEntries(entries: unknown[]): string {
  10. return gzipSync(Buffer.from(JSON.stringify(entries), "utf8")).toString("base64");
  11. }
  12. function setup(options?: Parameters<typeof createMobileLogPullCoordinator>[0]) {
  13. let counter = 0;
  14. const coordinator = createMobileLogPullCoordinator({
  15. createRequestId: () => `req-${++counter}`,
  16. ...options,
  17. });
  18. const sent: WebRemoteControlMobileLogPullRequestPayload[] = [];
  19. const shards: MobileLogPullShard[] = [];
  20. const owner = {};
  21. const start = (query = {}) =>
  22. coordinator.start({
  23. owner,
  24. query,
  25. send: (payload) => sent.push(payload),
  26. onShard: async (shard) => {
  27. shards.push(shard);
  28. },
  29. });
  30. return { coordinator, sent, shards, owner, start };
  31. }
  32. const meta = {
  33. zcode_type: "mobile-log-pull-response" as const,
  34. success: true as const,
  35. sources: ["log-files"],
  36. };
  37. describe("mobile log pull coordinator", () => {
  38. it("混合明文与 gzip 分片,按 cursor 续拉并汇总", async () => {
  39. const { coordinator, sent, shards, start } = setup();
  40. const pull = start({ keyword: "rc" });
  41. expect(sent[0]).toEqual({
  42. zcode_type: "mobile-log-pull-request",
  43. requestId: "req-1",
  44. keyword: "rc",
  45. acceptEncodings: ["gzip"],
  46. });
  47. coordinator.handleResponse({
  48. ...meta,
  49. requestId: "req-1",
  50. totalMatched: 3,
  51. returnedCount: 2,
  52. hasMore: true,
  53. cursor: "c1",
  54. encoding: "gzip",
  55. entryCount: 2,
  56. data: gzipEntries([
  57. { ts: 1, level: "info" },
  58. { ts: 2, level: "warn" },
  59. ]),
  60. });
  61. await vi.waitFor(() => expect(sent).toHaveLength(2));
  62. expect(sent[1]).toMatchObject({ requestId: "req-1", cursor: "c1" });
  63. coordinator.handleResponse({
  64. ...meta,
  65. requestId: "req-1",
  66. totalMatched: 3,
  67. returnedCount: 3,
  68. hasMore: false,
  69. truncated: true,
  70. entries: [{ ts: 3, level: "error" }],
  71. });
  72. await expect(pull).resolves.toEqual({
  73. requestId: "req-1",
  74. entryCount: 3,
  75. totalMatched: 3,
  76. shardCount: 2,
  77. compressedShardCount: 1,
  78. truncated: true,
  79. sources: ["log-files"],
  80. });
  81. expect(shards.map((shard) => shard.compressed)).toEqual([true, false]);
  82. });
  83. it("success:false + reason=unsupported-action 映射为 unsupported,其它原因为 mobile-error", async () => {
  84. const first = setup();
  85. const unsupported = first.start();
  86. first.coordinator.handleResponse({
  87. zcode_type: "mobile-log-pull-response",
  88. requestId: "req-1",
  89. success: false,
  90. reason: "unsupported-action",
  91. error: "no",
  92. });
  93. await expect(unsupported).rejects.toMatchObject({ code: "unsupported" });
  94. const second = setup();
  95. const busy = second.start();
  96. second.coordinator.handleResponse({
  97. zcode_type: "mobile-log-pull-response",
  98. requestId: "req-1",
  99. success: false,
  100. reason: "busy",
  101. error: "busy",
  102. });
  103. await expect(busy).rejects.toMatchObject({ code: "mobile-error" });
  104. });
  105. it("app-error 按 requestId 认领;不相关的 app-error 不消费", async () => {
  106. const { coordinator, start } = setup();
  107. const pull = start();
  108. expect(
  109. coordinator.handleAppError({ zcode_type: "app-error", reason: "unknown", error: "x" }),
  110. ).toBe(false);
  111. expect(
  112. coordinator.handleAppError({
  113. zcode_type: "app-error",
  114. requestId: "req-1",
  115. reason: "unsupported-action",
  116. error: "unknown",
  117. }),
  118. ).toBe(true);
  119. await expect(pull).rejects.toMatchObject({ code: "unsupported", entryCount: 0 });
  120. });
  121. it("单片超时失败,迟到分片被丢弃", async () => {
  122. vi.useFakeTimers();
  123. try {
  124. const { coordinator, start } = setup({ shardTimeoutMs: 1_000 });
  125. const pull = start();
  126. const assertion = expect(pull).rejects.toMatchObject({ code: "timeout" });
  127. await vi.advanceTimersByTimeAsync(1_001);
  128. await assertion;
  129. expect(
  130. coordinator.handleResponse({
  131. ...meta,
  132. requestId: "req-1",
  133. totalMatched: 0,
  134. returnedCount: 0,
  135. hasMore: false,
  136. entries: [],
  137. }),
  138. ).toBe(false);
  139. } finally {
  140. vi.useRealTimers();
  141. }
  142. });
  143. it("同一 owner 并发拉取返回 busy;cancelOwner 让在途拉取失败为 disconnected", async () => {
  144. const { coordinator, owner, start } = setup();
  145. const pull = start();
  146. await expect(start()).rejects.toMatchObject({ code: "busy" });
  147. coordinator.cancelOwner(owner, "stopped");
  148. await expect(pull).rejects.toMatchObject({ code: "disconnected" });
  149. });
  150. it("处理中收到的重复分片被丢弃,不会重复落盘", async () => {
  151. const { coordinator, shards, start } = setup();
  152. const pull = start();
  153. const response = {
  154. ...meta,
  155. requestId: "req-1",
  156. totalMatched: 1,
  157. returnedCount: 1,
  158. hasMore: false,
  159. entries: [{ ts: 1, level: "info" as const }],
  160. };
  161. coordinator.handleResponse(response);
  162. coordinator.handleResponse(response);
  163. await expect(pull).resolves.toMatchObject({ entryCount: 1, shardCount: 1 });
  164. expect(shards).toHaveLength(1);
  165. });
  166. it("gzip 分片 entryCount 不符或内容非法时失败为 invalid-shard", async () => {
  167. const { coordinator, start } = setup();
  168. const pull = start();
  169. coordinator.handleResponse({
  170. ...meta,
  171. requestId: "req-1",
  172. totalMatched: 1,
  173. returnedCount: 1,
  174. hasMore: false,
  175. encoding: "gzip",
  176. entryCount: 5,
  177. data: gzipEntries([{ ts: 1, level: "info" }]),
  178. });
  179. await expect(pull).rejects.toMatchObject({ code: "invalid-shard" });
  180. await expect(decodeCompressedMobileLogShard(gzipEntries([{ ts: 1 }]), 1)).rejects.toThrow(
  181. "schema",
  182. );
  183. await expect(decodeCompressedMobileLogShard("bm90LWd6aXA=", 0)).rejects.toThrow();
  184. });
  185. it("超过最大分片数时停止续拉并标记截断", async () => {
  186. const { coordinator, sent, start } = setup({ maxShards: 1 });
  187. const pull = start();
  188. coordinator.handleResponse({
  189. ...meta,
  190. requestId: "req-1",
  191. totalMatched: 10,
  192. returnedCount: 1,
  193. hasMore: true,
  194. cursor: "c1",
  195. entries: [{ ts: 1, level: "info" }],
  196. });
  197. await expect(pull).resolves.toMatchObject({ truncated: true, shardCount: 1 });
  198. expect(sent).toHaveLength(1);
  199. });
  200. });