t
This commit is contained in:
parent
4c4e767ec6
commit
9d70afb4cc
42 changed files with 1266 additions and 630 deletions
|
|
@ -2,6 +2,7 @@
|
|||
|
||||
function createJsonRepository({fsp,crypto,processId=process.pid}={}){
|
||||
if(!fsp?.readFile||!fsp?.writeFile||!fsp?.rename||!crypto?.randomBytes)throw new TypeError('Filesystem and crypto adapters are required');
|
||||
const retryableRenameCodes=new Set(['EACCES','EBUSY','EPERM']),renameRetryDelays=[20,50,100,200,400,800],sleep=milliseconds=>new Promise(resolve=>setTimeout(resolve,milliseconds));
|
||||
const read=async(file,{missing=null}={})=>{
|
||||
try{return JSON.parse(await fsp.readFile(file,'utf8'))}
|
||||
catch(error){if(error.code==='ENOENT'&&missing!==undefined)return typeof missing==='function'?missing():missing;throw error}
|
||||
|
|
@ -9,7 +10,7 @@ function createJsonRepository({fsp,crypto,processId=process.pid}={}){
|
|||
const write=async(file,value)=>{
|
||||
const temporary=`${file}.${processId}.${crypto.randomBytes(6).toString('hex')}.tmp`;
|
||||
await fsp.writeFile(temporary,JSON.stringify(value),{encoding:'utf8',mode:0o600});
|
||||
await fsp.rename(temporary,file);
|
||||
for(let attempt=0;;attempt++)try{await fsp.rename(temporary,file);break}catch(error){if(!retryableRenameCodes.has(error?.code)||attempt>=renameRetryDelays.length){await fsp.unlink?.(temporary).catch(()=>{});throw error}await sleep(renameRetryDelays[attempt])}
|
||||
};
|
||||
const remove=async file=>fsp.unlink(file).catch(error=>{if(error.code!=='ENOENT')throw error});
|
||||
return Object.freeze({read,write,remove});
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue