credential-fault.ts 1.0 KB

12345678910111213141516171819202122232425262728
  1. import { readFile } from "node:fs/promises";
  2. import { atomicWritePrivateTextFile, withFileLock } from "@zcode/shared/node";
  3. /** 故障期间连接流程也会保存凭据;不能用测试开始前的整文件快照覆盖这些新值。 */
  4. export async function withCredentialFault<T>(
  5. file: string,
  6. key: string,
  7. invalidValue: string,
  8. operation: () => Promise<T>,
  9. ): Promise<T> {
  10. const previous = await withFileLock(file, async () => {
  11. const current: Record<string, string> = JSON.parse(await readFile(file, "utf8"));
  12. const previous = current[key];
  13. current[key] = invalidValue;
  14. await atomicWritePrivateTextFile(file, JSON.stringify(current));
  15. return previous;
  16. });
  17. try {
  18. return await operation();
  19. } finally {
  20. await withFileLock(file, async () => {
  21. const current: Record<string, string> = JSON.parse(await readFile(file, "utf8"));
  22. if (previous === undefined) delete current[key];
  23. else current[key] = previous;
  24. await atomicWritePrivateTextFile(file, JSON.stringify(current));
  25. });
  26. }
  27. }