File size: 3,071 Bytes
6111b2b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
/**

 * Database compression scheduler - runs compression tasks based on settings.

 *

 * @module lib/db/compressionScheduler

 */

import { getDbInstance } from "./core";
import { getSettings } from "@/lib/localDb";

interface CompressionScheduleSettings {
  enabled: boolean;
  intervalHours: number;
  lastRun?: string;
}

/**

 * Run scheduled compression based on database settings.

 * Should be called on startup and periodically.

 */
export async function runScheduledCompression(): Promise<void> {
  const db = getDbInstance();
  const settings = await getSettings();

  const compressionSettings = (settings.databaseSettings as any)?.compression as
    | CompressionScheduleSettings
    | undefined;

  if (!compressionSettings?.enabled) {
    console.log("[CompressionScheduler] Compression scheduling is disabled");
    return;
  }

  const intervalHours = compressionSettings.intervalHours ?? 24;
  const lastRun = compressionSettings.lastRun ? new Date(compressionSettings.lastRun) : null;

  const now = new Date();
  const hoursSinceLastRun = lastRun
    ? (now.getTime() - lastRun.getTime()) / (1000 * 60 * 60)
    : Infinity;

  if (hoursSinceLastRun < intervalHours) {
    console.log(
      `[CompressionScheduler] Skipping compression - last run was ${hoursSinceLastRun.toFixed(1)}h ago (interval: ${intervalHours}h)`
    );
    return;
  }

  console.log("[CompressionScheduler] Running scheduled compression...");

  try {
    // Run VACUUM to reclaim space
    db.prepare("VACUUM").run();
    console.log("[CompressionScheduler] VACUUM completed");

    // Run ANALYZE to update statistics
    db.prepare("ANALYZE").run();
    console.log("[CompressionScheduler] ANALYZE completed");

    const updateStmt = db.prepare(`

      INSERT OR REPLACE INTO key_value (namespace, key, value)

      VALUES ('settings', 'databaseSettings', json_set(

        COALESCE((SELECT value FROM key_value WHERE namespace = 'settings' AND key = 'databaseSettings'), '{}'),

        '$.compression.lastRun',

        ?

      ))

    `);
    updateStmt.run(now.toISOString());

    console.log("[CompressionScheduler] Compression completed successfully");
  } catch (err: any) {
    console.error("[CompressionScheduler] Error during compression:", err);
    throw err;
  }
}

/**

 * Initialize compression scheduler on startup.

 * Call this once when the application starts.

 */
export async function initCompressionScheduler(): Promise<void> {
  console.log("[CompressionScheduler] Initializing compression scheduler...");

  try {
    await runScheduledCompression();
  } catch (err: any) {
    console.error("[CompressionScheduler] Failed to run initial compression:", err);
  }

  // Set up periodic check (every hour)
  setInterval(
    async () => {
      try {
        await runScheduledCompression();
      } catch (err: any) {
        console.error("[CompressionScheduler] Periodic compression check failed:", err);
      }
    },
    60 * 60 * 1000
  ); // 1 hour
}