Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
/dist
/examples/tmp
/node_modules
/node-win.log
/package-lock.json
/test-files
/venv
2 changes: 1 addition & 1 deletion examples/callbacks/cancel-fetch-data.callback.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { logger } from "@/logger";
import { logger } from "examples/drive";

export const cancelFetchDataCallback = (fileId: string) => {
logger.info({ event: "cancelFetchDataCallback", fileId });
Expand Down
2 changes: 1 addition & 1 deletion examples/callbacks/notify-delete.callback.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { logger } from "@/logger";
import { logger } from "examples/drive";

export const notifyDeleteCallback = (fileId: string, callback: (response: boolean) => void) => {
logger.info({ event: "notifyDeleteCallback", fileId });
Expand Down
2 changes: 1 addition & 1 deletion examples/callbacks/notify-message.callback.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { logger } from "@/logger";
import { logger } from "examples/drive";

export const notifyMessageCallback = (message: string, action: string, errorName: string, callback: (response: boolean) => void) => {
logger.info({ event: "notifyMessageCallback", message, action, errorName });
Expand Down
2 changes: 1 addition & 1 deletion examples/callbacks/notify-rename.callback.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { logger } from "@/logger";
import { logger } from "examples/drive";

export const notifyRenameCallback = (newName: string, fileId: string, callback: (response: boolean) => void) => {
logger.info({ event: "notifyRenameCallback", newName, fileId });
Expand Down
2 changes: 2 additions & 0 deletions examples/drive.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { createLogger } from "@/logger";
import VirtualDrive from "@/virtual-drive";

import settings from "./settings";

export const drive = new VirtualDrive(settings.syncRootPath, settings.defaultLogPath);
export const logger = createLogger(settings.defaultLogPath);
6 changes: 2 additions & 4 deletions examples/get-state.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
import yargs from "yargs";
import z from "zod";

import { logger } from "@/logger";

import { drive } from "./drive";
import { drive, logger } from "./drive";

const argv = yargs
.command("file", "El path del archivo para obtener el estado", {
Expand All @@ -24,5 +22,5 @@ if (data) {
const pendingStates = drive.getPlaceholderWithStatePending();
logger.info({ state, pendingStates });
} else {
console.error("Por favor especifica un archivo con --file <path>");
logger.error("Por favor especifica un archivo con --file <path>");
}
7 changes: 3 additions & 4 deletions examples/handlers/handle-add.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,15 @@
import { drive } from "examples/drive";
import { drive, logger } from "examples/drive";
import { addInfoItem } from "examples/info-items-manager";
import { v4 } from "uuid";

import { logger } from "@/logger";
import { QueueItem } from "@/queue/queueManager";
import { v4 } from "uuid";

export const handleAdd = async (task: QueueItem) => {
try {
logger.info({ fn: "handleAdd", task });
const id = task.isFolder ? v4() : addInfoItem(task.path);
drive.convertToPlaceholder(task.path, id);
} catch (error) {
logger.error(error, "handleAdd");
logger.error("handleAdd", error);
}
};
5 changes: 2 additions & 3 deletions examples/handlers/handle-change-size.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { drive } from "examples/drive";
import { drive, logger } from "examples/drive";

import { logger } from "@/logger";
import { QueueItem } from "@/queue/queueManager";

export const handleChangeSize = async (task: QueueItem) => {
Expand All @@ -11,6 +10,6 @@ export const handleChangeSize = async (task: QueueItem) => {
drive.updateFileIdentity(task.path, result, false);
drive.updateSyncStatus(task.path, task.isFolder, true);
} catch (error) {
logger.error(error, "handleChangeSize");
logger.error("handleChangeSize", error);
}
};
5 changes: 2 additions & 3 deletions examples/handlers/handle-dehydrate.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
import { drive } from "examples/drive";
import { drive, logger } from "examples/drive";

import { logger } from "@/logger";
import { QueueItem } from "@/queue/queueManager";

export const handleDehydrate = async (task: QueueItem) => {
try {
logger.info({ fn: "handleDehydrate", path: task.path });
drive.dehydrateFile(task.path);
} catch (error) {
logger.error(error, "handleDehydrate");
logger.error("handleDehydrate", error);
}
};
5 changes: 2 additions & 3 deletions examples/handlers/handle-hydrate.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
import { drive } from "examples/drive";
import { drive, logger } from "examples/drive";

import { logger } from "@/logger";
import { QueueItem } from "@/queue/queueManager";

export const handleHydrate = async (task: QueueItem) => {
try {
logger.info({ fn: "handleHydrate", path: task.path });
await drive.hydrateFile(task.path);
} catch (error) {
logger.error(error, "handleHydrate");
logger.error("handleHydrate", error);
}
};
3 changes: 1 addition & 2 deletions examples/register.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { logger } from "@/logger";
import { QueueManager } from "@/queue/queue-manager";
import VirtualDrive from "@/virtual-drive";

Expand All @@ -7,7 +6,7 @@ import { notifyDeleteCallback } from "./callbacks/notify-delete.callback";
import { fetchDataCallback } from "./callbacks/notify-fetch-data.callback";
import { notifyMessageCallback } from "./callbacks/notify-message.callback";
import { notifyRenameCallback } from "./callbacks/notify-rename.callback";
import { drive } from "./drive";
import { drive, logger } from "./drive";
import { handleAdd } from "./handlers/handle-add";
import { handleChangeSize } from "./handlers/handle-change-size";
import { handleDehydrate } from "./handlers/handle-dehydrate";
Expand Down
4 changes: 2 additions & 2 deletions index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { QueueManager } from "./src/queue/queue-manager";
import { IQueueManager, QueueItem, typeQueue, HandleAction, HandleActions } from "./src/queue/queueManager";
import { QueueItem, typeQueue, HandleAction, HandleActions } from "./src/queue/queueManager";
import VirtualDrive from "./src/virtual-drive";

export { VirtualDrive, QueueItem, typeQueue, IQueueManager, HandleAction, HandleActions, QueueManager };
export { VirtualDrive, QueueItem, typeQueue, HandleAction, HandleActions, QueueManager };
3 changes: 1 addition & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -48,10 +48,9 @@
"dependencies": {
"chokidar": "^3.6.0",
"lodash.chunk": "^4.2.0",
"pino": "^9.6.0",
"pino-pretty": "^13.0.0",
"tsconfig-paths": "^4.2.0",
"uuid": "^11.0.3",
"winston": "^3.17.0",
"yargs": "^17.7.2",
"zod": "^3.24.1"
}
Expand Down
8 changes: 0 additions & 8 deletions src/addon/addon-zod.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { z } from "zod";

import { logger } from "@/logger";
import { PinState, SyncState } from "@/types/placeholder.type";

export const addonZod = {
Expand All @@ -21,10 +20,3 @@ export const addonZod = {
updateSyncStatus: z.boolean(),
unregisterSyncRoot: z.number(),
};

export const parseAddonZod = <T>(fn: keyof typeof addonZod, data: T) => {
const schema = addonZod[fn];
const result = schema.safeParse(data);
if (result.error) logger.error(result.error, fn);
return data;
};
42 changes: 24 additions & 18 deletions src/logger.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,26 @@
import pino from "pino";
import { cwd } from "process";
import { resolve } from "path";
import { inspect } from "util";
import winston from "winston";

const transport = pino.transport({
targets: [
{
target: "pino/file",
options: { destination: `${cwd()}/node-win.log` },
},
{
target: "pino-pretty",
options: {
colorize: true,
singleLine: true,
},
},
],
});
const { format, transports } = winston;

export const logger = pino({}, transport);
export const createLogger = (path: string) => {
return winston.createLogger({
format: format.errors({ stack: true }),
transports: [
new transports.File({
filename: resolve(path),
format: format.combine(format.timestamp(), format.json()),
}),
new transports.Console({
format: format.combine(
format.printf(({ level, message, stack }) => {
const object: any = { level, message };
if (stack) object.stack = stack;
return inspect(object, { colors: true, depth: Infinity, breakLength: Infinity });
}),
),
}),
],
});
};
25 changes: 13 additions & 12 deletions src/queue/queue-manager.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
import fs from "fs";
import lodashChunk from "lodash.chunk";
import { Logger } from "winston";

// import { logger } from "@/logger";

import { HandleAction, HandleActions, IQueueManager, QueueItem, typeQueue } from "./queueManager";
import { HandleAction, HandleActions, QueueItem, typeQueue } from "./queueManager";

export type QueueHandler = {
handleAdd: HandleAction;
Expand All @@ -18,7 +17,7 @@ export type QueueManagerCallback = {
onTaskProcessing: () => Promise<void>;
};

export class QueueManager implements IQueueManager {
export class QueueManager {
private queues: { [key: string]: QueueItem[] } = {
add: [],
hydrate: [],
Expand All @@ -41,6 +40,7 @@ export class QueueManager implements IQueueManager {
private readonly notify: QueueManagerCallback;
private readonly persistPath: string;

logger?: Logger;
actions: HandleActions;

constructor(handlers: QueueHandler, notify: QueueManagerCallback, persistPath: string) {
Expand Down Expand Up @@ -79,7 +79,7 @@ export class QueueManager implements IQueueManager {
}

private loadQueueStateFromFile(): void {
console.debug("Loading queue state from file:" + this.persistPath);
this.logger?.debug("Loading queue state from file:" + this.persistPath);
if (this.persistPath) {
if (!fs.existsSync(this.persistPath)) {
this.saveQueueStateToFile();
Expand All @@ -105,10 +105,11 @@ export class QueueManager implements IQueueManager {
}

public enqueue(task: QueueItem): void {
console.debug(`Task enqueued: ${JSON.stringify(task)}`);
this.logger?.debug({ fn: "enqueue", task });
const existingTask = this.queues[task.type].find((item) => item.path === task.path && item.type === task.type);

if (existingTask) {
console.debug("Task already exists in queue. Skipping.");
this.logger?.info("Task already exists in queue. Skipping.");
return;
}

Expand All @@ -125,7 +126,6 @@ export class QueueManager implements IQueueManager {

// Inicia el temporizador de espera
this.enqueueTimeout = setTimeout(() => {
console.debug("Processing all tasks");
this.processAll();
}, this.enqueueDelay);
}
Expand Down Expand Up @@ -164,7 +164,6 @@ export class QueueManager implements IQueueManager {

for (const chunk of chunks) {
await this.notify.onTaskProcessing();

await Promise.all(chunk.map((task) => this.processTask(type, task)));
this.queues[type] = this.queues[type].slice(chunk.length);
}
Expand All @@ -181,16 +180,18 @@ export class QueueManager implements IQueueManager {
}
}

private async processTask(type: typeQueue, task: QueueItem): Promise<void> {
console.debug(`Processing ${type} task: ${JSON.stringify(task)}`);
private async processTask(type: typeQueue, task: QueueItem) {
this.logger?.debug({ fn: "processTask", task });

try {
await this.actions[task.type](task);
} catch (error) {
console.error(`Failed to process ${type} task:`, task, error);
this.logger?.error(`Failed to process ${type} task`, error);
}
}

public async processAll(): Promise<void> {
this.logger?.debug({ fn: "processAll" });
const taskTypes = Object.keys(this.queues) as typeQueue[];
await this.notify.onTaskProcessing();
await Promise.all(taskTypes.map((type: typeQueue) => this.processQueue(type)));
Expand Down
3 changes: 2 additions & 1 deletion src/virtual-drive.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { Status } from "./types/placeholder.type";
import { IQueueManager } from "./queue/queueManager";

import { addon } from "./addon";
import { createLogger } from "./logger";

interface ItemInfo {
path: string;
Expand Down Expand Up @@ -247,7 +248,7 @@ class VirtualDrive {

this.watcher.queueManager = queueManager;

this.watcher.logPath = loggerPath;
this.watcher.logger = createLogger(loggerPath);

this.watcher.syncRootPath = path;
this.watcher.options = {
Expand Down
11 changes: 7 additions & 4 deletions src/watcher/detect-context-menu-action.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ export class DetectContextMenuActionService {
const itemId = self.virtualDriveFn.CfGetPlaceHolderIdentity(path);
const isInDevice = self.fileInDevice.has(path);

self.writeLog({
self.logger.info({
event: "onRaw",
path,
status,
Expand Down Expand Up @@ -59,9 +59,12 @@ export class DetectContextMenuActionService {
status.pinState == PinState.OnlineOnly &&
status.syncState == SyncState.InSync
) {
if (curr.blocks === 0) {
return "Liberando espacio";
}
// TODO: we need to disable this for now even if dehydate it's called two times
// because files that are a .zip have blocks === 0, so they never dehydrate
// because it's seems that it's already been dehydrated
// if (curr.blocks === 0) {
// return "Liberando espacio";
// }

self.fileInDevice.delete(path);
self.queueManager.enqueue({ path, type: typeQueue.dehydrate, isFolder, fileId: itemId });
Expand Down
9 changes: 3 additions & 6 deletions src/watcher/events/on-add-dir.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,21 +6,18 @@ import { PinState, SyncState } from "@/types/placeholder.type";
import { Watcher } from "../watcher";

export class OnAddDirService {
execute({ self, path, stats }: TProps) {
execute({ self, path }: TProps) {
try {
self.writeLog("onAddDir", path, stats);

const status = self.virtualDriveFn.CfGetPlaceHolderState(path);
self.writeLog("status", status);
self.logger.info({ fn: "onAddDir", path, status });

if (status.pinState === PinState.AlwaysLocal || status.pinState === PinState.OnlineOnly || status.syncState === SyncState.InSync) {
return;
}

self.queueManager.enqueue({ path, type: typeQueue.add, isFolder: true });
} catch (error) {
self.writeLog("Error en onAddDir");
console.error(error);
self.logger.error("Error en onAddDir", error);
}
}
}
Expand Down
Loading