-
-
Notifications
You must be signed in to change notification settings - Fork 46
Expand file tree
/
Copy pathdatabase.ts
More file actions
10279 lines (9242 loc) · 376 KB
/
database.ts
File metadata and controls
10279 lines (9242 loc) · 376 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
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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import BetterSqlite3Database from 'better-sqlite3';
import path from 'path';
import fs from 'fs';
import { calculateDistance } from '../utils/distance.js';
import { isNodeComplete } from '../utils/nodeHelpers.js';
import { logger } from '../utils/logger.js';
import { getEnvironmentConfig } from '../server/config/environment.js';
import { UserModel } from '../server/models/User.js';
import { PermissionModel } from '../server/models/Permission.js';
import { APITokenModel } from '../server/models/APIToken.js';
import { registry } from '../db/migrations.js';
import { validateThemeDefinition as validateTheme } from '../utils/themeValidation.js';
// Drizzle ORM imports for dual-database support
import { createSQLiteDriver } from '../db/drivers/sqlite.js';
import { createPostgresDriver } from '../db/drivers/postgres.js';
import { createMySQLDriver } from '../db/drivers/mysql.js';
import { getDatabaseConfig, Database } from '../db/index.js';
import type { Pool as PgPool } from 'pg';
import type { Pool as MySQLPool } from 'mysql2/promise';
import {
SettingsRepository,
ChannelsRepository,
NodesRepository,
MessagesRepository,
TelemetryRepository,
AuthRepository,
TraceroutesRepository,
NeighborsRepository,
NotificationsRepository,
MiscRepository,
ChannelDatabaseRepository,
IgnoredNodesRepository,
EmbedProfileRepository,
} from '../db/repositories/index.js';
import type { DatabaseType, DbPacketLog as DbTypesPacketLog, DbPacketCountByNode, DbPacketCountByPortnum, DbDistinctRelayNode } from '../db/types.js';
// Configuration constants for traceroute history
const TRACEROUTE_HISTORY_LIMIT = 50;
const PENDING_TRACEROUTE_TIMEOUT_MS = 5 * 60 * 1000; // 5 minutes
export interface DbNode {
nodeNum: number;
nodeId: string;
longName: string;
shortName: string;
hwModel: number;
role?: number;
hopsAway?: number;
lastMessageHops?: number; // Hops from most recent packet (hopStart - hopLimit)
viaMqtt?: boolean;
macaddr?: string;
latitude?: number;
longitude?: number;
altitude?: number;
batteryLevel?: number;
voltage?: number;
channelUtilization?: number;
airUtilTx?: number;
lastHeard?: number;
snr?: number;
rssi?: number;
lastTracerouteRequest?: number;
firmwareVersion?: string;
channel?: number;
isFavorite?: boolean;
favoriteLocked?: boolean;
isIgnored?: boolean;
mobile?: number; // 0 = not mobile, 1 = mobile (moved >100m)
rebootCount?: number;
publicKey?: string;
hasPKC?: boolean;
lastPKIPacket?: number;
keyIsLowEntropy?: boolean;
duplicateKeyDetected?: boolean;
keyMismatchDetected?: boolean;
lastMeshReceivedKey?: string | null;
keySecurityIssueDetails?: string;
welcomedAt?: number;
// Position precision tracking (Migration 020)
positionChannel?: number; // Which channel the position came from
positionPrecisionBits?: number; // Position precision (0-32 bits, higher = more precise)
positionGpsAccuracy?: number; // GPS accuracy in meters
positionHdop?: number; // Horizontal Dilution of Precision
positionTimestamp?: number; // When this position was received (for upgrade/downgrade logic)
// Position override (Migration 040, updated in Migration 047 to boolean)
positionOverrideEnabled?: boolean; // false = disabled, true = enabled
latitudeOverride?: number; // Override latitude
longitudeOverride?: number; // Override longitude
altitudeOverride?: number; // Override altitude
positionOverrideIsPrivate?: boolean; // Override privacy (false = public, true = private)
// Remote admin discovery (Migration 055)
hasRemoteAdmin?: boolean; // Has remote admin access
lastRemoteAdminCheck?: number; // Unix timestamp ms of last check
remoteAdminMetadata?: string; // JSON string of metadata response
createdAt: number;
updatedAt: number;
}
export interface DbMessage {
id: string;
fromNodeNum: number;
toNodeNum: number;
fromNodeId: string;
toNodeId: string;
text: string;
channel: number;
portnum?: number;
requestId?: number;
timestamp: number;
rxTime?: number;
hopStart?: number;
hopLimit?: number;
relayNode?: number;
replyId?: number;
emoji?: number;
viaMqtt?: boolean;
rxSnr?: number;
rxRssi?: number;
createdAt: number;
ackFailed?: boolean;
deliveryState?: string;
wantAck?: boolean;
routingErrorReceived?: boolean;
ackFromNode?: number;
decryptedBy?: 'node' | 'server' | null;
}
export interface DbChannel {
id: number;
name: string;
psk?: string;
role?: number; // 0=Disabled, 1=Primary, 2=Secondary
uplinkEnabled: boolean;
downlinkEnabled: boolean;
positionPrecision?: number; // Location precision bits (0-32)
createdAt: number;
updatedAt: number;
}
export interface DbTelemetry {
id?: number;
nodeId: string;
nodeNum: number;
telemetryType: string;
timestamp: number;
value: number;
unit?: string;
createdAt: number;
packetTimestamp?: number; // Original timestamp from the packet (may be inaccurate if node has wrong time)
packetId?: number; // Meshtastic meshPacket.id for deduplication
// Position precision tracking metadata (Migration 020)
channel?: number; // Which channel this telemetry came from
precisionBits?: number; // Position precision bits (for latitude/longitude telemetry)
gpsAccuracy?: number; // GPS accuracy in meters (for position telemetry)
}
export interface DbTraceroute {
id?: number;
fromNodeNum: number;
toNodeNum: number;
fromNodeId: string;
toNodeId: string;
route: string;
routeBack: string;
snrTowards: string;
snrBack: string;
timestamp: number;
createdAt: number;
}
export interface DbRouteSegment {
id?: number;
fromNodeNum: number;
toNodeNum: number;
fromNodeId: string;
toNodeId: string;
distanceKm: number;
isRecordHolder: boolean;
timestamp: number;
createdAt: number;
}
export interface DbNeighborInfo {
id?: number;
nodeNum: number;
neighborNodeNum: number;
snr?: number;
lastRxTime?: number;
timestamp: number;
createdAt: number;
}
export interface DbPushSubscription {
id?: number;
userId?: number;
endpoint: string;
p256dhKey: string;
authKey: string;
userAgent?: string;
createdAt: number;
updatedAt: number;
lastUsedAt?: number;
}
// Re-export DbPacketLog from canonical db/types location
export type DbPacketLog = DbTypesPacketLog;
export type { DbPacketCountByNode, DbPacketCountByPortnum, DbDistinctRelayNode };
export interface DbCustomTheme {
id?: number;
name: string;
slug: string;
definition: string; // JSON string of theme colors
is_builtin: number; // SQLite uses 0/1 for boolean
created_by?: number;
created_at: number;
updated_at: number;
}
export interface ThemeDefinition {
base: string;
mantle: string;
crust: string;
text: string;
subtext1: string;
subtext0: string;
overlay2: string;
overlay1: string;
overlay0: string;
surface2: string;
surface1: string;
surface0: string;
lavender: string;
blue: string;
sapphire: string;
sky: string;
teal: string;
green: string;
yellow: string;
peach: string;
maroon: string;
red: string;
mauve: string;
pink: string;
flamingo: string;
rosewater: string;
// Optional chat bubble color overrides
chatBubbleSentBg?: string;
chatBubbleSentText?: string;
chatBubbleReceivedBg?: string;
chatBubbleReceivedText?: string;
}
class DatabaseService {
public db: BetterSqlite3Database.Database;
private isInitialized = false;
public userModel: UserModel;
public permissionModel: PermissionModel;
public apiTokenModel: APITokenModel;
// Cache for telemetry types per node (expensive GROUP BY query)
private telemetryTypesCache: Map<string, string[]> | null = null;
private telemetryTypesCacheTime: number = 0;
private static readonly TELEMETRY_TYPES_CACHE_TTL_MS = 60000; // 60 seconds
// Drizzle ORM database and repositories (for async operations and PostgreSQL/MySQL support)
private drizzleDatabase: Database | null = null;
public drizzleDbType: DatabaseType = 'sqlite';
private postgresPool: import('pg').Pool | null = null;
private mysqlPool: import('mysql2/promise').Pool | null = null;
// Promise that resolves when async initialization (PostgreSQL/MySQL) is complete
private readyPromise: Promise<void>;
private readyResolve!: () => void;
private readyReject!: (error: Error) => void;
private isReady = false;
// In-memory caches for PostgreSQL/MySQL (sync method compatibility)
// These caches allow sync methods like getSetting() and getNode() to work
// with async databases by caching data loaded at startup
private settingsCache: Map<string, string> = new Map();
private nodesCache: Map<number, DbNode> = new Map();
private channelsCache: Map<number, DbChannel> = new Map();
private _traceroutesCache: DbTraceroute[] = [];
private _traceroutesByNodesCache: Map<string, DbTraceroute[]> = new Map();
private cacheInitialized = false;
// Track nodes that have already had their "new node" notification sent
// to avoid duplicate notifications when node data is updated incrementally
private newNodeNotifiedSet: Set<number> = new Set();
// Ghost node suppression: nodeNum → expiresAt timestamp
// Prevents resurrection of ghost nodes after reboot detection
private suppressedGhostNodes: Map<number, number> = new Map();
/**
* Get the Drizzle database instance for direct access if needed
*/
getDrizzleDb(): Database | null {
return this.drizzleDatabase;
}
/**
* Get the PostgreSQL pool for direct queries (returns null for non-PostgreSQL)
*/
getPostgresPool(): import('pg').Pool | null {
return this.postgresPool;
}
/**
* Get the MySQL pool for direct queries (returns null for non-MySQL)
*/
getMySQLPool(): import('mysql2/promise').Pool | null {
return this.mysqlPool;
}
/**
* Get the current database type (sqlite, postgres, or mysql)
*/
getDatabaseType(): DatabaseType {
return this.drizzleDbType;
}
/**
* Get database version string
*/
async getDatabaseVersion(): Promise<string> {
try {
if (this.drizzleDbType === 'postgres' && this.postgresPool) {
const result = await this.postgresPool.query('SELECT version()');
const fullVersion = result.rows?.[0]?.version || 'Unknown';
// Extract just the version number from "PostgreSQL 16.2 (Debian 16.2-1.pgdg120+2) on x86_64-pc-linux-gnu..."
const match = fullVersion.match(/PostgreSQL\s+([\d.]+)/);
return match ? match[1] : fullVersion.split(' ').slice(0, 2).join(' ');
} else if (this.drizzleDbType === 'mysql' && this.mysqlPool) {
const [rows] = await this.mysqlPool.query('SELECT version() as version');
return (rows as any[])?.[0]?.version || 'Unknown';
} else if (this.db) {
const result = this.db.prepare('SELECT sqlite_version() as version').get() as { version: string } | undefined;
return result?.version || 'Unknown';
}
return 'Unknown';
} catch (error) {
logger.error('[DatabaseService] Failed to get database version:', error);
return 'Unknown';
}
}
/**
* Wait for the database to be fully initialized
* For SQLite, this resolves immediately
* For PostgreSQL/MySQL, this waits for async schema creation and repo initialization
*/
async waitForReady(): Promise<void> {
if (this.isReady) {
return;
}
return this.readyPromise;
}
/**
* Check if the database is ready (sync check)
*/
isDatabaseReady(): boolean {
return this.isReady;
}
// Repositories - will be initialized after Drizzle connection
public settingsRepo: SettingsRepository | null = null;
public channelsRepo: ChannelsRepository | null = null;
public nodesRepo: NodesRepository | null = null;
public messagesRepo: MessagesRepository | null = null;
public telemetryRepo: TelemetryRepository | null = null;
public authRepo: AuthRepository | null = null;
public traceroutesRepo: TraceroutesRepository | null = null;
public neighborsRepo: NeighborsRepository | null = null;
public notificationsRepo: NotificationsRepository | null = null;
public miscRepo: MiscRepository | null = null;
public channelDatabaseRepo: ChannelDatabaseRepository | null = null;
public ignoredNodesRepo: IgnoredNodesRepository | null = null;
public embedProfileRepo: EmbedProfileRepository | null = null;
/**
* Typed repository accessors — throw if database not initialized.
* Prefer these over the nullable public fields.
*/
get nodes(): NodesRepository {
if (!this.nodesRepo) throw new Error('Database not initialized');
return this.nodesRepo;
}
get messages(): MessagesRepository {
if (!this.messagesRepo) throw new Error('Database not initialized');
return this.messagesRepo;
}
get channels(): ChannelsRepository {
if (!this.channelsRepo) throw new Error('Database not initialized');
return this.channelsRepo;
}
get settings(): SettingsRepository {
if (!this.settingsRepo) throw new Error('Database not initialized');
return this.settingsRepo;
}
get telemetry(): TelemetryRepository {
if (!this.telemetryRepo) throw new Error('Database not initialized');
return this.telemetryRepo;
}
get traceroutes(): TraceroutesRepository {
if (!this.traceroutesRepo) throw new Error('Database not initialized');
return this.traceroutesRepo;
}
get neighbors(): NeighborsRepository {
if (!this.neighborsRepo) throw new Error('Database not initialized');
return this.neighborsRepo;
}
get auth(): AuthRepository {
if (!this.authRepo) throw new Error('Database not initialized');
return this.authRepo;
}
get notifications(): NotificationsRepository {
if (!this.notificationsRepo) throw new Error('Database not initialized');
return this.notificationsRepo;
}
get misc(): MiscRepository {
if (!this.miscRepo) throw new Error('Database not initialized');
return this.miscRepo;
}
get channelDatabase(): ChannelDatabaseRepository {
if (!this.channelDatabaseRepo) throw new Error('Database not initialized');
return this.channelDatabaseRepo;
}
get ignoredNodes(): IgnoredNodesRepository {
if (!this.ignoredNodesRepo) throw new Error('Database not initialized');
return this.ignoredNodesRepo;
}
get embedProfiles(): EmbedProfileRepository {
if (!this.embedProfileRepo) throw new Error('Database not initialized');
return this.embedProfileRepo;
}
constructor() {
logger.debug('🔧🔧🔧 DatabaseService constructor called');
// Initialize the ready promise - will be resolved when async initialization is complete
this.readyPromise = new Promise<void>((resolve, reject) => {
this.readyResolve = resolve;
this.readyReject = reject;
});
// Check database type FIRST before any initialization
const dbConfig = getDatabaseConfig();
const dbPath = getEnvironmentConfig().databasePath;
// For PostgreSQL or MySQL, skip SQLite initialization entirely
if (dbConfig.type === 'postgres' || dbConfig.type === 'mysql') {
logger.info(`📦 Using ${dbConfig.type === 'postgres' ? 'PostgreSQL' : 'MySQL'} database - skipping SQLite initialization`);
// Set drizzleDbType IMMEDIATELY so sync methods know we're using PostgreSQL/MySQL
// This is critical for methods like getSetting that check this before the async init completes
this.drizzleDbType = dbConfig.type;
// Create a dummy SQLite db object that will throw helpful errors if used
// This ensures code that accidentally uses this.db will fail fast
this.db = new Proxy({} as BetterSqlite3Database.Database, {
get: (_target, prop) => {
if (prop === 'exec' || prop === 'prepare' || prop === 'pragma') {
return () => {
throw new Error(`SQLite method '${String(prop)}' called but using ${dbConfig.type} database. Use Drizzle repositories instead.`);
};
}
return undefined;
},
});
// Models will not work with PostgreSQL/MySQL - they need to be migrated to use repositories
// For now, create them with the proxy db - they'll throw errors if used
this.userModel = new UserModel(this.db);
this.permissionModel = new PermissionModel(this.db);
this.apiTokenModel = new APITokenModel(this.db);
// Initialize Drizzle repositories (async) - this will create the schema
// The readyPromise will be resolved when this completes
this.initializeDrizzleRepositoriesForPostgres(dbPath);
// Skip SQLite-specific initialization
this.isInitialized = true;
return;
}
// SQLite initialization (existing code)
logger.debug('Initializing SQLite database at:', dbPath);
// Validate database directory access
const dbDir = path.dirname(dbPath);
try {
// Ensure the directory exists
if (!fs.existsSync(dbDir)) {
logger.debug(`Creating database directory: ${dbDir}`);
fs.mkdirSync(dbDir, { recursive: true });
}
// Verify directory is writable
fs.accessSync(dbDir, fs.constants.W_OK | fs.constants.R_OK);
// If database file exists, verify it's readable and writable
if (fs.existsSync(dbPath)) {
fs.accessSync(dbPath, fs.constants.W_OK | fs.constants.R_OK);
}
} catch (error: unknown) {
const err = error as { code?: string; message?: string };
logger.error('❌ DATABASE STARTUP ERROR ❌');
logger.error('═══════════════════════════════════════════════════════════');
logger.error('Failed to access database directory or file');
logger.error('');
logger.error(`Database path: ${dbPath}`);
logger.error(`Database directory: ${dbDir}`);
logger.error('');
if (err.code === 'EACCES' || err.code === 'EPERM') {
logger.error('PERMISSION DENIED - The database directory or file is not writable.');
logger.error('');
logger.error('For Docker deployments:');
logger.error(' 1. Check that your volume mount exists and is writable');
logger.error(' 2. Verify permissions on the host directory:');
logger.error(` chmod -R 755 /path/to/your/data/directory`);
logger.error(' 3. Example volume mount in docker-compose.yml:');
logger.error(' volumes:');
logger.error(' - ./meshmonitor-data:/data');
logger.error('');
logger.error('For bare metal deployments:');
logger.error(' 1. Ensure the data directory exists and is writable:');
logger.error(` mkdir -p ${dbDir}`);
logger.error(` chmod 755 ${dbDir}`);
} else if (err.code === 'ENOENT') {
logger.error('DIRECTORY NOT FOUND - Failed to create database directory.');
logger.error('');
logger.error('This usually means the parent directory does not exist or is not writable.');
logger.error(`Check that the parent directory exists: ${path.dirname(dbDir)}`);
} else {
logger.error(`Error: ${err.message}`);
logger.error(`Error code: ${err.code || 'unknown'}`);
}
logger.error('═══════════════════════════════════════════════════════════');
throw new Error(`Database directory access check failed: ${err.message}`);
}
// Now attempt to open the database with better error handling
this.db = this.openSqliteDatabase(dbPath, dbDir);
// Initialize models
this.userModel = new UserModel(this.db);
this.permissionModel = new PermissionModel(this.db);
this.apiTokenModel = new APITokenModel(this.db);
// Initialize Drizzle ORM and repositories
// This uses the same database file but through Drizzle for async operations
this.initializeDrizzleRepositories(dbPath);
this.initialize();
// Channel 0 will be created automatically when the device syncs its configuration
// Always ensure broadcast node exists for channel messages
this.ensureBroadcastNode();
// Ensure admin user exists for authentication
this.ensureAdminUser();
// SQLite is ready immediately after sync initialization
this.isReady = true;
this.readyResolve();
}
/**
* Initialize Drizzle ORM and all repositories
* This provides async database operations and supports both SQLite and PostgreSQL
*/
private initializeDrizzleRepositories(dbPath: string): void {
// Note: We call this synchronously but handle async PostgreSQL init via Promise
this.initializeDrizzleRepositoriesAsync(dbPath).catch((error) => {
logger.warn('[DatabaseService] Failed to initialize Drizzle repositories:', error);
logger.warn('[DatabaseService] Async repository methods will not be available');
});
}
/**
* Initialize Drizzle ORM for PostgreSQL/MySQL with proper ready promise handling
* This is used when NOT using SQLite - it sets up the async repos and resolves/rejects the readyPromise
*/
private initializeDrizzleRepositoriesForPostgres(dbPath: string): void {
this.initializeDrizzleRepositoriesAsync(dbPath)
.then(() => {
logger.info('[DatabaseService] PostgreSQL/MySQL initialization complete - database is ready');
this.isReady = true;
this.readyResolve();
// Ensure admin and anonymous users exist (same as SQLite path)
this.ensureAdminUser();
})
.catch((error) => {
logger.error('[DatabaseService] Failed to initialize PostgreSQL/MySQL:', error);
this.readyReject(error instanceof Error ? error : new Error(String(error)));
});
}
/**
* Async initialization of Drizzle ORM repositories
*/
private async initializeDrizzleRepositoriesAsync(dbPath: string): Promise<void> {
try {
logger.debug('[DatabaseService] Initializing Drizzle ORM repositories');
// Check database configuration to determine which driver to use
const dbConfig = getDatabaseConfig();
let drizzleDb: Database;
if (dbConfig.type === 'postgres' && dbConfig.postgresUrl) {
// Use PostgreSQL driver
logger.info('[DatabaseService] Using PostgreSQL driver for Drizzle repositories');
const { db, pool } = await createPostgresDriver({
connectionString: dbConfig.postgresUrl,
maxConnections: dbConfig.postgresMaxConnections || 10,
ssl: dbConfig.postgresSsl || false,
});
drizzleDb = db;
this.postgresPool = pool;
this.drizzleDbType = 'postgres';
// Create PostgreSQL schema if tables don't exist
await this.createPostgresSchema(pool);
} else if (dbConfig.type === 'mysql' && dbConfig.mysqlUrl) {
// Use MySQL driver
logger.info('[DatabaseService] Using MySQL driver for Drizzle repositories');
const { db, pool } = await createMySQLDriver({
connectionString: dbConfig.mysqlUrl,
maxConnections: dbConfig.mysqlMaxConnections || 10,
});
drizzleDb = db;
this.mysqlPool = pool;
this.drizzleDbType = 'mysql';
// Create MySQL schema if tables don't exist
await this.createMySQLSchema(pool);
} else {
// Use SQLite driver (default)
const { db } = createSQLiteDriver({
databasePath: dbPath,
enableWAL: false, // Already enabled on main connection
enableForeignKeys: false, // Already enabled on main connection
});
drizzleDb = db;
this.drizzleDbType = 'sqlite';
}
this.drizzleDatabase = drizzleDb;
// Initialize all repositories
this.settingsRepo = new SettingsRepository(drizzleDb, this.drizzleDbType);
this.channelsRepo = new ChannelsRepository(drizzleDb, this.drizzleDbType);
this.nodesRepo = new NodesRepository(drizzleDb, this.drizzleDbType);
this.messagesRepo = new MessagesRepository(drizzleDb, this.drizzleDbType);
this.telemetryRepo = new TelemetryRepository(drizzleDb, this.drizzleDbType);
// Auth repo for all backends - Migration 012 aligned SQLite schema with Drizzle definitions
this.authRepo = new AuthRepository(drizzleDb, this.drizzleDbType);
this.traceroutesRepo = new TraceroutesRepository(drizzleDb, this.drizzleDbType);
this.neighborsRepo = new NeighborsRepository(drizzleDb, this.drizzleDbType);
this.notificationsRepo = new NotificationsRepository(drizzleDb, this.drizzleDbType);
this.miscRepo = new MiscRepository(drizzleDb, this.drizzleDbType);
this.channelDatabaseRepo = new ChannelDatabaseRepository(drizzleDb, this.drizzleDbType);
this.ignoredNodesRepo = new IgnoredNodesRepository(drizzleDb, this.drizzleDbType);
this.embedProfileRepo = new EmbedProfileRepository(drizzleDb, this.drizzleDbType);
logger.info('[DatabaseService] Drizzle repositories initialized successfully');
// Load caches for PostgreSQL/MySQL to enable sync method compatibility
if (this.drizzleDbType === 'postgres' || this.drizzleDbType === 'mysql') {
await this.loadCachesFromDatabase();
}
} catch (error) {
// Log but don't fail - repositories are optional during migration period
logger.warn('[DatabaseService] Failed to initialize Drizzle repositories:', error);
logger.warn('[DatabaseService] Async repository methods will not be available');
throw error;
}
}
/**
* Load settings and nodes caches from database for sync method compatibility
* This enables getSetting() and getNode() to work with PostgreSQL/MySQL
*/
private async loadCachesFromDatabase(): Promise<void> {
try {
logger.info('[DatabaseService] Loading caches for sync method compatibility...');
// Load all settings into cache
if (this.settingsRepo) {
const settings = await this.settingsRepo.getAllSettings();
this.settingsCache.clear();
for (const [key, value] of Object.entries(settings)) {
this.settingsCache.set(key, value);
}
logger.info(`[DatabaseService] Loaded ${this.settingsCache.size} settings into cache`);
}
// Load all nodes into cache
if (this.nodesRepo) {
const nodes = await this.nodesRepo.getAllNodes();
this.nodesCache.clear();
for (const node of nodes) {
// Convert from repo DbNode to local DbNode (null -> undefined conversion is safe)
// The types only differ in null vs undefined for optional fields
const localNode: DbNode = {
nodeNum: node.nodeNum,
nodeId: node.nodeId,
longName: node.longName ?? '',
shortName: node.shortName ?? '',
hwModel: node.hwModel ?? 0,
role: node.role ?? undefined,
hopsAway: node.hopsAway ?? undefined,
lastMessageHops: node.lastMessageHops ?? undefined,
viaMqtt: node.viaMqtt ?? undefined,
macaddr: node.macaddr ?? undefined,
latitude: node.latitude ?? undefined,
longitude: node.longitude ?? undefined,
altitude: node.altitude ?? undefined,
batteryLevel: node.batteryLevel ?? undefined,
voltage: node.voltage ?? undefined,
channelUtilization: node.channelUtilization ?? undefined,
airUtilTx: node.airUtilTx ?? undefined,
lastHeard: node.lastHeard ?? undefined,
snr: node.snr ?? undefined,
rssi: node.rssi ?? undefined,
lastTracerouteRequest: node.lastTracerouteRequest ?? undefined,
firmwareVersion: node.firmwareVersion ?? undefined,
channel: node.channel ?? undefined,
isFavorite: node.isFavorite ?? undefined,
favoriteLocked: node.favoriteLocked ?? undefined,
isIgnored: node.isIgnored ?? undefined,
mobile: node.mobile ?? undefined,
rebootCount: node.rebootCount ?? undefined,
publicKey: node.publicKey ?? undefined,
hasPKC: node.hasPKC ?? undefined,
lastPKIPacket: node.lastPKIPacket ?? undefined,
keyIsLowEntropy: node.keyIsLowEntropy ?? undefined,
duplicateKeyDetected: node.duplicateKeyDetected ?? undefined,
keyMismatchDetected: node.keyMismatchDetected ?? undefined,
keySecurityIssueDetails: node.keySecurityIssueDetails ?? undefined,
welcomedAt: node.welcomedAt ?? undefined,
positionChannel: node.positionChannel ?? undefined,
positionPrecisionBits: node.positionPrecisionBits ?? undefined,
positionGpsAccuracy: node.positionGpsAccuracy ?? undefined,
positionHdop: node.positionHdop ?? undefined,
positionTimestamp: node.positionTimestamp ?? undefined,
positionOverrideEnabled: node.positionOverrideEnabled ?? undefined,
latitudeOverride: node.latitudeOverride ?? undefined,
longitudeOverride: node.longitudeOverride ?? undefined,
altitudeOverride: node.altitudeOverride ?? undefined,
positionOverrideIsPrivate: node.positionOverrideIsPrivate ?? undefined,
hasRemoteAdmin: node.hasRemoteAdmin ?? undefined,
lastRemoteAdminCheck: node.lastRemoteAdminCheck ?? undefined,
remoteAdminMetadata: node.remoteAdminMetadata ?? undefined,
createdAt: node.createdAt,
updatedAt: node.updatedAt,
};
this.nodesCache.set(node.nodeNum, localNode);
}
// Count nodes with welcomedAt set for auto-welcome diagnostics
const nodesWithWelcome = Array.from(this.nodesCache.values()).filter(n => n.welcomedAt !== null && n.welcomedAt !== undefined);
logger.info(`[DatabaseService] Loaded ${this.nodesCache.size} nodes into cache (${nodesWithWelcome.length} previously welcomed)`);
}
// Load all channels into cache
if (this.channelsRepo) {
const channels = await this.channelsRepo.getAllChannels();
this.channelsCache.clear();
for (const channel of channels) {
this.channelsCache.set(channel.id, channel);
}
logger.info(`[DatabaseService] Loaded ${this.channelsCache.size} channels into cache`);
}
// Load recent messages into cache for delivery state updates
if (this.messagesRepo) {
const messages = await this.messagesRepo.getMessages(500);
this._messagesCache = messages.map(m => this.convertRepoMessage(m));
logger.info(`[DatabaseService] Loaded ${this._messagesCache.length} messages into cache`);
}
// Load neighbor info into cache
if (this.neighborsRepo) {
const neighbors = await this.neighborsRepo.getAllNeighborInfo();
this._neighborsCache = neighbors.map(n => this.convertRepoNeighborInfo(n));
logger.info(`[DatabaseService] Loaded ${this._neighborsCache.length} neighbor records into cache`);
}
this.cacheInitialized = true;
logger.info('[DatabaseService] Caches loaded successfully');
} catch (error) {
logger.error('[DatabaseService] Failed to load caches:', error);
// Don't throw - caches are best-effort
}
}
private initialize(): void {
if (this.isInitialized) return;
// Pre-3.7 detection: check BEFORE createTables() so we can distinguish
// an existing pre-v3.7 database from a fresh install.
// If settings table already exists at this point, it's from a previous installation.
const settingsExists = this.db.prepare(
"SELECT name FROM sqlite_master WHERE type='table' AND name='settings'"
).all();
if (settingsExists.length > 0) {
// Check for v3.7+ markers: either the old migration_077 key (pre-clean-break)
// or the new migration_078 key (post-clean-break baseline)
const v37Key = this.db.prepare(
"SELECT value FROM settings WHERE key IN ('migration_077_ignored_nodes_nodenum_bigint', 'migration_078_create_embed_profiles')"
).get();
if (!v37Key) {
logger.error('This version requires MeshMonitor v3.7 or later.');
logger.error('Please upgrade to v3.7 first, then upgrade to this version.');
throw new Error('Database is pre-v3.7. Please upgrade to v3.7 first.');
}
}
this.createTables();
this.migrateSchema();
this.createIndexes();
this.runDataMigrations();
// Run all registered SQLite migrations via the migration registry
for (const migration of registry.getAll()) {
if (!migration.sqlite) continue;
try {
if (migration.selfIdempotent) {
// Old-style migrations (001-046) handle their own idempotency
migration.sqlite(this.db,
(key: string) => this.getSetting(key),
(key: string, value: string) => this.setSetting(key, value)
);
} else if (migration.settingsKey) {
// New-style migrations use settings key guard
if (this.getSetting(migration.settingsKey) !== 'completed') {
logger.debug(`Running migration ${String(migration.number).padStart(3, '0')}: ${migration.name}...`);
migration.sqlite(this.db,
(key: string) => this.getSetting(key),
(key: string, value: string) => this.setSetting(key, value)
);
this.setSetting(migration.settingsKey, 'completed');
logger.debug(`Migration ${String(migration.number).padStart(3, '0')} completed successfully`);
}
}
} catch (error) {
logger.error(`Error running migration ${String(migration.number).padStart(3, '0')} (${migration.name}):`, error);
throw error;
}
}
this.ensureAutomationDefaults();
this.warmupCaches();
this.isInitialized = true;
}
// Warm up caches on startup to avoid cold cache latency on first request
private warmupCaches(): void {
try {
logger.debug('🔥 Warming up database caches...');
// Pre-populate the telemetry types cache
this.getAllNodesTelemetryTypes();
logger.debug('✅ Cache warmup complete');
} catch (error) {
// Cache warmup failure is non-critical - cache will populate on first request
logger.warn('⚠️ Cache warmup failed (non-critical):', error);
}
}
private ensureAutomationDefaults(): void {
logger.debug('Ensuring automation default settings...');
try {
// Only set defaults if they don't exist
const automationSettings = {
autoAckEnabled: 'false',
autoAckRegex: '^(test|ping)',
autoAckUseDM: 'false',
autoAckTapbackEnabled: 'false',
autoAckReplyEnabled: 'true',
// New direct/multihop settings - default to true for backward compatibility
autoAckDirectEnabled: 'true',
autoAckDirectTapbackEnabled: 'true',
autoAckDirectReplyEnabled: 'true',
autoAckMultihopEnabled: 'true',
autoAckMultihopTapbackEnabled: 'true',
autoAckMultihopReplyEnabled: 'true',
autoAnnounceEnabled: 'false',
autoAnnounceIntervalHours: '6',
autoAnnounceMessage: 'MeshMonitor {VERSION} online for {DURATION} {FEATURES}',
autoAnnounceChannelIndexes: '[0]',
autoAnnounceOnStart: 'false',
autoAnnounceUseSchedule: 'false',
autoAnnounceSchedule: '0 */6 * * *',
tracerouteIntervalMinutes: '0',
autoUpgradeImmediate: 'false',
autoTimeSyncEnabled: 'false',
autoTimeSyncIntervalMinutes: '15',
autoTimeSyncExpirationHours: '24',
autoTimeSyncNodeFilterEnabled: 'false'
};
Object.entries(automationSettings).forEach(([key, defaultValue]) => {
const existing = this.getSetting(key);
if (existing === null) {
this.setSetting(key, defaultValue);
logger.debug(`✅ Set default for ${key}: ${defaultValue}`);
}
});
logger.debug('✅ Automation defaults ensured');
} catch (error) {
logger.error('❌ Failed to ensure automation defaults:', error);
throw error;
}
}
private ensureBroadcastNode(): void {
logger.debug('🔍 ensureBroadcastNode() called');
try {
const broadcastNodeNum = 4294967295; // 0xFFFFFFFF
const broadcastNodeId = '!ffffffff';
const existingNode = this.getNode(broadcastNodeNum);
logger.debug('🔍 getNode(4294967295) returned:', existingNode);
if (!existingNode) {
logger.debug('🔍 No broadcast node found, creating it');
this.upsertNode({
nodeNum: broadcastNodeNum,
nodeId: broadcastNodeId,
longName: 'Broadcast',
shortName: 'BCAST'
});
// Verify it was created
const verify = this.getNode(broadcastNodeNum);
logger.debug('🔍 After upsert, getNode(4294967295) returns:', verify);
} else {
logger.debug(`✅ Broadcast node already exists`);
}
} catch (error) {
logger.error('❌ Error in ensureBroadcastNode:', error);
}
}
private createTables(): void {
logger.debug('Creating database tables (v3.7 complete schema)...');
// ============================================================
// CORE TABLES (matches 001_v37_baseline.ts exactly)
// ============================================================
this.db.exec(`
CREATE TABLE IF NOT EXISTS nodes (
nodeNum INTEGER PRIMARY KEY,
nodeId TEXT UNIQUE NOT NULL,
longName TEXT,
shortName TEXT,
hwModel INTEGER,
role INTEGER,
hopsAway INTEGER,
lastMessageHops INTEGER,
viaMqtt INTEGER,
macaddr TEXT,
latitude REAL,
longitude REAL,
altitude REAL,
batteryLevel INTEGER,
voltage REAL,
channelUtilization REAL,
airUtilTx REAL,
lastHeard INTEGER,
snr REAL,
rssi INTEGER,
lastTracerouteRequest INTEGER,
firmwareVersion TEXT,
channel INTEGER,
isFavorite INTEGER DEFAULT 0,
favoriteLocked INTEGER DEFAULT 0,
isIgnored INTEGER DEFAULT 0,
mobile INTEGER DEFAULT 0,
rebootCount INTEGER,
publicKey TEXT,