model-context-budget-config-mock-server.ts 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146
  1. import { once } from "node:events";
  2. import { readFile } from "node:fs/promises";
  3. import { createServer, type ServerResponse } from "node:http";
  4. const LEGACY_SPEC_FRAGMENT = "conversation-session-model-output-token-budget";
  5. const PREFLIGHT_SPEC_FRAGMENT = "conversation-session-model-output-token-preflight";
  6. export type ModelContextBudgetConfigMockScenario =
  7. | "config-pending"
  8. | "legacy"
  9. | "preflight-default";
  10. export interface ModelContextBudgetConfigMockServer {
  11. baseUrl: string;
  12. scenario: ModelContextBudgetConfigMockScenario;
  13. stop(): Promise<void>;
  14. }
  15. export function resolveModelContextBudgetConfigMockScenario(
  16. specs: readonly string[],
  17. ): ModelContextBudgetConfigMockScenario | null {
  18. if (specs.some((spec) => spec.includes("conversation-session-config-independent-startup"))) {
  19. return "config-pending";
  20. }
  21. if (specs.some((spec) => spec.includes(PREFLIGHT_SPEC_FRAGMENT))) {
  22. return "preflight-default";
  23. }
  24. if (specs.some((spec) => spec.includes(LEGACY_SPEC_FRAGMENT))) {
  25. return "legacy";
  26. }
  27. return null;
  28. }
  29. export async function startModelContextBudgetConfigMockServer(
  30. scenario: ModelContextBudgetConfigMockScenario,
  31. ): Promise<ModelContextBudgetConfigMockServer> {
  32. // 修复原因:client/configs 是多个启动功能共享的配置源,不能为了 strategy 返回空 configs,
  33. // 否则套餐静态目录等无关消费者会在正式 E2E 中进入错误降级。
  34. const clientConfigFixtureUrl = new URL(
  35. "../fixtures/coding-plan-client-configs.json",
  36. import.meta.url,
  37. );
  38. const clientConfigPayload = JSON.parse(
  39. await readFile(clientConfigFixtureUrl, "utf8"),
  40. ) as ModelContextBudgetClientConfigFixture;
  41. if (scenario === "legacy") {
  42. clientConfigPayload.data.configs.modelContextBudget = {
  43. strategy: "legacy",
  44. };
  45. } else {
  46. // 默认策略 formal spec 必须省略字段,避免显式值掩盖缺省解析回归。
  47. delete clientConfigPayload.data.configs.modelContextBudget;
  48. }
  49. let configRequests = 0;
  50. let configResponses = 0;
  51. const heldResponses = new Set<ServerResponse>();
  52. const server = createServer((request, response) => {
  53. const url = new URL(request.url ?? "/", "http://127.0.0.1");
  54. if (request.method === "GET" && url.pathname === "/__scb/status") {
  55. sendJson(response, {
  56. blocked: scenario === "config-pending",
  57. configRequests,
  58. configResponses,
  59. });
  60. return;
  61. }
  62. if (request.method === "GET" && url.pathname === "/api/v1/client/configs") {
  63. configRequests += 1;
  64. if (scenario === "config-pending") {
  65. // 测试屏障保持请求 pending,不能用立即抛出“timeout”替代真实等待。
  66. heldResponses.add(response);
  67. response.on("close", () => heldResponses.delete(response));
  68. return;
  69. }
  70. configResponses += 1;
  71. sendJson(response, clientConfigPayload);
  72. return;
  73. }
  74. if (request.method === "GET" && url.pathname === "/api/v1/zcode-plan/billing/balance") {
  75. // 预算 E2E 不验证套餐;返回合法的“无套餐”快照,避免共享 endpoint 产生无关 404。
  76. sendJson(response, {
  77. code: 0,
  78. data: { balances: [], plans: [] },
  79. msg: "",
  80. success: true,
  81. });
  82. return;
  83. }
  84. if (request.method === "GET" && url.pathname === "/api/v2/releases/latest") {
  85. // provider preset 同步与 client/configs 共享 endpoint;返回固定 config_version,
  86. // 让它继续复用上面的完整本地 fixture,不能因 strategy mock 等待远端超时。
  87. sendJson(response, {
  88. config_version: "0.0.13",
  89. version: "0.25.1",
  90. });
  91. return;
  92. }
  93. sendJson(
  94. response,
  95. {
  96. code: 404,
  97. data: null,
  98. msg: `Unhandled model context budget E2E path: ${request.method} ${url.pathname}`,
  99. },
  100. 404,
  101. );
  102. });
  103. server.listen(0, "127.0.0.1");
  104. await once(server, "listening");
  105. const address = server.address();
  106. if (!address || typeof address === "string") {
  107. throw new Error("Model context budget E2E mock server did not bind to a TCP port");
  108. }
  109. return {
  110. baseUrl: `http://127.0.0.1:${address.port}`,
  111. scenario,
  112. stop: async () => {
  113. for (const response of heldResponses) response.destroy();
  114. server.close();
  115. server.closeAllConnections();
  116. await once(server, "close");
  117. },
  118. };
  119. }
  120. interface ModelContextBudgetClientConfigFixture {
  121. data: {
  122. configs: Record<string, unknown> & {
  123. modelContextBudget?: {
  124. strategy: "legacy" | "preflight-v1";
  125. };
  126. };
  127. };
  128. }
  129. function sendJson(response: ServerResponse, payload: unknown, statusCode = 200): void {
  130. response.writeHead(statusCode, {
  131. "content-type": "application/json; charset=utf-8",
  132. });
  133. response.end(JSON.stringify(payload));
  134. }