nodeApiClient.test.ts 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  1. import { afterEach, describe, expect, it, vi } from "vitest";
  2. import { ApiError } from "@zcode/shared";
  3. import { createNodeApiClient } from "../src/providers/api/nodeApiClient.js";
  4. describe("nodeApiClient", () => {
  5. afterEach(() => {
  6. vi.useRealTimers();
  7. });
  8. it("会给请求自动补 x-request-id", async () => {
  9. const fetchImpl = vi.fn(async () => new Response("{}", { status: 200 }));
  10. const client = createNodeApiClient({ fetchImpl });
  11. await client.request("https://example.com/oauth/token", {
  12. method: "POST",
  13. });
  14. const headers = new Headers(fetchImpl.mock.calls[0]?.[1]?.headers);
  15. expect(headers.get("x-request-id")).toMatch(
  16. /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,
  17. );
  18. });
  19. it("保留调用方显式传入的 x-request-id", async () => {
  20. const fetchImpl = vi.fn(async () => new Response("{}", { status: 200 }));
  21. const client = createNodeApiClient({ fetchImpl });
  22. await client.request("https://example.com/oauth/token", {
  23. method: "POST",
  24. headers: {
  25. "X-Request-Id": "caller-request-id",
  26. },
  27. });
  28. const headers = new Headers(fetchImpl.mock.calls[0]?.[1]?.headers);
  29. expect(headers.get("x-request-id")).toBe("caller-request-id");
  30. });
  31. it("401 且请求携带当前 ZCode JWT 时通知回调", async () => {
  32. const onZcodeJwtInvalid = vi.fn();
  33. const fetchImpl = vi.fn(
  34. async () =>
  35. new Response("", {
  36. status: 401,
  37. }),
  38. );
  39. const client = createNodeApiClient({
  40. fetchImpl,
  41. onZcodeJwtInvalid,
  42. isZcodeJwtRequest: (_input, headers) => headers.get("authorization") === "Bearer jwt",
  43. });
  44. await client.request("https://example.com/model", { headers: { Authorization: "Bearer jwt" } });
  45. expect(onZcodeJwtInvalid).toHaveBeenCalledTimes(1);
  46. });
  47. it("普通 401 不通知 ZCode JWT 失效", async () => {
  48. const onZcodeJwtInvalid = vi.fn();
  49. const fetchImpl = vi.fn(async () => new Response("", { status: 401 }));
  50. const client = createNodeApiClient({ fetchImpl, onZcodeJwtInvalid });
  51. await client.request("https://example.com/model");
  52. expect(onZcodeJwtInvalid).not.toHaveBeenCalled();
  53. });
  54. it("HTTP 200 业务 401 复用失效通知,保留原响应正文", async () => {
  55. const payload = { code: 401, msg: "登录状态已过期", success: false };
  56. const response = Response.json(payload);
  57. const onZcodeJwtInvalid = vi.fn();
  58. const client = createNodeApiClient({
  59. fetchImpl: async () => response,
  60. isZcodeJwtRequest: () => true,
  61. isBusinessUnauthorizedRequest: () => true,
  62. onZcodeJwtInvalid,
  63. });
  64. const result = await client.request("https://example.com/userinfo");
  65. expect(onZcodeJwtInvalid).toHaveBeenCalledOnce();
  66. expect(result).toBe(response);
  67. expect(result.status).toBe(200);
  68. expect(result.bodyUsed).toBe(false);
  69. expect(await result.json()).toEqual(payload);
  70. });
  71. it.each([
  72. "",
  73. "{",
  74. "<html>login expired</html>",
  75. "null",
  76. "[]",
  77. '{"code":"401","success":false}',
  78. '{"code":403,"success":false}',
  79. '{"code":500,"msg":"登录状态已过期"}',
  80. '{"code":200,"success":true}',
  81. ])("HTTP 200 非明确业务 401 不通知失效,保留原正文:%s", async (body) => {
  82. const onZcodeJwtInvalid = vi.fn();
  83. const client = createNodeApiClient({
  84. fetchImpl: async () => new Response(body),
  85. isZcodeJwtRequest: () => true,
  86. onZcodeJwtInvalid,
  87. });
  88. const response = await client.request("https://example.com/userinfo");
  89. expect(onZcodeJwtInvalid).not.toHaveBeenCalled();
  90. expect(await response.text()).toBe(body);
  91. });
  92. it("不匹配当前凭据的 HTTP 200 不读取响应副本", async () => {
  93. const response = Response.json({ code: 401 });
  94. const clone = vi.spyOn(response, "clone");
  95. const onZcodeJwtInvalid = vi.fn();
  96. const client = createNodeApiClient({
  97. fetchImpl: async () => response,
  98. isZcodeJwtRequest: () => false,
  99. onZcodeJwtInvalid,
  100. });
  101. expect(await client.request("https://example.com/model")).toBe(response);
  102. expect(clone).not.toHaveBeenCalled();
  103. expect(onZcodeJwtInvalid).not.toHaveBeenCalled();
  104. });
  105. it("当前 JWT 的 SSE 不读取正文,不等待 continuous 流结束", async () => {
  106. const response = new Response(new ReadableStream(), {
  107. headers: { "Content-Type": "text/event-stream; charset=utf-8" },
  108. });
  109. const clone = vi.spyOn(response, "clone");
  110. const onZcodeJwtInvalid = vi.fn();
  111. const client = createNodeApiClient({
  112. fetchImpl: async () => response,
  113. isZcodeJwtRequest: () => true,
  114. onZcodeJwtInvalid,
  115. });
  116. expect(await client.request("https://example.com/stream")).toBe(response);
  117. expect(clone).not.toHaveBeenCalled();
  118. expect(onZcodeJwtInvalid).not.toHaveBeenCalled();
  119. await response.body?.cancel();
  120. });
  121. it("业务 401 观察达到时间预算后放行原响应", async () => {
  122. const response = new Response(new ReadableStream(), {
  123. headers: { "Content-Type": "application/json" },
  124. });
  125. const onZcodeJwtInvalid = vi.fn();
  126. const client = createNodeApiClient({
  127. fetchImpl: async () => response,
  128. isZcodeJwtRequest: () => true,
  129. isBusinessUnauthorizedRequest: () => true,
  130. onZcodeJwtInvalid,
  131. businessUnauthorizedObservationTimeoutMs: 10,
  132. });
  133. const request = client.request("https://bigmodel.cn/api/biz/customer/getCustomerInfo", {
  134. headers: { Authorization: "Bearer jwt" },
  135. });
  136. await expect(request).resolves.toBe(response);
  137. expect(onZcodeJwtInvalid).not.toHaveBeenCalled();
  138. await response.body?.cancel();
  139. });
  140. it("普通当前 JWT 请求不会读取 HTTP 200 响应副本", async () => {
  141. const response = Response.json({ code: 401 });
  142. const clone = vi.spyOn(response, "clone");
  143. const onZcodeJwtInvalid = vi.fn();
  144. const client = createNodeApiClient({
  145. fetchImpl: async () => response,
  146. isZcodeJwtRequest: () => true,
  147. onZcodeJwtInvalid,
  148. });
  149. await expect(client.request("https://example.com/model")).resolves.toBe(response);
  150. expect(clone).not.toHaveBeenCalled();
  151. expect(onZcodeJwtInvalid).not.toHaveBeenCalled();
  152. });
  153. it("业务 401 观察超过正文预算后放行原响应", async () => {
  154. const body = "x".repeat(64 * 1024 + 1);
  155. const response = new Response(body, { headers: { "Content-Type": "application/json" } });
  156. const onZcodeJwtInvalid = vi.fn();
  157. const client = createNodeApiClient({
  158. fetchImpl: async () => response,
  159. isZcodeJwtRequest: () => true,
  160. isBusinessUnauthorizedRequest: () => true,
  161. onZcodeJwtInvalid,
  162. });
  163. await expect(
  164. client.request("https://bigmodel.cn/api/biz/customer/getCustomerInfo"),
  165. ).resolves.toBe(response);
  166. expect(onZcodeJwtInvalid).not.toHaveBeenCalled();
  167. expect((await response.text()).length).toBe(body.length);
  168. });
  169. it("会把 timeoutMs 转成统一的 ApiError", async () => {
  170. vi.useFakeTimers();
  171. const fetchImpl = vi.fn((input: RequestInfo | URL, init?: RequestInit) => {
  172. return new Promise<Response>((_resolve, reject) => {
  173. const signal = init?.signal;
  174. signal?.addEventListener(
  175. "abort",
  176. () => {
  177. reject(new DOMException("The operation was aborted.", "AbortError"));
  178. },
  179. { once: true },
  180. );
  181. });
  182. });
  183. const client = createNodeApiClient({ fetchImpl });
  184. const requestPromise = client.request("https://example.com/oauth/token", {
  185. method: "POST",
  186. timeoutMs: 10,
  187. });
  188. const expectation = expect(requestPromise).rejects.toEqual(
  189. expect.objectContaining<ApiError>({
  190. name: "ApiError",
  191. method: "POST",
  192. status: undefined,
  193. url: "https://example.com/oauth/token",
  194. }),
  195. );
  196. await vi.advanceTimersByTimeAsync(10);
  197. await expectation;
  198. });
  199. it("外部主动 abort 时不会误报成 timeout", async () => {
  200. const fetchImpl = vi.fn((input: RequestInfo | URL, init?: RequestInit) => {
  201. return new Promise<Response>((_resolve, reject) => {
  202. init?.signal?.addEventListener(
  203. "abort",
  204. () => {
  205. reject(new DOMException("The operation was aborted.", "AbortError"));
  206. },
  207. { once: true },
  208. );
  209. });
  210. });
  211. const client = createNodeApiClient({ fetchImpl });
  212. const controller = new AbortController();
  213. const requestPromise = client.request("https://example.com/oauth/token", {
  214. method: "POST",
  215. timeoutMs: 100,
  216. signal: controller.signal,
  217. });
  218. controller.abort();
  219. await expect(requestPromise).rejects.toMatchObject<ApiError>({
  220. name: "ApiError",
  221. method: "POST",
  222. status: undefined,
  223. url: "https://example.com/oauth/token",
  224. message: "The operation was aborted.",
  225. });
  226. });
  227. });