File size: 3,662 Bytes
0110783
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
'use strict';
/**

 * file-lock.js — concurrency-safe file locking primitive (Nomad scripts/ port).

 *

 * Ported from a production concurrency module, deployed at `91-team-tools/concurrency/lib/file-lock.js`,

 * desensitized: no hardcoded paths, no reference to any specific deployment's

 * history. Same algorithm, same defaults — atomic lock-file creation to queue

 * concurrent writers, stale-lock self-healing, atomic replace-via-rename.

 *

 * Used by append-log.js (safe team-log append) and available to any script in

 * this package that needs "many writers, one file, no corruption" guarantees.

 */
const fs = require('fs');
const crypto = require('crypto');

class LockError extends Error {
  constructor(message, code) {
    super(message);
    this.name = 'LockError';
    this.code = code || 'LOCK_ERROR';
  }
}

/** Synchronous sleep without busy-waiting (Atomics.wait blocks the current thread cheaply). */
function sleepSync(ms) {
  Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
}

/**

 * Atomically create a lock file to queue writers. If a lock already exists,

 * check its mtime — older than staleMs is treated as a crashed holder's

 * leftover and force-cleared (self-healing, no permanent deadlock).

 * @param {string} lockPath usually `<targetFile>.lock`

 * @param {{staleMs?:number, retryMax?:number, retryIntervalMs?:number, onWait?:Function, onStaleClear?:Function}} [opts]

 * @throws {LockError} if the lock cannot be acquired within retryMax attempts

 */
function acquireLockSync(lockPath, opts) {
  opts = opts || {};
  const staleMs = opts.staleMs != null ? opts.staleMs : 30 * 1000;
  const retryMax = opts.retryMax != null ? opts.retryMax : 30;
  const retryIntervalMs = opts.retryIntervalMs != null ? opts.retryIntervalMs : 1000;

  for (let i = 0; i < retryMax; i++) {
    try {
      fs.writeFileSync(lockPath, process.pid + ' ' + new Date().toISOString(), { flag: 'wx' });
      return; // lock acquired
    } catch (e) {
      if (e.code !== 'EEXIST') throw new LockError('Failed to create lock file: ' + e.message, 'LOCK_CREATE_FAIL');
      try {
        const age = Date.now() - fs.statSync(lockPath).mtimeMs;
        if (age > staleMs) {
          fs.unlinkSync(lockPath); // stale leftover — clear and retry next loop
          if (opts.onStaleClear) opts.onStaleClear(age);
          continue;
        }
      } catch (e2) {
        /* lock was just released by the holder — next loop will grab it */
      }
      if (i === 0 && opts.onWait) opts.onWait();
      sleepSync(retryIntervalMs);
    }
  }
  throw new LockError(
    'Still could not acquire the lock after ' + retryMax + 's. If you are sure no one else is writing, ' +
      'manually delete ' + lockPath + ' and retry.',
    'LOCK_TIMEOUT'
  );
}

function releaseLock(lockPath) {
  try {
    fs.unlinkSync(lockPath);
  } catch (e) {
    /* already cleared or never existed */
  }
}

/** Temp file + rename atomic replace (Node's rename on Windows overwrites an existing target). UTF-8, no BOM. */
function atomicWriteSync(targetPath, content) {
  const tmp = targetPath + '.tmp_' + process.pid + '_' + Date.now();
  fs.writeFileSync(tmp, content, 'utf8');
  fs.renameSync(tmp, targetPath);
}

function sha256Hex(content) {
  return crypto.createHash('sha256').update(content, 'utf8').digest('hex');
}

function fileSha256Hex(filePath) {
  return sha256Hex(fs.readFileSync(filePath, 'utf8'));
}

module.exports = {
  LockError,
  sleepSync,
  acquireLockSync,
  releaseLock,
  atomicWriteSync,
  sha256Hex,
  fileSha256Hex,
};