NodeLogging/src/filewriter.ts

253 lines
6.1 KiB
TypeScript
Raw Normal View History

2021-05-08 20:11:15 +00:00
import { Lock } from "@hibas123/utils";
import * as fs from "fs";
2019-03-26 01:50:26 +00:00
import * as path from "path";
2021-05-08 20:11:15 +00:00
import { Adapter, Message, Formatted } from "@hibas123/logging";
2019-04-01 03:51:27 +00:00
2019-04-05 02:40:34 +00:00
const MAX_FILE_SIZE = 500000000;
export class LoggingFiles implements Adapter {
file: Files;
2021-05-08 20:43:46 +00:00
constructor(private filename: string, private maxFileSize = MAX_FILE_SIZE) {}
2021-05-08 20:11:15 +00:00
init() {
if (!this.file) {
this.file = Files.getFile(this.filename);
2021-05-08 20:11:15 +00:00
this.file.init(this.maxFileSize);
}
}
flush(sync: boolean) {
this.file.flush(sync);
}
onMessage(message: Message) {
2021-05-08 20:11:15 +00:00
let msg = Buffer.from(Formatted.strip(message.text) + "\n");
this.file.write(msg);
}
2019-04-05 02:40:34 +00:00
close() {
this.file.close();
this.file = undefined;
2019-04-05 02:40:34 +00:00
}
}
2021-05-08 20:11:15 +00:00
//TODO: Optimise write path
2021-05-09 13:14:16 +00:00
const Debounce = (callback: () => void, iv = 500, max = 100) => {
let to: any;
2021-05-09 13:14:16 +00:00
let curr = 0;
return {
trigger: () => {
2021-05-09 13:14:16 +00:00
curr++;
if (curr >= max) {
if (to) {
clearTimeout(to);
to = undefined;
}
curr = 0;
callback();
} else if (!to) {
to = setTimeout(() => {
to = undefined;
2021-05-09 13:14:16 +00:00
curr = 0;
callback();
}, iv);
}
},
};
};
export class Files {
2019-04-05 02:40:34 +00:00
private open = 0;
private static files = new Map<string, Files>();
static getFile(filename: string): Files {
filename = path.resolve(filename);
let file = this.files.get(filename);
if (!file) {
file = new Files(filename);
this.files.set(filename, file);
}
2019-04-05 02:40:34 +00:00
file.open++;
return file;
}
2019-04-05 02:40:34 +00:00
private maxFileSize = MAX_FILE_SIZE;
private size: number = 0;
private stream: fs.WriteStream = undefined;
private lock = new Lock();
2021-05-09 13:14:16 +00:00
private debounce = Debounce(this.checkQueue.bind(this));
2021-05-08 20:43:46 +00:00
#initialized = false;
public get initlialized() {
2021-05-08 20:43:46 +00:00
return this.#initialized;
}
private constructor(private file: string) {}
2019-04-05 02:40:34 +00:00
public async init(maxFileSize: number) {
2021-05-08 20:43:46 +00:00
if (this.#initialized) return;
let lock = await this.lock.getLock();
2019-04-05 02:40:34 +00:00
this.maxFileSize == maxFileSize;
await this.initializeFile();
2021-05-08 20:43:46 +00:00
this.#initialized = true;
lock.release();
this.checkQueue();
}
private async initializeFile(new_file = false) {
try {
if (this.stream) {
this.stream.close();
}
const folder = path.dirname(this.file);
if (folder) {
if (!(await fsExists(folder))) {
await fsMkDir(folder).catch(() => {}); //Could happen, if two seperate instances want to create the same folder so ignoring
}
}
let size = 0;
if (await fsExists(this.file)) {
let stats = await fsStat(this.file);
2019-04-05 02:40:34 +00:00
if (new_file || stats.size >= this.maxFileSize) {
if (await fsExists(this.file + ".old"))
await fsUnlink(this.file + ".old");
await fsMove(this.file, this.file + ".old");
} else {
size = stats.size;
}
}
this.stream = fs.createWriteStream(this.file, { flags: "a" });
this.size = size;
} catch (e) {
console.log(e);
2021-05-08 20:43:46 +00:00
//TODO: is this the right behavior?
process.exit(1);
}
}
private queue: Buffer[] = [];
async checkQueue() {
if (this.lock.locked) return;
let lock = await this.lock.getLock();
let msg: Buffer;
while ((msg = this.queue.shift())) {
await this.write_to_file(msg);
}
lock.release();
}
2019-04-05 02:40:34 +00:00
public async close() {
await this.flush(false);
this.open--;
if (this.open <= 0) {
this.stream.close();
2019-04-05 02:40:34 +00:00
Files.files.delete(this.file);
}
}
2021-05-08 20:43:46 +00:00
public flush(sync: boolean) {
if (sync) {
// if sync flush, the process most likely is in failstate, so checkQueue stopped its work.
let msg: Buffer;
while ((msg = this.queue.shift())) {
this.stream.write(msg);
}
} else {
return Promise.resolve().then(async () => {
const lock = await this.lock.getLock();
lock.release();
await this.checkQueue();
});
}
}
private async write_to_file(data: Buffer) {
try {
if (
data.byteLength < this.maxFileSize &&
this.size + data.byteLength > this.maxFileSize
) {
await this.initializeFile(true);
}
this.size += data.byteLength;
this.stream.write(data);
} catch (err) {
2019-04-01 03:51:27 +00:00
// TODO: Better error handling!
console.error(err);
this.initializeFile(false);
this.write_to_file(data);
}
}
public write(data: Buffer) {
this.queue.push(data);
this.debounce.trigger();
}
2019-04-05 02:40:34 +00:00
public dispose() {}
}
function fsUnlink(path) {
2021-05-08 20:11:15 +00:00
return new Promise<void>((resolve, reject) => {
fs.unlink(path, (err) => {
if (err) reject(err);
else resolve();
});
});
}
function fsStat(path: string) {
return new Promise<fs.Stats>((resolve, reject) => {
fs.stat(path, (err, stats) => {
if (err) reject(err);
else resolve(stats);
});
});
}
function fsMove(oldPath: string, newPath: string) {
2021-05-08 20:11:15 +00:00
return new Promise<void>((resolve, reject) => {
let callback = (err?) => {
if (err) reject(err);
else resolve();
};
fs.rename(oldPath, newPath, function (err) {
if (err) {
if (err.code === "EXDEV") {
copy();
} else {
callback(err);
}
return;
}
callback();
});
function copy() {
fs.copyFile(oldPath, newPath, (err) => {
if (err) callback(err);
else fs.unlink(oldPath, callback);
});
}
});
}
function fsExists(path: string) {
return new Promise<boolean>((resolve, reject) => {
fs.exists(path, resolve);
});
}
function fsMkDir(path: string) {
2021-05-08 20:11:15 +00:00
return new Promise<void>((resolve, reject) => {
fs.mkdir(path, (err) => (err ? reject(err) : resolve()));
});
}