zcode-builtin-download.ts 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  1. import { z } from "zod";
  2. import {
  3. resolveClientConfigRefreshIntervalMs,
  4. resolveOptionalZCodeAuthorization,
  5. type ZCodeJwtTokenResolver,
  6. } from "@zcode/shared";
  7. import { decodeZCodeBuiltinRelease, type ZCodeBuiltinRelease } from "./zcode-builtin-release.js";
  8. const clientConfigSchema = z
  9. .object({
  10. code: z.literal(0),
  11. data: z
  12. .object({
  13. configs: z
  14. .object({
  15. builtin_provider_config_json: z
  16. .string()
  17. .url()
  18. .refine((value) => {
  19. const url = new URL(value);
  20. // 内网和测试部署也会提供 HTTP 配置地址;协议准入不按产品环境区分。
  21. return (
  22. (url.protocol === "https:" || url.protocol === "http:") &&
  23. !url.username &&
  24. !url.password
  25. );
  26. })
  27. .optional(),
  28. })
  29. .passthrough(),
  30. })
  31. .passthrough(),
  32. })
  33. .passthrough();
  34. export interface ZCodeBuiltinDownloadOptions {
  35. readonly endpointOrigin: string;
  36. readonly appVersion: string;
  37. readonly platform: string;
  38. readonly request: (url: string | URL, init: RequestInit) => Promise<Response>;
  39. readonly signal?: AbortSignal;
  40. readonly resolveZcodeJwtToken?: ZCodeJwtTokenResolver;
  41. /** 第一跳下发的地址与它相同时不请求 CDN;何时需要兜底重下由调用方决定。 */
  42. readonly reuseUrl?: string;
  43. }
  44. /** 每种结果都带第一跳下发的刷新间隔,供同步器排下一轮。 */
  45. export type ZCodeBuiltinDownloadResult =
  46. | {
  47. readonly kind: "release";
  48. readonly release: ZCodeBuiltinRelease;
  49. readonly url: string;
  50. readonly refreshIntervalMs: number;
  51. }
  52. | { readonly kind: "not-modified"; readonly url: string; readonly refreshIntervalMs: number }
  53. | { readonly kind: "missing"; readonly refreshIntervalMs: number };
  54. /** App/CLI 共用下载边界。总预算包含两次请求正文,不依赖 ApiClient 的响应头超时。 */
  55. export async function downloadZCodeBuiltinRelease(
  56. options: ZCodeBuiltinDownloadOptions,
  57. ): Promise<ZCodeBuiltinDownloadResult> {
  58. const controller = new AbortController();
  59. let timedOut = false;
  60. const timer = setTimeout(() => {
  61. timedOut = true;
  62. controller.abort();
  63. }, 20_000);
  64. timer.unref?.();
  65. const signal = options.signal
  66. ? AbortSignal.any([controller.signal, options.signal])
  67. : controller.signal;
  68. let stage = "client-config";
  69. try {
  70. const url = new URL("/api/v1/client/configs", options.endpointOrigin);
  71. url.searchParams.set("app_version", options.appVersion);
  72. url.searchParams.set("platform", options.platform);
  73. const authorization = await resolveOptionalZCodeAuthorization(options.resolveZcodeJwtToken);
  74. const payload = clientConfigSchema.parse(await readJson(url, authorization));
  75. // 间隔与地址各自校验:间隔写错只回落默认值,不能让整次 Built-in 刷新失败。
  76. const refreshIntervalMs = resolveClientConfigRefreshIntervalMs(payload.data.configs);
  77. const downloadUrl = payload.data.configs.builtin_provider_config_json;
  78. if (downloadUrl === undefined) return { kind: "missing", refreshIntervalMs };
  79. if (downloadUrl === options.reuseUrl) {
  80. return { kind: "not-modified", url: downloadUrl, refreshIntervalMs };
  81. }
  82. stage = "cdn";
  83. const release = decodeZCodeBuiltinRelease(await readJson(new URL(downloadUrl)));
  84. return { kind: "release", release, url: downloadUrl, refreshIntervalMs };
  85. } catch (error) {
  86. // 不能把带 query 的 URL、响应正文或 Schema 输入(可能含凭据)交给上层日志。
  87. const reason = signal.aborted
  88. ? timedOut
  89. ? "timeout"
  90. : "cancelled"
  91. : error instanceof DownloadBoundaryError
  92. ? error.message
  93. : error instanceof z.ZodError
  94. ? `invalid schema at ${error.issues[0]?.path.join(".") || "root"} (${error.issues[0]?.code})`
  95. : "invalid response";
  96. throw new Error(`ZCode Built-in ${stage}: ${reason}`);
  97. } finally {
  98. clearTimeout(timer);
  99. }
  100. async function readJson(url: URL, authorization?: string | null): Promise<unknown> {
  101. signal.throwIfAborted();
  102. // 只有第一跳配置请求接收可选登录头;CDN 调用不传入,避免向资源源站泄露 JWT。
  103. const response = await abortable(
  104. options
  105. .request(url, {
  106. method: "GET",
  107. signal,
  108. credentials: "omit",
  109. redirect: "error",
  110. ...(authorization ? { headers: { Authorization: authorization } } : {}),
  111. })
  112. .then((value) => {
  113. if (signal.aborted) {
  114. void value.body?.cancel().catch(() => {});
  115. signal.throwIfAborted();
  116. }
  117. return value;
  118. }),
  119. signal,
  120. );
  121. if (!response.ok) {
  122. void response.body?.cancel().catch(() => {});
  123. throw new DownloadBoundaryError(`HTTP ${response.status}`);
  124. }
  125. const reader = response.body?.getReader();
  126. if (!reader) throw new DownloadBoundaryError("empty body");
  127. const decoder = new TextDecoder();
  128. const chunks: string[] = [];
  129. let bytes = 0;
  130. try {
  131. for (;;) {
  132. const part = await abortable(reader.read(), signal);
  133. if (part.done) break;
  134. bytes += part.value.byteLength;
  135. if (bytes > 10_000_000) throw new DownloadBoundaryError("body limit exceeded");
  136. chunks.push(decoder.decode(part.value, { stream: true }));
  137. }
  138. chunks.push(decoder.decode());
  139. signal.throwIfAborted();
  140. return JSON.parse(chunks.join("")) as unknown;
  141. } catch (error) {
  142. // cancel 不得成为新的无期限等待;释放 reader 后底层请求仍由同一 signal 取消。
  143. void reader.cancel().catch(() => {});
  144. throw error;
  145. } finally {
  146. reader.releaseLock();
  147. }
  148. }
  149. }
  150. class DownloadBoundaryError extends Error {}
  151. function abortable<T>(pending: Promise<T>, signal: AbortSignal): Promise<T> {
  152. return new Promise<T>((resolve, reject) => {
  153. const abort = () => reject(signal.reason);
  154. signal.addEventListener("abort", abort, { once: true });
  155. if (signal.aborted) abort();
  156. void pending.then(resolve, reject).finally(() => signal.removeEventListener("abort", abort));
  157. });
  158. }