DB maintenance Added to purge old comments

pull/1/head
sloppyjosh 2024-02-27 00:11:00 -05:00
parent d2ecc922e9
commit 2a4b73ff14
4 changed files with 132 additions and 1 deletions

View File

@ -0,0 +1,4 @@
CREATE TABLE IF NOT EXISTS maintenance_log (
task_name TEXT PRIMARY KEY,
last_run TIMESTAMP NOT NULL
);

View File

@ -10,7 +10,7 @@ export class DatabaseService {
/**
* Creates a new DatabaseService instance with a provided database connection.
*
* @param {Database} db - The database connection to use for all database operations.
* @param {Database} db - The SQLite database connection.
*/
public constructor(db: Database) {
this.db = db;
@ -76,4 +76,50 @@ export class DatabaseService {
const result = await this.db.get(sql, [username]);
return !!result;
}
/**
* Retrieves the last run timestamp for a specified maintenance task.
* This method queries the `maintenance_log` table to find the last time a specific task was run.
*
* @param {string} taskName - The name of the maintenance task for which to retrieve the last run timestamp.
* @returns {Promise<Date | null>} A promise that resolves to the Date of the last run if found, or null if not found.
*/
public async getLastRunTimestamp(taskName: string): Promise<Date | null> {
const result = await this.db.get(`SELECT last_run FROM maintenance_log WHERE task_name = ?`, [taskName]);
return result ? new Date(result.last_run) : null;
}
/**
* Updates the last run timestamp for a specific maintenance task in the `maintenance_log` table.
* This method uses an "upsert" approach, which inserts a new record if one doesn't exist for the task,
* or updates the existing record if it does. This ensures that each task has only one record in the table
* reflecting its most recent execution time.
*
* @param {string} taskName - The name of the maintenance task for which to update the last run timestamp.
* @returns {Promise<void>} A promise that resolves when the operation is complete.
*/
public async updateLastRunTimestamp(taskName: string): Promise<void> {
// Assumes an "upsert" approach for the maintenance_log table
await this.db.run(
`INSERT INTO maintenance_log (task_name, last_run)
VALUES (?, ?)
ON CONFLICT(task_name)
DO UPDATE SET last_run = ?`,
[taskName, new Date(), new Date()]
);
}
/**
* Deletes comments from the database that are older than a specified number of days.
* This method is intended to be run as part of periodic maintenance tasks to keep the database size manageable.
*
* @param {number} [days=1] - The age of comments to be purged, in days. Defaults to 30 days.
*/
public async purgeOldComments(days: number = 1): Promise<void> {
console.log(`Purging comments older than ${days} days...`);
await this.db.run(`
DELETE FROM comments
WHERE datetime(created_utc, 'unixepoch') < datetime('now', '-${days} days')
`);
}
}

View File

@ -0,0 +1,77 @@
import { DatabaseService } from './database';
/**
* Manages and executes database maintenance tasks such as purging old comments.
* This service is responsible for periodically running maintenance tasks based on specified intervals.
*/
export class DatabaseMaintenanceService {
private databaseService: DatabaseService;
/**
* Initializes a new instance of the DatabaseMaintenanceService.
* @param {DatabaseService} databaseService - An instance of DatabaseService for database operations.
*/
constructor(databaseService: DatabaseService) {
this.databaseService = databaseService;
}
/**
* A list of maintenance tasks to be executed, each with a name, action, and interval.
*/
private maintenanceTasks = [
{
name: 'PurgeOldComments',
action: this.purgeOldComments.bind(this),
interval: 24 * 60 * 60 * 1000, // 24 hours in milliseconds
},
// Add more tasks here as needed
];
/**
* Executes all maintenance tasks that are due based on their defined intervals.
*/
public async runMaintenanceTasks() {
for (const task of this.maintenanceTasks) {
const shouldRun = await this.shouldRunTask(task.name, task.interval);
if (shouldRun) {
await task.action();
await this.updateLastRunTimestamp(task.name);
}
}
}
/**
* Determines whether a specific maintenance task should run based on its last execution time and defined interval.
*
* @param {string} taskName - The name of the task to check.
* @param {number} interval - The interval in milliseconds to determine if the task should run.
* @returns {Promise<boolean>} True if the task should run, otherwise false.
*/
private async shouldRunTask(taskName: string, interval: number): Promise<boolean> {
// Use the DatabaseService to check the last run timestamp from the maintenance_log table
const lastRun = await this.databaseService.getLastRunTimestamp(taskName);
if (!lastRun) return true; // Task has never run
const now = Date.now();
return (now - lastRun.getTime()) > interval;
}
/**
* Purges old comments from the database.
*/
private async purgeOldComments() {
console.log("Purging old comments...");
// Use the DatabaseService for the SQL operation
await this.databaseService.purgeOldComments();
}
/**
* Updates the last run timestamp for a specific maintenance task.
*
* @param {string} taskName - The name of the task for which to update the last run timestamp.
*/
private async updateLastRunTimestamp(taskName: string) {
// Use the DatabaseService to update the last run timestamp in the maintenance_log table
await this.databaseService.updateLastRunTimestamp(taskName);
}
}

View File

@ -6,6 +6,7 @@ import SessionManager from './rdrama/session/SessionManager';
import { CommentParser } from './rdrama/services/CommentParser';
import { DatabaseInitializer } from './db/initializeDatabase';
import { DatabaseService } from './db/services/database';
import { DatabaseMaintenanceService } from './db/services/databaseMaintenance';
import { CommentProcessor } from './rdrama/services/CommentProcessor';
// Import other necessary services or configurations
@ -23,6 +24,9 @@ async function startApplication() {
throw new Error('Failed to initialize the database.');
}
const databaseService = new DatabaseService(db)
const databaseMaintenance = new DatabaseMaintenanceService(databaseService)
console.log('Database Maintenance Start')
await databaseMaintenance.runMaintenanceTasks()
// Initialize services with any required dependencies
const commentFetcher = new CommentProcessor(databaseService);