source-server-release-faults.ts 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. import { randomUUID } from "node:crypto";
  2. import { rename, rm, writeFile } from "node:fs/promises";
  3. import type { SourceServerReleaseArchive, SourceServerReleaseDescriptor } from "@zcode/shared";
  4. import { normalizeRemoteArch, normalizeRemotePlatform } from "@zcode/server/remote/detectEnv.js";
  5. export function selectSourceServerReleaseArchive(
  6. descriptor: SourceServerReleaseDescriptor,
  7. environment: { platform: string; arch: string },
  8. ): SourceServerReleaseArchive {
  9. // 根因:旧用例固定破坏 x64 包,ARM64 目标仍正常安装,随后被误判为吞错。
  10. // 使用每台远端自己的架构和 descriptor 文件名,不能从 Desktop 架构或另一台目标推断。
  11. const target = `${normalizeRemotePlatform(environment.platform)}-${normalizeRemoteArch(environment.arch)}`;
  12. const matches = descriptor.archives.filter((archive) => archive.target === target);
  13. if (matches.length !== 1) {
  14. throw new Error(
  15. `Expected exactly one Source Server archive for ${target}, received ${matches.length}`,
  16. );
  17. }
  18. return matches[0]!;
  19. }
  20. export async function withSourceServerReleaseFileFault<T>(
  21. path: string,
  22. replacement: string | Uint8Array | null,
  23. run: () => Promise<T>,
  24. ): Promise<T> {
  25. const backup = `${path}.${randomUUID()}.fault-backup`;
  26. // 根因:断言抛错曾跳过文件恢复;直接覆写 staged 硬链接还会污染源包。
  27. // 保留原 inode,新建故障文件,并在所有退出路径恢复原文件。
  28. await rename(path, backup);
  29. try {
  30. if (replacement !== null) await writeFile(path, replacement);
  31. return await run();
  32. } finally {
  33. await rm(path, { force: true });
  34. await rename(backup, path);
  35. }
  36. }