Lock file on save and read (#824)

Fix #794
This commit is contained in:
allburov
2024-06-01 14:32:19 +07:00
committed by GitHub
parent fda4186306
commit 9065ab690f
3 changed files with 32 additions and 6 deletions

View File

@@ -1,3 +1,4 @@
import AsyncLock from 'async-lock'
import { mkdir, readFile, stat, unlink, writeFile } from 'fs/promises'
import { join } from 'path'
import { proto } from '../../WAProto'
@@ -5,6 +6,13 @@ import { AuthenticationCreds, AuthenticationState, SignalDataTypeMap } from '../
import { initAuthCreds } from './auth-utils'
import { BufferJSON } from './generics'
// We need to lock files due to the fact that we are using async functions to read and write files
// https://github.com/WhiskeySockets/Baileys/issues/794
// https://github.com/nodejs/node/issues/26338
// Default pending is 1000, set it to infinity
// https://github.com/rogierschouten/async-lock/issues/63
const fileLock = new AsyncLock({ maxPending: Infinity })
/**
* stores the full authentication state in a single folder.
* Far more efficient than singlefileauthstate
@@ -15,12 +23,20 @@ import { BufferJSON } from './generics'
export const useMultiFileAuthState = async(folder: string): Promise<{ state: AuthenticationState, saveCreds: () => Promise<void> }> => {
const writeData = (data: any, file: string) => {
return writeFile(join(folder, fixFileName(file)!), JSON.stringify(data, BufferJSON.replacer))
const filePath = join(folder, fixFileName(file)!)
return fileLock.acquire(
filePath,
() => writeFile(join(filePath), JSON.stringify(data, BufferJSON.replacer))
)
}
const readData = async(file: string) => {
try {
const data = await readFile(join(folder, fixFileName(file)!), { encoding: 'utf-8' })
const filePath = join(folder, fixFileName(file)!)
const data = await fileLock.acquire(
filePath,
() => readFile(filePath, { encoding: 'utf-8' })
)
return JSON.parse(data, BufferJSON.reviver)
} catch(error) {
return null
@@ -29,7 +45,11 @@ export const useMultiFileAuthState = async(folder: string): Promise<{ state: Aut
const removeData = async(file: string) => {
try {
await unlink(join(folder, fixFileName(file)!))
const filePath = join(folder, fixFileName(file)!)
await fileLock.acquire(
filePath,
() => unlink(filePath)
)
} catch{
}
@@ -87,4 +107,4 @@ export const useMultiFileAuthState = async(folder: string): Promise<{ state: Aut
return writeData(creds, 'creds.json')
}
}
}
}