File size: 9,152 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 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 | import fs from "node:fs";
import { DEFAULT_DATABASE_SETTINGS, type DatabaseSettings } from "@/types/databaseSettings";
import { backupDbFile } from "./backup";
import { DATA_DIR, SQLITE_FILE, getDbInstance } from "./core";
import { invalidateDbCache } from "./readCache";
import { getDatabaseStats } from "./stats";
const DATABASE_SETTINGS_NAMESPACE = "databaseSettings";
export type UserDatabaseSettings = Omit<DatabaseSettings, "location" | "stats">;
type DatabaseSettingsSection = keyof UserDatabaseSettings;
const DATABASE_SETTINGS_SECTIONS = Object.keys(
DEFAULT_DATABASE_SETTINGS
) as DatabaseSettingsSection[];
const LEGACY_FLAT_KEYS: {
[TSection in DatabaseSettingsSection]: Partial<
Record<keyof UserDatabaseSettings[TSection] & string, string[]>
>;
} = {
logs: {
detailedLogsEnabled: ["detailedLogsEnabled"],
callLogPipelineEnabled: ["callLogPipelineEnabled"],
maxDetailSizeKb: ["maxDetailSizeKb"],
ringBufferSize: ["ringBufferSize"],
},
backup: {
autoBackupEnabled: ["autoBackupEnabled"],
autoBackupFrequency: ["autoBackupFrequency"],
keepLastNBackups: ["keepLastNBackups"],
},
cache: {
semanticCacheEnabled: ["semanticCacheEnabled"],
semanticCacheMaxSize: ["semanticCacheMaxSize"],
semanticCacheTTL: ["semanticCacheTTL"],
promptCacheEnabled: ["promptCacheEnabled"],
promptCacheStrategy: ["promptCacheStrategy"],
alwaysPreserveClientCache: ["alwaysPreserveClientCache"],
},
retention: {
quotaSnapshots: ["quotaSnapshots"],
compressionAnalytics: ["compressionAnalytics"],
mcpAudit: ["mcpAudit"],
a2aEvents: ["a2aEvents"],
callLogs: ["callLogs"],
usageHistory: ["usageHistory"],
memoryEntries: ["memoryEntries"],
autoCleanupEnabled: ["autoCleanupEnabled"],
},
aggregation: {
enabled: ["aggregationEnabled", "enabled"],
rawDataRetentionDays: ["rawDataRetentionDays"],
granularity: ["granularity"],
},
optimization: {
autoVacuumMode: ["autoVacuumMode"],
scheduledVacuum: ["scheduledVacuum"],
vacuumHour: ["vacuumHour"],
pageSize: ["pageSize"],
cacheSize: ["cacheSize"],
optimizeOnStartup: ["optimizeOnStartup"],
},
};
function isRecord(value: unknown): value is Record<string, unknown> {
return value !== null && typeof value === "object" && !Array.isArray(value);
}
function cloneDefaultSettings(): UserDatabaseSettings {
return structuredClone(DEFAULT_DATABASE_SETTINGS) as UserDatabaseSettings;
}
function parseStoredValue(rawValue: unknown): unknown {
if (typeof rawValue !== "string") return rawValue;
try {
return JSON.parse(rawValue);
} catch {
return rawValue;
}
}
function toBooleanSetting(value: unknown): boolean | null {
if (typeof value === "boolean") return value;
if (typeof value === "number") return !Number.isNaN(value) && value !== 0;
if (typeof value !== "string") return null;
const normalized = value.trim().toLowerCase();
if (["1", "true", "yes", "on"].includes(normalized)) return true;
if (["0", "false", "no", "off"].includes(normalized)) return false;
return null;
}
function readNamespace(namespace: string): Record<string, unknown> {
const db = getDbInstance();
const rows = db
.prepare("SELECT key, value FROM key_value WHERE namespace = ?")
.all(namespace) as Array<{ key: string; value: string }>;
const values: Record<string, unknown> = {};
for (const row of rows) {
values[row.key] = parseStoredValue(row.value);
}
return values;
}
function mergeSectionObject(
target: UserDatabaseSettings,
section: DatabaseSettingsSection,
value: unknown
) {
if (!isRecord(value)) return;
const sectionTarget = target[section] as Record<string, unknown>;
const defaultSection = DEFAULT_DATABASE_SETTINGS[section] as Record<string, unknown>;
for (const key of Object.keys(defaultSection)) {
if (value[key] !== undefined) {
sectionTarget[key] = value[key];
}
}
}
function mergeTopLevelSections(target: UserDatabaseSettings, values: Record<string, unknown>) {
for (const section of DATABASE_SETTINGS_SECTIONS) {
mergeSectionObject(target, section, values[section]);
}
}
function mergeRuntimeLogSettings(target: UserDatabaseSettings, values: Record<string, unknown>) {
const pipelineEnabled = toBooleanSetting(values.call_log_pipeline_enabled);
if (pipelineEnabled !== null) {
target.logs.callLogPipelineEnabled = pipelineEnabled;
}
const legacyDetailedEnabled = toBooleanSetting(values.detailed_logs_enabled);
if (legacyDetailedEnabled !== null) {
target.logs.detailedLogsEnabled = legacyDetailedEnabled;
}
}
function mergeDatabaseSettingsNamespace(
target: UserDatabaseSettings,
values: Record<string, unknown>
) {
for (const section of DATABASE_SETTINGS_SECTIONS) {
const defaultSection = DEFAULT_DATABASE_SETTINGS[section] as Record<string, unknown>;
const sectionTarget = target[section] as Record<string, unknown>;
const flatAliases = LEGACY_FLAT_KEYS[section] as Partial<Record<string, string[]>>;
for (const key of Object.keys(defaultSection)) {
for (const alias of flatAliases[key] ?? []) {
if (values[alias] !== undefined) {
sectionTarget[key] = values[alias];
}
}
const nestedKey = `${section}.${key}`;
if (values[nestedKey] !== undefined) {
sectionTarget[key] = values[nestedKey];
}
}
}
}
function getWalSizeBytes(): number {
if (!SQLITE_FILE) return 0;
try {
const walPath = `${SQLITE_FILE}-wal`;
return fs.existsSync(walPath) ? fs.statSync(walPath).size : 0;
} catch {
return 0;
}
}
function getSchemaVersion(): number {
const db = getDbInstance();
try {
const row = db
.prepare("SELECT MAX(CAST(version AS INTEGER)) AS version FROM _omniroute_migrations")
.get() as { version: number | null } | undefined;
return row?.version ?? 0;
} catch {
return 0;
}
}
function getFreelistCount(): number {
try {
return getDbInstance().pragma("freelist_count", { simple: true }) as number;
} catch {
return 0;
}
}
function getIntegrityCheck(): "ok" | "error" | null {
try {
const result = getDbInstance().pragma("quick_check", { simple: true }) as string;
return result === "ok" ? "ok" : "error";
} catch {
return null;
}
}
export function getUserDatabaseSettings(): UserDatabaseSettings {
const settings = cloneDefaultSettings();
const mainSettings = readNamespace("settings");
const databaseSettingsValue = mainSettings[DATABASE_SETTINGS_NAMESPACE];
if (isRecord(databaseSettingsValue)) {
mergeTopLevelSections(settings, databaseSettingsValue);
}
mergeTopLevelSections(settings, mainSettings);
mergeDatabaseSettingsNamespace(settings, readNamespace(DATABASE_SETTINGS_NAMESPACE));
mergeRuntimeLogSettings(settings, mainSettings);
return settings;
}
export function getDatabaseSettings(): DatabaseSettings {
const dbStats = getDatabaseStats();
return {
...getUserDatabaseSettings(),
location: {
databasePath: SQLITE_FILE ?? ":memory:",
dataDir: DATA_DIR,
walSizeBytes: getWalSizeBytes(),
schemaVersion: getSchemaVersion(),
},
stats: {
databaseSizeBytes: dbStats.totalSize,
pageCount: dbStats.pageCount,
freelistCount: getFreelistCount(),
lastVacuumAt: null,
lastOptimizationAt: null,
integrityCheck: getIntegrityCheck(),
},
};
}
export function updateDatabaseSettings(
updates: Partial<UserDatabaseSettings>
): UserDatabaseSettings {
const nextSettings = getUserDatabaseSettings();
for (const section of DATABASE_SETTINGS_SECTIONS) {
if (updates[section] !== undefined) {
mergeSectionObject(nextSettings, section, updates[section]);
}
}
const db = getDbInstance();
const insert = db.prepare(
"INSERT OR REPLACE INTO key_value (namespace, key, value) VALUES (?, ?, ?)"
);
const settingsInsert = db.prepare(
"INSERT OR REPLACE INTO key_value (namespace, key, value) VALUES ('settings', ?, ?)"
);
const requestedLogs = updates.logs as Partial<UserDatabaseSettings["logs"]> | undefined;
const pipelineEnabled = requestedLogs?.callLogPipelineEnabled;
const detailedEnabled = requestedLogs?.detailedLogsEnabled;
const tx = db.transaction(() => {
for (const section of DATABASE_SETTINGS_SECTIONS) {
const sectionValues = nextSettings[section] as Record<string, unknown>;
for (const [key, value] of Object.entries(sectionValues)) {
insert.run(DATABASE_SETTINGS_NAMESPACE, `${section}.${key}`, JSON.stringify(value));
}
}
if (pipelineEnabled !== undefined) {
settingsInsert.run("call_log_pipeline_enabled", JSON.stringify(Boolean(pipelineEnabled)));
}
});
tx();
backupDbFile("pre-write");
invalidateDbCache("settings");
return nextSettings;
}
|