forked from codebymitch/TitanBot
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwrapper.js
More file actions
194 lines (168 loc) · 5.54 KB
/
Copy pathwrapper.js
File metadata and controls
194 lines (168 loc) · 5.54 KB
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
import { pgDb } from '../postgresDatabase.js';
import { MemoryStorage } from '../memoryStorage.js';
import { logger } from '../logger.js';
import { validateGuildConfigOrThrow } from '../schemas.js';
class DatabaseWrapper {
constructor() {
this.initialized = false;
this.db = null;
this.useFallback = false;
this.connectionType = 'none';
this.degradedModeWarningShown = false;
this.degradedReason = null;
}
async initialize() {
if (this.initialized) {
return;
}
try {
logger.info('Attempting to connect to PostgreSQL...');
const pgConnected = await pgDb.connect();
if (pgConnected) {
this.db = pgDb;
this.connectionType = 'postgresql';
this.degradedReason = null;
logger.info('✅ PostgreSQL Database initialized - using persistent database');
this.initialized = true;
return;
}
const pgFailure = pgDb.getLastFailure?.();
if (pgFailure?.reason === 'SCHEMA_VERSION_MISMATCH') {
const schemaError = new Error(
`Schema version mismatch detected (${pgFailure.message}). Run migrations before startup.`,
);
schemaError.code = 'SCHEMA_VERSION_MISMATCH';
throw schemaError;
}
} catch (error) {
logger.warn('PostgreSQL connection failed:', error.message);
if (error.code === 'SCHEMA_VERSION_MISMATCH') {
throw error;
}
}
this.db = new MemoryStorage();
this.useFallback = true;
this.connectionType = 'memory';
this.degradedReason = 'POSTGRES_UNAVAILABLE';
logger.warn('⚠️ DATABASE DEGRADED MODE ENABLED - Using in-memory storage (data will be lost on restart)');
logger.warn('⚠️ Please check PostgreSQL connection and restart the bot when fixed');
this.initialized = true;
this.degradedModeWarningShown = true;
}
async set(key, value, ttl = null) {
if (this.useFallback) {
logger.debug(`[DEGRADED] Writing to memory: ${key}`);
}
if (typeof key === 'string' && /^guild:[^:]+:config$/.test(key)) {
const guildId = key.split(':')[1];
validateGuildConfigOrThrow(value, {
guildId,
errorCode: 'VALIDATION_FAILED',
});
}
return this.db.set(key, value, ttl);
}
async get(key, defaultValue = null) {
return this.db.get(key, defaultValue);
}
async delete(key) {
if (this.useFallback) {
logger.debug(`[DEGRADED] Deleting from memory: ${key}`);
}
return this.db.delete(key);
}
async list(prefix) {
return this.db.list(prefix);
}
async exists(key) {
if (this.db.exists) {
return this.db.exists(key);
}
const value = await this.db.get(key);
return value !== null;
}
async increment(key, amount = 1) {
if (this.useFallback) {
logger.debug(`[DEGRADED] Incrementing in memory: ${key}`);
}
if (this.db.increment) {
return this.db.increment(key, amount);
}
const current = await this.db.get(key, 0);
const newValue = current + amount;
await this.db.set(key, newValue);
return newValue;
}
async decrement(key, amount = 1) {
if (this.useFallback) {
logger.debug(`[DEGRADED] Decrementing in memory: ${key}`);
}
if (this.db.decrement) {
return this.db.decrement(key, amount);
}
const current = await this.db.get(key, 0);
const newValue = current - amount;
await this.db.set(key, newValue);
return newValue;
}
isDegraded() {
return this.useFallback;
}
isAvailable() {
return this.db && !this.useFallback;
}
getStatus() {
return {
initialized: this.initialized,
connectionType: this.connectionType,
isDegraded: this.useFallback,
isAvailable: this.isAvailable(),
degradedReason: this.degradedReason,
};
}
getConnectionType() {
return this.connectionType;
}
}
export const db = new DatabaseWrapper();
export async function initializeDatabase() {
try {
logger.info('Initializing Database (PostgreSQL > Memory fallback)...');
await db.initialize();
logger.info('✅ Database initialized');
return { db };
} catch (error) {
logger.error('❌ Database Initialization Error:', error);
if (error.code === 'SCHEMA_VERSION_MISMATCH') {
throw error;
}
return { db };
}
}
export async function getFromDb(key, defaultValue = null) {
try {
const value = await db.get(key);
return value === null ? defaultValue : value;
} catch (error) {
logger.error(`Error getting value for key ${key}:`, error);
return defaultValue;
}
}
export async function setInDb(key, value, ttl = null) {
try {
await db.set(key, value, ttl);
return true;
} catch (error) {
logger.error(`Error setting value for key ${key}:`, error);
return false;
}
}
export async function deleteFromDb(key) {
try {
await db.delete(key);
return true;
} catch (error) {
logger.error(`Error deleting key ${key}:`, error);
return false;
}
}