privateFilePersistence.ts 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  1. import { createHash } from "node:crypto";
  2. import { chmod, mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
  3. import { basename, dirname, join } from "node:path";
  4. import { setTimeout as sleep } from "node:timers/promises";
  5. import { acquireFileLock } from "./atomicFileLock.js";
  6. const DEFAULT_LOCK_RETRY_DELAYS_MS = [25, 50, 100, 200, 400] as const;
  7. const DEFAULT_LOCK_OWNERLESS_GRACE_MS = 100;
  8. const DEFAULT_LOCK_MAX_WAIT_MS = 8_000;
  9. const DEFAULT_RENAME_RETRY_DELAYS_MS = [50, 100, 200, 400, 800] as const;
  10. const processFileLockTails = new Map<string, Promise<void>>();
  11. export interface SharedFileLockOptions {
  12. lockRetryDelaysMs?: readonly number[];
  13. lockOwnerlessGraceMs?: number;
  14. lockMaxWaitMs?: number;
  15. }
  16. function getErrorCode(error: unknown): string | undefined {
  17. if (typeof error !== "object" || error === null || !("code" in error)) {
  18. return undefined;
  19. }
  20. const code = (error as { code?: unknown }).code;
  21. return typeof code === "string" ? code : undefined;
  22. }
  23. function isRetryableRenameError(error: unknown): boolean {
  24. const code = getErrorCode(error);
  25. return code === "EPERM" || code === "EBUSY" || code === "EACCES";
  26. }
  27. async function renameWithRetry(
  28. tempFile: string,
  29. filePath: string,
  30. retryDelaysMs: readonly number[],
  31. ): Promise<void> {
  32. for (let attempt = 0; ; attempt += 1) {
  33. try {
  34. await rename(tempFile, filePath);
  35. return;
  36. } catch (error) {
  37. const delayMs = retryDelaysMs[attempt];
  38. if (delayMs === undefined || !isRetryableRenameError(error)) {
  39. throw error;
  40. }
  41. await sleep(delayMs);
  42. }
  43. }
  44. }
  45. export async function withFileLock<T>(
  46. filePath: string,
  47. operation: () => Promise<T>,
  48. options: SharedFileLockOptions = {},
  49. ): Promise<T> {
  50. // 同一进程几十个 caller 同时轮询目录锁会形成惊群,后排请求可能在
  51. // 很短的实际写入之后仍撞上 8 秒超时。先做进程内 FIFO,每个进程只让队首竞争 OS 锁。
  52. const previousTail = processFileLockTails.get(filePath) ?? Promise.resolve();
  53. let releaseProcessQueue!: () => void;
  54. const currentTail = new Promise<void>((resolve) => {
  55. releaseProcessQueue = resolve;
  56. });
  57. processFileLockTails.set(filePath, currentTail);
  58. await previousTail;
  59. let releaseLock: (() => Promise<void>) | undefined;
  60. try {
  61. await mkdir(dirname(filePath), { recursive: true });
  62. releaseLock = await acquireFileLock(
  63. filePath,
  64. options.lockRetryDelaysMs ?? DEFAULT_LOCK_RETRY_DELAYS_MS,
  65. options.lockOwnerlessGraceMs ?? DEFAULT_LOCK_OWNERLESS_GRACE_MS,
  66. options.lockMaxWaitMs ?? DEFAULT_LOCK_MAX_WAIT_MS,
  67. );
  68. return await operation();
  69. } finally {
  70. try {
  71. await releaseLock?.();
  72. } finally {
  73. releaseProcessQueue();
  74. if (processFileLockTails.get(filePath) === currentTail) {
  75. processFileLockTails.delete(filePath);
  76. }
  77. }
  78. }
  79. }
  80. export async function atomicWritePrivateTextFile(
  81. filePath: string,
  82. content: string,
  83. renameRetryDelaysMs: readonly number[] = DEFAULT_RENAME_RETRY_DELAYS_MS,
  84. ): Promise<void> {
  85. const directory = dirname(filePath);
  86. const tempPath = join(
  87. directory,
  88. `.${basename(filePath)}.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`,
  89. );
  90. await mkdir(directory, { recursive: true });
  91. try {
  92. await writeFile(tempPath, content, { encoding: "utf-8", mode: 0o600 });
  93. await renameWithRetry(tempPath, filePath, renameRetryDelaysMs);
  94. } catch (error) {
  95. await rm(tempPath, { force: true }).catch(() => undefined);
  96. throw error;
  97. }
  98. }
  99. export async function backupCorruptFile(filePath: string): Promise<string> {
  100. const content = await readFile(filePath);
  101. const contentId = createHash("sha256").update(content).digest("hex").slice(0, 24);
  102. const backupPath = `${filePath}.corrupt-${contentId}.bak`;
  103. try {
  104. // 同一损坏凭据会被 Desktop、CLI 和重试循环反复读取。按内容确定备份名并
  105. // 排他创建,让失败路径稳定收敛到一份证据,同时避免 copyFile 继承历史宽松权限。
  106. await writeFile(backupPath, content, { flag: "wx", mode: 0o600 });
  107. } catch (error) {
  108. if (getErrorCode(error) !== "EEXIST") throw error;
  109. }
  110. await chmod(backupPath, 0o600);
  111. return backupPath;
  112. }