MCPcopy Create free account
hub / github.com/Noumena-Network/code / acquireLock

Function acquireLock

src/utils/autoUpdater.ts:186–259  ·  view source on GitHub ↗

* Attempts to acquire a lock for auto-updater * @returns true if lock was acquired, false if another process holds the lock

()

Source from the content-addressed store, hash-verified

184 * @returns true if lock was acquired, false if another process holds the lock
185 */
186async function acquireLock(): Promise<boolean> {
187 const fs = getFsImplementation()
188 const lockPath = getLockFilePath()
189
190 // Check for existing lock: 1 stat() on the happy path (fresh lock or ENOENT),
191 // 2 on stale-lock recovery (re-verify staleness immediately before unlink).
192 try {
193 const stats = await fs.stat(lockPath)
194 const age = Date.now() - stats.mtimeMs
195 if (age < LOCK_TIMEOUT_MS) {
196 return false
197 }
198 // Lock is stale, remove it before taking over. Re-verify staleness
199 // immediately before unlinking to close a TOCTOU race: if two processes
200 // both observe the stale lock, A unlinks + writes a fresh lock, then B
201 // would unlink A's fresh lock and both believe they hold it. A fresh
202 // lock has a recent mtime, so re-checking staleness makes B back off.
203 try {
204 const recheck = await fs.stat(lockPath)
205 if (Date.now() - recheck.mtimeMs < LOCK_TIMEOUT_MS) {
206 return false
207 }
208 await fs.unlink(lockPath)
209 } catch (err) {
210 if (!isENOENT(err)) {
211 logError(err as Error)
212 return false
213 }
214 }
215 } catch (err) {
216 if (!isENOENT(err)) {
217 logError(err as Error)
218 return false
219 }
220 // ENOENT: no lock file, proceed to create one
221 }
222
223 // Create lock file atomically with O_EXCL (flag: 'wx'). If another process
224 // wins the race and creates it first, we get EEXIST and back off.
225 // Lazy-mkdir the config dir on ENOENT.
226 try {
227 await writeFile(lockPath, `${process.pid}`, {
228 encoding: 'utf8',
229 flag: 'wx',
230 })
231 return true
232 } catch (err) {
233 const code = getErrnoCode(err)
234 if (code === 'EEXIST') {
235 return false
236 }
237 if (code === 'ENOENT') {
238 try {
239 // fs.mkdir from getFsImplementation() is always recursive:true and
240 // swallows EEXIST internally, so a dir-creation race cannot reach the
241 // catch below — only writeFile's EEXIST (true lock contention) can.
242 await fs.mkdir(getClaudeConfigHomeDir())
243 await writeFile(lockPath, `${process.pid}`, {

Callers 1

installGlobalPackageFunction · 0.85

Calls 5

getFsImplementationFunction · 0.85
getLockFilePathFunction · 0.85
isENOENTFunction · 0.85
getErrnoCodeFunction · 0.85
logErrorFunction · 0.70

Tested by

no test coverage detected