import type { EventConfig, Handlers } from 'motia'; import { z } from 'zod'; import { DatabaseManager, BackupStorage } from '@buzztrail/accounts-backup'; export const config: EventConfig = { type: 'event', name: 'CleanupExpiredBackups', description: 'Clean up expired backups and free storage space', flows: ['cleanup-flow'], subscribes: ['cleanup-start'], emits: ['cleanup-workflow-finished'], input: z.object({ retentionDays: z.number().default(30), forceCleanup: z.boolean().default(false) }) }; export const handler: Handlers['CleanupExpiredBackups'] = async (input, { logger, emit, state }) => { logger.info('๐Ÿงน [Motia Step] Starting cleanup of expired backups...', { input }); try { const db = DatabaseManager.getInstance(); const storage = new BackupStorage('./backup-data', db); const startTime = new Date().toISOString(); let totalDeleted = 0; let totalStorageFreed = 0; const cleanupResults = []; // Get all customers const customers = await db.getAllCustomers(); logger.info(`๐Ÿ“‹ [Motia Step] Checking ${customers.length} customers for expired backups`); // Clean up expired backups for each customer for (const customer of customers) { try { logger.info(`๐Ÿงน [Motia Step] Cleaning up backups for ${customer.customer_name}`); // Get backup stats before cleanup const beforeStats = await storage.getBackupStats(customer.customer_id); // Clean up old backups in filesystem const deletedCount = await storage.cleanupOldBackups(customer.customer_id, input.retentionDays); // Get stats after cleanup const afterStats = await storage.getBackupStats(customer.customer_id); const storageFreed = beforeStats.totalSize - afterStats.totalSize; if (deletedCount > 0) { logger.info(`โœ… [Motia Step] Cleaned up ${deletedCount} expired backups for ${customer.customer_name}, freed ${Math.round(storageFreed / 1024)} KB`); } totalDeleted += deletedCount; totalStorageFreed += storageFreed; cleanupResults.push({ customerId: customer.customer_id, customerName: customer.customer_name, deletedBackups: deletedCount, storageFreed, status: 'success' }); } catch (customerError) { logger.error(`โŒ [Motia Step] Cleanup failed for ${customer.customer_name}:`, customerError); cleanupResults.push({ customerId: customer.customer_id, customerName: customer.customer_name, deletedBackups: 0, storageFreed: 0, status: 'failed', error: customerError.message }); } } // Clean up expired backup records from database const expiredDbBackups = await db.deleteExpiredBackups(); logger.info(`๐Ÿ“‹ [Motia Step] Removed ${expiredDbBackups} expired backup records from database`); // Store cleanup results in state const summary = { workflowName: 'cleanup-flow', customersProcessed: customers.length, totalBackupsDeleted: totalDeleted, expiredDbRecordsDeleted: expiredDbBackups, totalStorageFreed, totalStorageFreedMB: Math.round(totalStorageFreed / (1024 * 1024) * 100) / 100, retentionDays: input.retentionDays, startedAt: startTime, completedAt: new Date().toISOString(), results: cleanupResults }; await state.set('cleanup-summary', 'latest', summary); const successCount = cleanupResults.filter(r => r.status === 'success').length; const failureCount = cleanupResults.filter(r => r.status === 'failed').length; logger.info(`๐Ÿ [Motia Step] Cleanup completed:`, { customers: customers.length, successful: successCount, failed: failureCount, backupsDeleted: totalDeleted, dbRecordsDeleted: expiredDbBackups, storageFreedMB: summary.totalStorageFreedMB }); await emit({ topic: 'cleanup-workflow-finished', data: summary }); } catch (error) { logger.error('โŒ [Motia Step] Cleanup workflow failed:', error); throw error; } };