official-coding-plan-gateway.test.ts 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  1. import http from "node:http";
  2. import type { AddressInfo } from "node:net";
  3. import { afterEach, describe, expect, it, vi } from "vitest";
  4. import { createStaticProviderEndpointRoutingPort } from "../src/model/official-coding-plan-gateway.js";
  5. import { createProviderEndpointRoutingFetch } from "../src/model/provider-endpoint-routing-fetch.js";
  6. const SOURCE = "https://open.bigmodel.cn/api/anthropic/v1/messages";
  7. const ORIGIN = "https://gateway.example.test";
  8. const TARGET_PATH = "/api/v1/ultra/anthropic/v1/messages";
  9. afterEach(() => vi.unstubAllGlobals());
  10. describe("static provider endpoint routing", () => {
  11. it.each([
  12. [SOURCE, TARGET_PATH],
  13. ["https://OPEN.BIGMODEL.CN:443/api/anthropic/v1/messages/", TARGET_PATH],
  14. ["https://api.z.ai/api/anthropic/v1/messages", "/api/v1/ultra-zai/anthropic/v1/messages"],
  15. ])("routes %s with query preserved and no configuration IO", async (source, target) => {
  16. const network = vi.fn(() => {
  17. throw new Error("unexpected configuration request");
  18. });
  19. vi.stubGlobal("fetch", network);
  20. const port = createStaticProviderEndpointRoutingPort(ORIGIN);
  21. await expect(port.resolve(`${source}?id=a%2Bb&empty=`)).resolves.toEqual({
  22. routed: true,
  23. url: `${ORIGIN}${target}?id=a%2Bb&empty=`,
  24. });
  25. expect(network).not.toHaveBeenCalled();
  26. });
  27. it.each([
  28. "http://open.bigmodel.cn/api/anthropic/v1/messages",
  29. "https://open.bigmodel.cn:444/api/anthropic/v1/messages",
  30. "https://open.bigmodel.cn/api/anthropic/v1/messages/count_tokens",
  31. "https://open.bigmodel.cn/api/anthropic/v1/complete",
  32. "https://sub.open.bigmodel.cn/api/anthropic/v1/messages",
  33. "https://provider.example.test/api/anthropic/v1/messages",
  34. "not a URL",
  35. ])("leaves unmatched endpoint %s unchanged", async (url) => {
  36. await expect(createStaticProviderEndpointRoutingPort(ORIGIN).resolve(url)).resolves.toEqual({
  37. routed: false,
  38. url,
  39. });
  40. });
  41. it.each(["string", "URL", "Request"])("uses the common transport with %s input", async (kind) => {
  42. const controller = new AbortController();
  43. const body = JSON.stringify({ stream: true, model: "example" });
  44. const init = {
  45. method: "POST",
  46. body,
  47. signal: controller.signal,
  48. headers: {
  49. Host: "open.bigmodel.cn",
  50. Authorization: "Bearer example",
  51. "x-api-key": "example-key",
  52. },
  53. };
  54. const response = new Response("data: first\n\ndata: second\n\n", { status: 200 });
  55. let sent: Request | undefined;
  56. const transport = createProviderEndpointRoutingFetch({
  57. routingPort: createStaticProviderEndpointRoutingPort(ORIGIN),
  58. fetch: async (input, options) => {
  59. sent = new Request(input, options);
  60. return response;
  61. },
  62. });
  63. const input =
  64. kind === "Request" ? new Request(SOURCE, init) : kind === "URL" ? new URL(SOURCE) : SOURCE;
  65. expect(await transport(input, kind === "Request" ? undefined : init)).toBe(response);
  66. expect(sent?.url).toBe(`${ORIGIN}${TARGET_PATH}`);
  67. expect(sent?.method).toBe("POST");
  68. expect(sent?.headers.get("host")).toBeNull();
  69. expect(sent?.headers.get("authorization")).toBe("Bearer example");
  70. expect(sent?.headers.get("x-api-key")).toBe("example-key");
  71. await expect(sent?.text()).resolves.toBe(body);
  72. controller.abort();
  73. expect(sent?.signal.aborted).toBe(true);
  74. await expect(response.text()).resolves.toBe("data: first\n\ndata: second\n\n");
  75. });
  76. it("sends the routed request to an actual gateway without a configuration request", async () => {
  77. const received: Array<{
  78. url: string;
  79. host: string | undefined;
  80. auth: string | undefined;
  81. body: string;
  82. }> = [];
  83. const server = http.createServer(async (request, response) => {
  84. const chunks: Buffer[] = [];
  85. for await (const chunk of request) chunks.push(Buffer.from(chunk));
  86. received.push({
  87. url: request.url!,
  88. host: request.headers.host,
  89. auth: request.headers.authorization,
  90. body: Buffer.concat(chunks).toString(),
  91. });
  92. response.writeHead(200, { "content-type": "text/event-stream" });
  93. response.end("data: complete\n\n");
  94. });
  95. await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
  96. const origin = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
  97. try {
  98. const fetch = createProviderEndpointRoutingFetch({
  99. routingPort: createStaticProviderEndpointRoutingPort(origin),
  100. fetch: globalThis.fetch,
  101. });
  102. const response = await fetch(`${SOURCE}?stream=true`, {
  103. method: "POST",
  104. body: "request-body",
  105. headers: { Host: "open.bigmodel.cn", Authorization: "Bearer example" },
  106. });
  107. expect(await response.text()).toBe("data: complete\n\n");
  108. expect(received).toEqual([
  109. {
  110. url: `${TARGET_PATH}?stream=true`,
  111. host: new URL(origin).host,
  112. auth: "Bearer example",
  113. body: "request-body",
  114. },
  115. ]);
  116. } finally {
  117. await new Promise<void>((resolve, reject) =>
  118. server.close((error) => (error ? reject(error) : resolve())),
  119. );
  120. }
  121. });
  122. });