-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathTable.ts
More file actions
4600 lines (4533 loc) · 181 KB
/
Table.ts
File metadata and controls
4600 lines (4533 loc) · 181 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
/**
* This module provides the main table implementation of the Resource API, providing full access to Harper
* tables through the interface defined by the Resource class. This module is responsible for handling these
* table-level interactions, loading records, updating records, querying, and more.
*/
import { CONFIG_PARAMS, OPERATIONS_ENUM, SYSTEM_TABLE_NAMES, SYSTEM_SCHEMA_NAME } from '../utility/hdbTerms.ts';
import { type Database } from 'lmdb';
import { getIndexedValues } from '../utility/lmdb/commonUtility.js';
import { getThisNodeId, exportIdMapping } from './nodeIdMapping.ts';
import lodash from 'lodash';
import { ExtendedIterable, SKIP } from '@harperfast/extended-iterable';
import type {
ResourceInterface,
SubscriptionRequest,
Id,
Context,
Condition,
Sort,
SubSelect,
RequestTargetOrId,
} from './ResourceInterface.ts';
import type { User } from '../security/user.ts';
import lmdbProcessRows from '../dataLayer/harperBridge/lmdbBridge/lmdbUtility/lmdbProcessRows.js';
import { Resource, transformForSelect } from './Resource.ts';
import { when, promiseNormalize } from '../utility/when.ts';
import { DatabaseTransaction, ImmediateTransaction, TRANSACTION_STATE } from './DatabaseTransaction.ts';
import * as envMngr from '../utility/environment/environmentManager.js';
import { addSubscription } from './transactionBroadcast.ts';
import { handleHDBError, ClientError, ServerError, AccessViolation } from '../utility/errors/hdbError.js';
import * as signalling from '../utility/signalling.js';
import { SchemaEventMsg, UserEventMsg } from '../server/threads/itc.js';
import { databases, table } from './databases.ts';
import {
searchByIndex,
findAttribute,
estimateCondition,
flattenKey,
COERCIBLE_OPERATORS,
executeConditions,
} from './search.ts';
import { logger } from '../utility/logging/logger.ts';
import { Addition, assignTrackedAccessors, updateAndFreeze, hasChanges, GenericTrackedObject } from './tracked.ts';
import { transaction, contextStorage } from './transaction.ts';
import { MAXIMUM_KEY, writeKey, compareKeys } from 'ordered-binary';
import { getWorkerIndex, getWorkerCount } from '../server/threads/manageThreads.js';
import { HAS_BLOBS, auditRetention, removeAuditEntry } from './auditStore.ts';
import { autoCast, autoCastBooleanStrict } from '../utility/common_utils.js';
import {
recordUpdater,
removeEntry,
PENDING_LOCAL_TIME,
type RecordObject,
type Entry,
entryMap,
} from './RecordEncoder.ts';
import { recordAction, recordActionBinary } from './analytics/write.ts';
import { rebuildUpdateBefore } from './crdt.ts';
import { appendHeader } from '../server/serverHelpers/Headers.ts';
import fs from 'node:fs';
import { Blob, deleteBlobsInObject, findBlobsInObject, startPreCommitBlobsForRecord } from './blob.ts';
import { onStorageReclamation } from '../server/storageReclamation.ts';
import { RequestTarget } from './RequestTarget.ts';
import harperLogger from '../utility/logging/harper_logger.js';
import { throttle } from '../server/throttle.ts';
import { RocksDatabase } from '@harperfast/rocksdb-js';
import { LMDBTransaction, ImmediateTransaction as ImmediateLMDBTransaction } from './LMDBTransaction';
import { contentTypes } from '../server/serverHelpers/contentTypes';
const { sortBy } = lodash;
const { validateAttribute } = lmdbProcessRows;
export type Attribute = {
name: string;
type: 'ID' | 'Int' | 'Float' | 'Long' | 'String' | 'Boolean' | 'Date' | 'Bytes' | 'Any' | 'BigInt' | 'Blob' | string;
assignCreatedTime?: boolean;
assignUpdatedTime?: boolean;
nullable?: boolean;
expiresAt?: boolean;
isPrimaryKey?: boolean;
indexed?: unknown;
relationship?: unknown;
computed?: unknown;
properties?: Array<Attribute>;
elements?: Attribute;
};
type MaybePromise<T> = T | Promise<T>;
const NULL_WITH_TIMESTAMP = new Uint8Array(9);
NULL_WITH_TIMESTAMP[8] = 0xc0; // null
const UNCACHEABLE_TIMESTAMP = Infinity; // we use this when dynamic content is accessed that we can't safely cache, and this prevents earlier timestamps from change the "last" modification
const RECORD_PRUNING_INTERVAL = 60000; // one minute
envMngr.initSync();
const LMDB_PREFETCH_WRITES = envMngr.get(CONFIG_PARAMS.STORAGE_PREFETCHWRITES);
const LOCK_TIMEOUT = 10000;
export const INVALIDATED = 1;
export const EVICTED = 8; // note that 2 is reserved for timestamps
const TEST_WRITE_KEY_BUFFER = Buffer.allocUnsafeSlow(8192);
const MAX_KEY_BYTES = 1978;
const EVENT_HIGH_WATER_MARK = 100;
const FULL_PERMISSIONS = {
read: true,
insert: true,
update: true,
delete: true,
isSuperUser: true,
};
export interface Table {
primaryStore: Database;
auditStore: Database;
indices: {};
databasePath: string;
tableName: string;
databaseName: string;
attributes: Attribute[];
primaryKey: string;
splitSegments?: boolean;
replicate?: boolean;
subscriptions: Map<any, Function[]>;
expirationMS: number;
indexingOperations?: Promise<void>;
source?: new () => ResourceInterface;
Transaction: ReturnType<typeof makeTable>;
}
type ResidencyDefinition = number | string[] | void;
/**
* This returns a Table class for the given table settings (determined from the metadata table)
* Instances of the returned class are Resource instances, intended to provide a consistent view or transaction of the table
* @param options
*/
export function makeTable(options) {
const {
primaryKey,
indices,
tableId,
tableName,
primaryStore,
databasePath,
databaseName,
auditStore,
schemaDefined,
dbisDB: dbisDb,
sealed,
splitSegments,
replicate,
} = options;
let { expirationMS: expirationMs, evictionMS: evictionMs, audit, trackDeletes } = options;
evictionMs ??= 0;
let { attributes }: { attributes: Attribute[] } = options;
if (!attributes) attributes = [];
const updateRecord = recordUpdater(primaryStore, tableId, auditStore);
let sourceLoad: any; // if a source has a load function (replicator), record it here
let hasSourceGet: any;
let primaryKeyAttribute: Attribute = {};
let lastEvictionCompletion: Promise<void> = Promise.resolve();
let createdTimeProperty: Attribute, updatedTimeProperty: Attribute, expiresAtProperty: Attribute;
for (const attribute of attributes) {
if (attribute.assignCreatedTime || attribute.name === '__createdtime__') createdTimeProperty = attribute;
if (attribute.assignUpdatedTime || attribute.name === '__updatedtime__') updatedTimeProperty = attribute;
if (attribute.expiresAt) expiresAtProperty = attribute;
if (attribute.isPrimaryKey) primaryKeyAttribute = attribute;
}
let deleteCallbackHandle: { remove: () => void };
let prefetchIds = [];
let prefetchCallbacks = [];
let untilNextPrefetch = 1;
let nonPrefetchSequence = 2;
let cleanupInterval = 86400000;
let cleanupPriority = 0;
let lastCleanupInterval: number;
let cleanupTimer: NodeJS.Timeout;
let propertyResolvers: any;
let hasRelationships = false;
let runningRecordExpiration: boolean;
const isRocksDB = primaryStore instanceof RocksDatabase;
type BigInt64ArrayAndMaxSafeId = BigInt64Array & { maxSafeId: number };
let idIncrementer: BigInt64ArrayAndMaxSafeId;
let replicateToCount;
const databaseReplications = envMngr.get(CONFIG_PARAMS.REPLICATION_DATABASES);
if (Array.isArray(databaseReplications)) {
for (const dbReplication of databaseReplications) {
if (dbReplication.name === databaseName && dbReplication.replicateTo >= 0) {
replicateToCount = dbReplication.replicateTo;
break;
}
}
}
const MAX_PREFETCH_SEQUENCE = 10;
const MAX_PREFETCH_BUNDLE = 6;
if (audit) addDeleteRemoval();
onStorageReclamation(primaryStore.path, (priority: number) => {
if (hasSourceGet) return scheduleCleanup(priority);
});
class Updatable extends GenericTrackedObject implements RecordObject {
declare set: (property: string, value: any) => void;
declare getProperty: (property: string) => any;
getUpdatedTime(): number {
return entryMap.get(this.getRecord())?.version;
}
getExpiresAt(): number {
return entryMap.get(this.getRecord())?.expiresAt;
}
addTo(property: string, value: number | bigint) {
if (typeof value === 'number' || typeof value === 'bigint') {
this.set(property, new Addition(value));
} else {
throw new Error('Can not add or subtract a non-numeric value');
}
}
subtractFrom(property: string, value: number | bigint) {
return this.addTo(property, -value);
}
}
class TableResource<Record extends object = any> extends Resource<Record> {
#record: any; // the stored/frozen record from the database and stored in the cache (should not be modified directly)
#changes: any; // the changes to the record that have been made (should not be modified directly)
#version?: number; // version of the record
#entry?: Entry; // the entry from the database
#savingOperation?: any; // operation for the record is currently being saved
declare getProperty: (name: string) => any;
static name = tableName; // for display/debugging purposes
static primaryStore = primaryStore;
static auditStore = auditStore;
static primaryKey = primaryKey;
static tableName = tableName;
static tableId = tableId;
static indices = indices;
static audit = audit;
static databasePath = databasePath;
static databaseName = databaseName;
static attributes = attributes;
static replicate = replicate;
static sealed = sealed;
static splitSegments = splitSegments ?? true;
static createdTimeProperty = createdTimeProperty;
static updatedTimeProperty = updatedTimeProperty;
static propertyResolvers;
static userResolvers = {};
static source?: typeof TableResource;
declare static sourceOptions: any;
declare static intermediateSource: boolean;
static getResidencyById: (id: Id) => number | void;
static get expirationMS() {
return expirationMs;
}
static dbisDB = dbisDb;
static schemaDefined = schemaDefined;
/**
* This defines a source for a table. This effectively makes a table into a cache, where the canonical
* source of data (or source of truth) is provided here in the Resource argument. Additional options
* can be provided to indicate how the caching should be handled.
* @param source
* @param options
* @returns
*/
static sourcedFrom(source, options) {
// define a source for retrieving invalidated entries for caching purposes
if (options) {
this.sourceOptions = options;
if (options.expiration || options.eviction || options.scanInterval) this.setTTLExpiration(options);
}
if (options?.intermediateSource) {
source.intermediateSource = true;
// intermediateSource should register sourceLoad and setup subscription but not assign to this.source
} else {
if (this.source) {
if (this.source.name === source.name) {
// if we are adding a source that is already set, we don't add it again
return;
}
throw new Error('Can not have multiple sources');
}
this.source = source;
}
hasSourceGet = hasSourceGet || (source.get && (!source.get.reliesOnPrototype || source.prototype.get));
sourceLoad = sourceLoad || source.load;
const shouldRevalidateEvents = this.source?.shouldRevalidateEvents;
// External data source may provide a subscribe method, allowing for real-time proactive delivery
// of data from the source to this caching table. This is generally greatly superior to expiration-based
// caching since it much for accurately ensures freshness and maximizing caching time.
// Here we subscribe the external data source if it is available, getting notification events
// as they come in, and directly writing them to this table. We use the notification option to ensure
// that we don't re-broadcast these as "requested" changes back to the source.
(async () => {
let userRoleUpdate = false;
let lastSequenceId;
// perform the write of an individual write event
const writeUpdate = async (event, context) => {
const value = event.value;
const Table = event.table ? databases[databaseName][event.table] : TableResource;
if (
databaseName === SYSTEM_SCHEMA_NAME &&
(event.table === SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME || event.table === SYSTEM_TABLE_NAMES.USER_TABLE_NAME)
) {
userRoleUpdate = true;
}
if (event.id === undefined) {
event.id = value[Table.primaryKey];
if (event.id === undefined) throw new Error('Replication message without an id ' + JSON.stringify(event));
}
event.source = source;
const options = {
residencyId: getResidencyId(event.residencyList),
isNotification: true,
ensureLoaded: false,
nodeId: event.nodeId,
viaNodeId: event.viaNodeId,
async: true,
};
const id = event.id;
const resource: TableResource = await Table.getResource(id, context, options);
if (event.finished) await event.finished;
switch (event.type) {
case 'put':
return shouldRevalidateEvents
? resource._writeInvalidate(id, value, options)
: resource._writeUpdate(id, value, true, options);
case 'patch':
return shouldRevalidateEvents
? resource._writeInvalidate(id, value, options)
: resource._writeUpdate(id, value, false, options);
case 'delete':
return resource._writeDelete(id, options);
case 'publish':
case 'message':
return resource._writePublish(id, value, options);
case 'invalidate':
return resource._writeInvalidate(id, value, options);
case 'relocate':
return resource._writeRelocate(id, options);
default:
logger.error?.('Unknown operation', event.type, event.id);
}
};
try {
const hasSubscribe = source.subscribe;
// if subscriptions come in out-of-order, we need to track deletes to ensure consistency
if (hasSubscribe && trackDeletes == undefined) trackDeletes = true;
const subscriptionOptions = {
// this is used to indicate that all threads are (presumably) making this subscription
// and we do not need to propagate events across threads (more efficient)
crossThreads: false,
// this is used to indicate that we want, if possible, immediate notification of writes
// within the process (not supported yet)
inTransactionUpdates: true,
// supports transaction operations
supportsTransactions: true,
// don't need the current state, should be up-to-date
omitCurrent: true,
};
const subscribeOnThisThread = source.subscribeOnThisThread
? source.subscribeOnThisThread(getWorkerIndex(), subscriptionOptions)
: getWorkerIndex() === 0;
const subscription = hasSubscribe && subscribeOnThisThread && (await source.subscribe?.(subscriptionOptions));
if (subscription) {
let txnInProgress;
// we listen for events by iterating through the async iterator provided by the subscription
for await (const event of subscription) {
try {
const firstWrite = event.type === 'transaction' ? event.writes[0] : event;
if (!firstWrite) {
logger.error?.('Bad subscription event', event);
continue;
}
event.source = source;
if (event.type === 'end_txn') {
txnInProgress?.resolve();
let updateRecordedSequenceId: () => void;
if (event.localTime && lastSequenceId !== event.localTime) {
if (event.remoteNodeIds?.length > 0) {
updateRecordedSequenceId = () => {
// the key for tracking the sequence ids and txn times received from this node
const seqKey = [Symbol.for('seq'), event.remoteNodeIds[0]];
const existingSeq = dbisDb.get(seqKey);
let nodeStates = existingSeq?.nodes;
if (!nodeStates) {
// if we don't have a list of nodes, we need to create one, with the main one using the existing seqId
nodeStates = [];
}
// if we are not the only node in the list, we are getting proxied subscriptions, and we need
// to track this separately
// track the other nodes in the list
for (const nodeId of event.remoteNodeIds.slice(1)) {
let nodeState = nodeStates.find((existingNode) => existingNode.id === nodeId);
// remove any duplicates
nodeStates = nodeStates.filter(
(existingNode) => existingNode.id !== nodeId || existingNode === nodeState
);
if (!nodeState) {
nodeState = { id: nodeId, seqId: 0 };
nodeStates.push(nodeState);
}
nodeState.seqId = Math.max(existingSeq?.seqId ?? 1, event.localTime);
if (nodeId === txnInProgress?.nodeId) {
nodeState.lastTxnTime = event.timestamp;
}
}
const seqId = Math.max(existingSeq?.seqId ?? 1, event.localTime);
logger.trace?.(
'Received txn',
databaseName,
seqId,
new Date(seqId),
event.localTime,
new Date(event.localTime),
event.remoteNodeIds
);
dbisDb.put(seqKey, {
seqId,
nodes: nodeStates,
});
};
lastSequenceId = event.localTime;
}
}
if (event.onCommit) {
// if there was an onCommit callback, call that. This function can be async
// and if so, we want to delay the recording of the sequence id until it finished
// (as it can be used to indicate more associated actions, like blob transfer, are in flight)
const onCommitFinished = txnInProgress
? txnInProgress.committed.then(event.onCommit)
: event.onCommit();
if (updateRecordedSequenceId) {
if (onCommitFinished?.then) onCommitFinished.then(updateRecordedSequenceId);
else updateRecordedSequenceId();
}
} else if (updateRecordedSequenceId) updateRecordedSequenceId();
continue;
}
if (txnInProgress) {
if (event.beginTxn) {
// if we are starting a new transaction, finish the existing one
txnInProgress.resolve();
} else {
// write in the current transaction if one is in progress
txnInProgress.writePromises.push(writeUpdate(event, txnInProgress));
continue;
}
}
// use the version as the transaction timestamp
if (!event.timestamp && event.version) event.timestamp = event.version;
const commitResolution = transaction(event, () => {
if (event.type === 'transaction') {
// if it is a transaction, we need to individually iterate through each write event
const promises: Promise<any>[] = [];
for (const write of event.writes) {
try {
promises.push(writeUpdate(write, event));
} catch (error) {
(error as Error).message +=
' writing ' + JSON.stringify(write) + ' of event ' + JSON.stringify(event);
throw error;
}
}
return Promise.all(promises);
} else if (event.type === 'define_schema') {
// ensure table has the provided attributes
const updatedAttributes = this.attributes.slice(0);
let hasChanges = false;
for (const attribute of event.attributes) {
if (!updatedAttributes.find((existing) => existing.name === attribute.name)) {
updatedAttributes.push(attribute);
hasChanges = true;
}
}
if (hasChanges) {
table({
table: tableName,
database: databaseName,
attributes: updatedAttributes,
origin: 'cluster',
});
signalling.signalSchemaChange(
new SchemaEventMsg(process.pid, OPERATIONS_ENUM.CREATE_TABLE, databaseName, tableName)
);
}
} else {
if (event.beginTxn) {
// if we are beginning a new transaction, we record the current
// event/context as transaction in progress and then future events
// are applied with that context until the next transaction begins/ends
txnInProgress = event;
txnInProgress.writePromises = [writeUpdate(event, event)];
return new Promise((resolve) => {
// callback for when this transaction is finished (will be called on next txn begin/end).
txnInProgress.resolve = () => resolve(Promise.all(txnInProgress.writePromises)); // and make sure we wait for the write update to finish
});
}
return writeUpdate(event, event);
}
});
if (txnInProgress) txnInProgress.committed = commitResolution;
if (userRoleUpdate && commitResolution && !commitResolution?.waitingForUserChange) {
// if the user role changed, asynchronously signal the user change (but don't block this function)
commitResolution.then(() => signalling.signalUserChange(new UserEventMsg(process.pid)));
commitResolution.waitingForUserChange = true; // only need to send one signal per transaction
}
if (event.onCommit) {
if (commitResolution) commitResolution.then(event.onCommit);
else event.onCommit();
}
} catch (error) {
logger.error?.('error in subscription handler', error);
}
}
}
} catch (error) {
logger.error?.(error);
}
})();
return this;
}
// define a caching table as one that has a origin source with a get
static get isCaching() {
return hasSourceGet;
}
/** Indicates if the events should be revalidated when they are received. By default we do this if the get
* method is overriden */
static get shouldRevalidateEvents() {
return this.prototype.get !== TableResource.prototype.get;
}
/**
* Gets a resource instance, as defined by the Resource class, adding the table-specific handling
* of also loading the stored record into the resource instance.
* @param target
* @param request
* @param resourceOptions An important option is ensureLoaded, which can be used to indicate that it is necessary for a caching table to load data from the source if there is not a local copy of the data in the table (usually not necessary for a delete, for example).
* @returns
*/
static getResource<Record extends object = any>(
target: RequestTarget,
request: Context,
resourceOptions?: any
): Promise<TableResource<Record>> | TableResource<Record> {
const resource: TableResource = super.getResource(target, request, resourceOptions) as any;
if (this.loadAsInstance !== false) {
return resource._loadRecord(target, request, resourceOptions);
}
return resource;
}
_loadRecord<Record extends object = any>(
target: RequestTarget,
request: Context,
resourceOptions?: any
): MaybePromise<TableResource<Record>> {
const id = target && typeof target === 'object' ? target.id : target;
if (id == null) return this;
checkValidId(id);
try {
if (this.getRecord?.()) return this; // already loaded, don't reload, current version may have modifications
if (typeof id === 'object' && id && !Array.isArray(id)) {
throw new Error(`Invalid id ${JSON.stringify(id)}`);
}
const sync = target?.sync || primaryStore.cache?.get?.(id);
const txn = txnForContext(request);
const readTxn = txn.getReadTxn();
if (readTxn?.isDone) {
throw new Error('You can not read from a transaction that has already been committed/aborted');
}
return loadLocalRecord(
id,
request,
{ transaction: readTxn, ensureLoaded: resourceOptions?.ensureLoaded },
sync,
(entry) => {
if (entry) {
TableResource._updateResource(this, entry);
} else this.#record = null;
if (request.onlyIfCached) {
// don't go into the loading from source condition, but HTTP spec says to
// return 504 (rather than 404) if there is no content and the cache-control header
// dictates not to go to source
if (!this.doesExist()) throw new ServerError('Entry is not cached', 504);
} else if (resourceOptions?.ensureLoaded) {
const loadingFromSource = ensureLoadedFromSource(
this.constructor.source,
id,
entry,
request,
this,
target
);
if (loadingFromSource) {
txn?.disregardReadTxn(); // this could take some time, so don't keep the transaction open if possible
return when(loadingFromSource, (entry) => {
TableResource._updateResource(this, entry);
return this;
});
} else if (hasSourceGet) target.loadedFromSource = false; // mark it as cached
}
return this;
}
);
} catch (error) {
if (error.message.includes('Unable to serialize object')) error.message += ': ' + JSON.stringify(id);
throw error;
}
}
static _updateResource(resource, entry) {
resource.#entry = entry;
resource.#record = entry?.value ?? null;
resource.#version = entry?.version;
}
/**
* This is a request to explicitly ensure that the record is loaded from source, rather than only using the local record.
* This will load from source if the current record is expired, missing, or invalidated.
* @returns
*/
ensureLoaded() {
const loadedFromSource = ensureLoadedFromSource(
this.constructor.source,
this.getId(),
this.#entry,
this.getContext()
);
if (loadedFromSource) {
return when(loadedFromSource, (entry) => {
this.#entry = entry;
this.#record = entry.value;
this.#version = entry.version;
});
}
}
static getNewId(): any {
const type = primaryKeyAttribute?.type;
// the default Resource behavior is to return a GUID, but for a table we can return incrementing numeric keys if the type is (or can be) numeric
if (type === 'String' || type === 'ID') return super.getNewId();
if (!idIncrementer) {
// if there is no id incrementer yet, we get or create one
const idAllocationEntry = primaryStore.getEntry(Symbol.for('id_allocation'));
let idAllocation = idAllocationEntry?.value;
let lastKey;
if (
idAllocation &&
idAllocation.nodeName === server.hostname &&
(!hasOtherProcesses(primaryStore) || idAllocation.pid === process.pid)
) {
// the database has an existing id allocation that we can continue from
const startingId = idAllocation.start;
const endingId = idAllocation.end;
lastKey = startingId;
// once it is loaded, we need to find the last key in the allocated range and start from there
for (const key of primaryStore.getKeys({ start: endingId, end: startingId, limit: 1, reverse: true })) {
lastKey = key;
}
} else {
// we need to create a new id allocation
idAllocation = createNewAllocation(idAllocationEntry?.version ?? null);
lastKey = idAllocation.start;
}
// all threads will use a shared buffer to atomically increment the id
// first, we create our proposed incrementer buffer that will be used if we are the first thread to get here
// and initialize it with the starting id
idIncrementer = new BigInt64Array([BigInt(lastKey) + 1n]) as BigInt64ArrayAndMaxSafeId;
// now get the selected incrementer buffer, this is the shared buffer was first registered and that all threads will use
idIncrementer = new BigInt64Array(
primaryStore.getUserSharedBuffer('id', idIncrementer.buffer)
) as BigInt64ArrayAndMaxSafeId;
// and we set the maximum safe id to the end of the allocated range before we check for conflicting ids again
idIncrementer.maxSafeId = idAllocation.end;
}
// this is where we actually do the atomic incrementation. All the threads should be pointing to the same
// memory location of this incrementer, so we can be sure that the id is unique and sequential.
const nextId = Number(Atomics.add(idIncrementer, 0, 1n));
const asyncIdExpansionThreshold = type === 'Int' ? 0x200 : 0x100000;
if (nextId + asyncIdExpansionThreshold >= idIncrementer.maxSafeId) {
const updateEnd = (inTxn) => {
// we update the end of the allocation range after verifying we don't have any conflicting ids in front of us
idIncrementer.maxSafeId = nextId + (type === 'Int' ? 0x3ff : 0x3fffff);
let idAfter = (type === 'Int' ? Math.pow(2, 31) : Math.pow(2, 49)) - 1;
const readTxn = inTxn ? undefined : primaryStore.useReadTransaction?.();
// get the latest id after the read transaction to make sure we aren't reading any new ids that we assigned from this node
const newestId = Number(idIncrementer[0]);
for (const key of primaryStore.getKeys({
start: newestId + 1,
end: idAfter,
limit: 1,
transaction: readTxn,
})) {
idAfter = key;
}
readTxn?.done();
const { value: updatedIdAllocation, version } = primaryStore.getEntry(Symbol.for('id_allocation'));
if (idIncrementer.maxSafeId < idAfter) {
// note that this is just a noop/direct callback if we are inside the sync transaction
// first check to see if it actually got updated by another thread
if (updatedIdAllocation.end > idIncrementer.maxSafeId - 100) {
// the allocation was already updated by another thread
return;
}
logger.info?.('New id allocation', nextId, idIncrementer.maxSafeId, version);
primaryStore.put(
Symbol.for('id_allocation'),
{
start: updatedIdAllocation.start,
end: idIncrementer.maxSafeId,
nodeName: server.hostname,
pid: process.pid,
},
Date.now(),
version
);
} else {
// indicate that we have run out of ids in the allocated range, so we need to allocate a new range
logger.warn?.(
`Id conflict detected, starting new id allocation range, attempting to allocate to ${idIncrementer.maxSafeId}, but id of ${idAfter} detected`
);
const idAllocation = createNewAllocation(version);
// reassign the incrementer to the new range/starting point
if (!idAllocation.alreadyUpdated) Atomics.store(idIncrementer, 0, BigInt(idAllocation.start + 1));
// and we set the maximum safe id to the end of the allocated range before we check for conflicting ids again
idIncrementer.maxSafeId = idAllocation.end;
}
};
if (nextId + asyncIdExpansionThreshold === idIncrementer.maxSafeId) {
setImmediate(updateEnd); // if we are getting kind of close to the end, we try to update it asynchronously
} else if (nextId + 100 >= idIncrementer.maxSafeId) {
logger.warn?.(
`Synchronous id allocation required on table ${tableName}${
type == 'Int'
? ', it is highly recommended that you use Long or Float as the type for auto-incremented primary keys'
: ''
}`
);
// if we are very close to the end, synchronously update
primaryStore.transactionSync(() => updateEnd(true));
}
//TODO: Add a check to recordUpdate to check if a new id infringes on the allocated id range
}
return nextId;
function createNewAllocation(expectedVersion) {
// there is no id allocation (or it is for the wrong node name or used up), so we need to create one
// start by determining the max id for the type
const maxId = (type === 'Int' ? Math.pow(2, 31) : Math.pow(2, 49)) - 1;
let safeDistance = maxId / 4; // we want to allocate ids in a range that is at least 1/4 of the total id space from ids in either direction
let idBefore: number, idAfter: number;
let complained = false;
let lastKey;
let idAllocation;
do {
// we start with a random id and verify that there is a good gap in the ids to allocate a decent range
lastKey = Math.floor(Math.random() * maxId);
idAllocation = {
start: lastKey,
end: lastKey + (type === 'Int' ? 0x400 : 0x400000),
nodeName: server.hostname,
pid: process.pid,
};
idBefore = 0;
// now find the next id before the last key
for (const key of primaryStore.getKeys({ start: lastKey, end: true, limit: 1, reverse: true })) {
idBefore = key;
}
idAfter = maxId;
// and next key after
for (const key of primaryStore.getKeys({ start: lastKey + 1, end: maxId, limit: 1 })) {
idAfter = key;
}
safeDistance *= 0.875; // if we fail, we try again with a smaller range, looking for a good gap without really knowing how packed the ids are
if (safeDistance < 1000 && !complained) {
complained = true;
logger.error?.(
`Id allocation in table ${tableName} is very dense, limited safe range of numbers to allocate ids in${
type === 'Int'
? ', it is highly recommended that you use Long or Float as the type for auto-incremented primary keys'
: ''
}`,
lastKey,
idBefore,
idAfter,
safeDistance
);
}
// see if we maintained an adequate distance from the surrounding ids
} while (!(safeDistance < idAfter - lastKey && (safeDistance < lastKey - idBefore || idBefore === 0)));
// we have to ensure that the id allocation is atomic and multiple threads don't set different ids, so we use a sync transaction
return primaryStore.transactionSync(() => {
// first check to see if it actually got set by another thread
const updatedIdAllocation = primaryStore.getEntry(Symbol.for('id_allocation'));
if ((updatedIdAllocation?.version ?? null) == expectedVersion) {
logger.info?.('Allocated new id range', idAllocation);
primaryStore.put(Symbol.for('id_allocation'), idAllocation, Date.now());
return idAllocation;
} else {
logger.debug?.('Looks like ids were already allocated');
return { alreadyUpdated: true, ...updatedIdAllocation.value };
}
});
}
}
/**
* Set TTL expiration for records in this table. On retrieval, record timestamps are checked for expiration.
* This also informs the scheduling for record eviction.
* @param expirationTime Time in seconds until records expire (are stale)
* @param evictionTime Time in seconds until records are evicted (removed)
*/
static setTTLExpiration(expiration: number | { expiration: number; eviction?: number; scanInterval?: number }) {
// we set up a timer to remove expired entries. we only want the timer/reaper to run in one thread,
// so we use the first one
if (typeof expiration === 'number') {
expirationMs = expiration * 1000;
if (!evictionMs) evictionMs = 0; // by default, no extra time for eviction
} else if (expiration && typeof expiration === 'object') {
// an object with expiration times/options specified
expirationMs = expiration.expiration * 1000;
evictionMs = (expiration.eviction || 0) * 1000;
cleanupInterval = expiration.scanInterval * 1000;
} else throw new Error('Invalid expiration value type');
if (expirationMs < 0) throw new Error('Expiration can not be negative');
// default to one quarter of the total eviction time, and make sure it fits into a 32-bit signed integer
cleanupInterval = cleanupInterval || (expirationMs + evictionMs) / 4;
scheduleCleanup();
}
static getResidencyRecord(id: Id) {
return dbisDb.get([Symbol.for('residency_by_id'), id]);
}
static setResidency(getResidency?: (record: object, context: Context) => ResidencyDefinition) {
TableResource.getResidency =
getResidency &&
((record: object, context: Context) => {
try {
return getResidency(record, context);
} catch (error: unknown) {
(error as Error).message += ` in residency function for table ${tableName}`;
throw error;
}
});
}
static setResidencyById(getResidencyById?: (id: Id) => number | void) {
TableResource.getResidencyById =
getResidencyById &&
((id: Id) => {
try {
return getResidencyById(id);
} catch (error: unknown) {
(error as Error).message += ` in residency function for table ${tableName}`;
throw error;
}
});
}
static getResidency(record: object, context: Context) {
if (TableResource.getResidencyById) {
return TableResource.getResidencyById(record[primaryKey]);
}
let count = replicateToCount;
if (context.replicateTo != undefined) {
// if the context specifies where we are replicating to, use that
if (Array.isArray(context.replicateTo)) {
return context.replicateTo.includes(server.hostname)
? context.replicateTo
: [server.hostname, ...context.replicateTo];
}
if (context.replicateTo >= 0) count = context.replicateTo;
}
if (count >= 0 && server.nodes) {
// if we are given a count, choose nodes and return them
const replicateTo = [server.hostname]; // start with ourselves, we should always be in the list
if (context.previousResidency) {
// if we have a previous residency, we should preserve it
replicateTo.push(...context.previousResidency.slice(0, count));
} else {
// otherwise need to create a new list of nodes to replicate to, based on available nodes
// randomize this to ensure distribution of data
const nodes = server.nodes.map((node) => node.name);
const startingIndex = Math.floor(nodes.length * Math.random());
replicateTo.push(...nodes.slice(startingIndex, startingIndex + count));
const remainingToAdd = startingIndex + count - nodes.length;
if (remainingToAdd > 0) replicateTo.push(...nodes.slice(0, remainingToAdd));
}
return replicateTo;
}
return; // returning undefined will return the default residency of replicating everywhere
}
/**
* Turn on auditing at runtime
*/
static enableAuditing() {
if (audit) return; // already enabled
audit = true;
addDeleteRemoval();
TableResource.audit = true;
}
/**
* Coerce the id as a string to the correct type for the primary key
* @param id
* @returns
*/
static coerceId(id: string): number | string {
if (id === '') return null;
return coerceType(id, primaryKeyAttribute);
}
static async dropTable() {
delete databases[databaseName][tableName];
for (const entry of primaryStore.getRange({ versions: true, snapshot: false, lazy: true })) {
if (entry.metadataFlags & HAS_BLOBS && entry.value) {
deleteBlobsInObject(entry.value);
}
}
if (databaseName === databasePath) {
// part of a database
for (const attribute of attributes) {
dbisDb.remove(TableResource.tableName + '/' + attribute.name);
const index = indices[attribute.name];
index?.drop();
}
dbisDb.remove(TableResource.tableName + '/');
primaryStore.drop();
await dbisDb.committed;
} else {
// legacy table per database
await primaryStore.close();
fs.unlinkSync(primaryStore.path);
}
signalling.signalSchemaChange(
new SchemaEventMsg(process.pid, OPERATIONS_ENUM.DROP_TABLE, databaseName, tableName)
);
}
/**
* This retrieves the data of this resource. By default, with no argument, just return `this`.
*/
get(): TableResource<Record> | undefined;
/**
* This retrieves the data of this resource.
* @param target - If included, is an identifier/query that specifies the requested target to retrieve and query
*/
get(target: RequestTargetOrId): Record | AsyncIterable<Record> | Promise<Record | AsyncIterable<Record>>;
get(
target?: RequestTargetOrId
): TableResource<Record> | undefined | Record | AsyncIterable<Record> | Promise<Record | AsyncIterable<Record>> {
const constructor: Resource = this.constructor;
if (typeof target === 'string' && constructor.loadAsInstance !== false) return this.getProperty(target);
if (isSearchTarget(target)) {
// go back to the static search method so it gets a chance to override
return constructor.search(target, this.getContext());
}
if (target && target.id === undefined && !target.toString()) {
const description = {
// basically a describe call
records: './', // an href to the records themselves
name: tableName,
database: databaseName,
auditSize: auditStore?.getStats().entryCount,
attributes,
recordCount: undefined,
estimatedRecordRange: undefined,
};
if (this.getContext()?.includeExpensiveRecordCountEstimates) {
return TableResource.getRecordCount().then((recordCount) => {
description.recordCount = recordCount.recordCount;
description.estimatedRecordRange = recordCount.estimatedRange;
return description;
});
}
return description;
}
if (target !== undefined && constructor.loadAsInstance === false) {
const context = this.getContext();
const txn = txnForContext(context);
const readTxn = txn.getReadTxn();
if (readTxn?.isDone) {
throw new Error('You can not read from a transaction that has already been committed/aborted');
}
const id = requestTargetToId(target);
checkValidId(id);
let allowed = true;
if (target.checkPermission) {
// requesting authorization verification
allowed = this.allowRead(context.user, target, context);
}
return promiseNormalize(
when(
when(allowed, (allowed: boolean) => {
if (!allowed) {
throw new AccessViolation(context.user);
}
const ensureLoaded = true;
return loadLocalRecord(id, context, { transaction: readTxn, ensureLoaded }, false, (entry) => {
if (context.onlyIfCached) {
// don't go into the loading from source condition, but HTTP spec says to
// return 504 (rather than 404) if there is no content and the cache-control header
// dictates not to go to source
if (!entry?.value) throw new ServerError('Entry is not cached', 504);
} else if (ensureLoaded) {
const loadingFromSource = ensureLoadedFromSource(
constructor.source,
id,