Bugfix: fix race conditions
This commit is contained in:
+8
-35
@@ -1,19 +1,17 @@
|
||||
import fs from "fs";
|
||||
import delay from "../../utils/delay";
|
||||
import { SyncFoldersFnParams } from "../../types";
|
||||
import sync from "../../utils/sync";
|
||||
import SyncScheduler from "../../utils/sync-scheduler";
|
||||
|
||||
export default async function watchFolders({
|
||||
folders,
|
||||
options,
|
||||
}: SyncFoldersFnParams) {
|
||||
let timeout: any;
|
||||
const UPDATE_TIMEOUT = 1000;
|
||||
|
||||
try {
|
||||
const dirs = folders;
|
||||
|
||||
console.log("global.SYNCING", global.SYNCING);
|
||||
console.log(`Now handling ${dirs.length} Directories`);
|
||||
|
||||
/**
|
||||
@@ -21,6 +19,11 @@ export default async function watchFolders({
|
||||
*/
|
||||
const INTERVAL = options?.interval ? options.interval : UPDATE_TIMEOUT;
|
||||
|
||||
const scheduler = new SyncScheduler(
|
||||
(dirPath, firstRun) => sync({ dirPath, dirs, options, firstRun }),
|
||||
INTERVAL
|
||||
);
|
||||
|
||||
for (let i = 0; i < dirs.length; i++) {
|
||||
const dir = dirs[i];
|
||||
|
||||
@@ -31,8 +34,6 @@ export default async function watchFolders({
|
||||
|
||||
const dirPath = typeof dir == "string" ? dir : dir.path;
|
||||
|
||||
console.log("global.SYNCING", global.SYNCING);
|
||||
|
||||
if (
|
||||
(typeof dir == "string" && !fs.existsSync(dirPath)) ||
|
||||
(typeof dir == "object" &&
|
||||
@@ -70,27 +71,10 @@ export default async function watchFolders({
|
||||
}
|
||||
|
||||
if (typeof dir == "string") {
|
||||
await delay();
|
||||
|
||||
fs.watch(dirPath, { recursive: true }, (evt, fileName) => {
|
||||
console.log("Folder Changed", evt, fileName);
|
||||
|
||||
if (global.SYNCING) {
|
||||
console.log("Existing Sync found. Returning ...");
|
||||
return;
|
||||
}
|
||||
|
||||
clearTimeout(timeout);
|
||||
|
||||
timeout = setTimeout(() => {
|
||||
console.log("Folder Syncing in progress ...");
|
||||
|
||||
global.SYNCING = true;
|
||||
|
||||
sync({ dirPath, dirs, options }).finally(() => {
|
||||
process.exit(global.SYNC_SUCCESS_EXIT_CODE);
|
||||
});
|
||||
}, INTERVAL);
|
||||
scheduler.schedule(dirPath);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -104,18 +88,7 @@ export default async function watchFolders({
|
||||
? lastUpdatedDir
|
||||
: lastUpdatedDir.path;
|
||||
|
||||
global.SYNCING = true;
|
||||
|
||||
await sync({
|
||||
dirPath: lastUpdatedDirPath,
|
||||
dirs,
|
||||
options,
|
||||
firstRun: true,
|
||||
});
|
||||
|
||||
setTimeout(() => {
|
||||
global.SYNCING = false;
|
||||
}, UPDATE_TIMEOUT);
|
||||
scheduler.enqueue(lastUpdatedDirPath, true);
|
||||
} catch (error: any) {
|
||||
console.log("ERROR:", error.message);
|
||||
process.exit(0);
|
||||
|
||||
Reference in New Issue
Block a user