@trap_stevo/star-vault
Version:
Unleash the future of data management with the ultimate platform for secure, scalable, and dynamic data operations. Power the next generation of applications by combining advanced encryption, revolutionary real-time querying, and seamless synchronization
168 lines (167 loc) • 8.36 kB
JavaScript
;
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t["return"] || t["return"](); } finally { if (u) throw o; } } }; }
function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
var EngineUtilityManager = require("../HUDManagers/EngineUtilityManager");
var crypto = require("crypto");
var path = require("path");
var fs = require("fs");
var StarLogger = /*#__PURE__*/function () {
function StarLogger(logPath) {
var maxLogSizeBytes = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 5 * 1024 * 1024;
var retention = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : "30d";
var dirMode = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 448;
var fileMode = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 384;
_classCallCheck(this, StarLogger);
this.logPath = logPath;
this.maxLogSizeBytes = maxLogSizeBytes;
this.retentionMs = EngineUtilityManager.convertDuration(retention);
this.fileMode = fileMode;
this.dirMode = dirMode;
if (!fs.existsSync(logPath)) {
fs.mkdirSync(logPath, {
recursive: true,
mode: this.dirMode
});
}
}
return _createClass(StarLogger, [{
key: "logWrite",
value: function logWrite(collection, record) {
var clientInfo = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
var action = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : "WRITE";
var logFile = path.join(this.logPath, "".concat(collection, ".log"));
var dir = path.dirname(logFile);
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, {
recursive: true,
mode: this.dirMode
});
}
this.checkLogRotation(logFile);
var eventID = "".concat(collection, ":").concat(record.id, ":").concat(Date.now());
var checksum = crypto.createHash("sha256").update(JSON.stringify(record)).digest("hex");
var logEntry = {
timestamp: new Date().toISOString(),
client: clientInfo,
data: record,
checksum: checksum,
eventID: eventID,
action: action
};
fs.appendFileSync(logFile, JSON.stringify(logEntry) + "\n", {
mode: this.fileMode
});
}
}, {
key: "recoverWrites",
value: function recoverWrites(collection) {
var logFile = path.join(this.logPath, "".concat(collection, ".log"));
if (!fs.existsSync(logFile)) {
return [];
}
var logs = fs.readFileSync(logFile, "utf-8").split("\n").filter(Boolean);
var validLogs = [];
var _iterator = _createForOfIteratorHelper(logs),
_step;
try {
for (_iterator.s(); !(_step = _iterator.n()).done;) {
var line = _step.value;
try {
var entry = JSON.parse(line);
var verify = crypto.createHash("sha256").update(JSON.stringify(entry.data)).digest("hex");
if (verify !== entry.checksum) {
var _entry$data;
console.warn("[StarVault | Star logger] ~ Checksum mismatch for ".concat((_entry$data = entry.data) === null || _entry$data === void 0 ? void 0 : _entry$data.id, ", skipping."));
continue;
}
validLogs.push(entry);
} catch (e) {
console.warn("[StarVault | Star logger] ~ Parse error ~", e.message);
continue;
}
}
} catch (err) {
_iterator.e(err);
} finally {
_iterator.f();
}
return validLogs;
}
}, {
key: "logSystemAction",
value: function logSystemAction(action, collection, details) {
var _details$id;
var clientInfo = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
var logFile = path.join(this.logPath, "system.log");
var dir = path.dirname(logFile);
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, {
recursive: true,
mode: this.dirMode
});
}
var eventID = "".concat(collection, ":").concat((_details$id = details === null || details === void 0 ? void 0 : details.id) !== null && _details$id !== void 0 ? _details$id : action, ":").concat(Date.now());
var logEntry = {
timestamp: new Date().toISOString(),
client: clientInfo,
eventID: eventID,
action: action,
collection: collection,
details: details
};
fs.appendFileSync(logFile, JSON.stringify(logEntry) + "\n", {
mode: this.fileMode
});
}
}, {
key: "clearLog",
value: function clearLog(collection) {
var logFile = path.join(this.logPath, "".concat(collection, ".log"));
if (fs.existsSync(logFile)) {
fs.unlinkSync(logFile);
}
}
}, {
key: "checkLogRotation",
value: function checkLogRotation(logFile) {
if (fs.existsSync(logFile)) {
var stats = fs.statSync(logFile);
if (stats.size > this.maxLogSizeBytes) {
this.rotateLog(logFile);
}
}
}
}, {
key: "rotateLog",
value: function rotateLog(logFile) {
var timestamp = new Date().toISOString().replace(/[:.]/g, "-");
var archiveFile = "".concat(logFile, ".").concat(timestamp, ".archived");
fs.renameSync(logFile, archiveFile);
fs.chmodSync(archiveFile, this.fileMode);
this.cleanupOldLogs();
}
}, {
key: "cleanupOldLogs",
value: function cleanupOldLogs() {
var _this = this;
var files = fs.readdirSync(this.logPath);
var now = Date.now();
files.forEach(function (file) {
var filePath = path.join(_this.logPath, file);
var stats = fs.statSync(filePath);
if (now - stats.mtimeMs > _this.retentionMs) {
fs.unlinkSync(filePath);
}
});
}
}]);
}();
;
module.exports = StarLogger;