import DataLoader from 'dataloader'; import invariant from 'invariant'; import type { EntityDatabaseAdapter } from '../EntityDatabaseAdapter.ts'; import type { EntityQueryContext, EntityTransactionalQueryContext } from '../EntityQueryContext.ts'; import { TransactionalDataLoaderMode } from '../EntityQueryContext.ts'; import type { EntityQueryContextProvider } from '../EntityQueryContextProvider.ts'; import { partitionErrors } from '../entityUtils.ts'; import { timeAndLogLoadMapEventAsync, timeAndLogLoadOneEventAsync, } from '../metrics/EntityMetricsUtils.ts'; import type { IEntityMetricsAdapter } from '../metrics/IEntityMetricsAdapter.ts'; import { EntityMetricsLoadType, IncrementLoadCountEventType, } from '../metrics/IEntityMetricsAdapter.ts'; import { computeIfAbsent } from '../utils/collections/maps.ts'; import type { IEntityLoadKey, IEntityLoadValue, LoadPair } from './EntityLoadInterfaces.ts'; import type { ReadThroughEntityCache } from './ReadThroughEntityCache.ts'; type DataLoaderMap> = Map< string, DataLoader[]> >; /** * A data manager is responsible for orchestrating multiple sources of entity * data including local caches, EntityCacheAdapter, and EntityDatabaseAdapter. * * It is also responsible for invalidating all sources of data when mutated using EntityMutator. * * @internal */ export class EntityDataManager< TFields extends Record, TIDField extends keyof TFields, > { // map from (load method type + data manager data loader key) to dataloader private readonly dataLoaders: DataLoaderMap = new Map(); // map from transaction id to dataloader map private readonly transactionalDataLoaders: Map> = new Map(); constructor( private readonly databaseAdapter: EntityDatabaseAdapter, private readonly entityCache: ReadThroughEntityCache, private readonly queryContextProvider: EntityQueryContextProvider, private readonly metricsAdapter: IEntityMetricsAdapter, private readonly entityClassName: string, ) {} private getDataLoaderForLoadKey< TLoadKey extends IEntityLoadKey, TSerializedLoadValue, TLoadValue extends IEntityLoadValue, >(key: TLoadKey): DataLoader[]> { return computeIfAbsent( this.dataLoaders, key.getLoadMethodType() + key.getDataManagerDataLoaderKey(), () => { return new DataLoader( async ( serializedLoadValues: readonly TSerializedLoadValue[], ): Promise => { const values = serializedLoadValues.map((serializedLoadValue) => key.deserializeLoadValue(serializedLoadValue), ); const objectMap = await this.loadManyForNonTransactionalDataLoaderAsync(key, values); return values.map((value) => objectMap.get(value) ?? []); }, ); }, ); } private async loadManyForNonTransactionalDataLoaderAsync< TLoadKey extends IEntityLoadKey, TSerializedLoadValue, TLoadValue extends IEntityLoadValue, >( key: TLoadKey, values: readonly TLoadValue[], ): Promise[]>> { this.metricsAdapter.incrementDataManagerLoadCount({ type: IncrementLoadCountEventType.CACHE, isInTransaction: false, fieldValueCount: values.length, entityClassName: this.entityClassName, loadType: key.getLoadMethodType(), }); return await this.entityCache.readManyThroughAsync(key, values, async (fetcherValues) => { this.metricsAdapter.incrementDataManagerLoadCount({ type: IncrementLoadCountEventType.DATABASE, isInTransaction: false, fieldValueCount: fetcherValues.length, entityClassName: this.entityClassName, loadType: key.getLoadMethodType(), }); return await this.databaseAdapter.fetchManyWhereAsync( this.queryContextProvider.getQueryContext(), key, fetcherValues, ); }); } private getTransactionalDataLoaderForLoadKey< TLoadKey extends IEntityLoadKey, TSerializedLoadValue, TLoadValue extends IEntityLoadValue, >( queryContext: EntityTransactionalQueryContext, key: TLoadKey, ): DataLoader[]> { const dataLoaderMapForTransaction = computeIfAbsent( this.transactionalDataLoaders, queryContext.transactionId, () => { queryContext.appendTransactionEndCallback(() => { this.transactionalDataLoaders.delete(queryContext.transactionId); }); return new Map(); }, ); return computeIfAbsent( dataLoaderMapForTransaction, key.getLoadMethodType() + key.getDataManagerDataLoaderKey(), () => { return new DataLoader( async ( serializedLoadValues: readonly TSerializedLoadValue[], ): Promise => { const values = serializedLoadValues.map((serializedLoadValue) => key.deserializeLoadValue(serializedLoadValue), ); const objectMap = await this.loadManyForTransactionalDataLoaderAsync( queryContext, key, values, ); return values.map((value) => objectMap.get(value) ?? []); }, { // only cache if transactional dataloader caching is enabled for the transactional query context cache: queryContext.transactionalDataLoaderMode === TransactionalDataLoaderMode.ENABLED, }, ); }, ); } private async loadManyForTransactionalDataLoaderAsync< TLoadKey extends IEntityLoadKey, TSerializedLoadValue, TLoadValue extends IEntityLoadValue, >( queryContext: EntityTransactionalQueryContext, key: TLoadKey, values: readonly TLoadValue[], ): Promise[]>> { this.metricsAdapter.incrementDataManagerLoadCount({ type: IncrementLoadCountEventType.DATABASE, isInTransaction: true, fieldValueCount: values.length, entityClassName: this.entityClassName, loadType: key.getLoadMethodType(), }); return await this.databaseAdapter.fetchManyWhereAsync(queryContext, key, values); } /** * Load many objects through read-through dataloader (batcher) and cache (optional). * * @param queryContext - query context in which to perform the load * @param key - load key being queried * @param values - load values being queried for the key * @returns map from load value to objects that match the query for that load value */ async loadManyEqualingAsync< TLoadKey extends IEntityLoadKey, TSerializedLoadValue, TLoadValue extends IEntityLoadValue, >( queryContext: EntityQueryContext, key: TLoadKey, values: readonly TLoadValue[], ): Promise[]>> { return await timeAndLogLoadMapEventAsync( this.metricsAdapter, EntityMetricsLoadType.LOAD_MANY, this.entityClassName, queryContext, )(this.loadManyEqualingInternalAsync(queryContext, key, values)); } private async loadManyEqualingInternalAsync< TLoadKey extends IEntityLoadKey, TSerializedLoadValue, TLoadValue extends IEntityLoadValue, >( queryContext: EntityQueryContext, key: TLoadKey, values: readonly TLoadValue[], ): Promise[]>> { key.validateRuntimeLoadValuesForDataManagerDataLoader(values, this.entityClassName); if ( queryContext.isInTransaction() && queryContext.transactionalDataLoaderMode === TransactionalDataLoaderMode.DISABLED ) { this.metricsAdapter.incrementDataManagerLoadCount({ type: IncrementLoadCountEventType.DATABASE, isInTransaction: true, fieldValueCount: values.length, entityClassName: this.entityClassName, loadType: key.getLoadMethodType(), }); return await this.databaseAdapter.fetchManyWhereAsync(queryContext, key, values); } this.metricsAdapter.incrementDataManagerLoadCount({ type: IncrementLoadCountEventType.DATALOADER, isInTransaction: queryContext.isInTransaction(), fieldValueCount: values.length, entityClassName: this.entityClassName, loadType: key.getLoadMethodType(), }); const dataLoader = queryContext.isInTransaction() ? this.getTransactionalDataLoaderForLoadKey(queryContext, key) : this.getDataLoaderForLoadKey(key); const results = await dataLoader.loadMany(values.map((v) => key.serializeLoadValue(v))); const [successfulValues, errors] = partitionErrors(results); if (errors.length > 0) { const error = errors[0]!; throw error; } invariant( values.length === successfulValues.length, `length mismatch between values (${values.length}) and successful values (${successfulValues.length})`, ); const mapToReturn = key.vendNewLoadValueMap[]>(); for (let i = 0; i < successfulValues.length; i++) { mapToReturn.set(values[i]!, successfulValues[i]!); } return mapToReturn; } /** * Load one object matching load key and load value if at least one matching object exists. * Returned object is not guaranteed to be deterministic. * * Used when evaluating EntityEdgeDeletionAuthorizationInferenceBehavior.ONE_IMPLIES_ALL. * * @param queryContext - query context in which to perform the load * @param key - load key being queried * @param values - load value being queried for the key * @returns at most one that match the query for that load value */ public async loadOneEqualingAsync< TLoadKey extends IEntityLoadKey, TSerializedLoadValue, TLoadValue extends IEntityLoadValue, >( queryContext: EntityQueryContext, key: TLoadKey, value: TLoadValue, ): Promise | null> { return await timeAndLogLoadOneEventAsync( this.metricsAdapter, EntityMetricsLoadType.LOAD_ONE, this.entityClassName, queryContext, )(this.databaseAdapter.fetchOneWhereAsync(queryContext, key, value)); } private async invalidateOneAsync< TLoadKey extends IEntityLoadKey, TSerializedLoadValue, TLoadValue extends IEntityLoadValue, >(key: TLoadKey, value: TLoadValue): Promise { await this.entityCache.invalidateManyAsync(key, [value]); this.getDataLoaderForLoadKey(key).clear(key.serializeLoadValue(value)); } private invalidateOneForTransaction< TLoadKey extends IEntityLoadKey, TSerializedLoadValue, TLoadValue extends IEntityLoadValue, >(queryContext: EntityTransactionalQueryContext, key: TLoadKey, value: TLoadValue): void { this.getTransactionalDataLoaderForLoadKey(queryContext, key).clear( key.serializeLoadValue(value), ); } /** * Invalidate all caches, in-memory or otherwise, for sets of key-value pairs. * @param pairs - key-value pairs to invalidate */ public async invalidateKeyValuePairsAsync( pairs: readonly LoadPair[], ): Promise { await Promise.all(pairs.map(([key, value]) => this.invalidateOneAsync(key, value))); } /** * Invalidate all in-memory caches for sets of key-value pairs for all transactions and parent transactions. * @param pairs - key-value pairs to invalidate */ public invalidateKeyValuePairsForTransaction( queryContext: EntityTransactionalQueryContext, pairs: readonly LoadPair[], ): void { if (queryContext.transactionalDataLoaderMode === TransactionalDataLoaderMode.DISABLED) { return; } // invalidate all query contexts in transaction tree const outermostTransactionalQueryContext = EntityDataManager.getOutermostTransactionalQueryContextIfInNestedTransaction(queryContext); const allQueryContextsToInvalidate = [ outermostTransactionalQueryContext, ...EntityDataManager.getAllDescendantTransactionalQueryContexts( outermostTransactionalQueryContext, ), ]; for (const currentQueryContext of allQueryContextsToInvalidate) { for (const [key, value] of pairs) { this.invalidateOneForTransaction(currentQueryContext, key, value); } } } /** * Traverse to root of transactional query context tree. */ private static getOutermostTransactionalQueryContextIfInNestedTransaction( queryContext: EntityTransactionalQueryContext, ): EntityTransactionalQueryContext { if (queryContext.isInNestedTransaction()) { return EntityDataManager.getOutermostTransactionalQueryContextIfInNestedTransaction( queryContext.parentQueryContext, ); } else { return queryContext; } } /** * Get a list of all child query contexts recursively for a given query context. */ private static getAllDescendantTransactionalQueryContexts( queryContext: EntityTransactionalQueryContext, ): readonly EntityTransactionalQueryContext[] { if (queryContext.childQueryContexts.length === 0) { return []; } return queryContext.childQueryContexts.flatMap((childQueryContext) => { return [ childQueryContext, ...EntityDataManager.getAllDescendantTransactionalQueryContexts(childQueryContext), ]; }); } }