2021-09-27 17:40:38 +02:00
|
|
|
const { R } = require("redbean-node");
|
2023-05-12 18:55:48 +02:00
|
|
|
const { log } = require("../../src/util");
|
2024-10-09 01:43:44 +02:00
|
|
|
const { setSetting, setting } = require("../util-server");
|
2023-02-12 10:59:07 +02:00
|
|
|
const Database = require("../database");
|
2021-09-27 17:40:38 +02:00
|
|
|
|
2021-10-12 17:28:21 +02:00
|
|
|
const DEFAULT_KEEP_PERIOD = 180;
|
2021-09-27 17:40:38 +02:00
|
|
|
|
2023-05-12 18:55:48 +02:00
|
|
|
/**
|
|
|
|
* Clears old data from the heartbeat table of the database.
|
2023-08-11 09:46:41 +02:00
|
|
|
* @returns {Promise<void>} A promise that resolves when the data has been cleared.
|
2023-05-12 18:55:48 +02:00
|
|
|
*/
|
2021-10-09 17:33:47 +02:00
|
|
|
|
2023-05-12 18:55:48 +02:00
|
|
|
const clearOldData = async () => {
|
2024-10-09 01:43:44 +02:00
|
|
|
let period = await setting("keepDataPeriodDays");
|
2021-10-09 17:33:47 +02:00
|
|
|
|
|
|
|
// Set Default Period
|
|
|
|
if (period == null) {
|
2024-10-09 01:43:44 +02:00
|
|
|
await setSetting("keepDataPeriodDays", DEFAULT_KEEP_PERIOD, "general");
|
2021-10-09 17:33:47 +02:00
|
|
|
period = DEFAULT_KEEP_PERIOD;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Try parse setting
|
|
|
|
let parsedPeriod;
|
|
|
|
try {
|
|
|
|
parsedPeriod = parseInt(period);
|
|
|
|
} catch (_) {
|
2023-05-12 18:55:48 +02:00
|
|
|
log.warn("clearOldData", "Failed to parse setting, resetting to default..");
|
2024-10-09 01:43:44 +02:00
|
|
|
await setSetting("keepDataPeriodDays", DEFAULT_KEEP_PERIOD, "general");
|
2021-10-09 17:33:47 +02:00
|
|
|
parsedPeriod = DEFAULT_KEEP_PERIOD;
|
|
|
|
}
|
|
|
|
|
2023-01-08 21:09:06 +02:00
|
|
|
if (parsedPeriod < 1) {
|
2023-05-12 18:55:48 +02:00
|
|
|
log.info("clearOldData", `Data deletion has been disabled as period is less than 1. Period is ${parsedPeriod} days.`);
|
2023-01-08 21:09:06 +02:00
|
|
|
} else {
|
|
|
|
|
2023-05-12 18:55:48 +02:00
|
|
|
log.debug("clearOldData", `Clearing Data older than ${parsedPeriod} days...`);
|
2023-01-08 21:09:06 +02:00
|
|
|
|
2023-02-12 10:59:07 +02:00
|
|
|
const sqlHourOffset = Database.sqlHourOffset();
|
|
|
|
|
2023-01-08 21:09:06 +02:00
|
|
|
try {
|
|
|
|
await R.exec(
|
2023-02-12 10:59:07 +02:00
|
|
|
"DELETE FROM heartbeat WHERE time < " + sqlHourOffset,
|
|
|
|
[ parsedPeriod * -24 ]
|
2023-01-08 21:09:06 +02:00
|
|
|
);
|
2023-07-07 22:57:53 +02:00
|
|
|
|
2023-08-31 23:19:21 +02:00
|
|
|
if (Database.dbConfig.type === "sqlite") {
|
|
|
|
await R.exec("PRAGMA optimize;");
|
|
|
|
}
|
2023-01-08 21:09:06 +02:00
|
|
|
} catch (e) {
|
2023-05-12 18:55:48 +02:00
|
|
|
log.error("clearOldData", `Failed to clear old data: ${e.message}`);
|
2023-01-08 21:09:06 +02:00
|
|
|
}
|
2021-10-09 17:33:47 +02:00
|
|
|
}
|
2023-05-12 18:55:48 +02:00
|
|
|
};
|
2021-09-27 17:40:38 +02:00
|
|
|
|
2023-05-12 18:55:48 +02:00
|
|
|
module.exports = {
|
|
|
|
clearOldData,
|
|
|
|
};
|