sequence.ts 1.98 KB
Newer Older
1
import fs from 'fs';
2
import {FS_ERROR} from '../interfaces/index';
3
4


5
6
7
8
9
10
11
const LOCK_FILE_PATH=process.env.LOCK_FILE_PATH || "/tmp/audit/sequence"
const SEQUENCE_FILE = process.env.SEQUENCE_FILE || "/tmp/audit/sequence"
const TIMEOUT_LOCK_FILE = 10000;

const delay = (ms:number) => new Promise(resolve => setTimeout(resolve, ms))

const lockFile = async (path:string,timeout:number=0):Promise<number> => { 
Panagiotis Skarvelis's avatar
Panagiotis Skarvelis committed
12
13
    //if the file exists for long time have to delete it
    // because probably something is broken on some node..
Panagiotis Skarvelis's avatar
Panagiotis Skarvelis committed
14
    // this works but may be not the best solution
15
    if (timeout++>TIMEOUT_LOCK_FILE) {console.log(timeout," times loop, try to unlock");await delay(1000);unlockFile(path)};
16
    const lockPath = `${path}.lock`
17
18
19
20
21
22
    try {
       return fs.openSync(lockPath, fs.constants.O_CREAT | fs.constants.O_EXCL | fs.constants.O_RDWR)
    } catch (error) {
        if ((error as FS_ERROR).code!=="EEXIST") console.log((error as FS_ERROR).message);
        return lockFile(path,timeout)
    }
23
}
24
const unlockFile =  async (path:string,timeout:number=0):Promise<void> => {
25
    const lockPath = `${path}.lock`
26
27
28
29
30
31
32
33
34
35
36
37
38
39
    if (timeout++>TIMEOUT_LOCK_FILE) {console.log(timeout," times loop, unlock exit"); return};
    try { 
      return fs.unlinkSync(lockPath)
    }
    catch(error) {
    if ((error as FS_ERROR).code==="ENOENT") {
        return;
    } else {
        console.log((error as FS_ERROR).message);
        await delay(500);
        return unlockFile(path,timeout++);
    }
    
   } 
40
41
42
43
44
45
46
}

/**
 * 
 * @param seqfile 
 * @returns number
 */
Panagiotis Skarvelis's avatar
Panagiotis Skarvelis committed
47
const sequence = async (seqfile:string="",lockfile:string="") =>{
48
49

let SEQF = SEQUENCE_FILE;
Panagiotis Skarvelis's avatar
Panagiotis Skarvelis committed
50
let LFP = LOCK_FILE_PATH;
51
if (seqfile!=="") SEQF = seqfile;
Panagiotis Skarvelis's avatar
Panagiotis Skarvelis committed
52
53
if (lockfile!=="") LFP = lockfile;

54
55
56
57
58

if (!fs.existsSync(SEQF)) {
    fs.writeFileSync(SEQF, "0")
}

59
const abla = lockFile(LFP);
60
61
let seq:number = ~~fs.readFileSync(SEQF); //Read as integer ~~ is synonimus for parseInt
fs.writeFileSync(SEQF, "" + ++seq);
62
const oubla = unlockFile(LFP);
63
64
65
66
return seq;
}

export default sequence;