-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathdatabases.ts
More file actions
1422 lines (1363 loc) · 51.9 KB
/
Copy pathdatabases.ts
File metadata and controls
1422 lines (1363 loc) · 51.9 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 { EventEmitter } from 'node:events';
import { initSync, getHdbBasePath, get as envGet } from '../utility/environment/environmentManager.js';
import { INTERNAL_DBIS_NAME } from '../utility/lmdb/terms.js';
import { open, compareKeys, type Database, type RootDatabase } from 'lmdb';
import { join, extname, basename } from 'path';
import { existsSync, readdirSync, readFileSync, mkdirSync } from 'node:fs';
import { unlink } from 'node:fs/promises';
import {
getBaseSchemaPath,
getTransactionAuditStoreBasePath,
} from '../dataLayer/harperBridge/lmdbBridge/lmdbUtility/initializePaths.js';
import { makeTable } from './Table.ts';
import OpenEnvironmentObject from '../utility/lmdb/OpenEnvironmentObject.js';
import { CONFIG_PARAMS, LEGACY_DATABASES_DIR_NAME, DATABASES_DIR_NAME } from '../utility/hdbTerms.ts';
import { getConfigPath } from '../config/configUtils.js';
import { _assignPackageExport } from '../globals.js';
import { getIndexedValues } from '../utility/lmdb/commonUtility.js';
import * as signalling from '../utility/signalling.js';
import { SchemaEventMsg } from '../server/threads/itc.js';
import { workerData } from 'worker_threads';
import harperLogger from '../utility/logging/harper_logger.js';
const { forComponent } = harperLogger;
import * as manageThreads from '../server/threads/manageThreads.js';
import { openAuditStore, readAuditEntry, createAuditEntry, type AuditRecord } from './auditStore.ts';
import { handleLocalTimeForGets, IndexRecordEncoder } from './RecordEncoder.ts';
import { deleteRootBlobPathsForDB } from './blob.ts';
import { CUSTOM_INDEXES } from './indexes/customIndexes.ts';
import { OpenDBIObject } from '../utility/lmdb/OpenDBIObject.js';
import { RocksDatabase, type RocksDatabaseOptions } from '@harperfast/rocksdb-js';
import { replayLogs } from './replayLogs.ts';
import { totalmem } from 'node:os';
import { RocksIndexStore } from './RocksIndexStore.ts';
import { when } from '../utility/when.ts';
import { isProcessRunning } from '../utility/processManagement/processManagement.js';
function createOpenDBIObject(dupSort = false, isPrimary = false) {
return new OpenDBIObject(dupSort, isPrimary);
}
const logger = forComponent('storage');
const DEFAULT_DATABASE_NAME = 'data';
const DEFINED_TABLES = Symbol('defined-tables');
const DEFAULT_COMPRESSION_THRESHOLD = (envGet(CONFIG_PARAMS.STORAGE_PAGESIZE) || 4096) - 60; // larger than this requires multiple pages
initSync();
// I don't know if this is the best place for this, but somewhere we need to specify which tables
// replicate by default:
export const NON_REPLICATING_SYSTEM_TABLES = [
'hdb_temp',
'hdb_certificate',
'hdb_raw_analytics',
'hdb_session_will',
'hdb_job',
'hdb_info',
];
export type Table = ReturnType<typeof makeTable> & {
indexingOperation?: any;
origin?: string;
schemaVersion?: number;
};
export interface Tables {
[tableName: string]: Table;
[DEFINED_TABLES]?: Set<string>;
}
export interface Databases {
[databaseName: string]: Tables;
}
// note: technically `Database` is either a `LMDBStore` or a `CachingStore`
interface LMDBDatabase extends Database {
customIndex?: any;
isIndexing?: boolean;
indexNulls?: boolean;
}
interface LMDBRootDatabase extends RootDatabase {
auditStore?: LMDBRootDatabase;
databaseName?: string;
dbisDb?: LMDBDatabase;
isLegacy?: boolean;
needsDeletion?: boolean;
path?: string;
status?: 'open' | 'closed';
}
interface RocksDatabaseEx extends RocksDatabase {
customIndex?: any;
env: Record<string, any>;
isLegacy?: boolean;
isIndexing?: boolean;
indexNulls?: boolean;
getEntry?: (id: string | number | (string | number)[] | Buffer, options?: any) => { value: any };
}
interface RocksRootDatabase extends RocksDatabaseEx {
auditStore?: RocksDatabaseEx;
databaseName?: string;
dbisDb?: RocksDatabaseEx;
}
export type RootDatabaseKind = LMDBRootDatabase | RocksRootDatabase;
export type DatabaseWatcherEventMap = {
updateTable: [table: Table, originIsNotCluster?: boolean];
dropTable: [tableName: string, databaseName: string];
dropDatabase: [databaseName: string];
};
export const databaseEventsEmitter = new EventEmitter<DatabaseWatcherEventMap>();
export const tables: Tables = Object.create(null);
export const databases: Databases = Object.create(null);
function openRocksDatabase(path: string, options: RocksDatabaseOptions & { dupSort?: boolean }) {
options.disableWAL ??= true;
// Read RocksDB memory config lazily so env/CLI overrides applied after module load are
// respected. The block cache falls back to 25% of constrained (cgroup) memory when not
// configured; the WriteBufferManager is opt-in (0 disables).
//
// We enforce types rather than coerce — values from YAML config and env vars flow
// through configUtils.castConfigValue which produces proper numbers/booleans/null,
// so anything else is misconfiguration and should fall through to the default.
//
// Note: writeBufferManagerCostToCache and writeBufferManagerAllowStall are fixed at WBM
// creation time inside rocksdb-js (the underlying RocksDB API doesn't support changing
// costToCache on a live manager, and allowStall is only re-applied when explicitly changed).
// In practice that's fine — these come from process-level config that doesn't change.
const configuredBlockCacheSize = envGet(CONFIG_PARAMS.STORAGE_ROCKS_BLOCKCACHESIZE);
const blockCacheSize =
typeof configuredBlockCacheSize === 'number' && configuredBlockCacheSize > 0
? configuredBlockCacheSize
: Math.min(process.constrainedMemory?.() ?? Infinity, totalmem()) * 0.25;
const writeBufferManagerSize = envGet(CONFIG_PARAMS.STORAGE_ROCKS_WRITEBUFFERMANAGERSIZE);
const writeBufferManagerCostToCache = envGet(CONFIG_PARAMS.STORAGE_ROCKS_WRITEBUFFERMANAGERCOSTTOCACHE);
const writeBufferManagerAllowStall = envGet(CONFIG_PARAMS.STORAGE_ROCKS_WRITEBUFFERMANAGERALLOWSTALL);
RocksDatabase.config({
blockCacheSize,
...(typeof writeBufferManagerSize === 'number' && writeBufferManagerSize > 0
? { writeBufferManagerSize }
: {}),
...(typeof writeBufferManagerCostToCache === 'boolean'
? { writeBufferManagerCostToCache }
: {}),
...(typeof writeBufferManagerAllowStall === 'boolean'
? { writeBufferManagerAllowStall }
: {}),
});
if (!existsSync(path)) {
mkdirSync(path, { recursive: true });
}
let db: RocksRootDatabase;
if (options.dupSort) {
db = new RocksIndexStore(path, options).open() as RocksDatabaseEx;
} else {
db = RocksDatabase.open(path, options) as RocksDatabaseEx;
// the RocksDB put and remove return promises, which masks thrown errors in non-awaiting calls to put/remove,
// making them unsafe to replace LMDB methods, which will synchronously throw errors if there is a problem
db.put = db.putSync;
db.remove = db.removeSync;
db.encoder.name = options.name;
}
db.env = {};
return db;
}
const lmdbDatabaseEnvs = new Map<string, LMDBRootDatabase>();
const rocksdbDatabaseEnvs = new Map<string, RocksDatabaseEx>();
// set the following in both global and exports
_assignPackageExport('databases', databases);
_assignPackageExport('tables', tables);
const NEXT_TABLE_ID = Symbol.for('next-table-id');
let loadedDatabases; // indicates if we have loaded databases from the file system yet
// This is used to track all the databases that are found when iterating through the file system so that anything that is missing
// can be removed:
let definedDatabases: Map<string, Set<string>>;
/**
* This gets the set of tables from the default database ("data").
*/
export function getTables(): Tables {
if (!loadedDatabases) {
getDatabases();
}
return tables || {};
}
/**
* This provides the main entry point for getting the set of all Harper tables (organized by schemas/databases).
* This proactively scans the known
* databases/schemas directories and finds any databases and opens them. This done proactively so that there is a fast
* object available to all consumers that doesn't require runtime checks for database open states.
* This also attaches the audit store associated with table. Note that legacy tables had a single audit table per db table
* but in newer multi-table databases, there is one consistent, integrated audit table for the database since transactions
* can span any tables in the database.
*/
export function getDatabases(): Databases {
if (loadedDatabases) {
return databases;
}
loadedDatabases = true;
definedDatabases = new Map();
const hdbBasePath = getHdbBasePath();
let databasePath = hdbBasePath && join(hdbBasePath, DATABASES_DIR_NAME);
const schemaConfigs = envGet(CONFIG_PARAMS.DATABASES) || {};
// not sure why this doesn't work with the environmemt manager
if (process.env.SCHEMAS_DATA_PATH) schemaConfigs.data = { path: process.env.SCHEMAS_DATA_PATH };
databasePath =
process.env.STORAGE_PATH ||
getConfigPath(CONFIG_PARAMS.STORAGE_PATH) ||
(databasePath && (existsSync(databasePath) ? databasePath : join(getHdbBasePath(), LEGACY_DATABASES_DIR_NAME)));
if (!databasePath) return;
if (existsSync(databasePath)) {
// First load all the databases from our main database folder
// TODO: Load any databases defined with explicit storage paths from the config
for (const databaseEntry of readdirSync(databasePath, { withFileTypes: true })) {
const dbName = basename(databaseEntry.name, '.mdb');
const dbPath = join(databasePath, databaseEntry.name);
if (
databaseEntry.isFile() &&
extname(databaseEntry.name).toLowerCase() === '.mdb' &&
!schemaConfigs[dbName]?.path
) {
logger.trace(`loading lmdb database: ${dbPath}`);
readMetaDb(dbPath, null, dbName);
continue;
}
try {
const files = readdirSync(dbPath, { withFileTypes: true });
if (
files.find((file) => file.name === 'CURRENT')?.isFile() &&
files.some((file) => file.name.startsWith('MANIFEST-')) &&
!schemaConfigs[dbName]?.path
) {
readRocksMetaDb(dbPath, null, dbName);
continue;
}
} catch (err) {
if (!('code' in err && (err.code === 'ENOENT' || err.code === 'ENOTDIR'))) {
throw err;
}
}
}
}
// now we load databases from the legacy "schema" directory folder structure
const baseSchemaPath = getBaseSchemaPath();
if (existsSync(baseSchemaPath)) {
for (const schemaEntry of readdirSync(baseSchemaPath, { withFileTypes: true })) {
if (!schemaEntry.isFile()) {
const schemaPath = join(baseSchemaPath, schemaEntry.name);
const schemaAuditPath = join(getTransactionAuditStoreBasePath(), schemaEntry.name);
for (const tableEntry of readdirSync(schemaPath, { withFileTypes: true })) {
if (tableEntry.isFile() && extname(tableEntry.name).toLowerCase() === '.mdb') {
const auditPath = join(schemaAuditPath, tableEntry.name);
readMetaDb(
join(schemaPath, tableEntry.name),
basename(tableEntry.name, '.mdb'),
schemaEntry.name,
auditPath,
true
);
}
}
}
}
}
if (schemaConfigs) {
for (const dbName in schemaConfigs) {
const schemaConfig = schemaConfigs[dbName];
const databasePath = schemaConfig.path;
if (existsSync(databasePath)) {
for (const databaseEntry of readdirSync(databasePath, { withFileTypes: true })) {
if (databaseEntry.isFile() && extname(databaseEntry.name).toLowerCase() === '.mdb') {
readMetaDb(join(databasePath, databaseEntry.name), basename(databaseEntry.name, '.mdb'), dbName);
} else {
try {
const dbPath = join(databasePath, databaseEntry.name);
const files = readdirSync(dbPath, { withFileTypes: true });
if (
files.find((file) => file.name === 'CURRENT')?.isFile() &&
files.some((file) => file.name.startsWith('MANIFEST-'))
) {
readRocksMetaDb(dbPath, null, dbName);
continue;
}
} catch (err) {
if (!('code' in err && (err.code === 'ENOENT' || err.code === 'ENOTDIR'))) {
throw err;
}
}
}
}
}
const tableConfigs = schemaConfig.tables;
if (tableConfigs) {
for (const tableName in tableConfigs) {
const tableConfig = tableConfigs[tableName];
const tablePath = join(tableConfig.path, basename(tableName + '.mdb'));
if (existsSync(tablePath)) {
readMetaDb(tablePath, tableName, dbName, null, true);
}
}
}
//TODO: Iterate configured table paths
}
}
// now remove any databases or tables that have been removed
for (const dbName in databases) {
const definedTables = definedDatabases.get(dbName);
if (definedTables) {
const tables = databases[dbName];
if (dbName.includes('delete')) logger.trace(`defined tables ${Array.from(definedTables.keys())}`);
for (const tableName in tables) {
if (!definedTables.has(tableName)) {
logger.trace(`delete table class ${tableName}`);
delete tables[tableName];
}
}
} else {
delete databases[dbName];
if (dbName === 'data') {
for (const tableName in tables) {
delete tables[tableName];
}
delete tables[DEFINED_TABLES];
}
}
}
if (envGet(CONFIG_PARAMS.ANALYTICS_REPLICATE) === false) {
if (!NON_REPLICATING_SYSTEM_TABLES.includes('hdb_analytics')) NON_REPLICATING_SYSTEM_TABLES.push('hdb_analytics');
} else {
// auditing must be enabled for replication
databases.system?.hdb_analytics?.enableAuditing();
databases.system?.hdb_analytics_hostname?.enableAuditing();
}
if (databases.system) {
for (const tableName of NON_REPLICATING_SYSTEM_TABLES) {
if (databases.system[tableName]) {
databases.system[tableName].replicate = false;
}
}
}
return databases;
}
/**
* This is responsible for reading the internal dbi of a single database file to get a list of all the tables and
* their indexed or registered attributes
* @param path
* @param defaultTable
* @param databaseName
*/
export function readMetaDb(
path: string,
defaultTable?: string,
databaseName: string = DEFAULT_DATABASE_NAME,
auditPath?: string,
isLegacy?: boolean
) {
const envInit = new OpenEnvironmentObject(path, false);
try {
let rootStore = lmdbDatabaseEnvs.get(path);
if (rootStore) {
rootStore.needsDeletion = false;
} else {
rootStore = open(envInit);
lmdbDatabaseEnvs.set(path, rootStore);
}
return initStores(path, rootStore, databaseName, defaultTable, auditPath, isLegacy);
} catch (error) {
error.message += ` opening database ${path}`;
throw error;
}
}
function readRocksMetaDb(path: string, defaultTable?: string, databaseName: string = DEFAULT_DATABASE_NAME) {
try {
logger.trace(`loading rocksdb database: ${path}`);
if (process.env.HARPER_PARENT_PROCESS_PID) {
const parentProcessPid = parseInt(process.env.HARPER_PARENT_PROCESS_PID);
if (isProcessRunning(parentProcessPid)) {
logger.info(`Parent process ${parentProcessPid} is still running!`);
}
}
let rootStore: RocksDatabaseEx | undefined = rocksdbDatabaseEnvs.get(path);
if (rootStore) {
initStores(path, rootStore, databaseName, defaultTable);
} else {
rootStore = openRocksDatabase(path, { disableWAL: false, enableStats: true }) as RocksDatabaseEx;
rocksdbDatabaseEnvs.set(path, rootStore);
initStores(path, rootStore, databaseName, defaultTable);
replayLogs(rootStore, databases[databaseName]);
}
return rootStore;
} catch (error) {
error.message += ` opening database ${path}`;
throw error;
}
}
function initStores(
path: string,
rootStore: RootDatabaseKind,
databaseName: string,
defaultTable?: string,
auditPath?: string,
isLegacy?: boolean
) {
const envInit = new OpenEnvironmentObject(path, false);
const internalDbiInit = createOpenDBIObject(false);
let attributesDbi = rootStore.dbisDb;
if (!attributesDbi) {
if (rootStore instanceof RocksDatabase) {
attributesDbi = openRocksDatabase(rootStore.path, {
...internalDbiInit,
disableWAL: false,
name: INTERNAL_DBIS_NAME,
}) as RocksDatabaseEx;
} else {
attributesDbi = rootStore.openDB(INTERNAL_DBIS_NAME, internalDbiInit);
}
rootStore.dbisDb = attributesDbi;
}
let auditStore = rootStore.auditStore;
if (!auditStore) {
if (auditPath) {
if (existsSync(auditPath)) {
envInit.path = auditPath;
if (rootStore instanceof RocksDatabase) {
auditStore = openAuditStore(rootStore);
} else {
auditStore = open({
...envInit,
encoder: {
encode: (auditRecord: AuditRecord) => createAuditEntry(auditRecord),
decode: (encoding: Buffer) => readAuditEntry(encoding),
},
});
}
auditStore.isLegacy = true;
}
} else {
auditStore = openAuditStore(rootStore);
}
}
const tables = ensureDB(databaseName);
const definedTables = tables[DEFINED_TABLES];
definedTables.rootStore = rootStore;
const tablesToLoad = new Map<string, any>();
for (const result of attributesDbi.getRange({ start: false })) {
const { key, value } = result as { key: string; value: any };
let [tableName, attribute_name] = key.toString().split('/');
if (attribute_name === '') {
// primary key
attribute_name = value.name;
} else if (!attribute_name) {
attribute_name = tableName;
tableName = defaultTable;
if (!value.name) {
// legacy attribute
value.name = attribute_name;
value.indexed = !value.isPrimaryKey;
}
}
definedTables?.add(tableName);
let tableDef = tablesToLoad.get(tableName);
if (!tableDef) tablesToLoad.set(tableName, (tableDef = { attributes: [] }));
if (attribute_name == null || value.isPrimaryKey) tableDef.primary = value;
if (attribute_name != null) tableDef.attributes.push(value);
Object.defineProperty(value, 'key', { value: key, configurable: true });
}
for (const [tableName, tableDef] of tablesToLoad) {
let { attributes, primary: primaryAttribute } = tableDef;
if (!primaryAttribute) {
// this isn't defined, find it in the attributes
for (const attribute of attributes) {
if (attribute.isPrimaryKey) {
primaryAttribute = attribute;
break;
}
}
if (!primaryAttribute) {
logger.warn(
`Unable to find a primary key attribute on table ${tableName}, with attributes: ${JSON.stringify(attributes)}`
);
continue;
}
}
// if the table has already been defined, use that class, don't create a new one
let table = tables[tableName];
// unless its store was migrated to a different engine (e.g. LMDB to RocksDB on startup)
const recreateForEngineChange =
!!table && (table as any).primaryStore?.rootStore instanceof RocksDatabase !== rootStore instanceof RocksDatabase;
let indices = {},
existingAttributes = [];
let tableId;
let primaryStore;
const audit =
typeof primaryAttribute.audit === 'boolean' ? primaryAttribute.audit : envGet(CONFIG_PARAMS.LOGGING_AUDITLOG);
const trackDeletes = primaryAttribute.trackDeletes;
const expiration = primaryAttribute.expiration;
const eviction = primaryAttribute.eviction;
const sealed = primaryAttribute.sealed;
const splitSegments = primaryAttribute.splitSegments;
const replicate = primaryAttribute.replicate;
if (table && !recreateForEngineChange) {
indices = table.indices;
existingAttributes = table.attributes;
table.schemaVersion++;
} else {
tableId = primaryAttribute.tableId;
if (tableId) {
if (tableId >= (attributesDbi.getSync(NEXT_TABLE_ID) || 0)) {
attributesDbi.putSync(NEXT_TABLE_ID, tableId + 1);
logger.info(`Updating next table id (it was out of sync) to ${tableId + 1} for ${tableName}`);
}
} else {
primaryAttribute.tableId = tableId = attributesDbi.getSync(NEXT_TABLE_ID);
if (!tableId) tableId = 1;
logger.debug(`Table {tableName} missing an id, assigning {tableId}`);
attributesDbi.putSync(NEXT_TABLE_ID, tableId + 1);
attributesDbi.putSync(primaryAttribute.key, primaryAttribute);
}
const dbiInit = createOpenDBIObject(!primaryAttribute.isPrimaryKey, primaryAttribute.isPrimaryKey);
dbiInit.compression = primaryAttribute.compression;
if (dbiInit.compression) {
const compressionThreshold =
envGet(CONFIG_PARAMS.STORAGE_COMPRESSION_THRESHOLD) || DEFAULT_COMPRESSION_THRESHOLD; // this is the only thing that can change;
dbiInit.compression.threshold = compressionThreshold;
}
if (rootStore instanceof RocksDatabase) {
primaryStore = handleLocalTimeForGets(
openRocksDatabase(rootStore.path, { ...dbiInit, name: primaryAttribute.key }),
rootStore
);
} else {
primaryStore = handleLocalTimeForGets(rootStore.openDB(primaryAttribute.key, dbiInit), rootStore);
}
rootStore.databaseName = databaseName;
primaryStore.tableId = tableId;
}
let attributesUpdated: boolean;
for (const attribute of attributes) {
attribute.attribute = attribute.name;
try {
// now load the non-primary keys, opening the dbs as necessary for indices
if (!attribute.isPrimaryKey && (attribute.indexed || (attribute.attribute && !attribute.name))) {
if (!indices[attribute.name]) {
const dbi = openIndex(attribute.key, rootStore, attribute);
indices[attribute.name] = dbi;
indices[attribute.name].indexNulls = attribute.indexNulls;
}
const existingAttribute = existingAttributes.find(
(existingAttribute) => existingAttribute.name === attribute.name
);
if (existingAttribute) existingAttributes.splice(existingAttributes.indexOf(existingAttribute), 1, attribute);
else existingAttributes.push(attribute);
attributesUpdated = true;
}
} catch (error) {
logger.error(`Error trying to update attribute`, attribute, existingAttributes, indices, error);
}
}
for (const existingAttribute of existingAttributes) {
const attribute = attributes.find((attribute) => attribute.name === existingAttribute.name);
if (!attribute) {
if (existingAttribute.isPrimaryKey) {
logger.error(
new Error('Unable to remove existing primary key attribute'),
existingAttribute,
'from attributes',
existingAttributes,
'in',
tableName,
'requesting new attribute list',
attributes,
'full metadata list',
Array.from(attributesDbi.getRange({ start: false }))
);
continue;
}
if (existingAttribute.indexed) {
// we only remove attributes if they were indexed, in order to support dropAttribute that removes dynamic indexed attributes
existingAttributes.splice(existingAttributes.indexOf(existingAttribute), 1);
attributesUpdated = true;
}
}
}
if (table && !recreateForEngineChange) {
if (attributesUpdated) {
table.schemaVersion++;
table.updatedAttributes();
}
} else {
table = setTable(
tables,
tableName,
makeTable({
primaryStore,
auditStore,
audit,
sealed,
splitSegments,
replicate,
expirationMS: expiration && expiration * 1000,
evictionMS: eviction && eviction * 1000,
trackDeletes,
tableName,
tableId,
primaryKey: primaryAttribute.name,
databasePath: isLegacy ? `${databaseName}/${tableName}` : databaseName,
databaseName,
indices,
attributes,
schemaDefined: primaryAttribute.schemaDefined,
dbisDB: attributesDbi,
})
);
table.schemaVersion = 1;
databaseEventsEmitter.emit('updateTable', table);
}
}
return rootStore;
}
export function resetDatabases() {
loadedDatabases = false;
for (const store of Object.values(lmdbDatabaseEnvs)) {
store.needsDeletion = true;
}
getDatabases();
for (const [path, store] of lmdbDatabaseEnvs) {
if (store.needsDeletion && !path.endsWith('system.mdb')) {
store.close();
lmdbDatabaseEnvs.delete(path);
}
}
return databases;
}
interface TableDefinition {
table: string;
database?: string;
path?: string;
expiration?: number;
eviction?: number;
scanInterval?: number;
audit?: boolean;
sealed?: boolean;
splitSegments?: boolean;
replicate?: boolean;
trackDeletes?: boolean;
attributes: any[];
schemaDefined?: boolean;
origin?: string;
}
/**
* Ensure that we have this database object (that holds a set of tables) set up
* @param databaseName
* @returns
*/
function ensureDB(databaseName) {
let dbTables = databases[databaseName];
if (!dbTables) {
if (databaseName === 'data')
// preserve the data tables objet
dbTables = databases[databaseName] = tables;
else if (databaseName === 'system')
// make system non-enumerable
Object.defineProperty(databases, 'system', {
value: (dbTables = Object.create(null)),
configurable: true, // no enum
});
else {
dbTables = databases[databaseName] = Object.create(null);
}
}
if (definedDatabases && !definedDatabases.has(databaseName)) {
const definedTables = new Set<string>(); // we create this so we can determine what was found in a reset and remove any removed dbs/tables
dbTables[DEFINED_TABLES] = definedTables;
definedDatabases.set(databaseName, definedTables);
}
return dbTables;
}
/**
* Set the table class into the database's tables object
* @param tables
* @param tableName
* @param Table
* @returns
*/
function setTable(tables, tableName, Table) {
tables[tableName] = Table;
return Table;
}
/**
* Get root store for a database
* @param options
* @returns
*/
export function database({ database: databaseName, table: tableName }) {
if (!databaseName) databaseName = DEFAULT_DATABASE_NAME;
getDatabases();
ensureDB(databaseName);
const definedDatabase = definedDatabases.get(databaseName);
if (definedDatabase?.rootStore) {
return definedDatabase.rootStore;
}
const databaseConfig = envGet(CONFIG_PARAMS.DATABASES) || {};
if (process.env.SCHEMAS_DATA_PATH) {
databaseConfig.data = { path: process.env.SCHEMAS_DATA_PATH };
}
const tablePath = tableName && databaseConfig[databaseName]?.tables?.[tableName]?.path;
const hdbBasePath = getHdbBasePath();
const databasePath =
tablePath ||
databaseConfig[databaseName]?.path ||
process.env.STORAGE_PATH ||
getConfigPath(CONFIG_PARAMS.STORAGE_PATH) ||
(existsSync(join(hdbBasePath, DATABASES_DIR_NAME))
? join(hdbBasePath, DATABASES_DIR_NAME)
: join(hdbBasePath, LEGACY_DATABASES_DIR_NAME));
let rootStore: RootDatabaseKind;
const useRocksdb = (process.env.HARPER_STORAGE_ENGINE || envGet(CONFIG_PARAMS.STORAGE_ENGINE)) !== 'lmdb';
if (useRocksdb) {
const path = join(databasePath, tablePath ? tableName : databaseName);
rootStore = rocksdbDatabaseEnvs.get(path);
if (!rootStore || rootStore.status === 'closed') {
rootStore = openRocksDatabase(path, {
disableWAL: false,
enableStats: true,
});
rocksdbDatabaseEnvs.set(path, rootStore);
}
} else {
const path = join(databasePath, `${tablePath ? tableName : databaseName}.mdb`);
rootStore = lmdbDatabaseEnvs.get(path);
if (!rootStore || rootStore.status === 'closed') {
// TODO: validate database name
const envInit = new OpenEnvironmentObject(path, false);
rootStore = open(envInit);
lmdbDatabaseEnvs.set(path, rootStore);
}
}
if (!rootStore.auditStore) {
rootStore.auditStore = openAuditStore(rootStore);
}
if (definedDatabase) definedDatabase.rootStore = rootStore;
return rootStore;
}
/**
* Delete the database
* @param databaseName
*/
export async function dropDatabase(databaseName) {
if (!databases[databaseName]) throw new Error('Database does not exist');
const dbTables = databases[databaseName];
let rootStore;
for (const tableName in dbTables) {
const table = dbTables[tableName];
rootStore = table.primaryStore.rootStore;
lmdbDatabaseEnvs.delete(rootStore.path);
rocksdbDatabaseEnvs.delete(rootStore.path);
}
for (const tableName in dbTables) {
databaseEventsEmitter.emit('dropTable', tableName, databaseName);
}
if (databaseName === 'data') {
for (const tableName in tables) {
delete tables[tableName];
}
delete tables[DEFINED_TABLES];
}
delete databases[databaseName];
databaseEventsEmitter.emit('dropDatabase', databaseName);
if (rootStore) {
if (rootStore.status === 'open') {
if (rootStore instanceof RocksDatabase) {
rootStore.close();
rootStore.destroy();
} else {
await rootStore.close();
await unlink(rootStore.path);
}
}
} else {
rootStore = database({ database: databaseName, table: null });
if (rootStore instanceof RocksDatabase) {
rootStore.close();
rootStore.destroy();
} else if (rootStore.status === 'open') {
await rootStore.close();
await unlink(rootStore.path);
}
}
await deleteRootBlobPathsForDB(rootStore);
}
// opens an index, consulting with custom indexes that may use alternate store configuration
function openIndex(dbiKey: string, rootStore: RootDatabaseKind, attribute: any) {
const objectStorage =
attribute.isPrimaryKey || (attribute.indexed.type && CUSTOM_INDEXES[attribute.indexed.type]?.useObjectStore);
const dbiInit = createOpenDBIObject(!objectStorage, objectStorage);
// Custom-index object stores (e.g. HNSW vector graphs) must keep writing typed structs regardless
// of the storage.randomAccessFields opt-out — their internal nodes are mutated in place and depend
// on random-access struct encoding (see IndexRecordEncoder).
if (attribute.indexed?.type && CUSTOM_INDEXES[attribute.indexed.type]?.useObjectStore) {
dbiInit.encoder = { Encoder: IndexRecordEncoder };
}
let dbi:
| LMDBDatabase
| (RocksDatabase & {
customIndex?: any;
isIndexing?: boolean;
indexNulls?: boolean;
rootStore?: RocksRootDatabase;
});
if (rootStore instanceof RocksDatabase) {
dbi = openRocksDatabase(rootStore.path, { ...dbiInit, name: dbiKey });
dbi.rootStore = rootStore;
} else {
dbi = rootStore.openDB(dbiKey, dbiInit);
}
if (attribute.indexed.type) {
const CustomIndex = CUSTOM_INDEXES[attribute.indexed.type];
if (CustomIndex) {
dbi.customIndex = new CustomIndex(dbi, attribute.indexed);
} else {
logger.error(`The indexing type '${attribute.indexed.type}' is unknown`);
}
}
return dbi;
}
/**
* This can be called to ensure that the specified table exists and if it does not exist, it should be created.
* @param tableName
* @param databaseName
* @param customPath
* @param expiration
* @param eviction
* @param scanInterval
* @param attributes
* @param audit
* @param sealed
* @param splitSegments
* @param replicate
*/
export function table<TableResourceType>(tableDefinition: TableDefinition): TableResourceType {
let {
table: tableName,
database: databaseName,
expiration,
eviction,
scanInterval,
attributes,
audit,
sealed,
splitSegments,
replicate,
trackDeletes,
schemaDefined,
origin,
} = tableDefinition;
if (!databaseName) databaseName = DEFAULT_DATABASE_NAME;
const rootStore = database({ database: databaseName, table: tableName });
const tables = databases[databaseName];
logger.trace(`Defining ${tableName} in ${databaseName}`);
let Table = tables?.[tableName];
if (rootStore.status === 'closed') {
throw new Error(`Can not use a closed data store for ${tableName}`);
}
let primaryKey;
let primaryKeyAttribute;
let attributesDbi;
if (schemaDefined == undefined) schemaDefined = true;
const internalDbiInit = createOpenDBIObject(false);
for (const attribute of attributes) {
if (attribute.attribute && !attribute.name) {
// there is some legacy code that calls the attribute's name the attribute's attribute
attribute.name = attribute.attribute;
attribute.indexed = true;
} else attribute.attribute = attribute.name;
if (attribute.expiresAt) attribute.indexed = true;
}
let hasChanges;
let releaseExclusiveLock: () => void;
if (Table) {
primaryKey = Table.primaryKey;
if (Table.primaryStore.rootStore.status === 'closed') {
throw new Error(`Can not use a closed data store from ${tableName} class`);
}
// it table already exists, get the split segments setting
if (splitSegments == undefined) splitSegments = Table.splitSegments;
Table.attributes.splice(0, Table.attributes.length, ...attributes);
} else {
const auditStore = rootStore.auditStore;
primaryKeyAttribute = attributes.find((attribute) => attribute.isPrimaryKey) || {};
primaryKey = primaryKeyAttribute.name;
primaryKeyAttribute.isPrimaryKey = true;
primaryKeyAttribute.schemaDefined = schemaDefined;
// can't change compression after the fact (except threshold), so save only when we create the table
primaryKeyAttribute.compression = getDefaultCompression();
if (trackDeletes) primaryKeyAttribute.trackDeletes = true;
audit = primaryKeyAttribute.audit = typeof audit === 'boolean' ? audit : envGet(CONFIG_PARAMS.LOGGING_AUDITLOG);
if (expiration) primaryKeyAttribute.expiration = expiration;
if (eviction) primaryKeyAttribute.eviction = eviction;
splitSegments ??= false;
primaryKeyAttribute.splitSegments = splitSegments; // always default to not splitting segments going forward
if (typeof sealed === 'boolean') primaryKeyAttribute.sealed = sealed;
if (typeof replicate === 'boolean') primaryKeyAttribute.replicate = replicate;
if (origin) {
if (!primaryKeyAttribute.origins) primaryKeyAttribute.origins = [origin];
else if (!primaryKeyAttribute.origins.includes(origin)) primaryKeyAttribute.origins.push(origin);
}
logger.trace(`${tableName} table loading, opening primary store`);
const dbiInit = createOpenDBIObject(false, true);
dbiInit.compression = primaryKeyAttribute.compression;
const dbiName = tableName + '/';
if (rootStore instanceof RocksDatabase) {
attributesDbi = rootStore.dbisDb = openRocksDatabase(rootStore.path, {
...internalDbiInit,
disableWAL: false,
name: INTERNAL_DBIS_NAME,
});
} else {
attributesDbi = rootStore.dbisDb = rootStore.openDB(INTERNAL_DBIS_NAME, internalDbiInit);
}
exclusiveLock(); // get an exclusive lock on the database so we can verify that we are the only thread creating the table (and assigning the table id)
if (attributesDbi.getSync(dbiName)) {
// table was created while we were setting up
if (releaseExclusiveLock) releaseExclusiveLock();
resetDatabases();
return table(tableDefinition);
}
let primaryStore;
if (rootStore instanceof RocksDatabase) {
primaryStore = openRocksDatabase(rootStore.path, { ...dbiInit, name: dbiName });
} else {
primaryStore = rootStore.openDB(dbiName, dbiInit);
}
primaryStore = handleLocalTimeForGets(primaryStore, rootStore);
rootStore.databaseName = databaseName;
primaryStore.tableId = attributesDbi.getSync(NEXT_TABLE_ID);
logger.trace(`Assigning new table id ${primaryStore.tableId} for ${tableName}`);
if (!primaryStore.tableId) primaryStore.tableId = 1;
attributesDbi.put(NEXT_TABLE_ID, primaryStore.tableId + 1);
primaryKeyAttribute.tableId = primaryStore.tableId;
Table = setTable(
tables,
tableName,
makeTable({
primaryStore,
auditStore,
audit,
sealed,
splitSegments,
replicate,
trackDeletes,
expirationMS: expiration && expiration * 1000,
evictionMS: eviction && eviction * 1000,
primaryKey,
tableName,
tableId: primaryStore.tableId,
databasePath: databaseName,
databaseName,
indices: {},
attributes,
schemaDefined,
dbisDB: attributesDbi,
})
);