zcode-builtin-provider-config-materializer.ts 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. import { readFile } from "node:fs/promises";
  2. import { join } from "node:path";
  3. import { atomicWritePrivateTextFile, withFileLock } from "@zcode/shared/node";
  4. import {
  5. decodeZCodeBuiltinRelease,
  6. serializeZCodeBuiltinRelease,
  7. } from "./zcode-builtin-release.js";
  8. export interface MaterializeZCodeBuiltinProviderConfigOptions {
  9. readonly environmentConfigRoot: string;
  10. readonly content: string;
  11. }
  12. /**
  13. * 在环境目录释放唯一随包基线;升级以退出旧进程为前提,不保留历史 hash 副本。
  14. * 与下载配置分离,并复用统一锁及原子写入,避免并发启动读到半份 JSON。
  15. */
  16. export async function materializeZCodeBuiltinProviderConfig(
  17. options: MaterializeZCodeBuiltinProviderConfigOptions,
  18. ): Promise<string> {
  19. const content = `${serializeZCodeBuiltinRelease(
  20. decodeZCodeBuiltinRelease(JSON.parse(options.content)),
  21. )}\n`;
  22. const filePath = join(
  23. options.environmentConfigRoot,
  24. "runtime",
  25. "provider",
  26. "bundled",
  27. "zcode-builtin.json",
  28. );
  29. await withFileLock(filePath, async () => {
  30. if ((await readOptionalFile(filePath)) !== content) {
  31. await atomicWritePrivateTextFile(filePath, content);
  32. }
  33. });
  34. return filePath;
  35. }
  36. async function readOptionalFile(filePath: string): Promise<string | null> {
  37. try {
  38. return await readFile(filePath, "utf8");
  39. } catch (error) {
  40. if (isNodeError(error) && error.code === "ENOENT") return null;
  41. throw error;
  42. }
  43. }
  44. function isNodeError(error: unknown): error is NodeJS.ErrnoException {
  45. return error instanceof Error && "code" in error;
  46. }