@memberjunction/generic-database-provider 6.1.2 → 6.2.0-edge.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/GenericDatabaseProvider.d.ts +111 -4
- package/dist/GenericDatabaseProvider.d.ts.map +1 -1
- package/dist/GenericDatabaseProvider.js +281 -21
- package/dist/GenericDatabaseProvider.js.map +1 -1
- package/dist/SqlLogger.d.ts.map +1 -1
- package/dist/SqlLogger.js +4 -2
- package/dist/SqlLogger.js.map +1 -1
- package/dist/TransactionFrameTracker.d.ts +72 -0
- package/dist/TransactionFrameTracker.d.ts.map +1 -0
- package/dist/TransactionFrameTracker.js +130 -0
- package/dist/TransactionFrameTracker.js.map +1 -0
- package/dist/saveTypes.d.ts +2 -0
- package/dist/saveTypes.d.ts.map +1 -1
- package/package.json +14 -14
|
@@ -33,6 +33,7 @@ import { SimpleVectorServiceProvider } from '@memberjunction/ai-vectors-memory';
|
|
|
33
33
|
import { QueueManager } from '@memberjunction/queue';
|
|
34
34
|
import { BuildEntityActionDispatchKey, EntityActionDispatchGuard, EntityActionEngineServer } from '@memberjunction/actions';
|
|
35
35
|
import { BuildEntityChangeContext } from '@memberjunction/actions-base';
|
|
36
|
+
import { TransactionFrameTracker } from './TransactionFrameTracker.js';
|
|
36
37
|
import { EncryptionEngine } from '@memberjunction/encryption';
|
|
37
38
|
import { GeoCodeSyncService } from '@memberjunction/geo-core';
|
|
38
39
|
/**
|
|
@@ -82,6 +83,21 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
82
83
|
* throwing 'No active transaction to rollback' on top of the real error (#4447).
|
|
83
84
|
*/
|
|
84
85
|
this._abandonedByFailedCommit = false;
|
|
86
|
+
/**
|
|
87
|
+
* Work waiting for the outermost commit (see {@link RunAfterCommit}). `Depth` is the frame that
|
|
88
|
+
* currently owns the entry: a savepoint rollback drops the entries its frame owns, a savepoint
|
|
89
|
+
* release hands them to the enclosing frame.
|
|
90
|
+
*/
|
|
91
|
+
this._postCommitTasks = [];
|
|
92
|
+
/**
|
|
93
|
+
* Tasks whose own transaction already settled, held back because an UNRELATED transaction is
|
|
94
|
+
* open on this instance. Running them now would enlist their writes in it — on one connection,
|
|
95
|
+
* that means a rollback of work that has nothing to do with them. Drained when this provider
|
|
96
|
+
* goes idle, whichever way that transaction ends.
|
|
97
|
+
*/
|
|
98
|
+
this._idlePostCommitTasks = [];
|
|
99
|
+
/** Identity of each open frame and the fate of recent transactions, for {@link PostCommitToken}s. */
|
|
100
|
+
this._frameTracker = new TransactionFrameTracker();
|
|
85
101
|
this._txMutex = Promise.resolve();
|
|
86
102
|
}
|
|
87
103
|
/**
|
|
@@ -350,6 +366,10 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
350
366
|
// built any later would report that nothing changed. Everything below this line may yield;
|
|
351
367
|
// nothing above it does.
|
|
352
368
|
const entityChange = BuildEntityChangeContext(entity);
|
|
369
|
+
// Same reason: by the first `await` the save's transaction may already have committed or
|
|
370
|
+
// rolled back. The token ties a Durable After* run to the transaction that caused it, so a
|
|
371
|
+
// rolled-back save never fires it (see RunAfterCommit).
|
|
372
|
+
const postCommitToken = this.CapturePostCommitToken();
|
|
353
373
|
try {
|
|
354
374
|
const engine = EntityActionEngineServer.Instance;
|
|
355
375
|
await engine.Config(false, user);
|
|
@@ -383,6 +403,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
383
403
|
InvocationType: invocationTypeEntity,
|
|
384
404
|
ContextUser: user,
|
|
385
405
|
EntityChange: entityChange,
|
|
406
|
+
PostCommitToken: postCommitToken,
|
|
386
407
|
});
|
|
387
408
|
// null means the binding is scoped (ScopeEntityID/ScopeRecordID) and this record falls
|
|
388
409
|
// outside it — the action never ran, so there is no result to report.
|
|
@@ -414,6 +435,9 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
414
435
|
* until after transaction commit (see SQLServerDataProvider).
|
|
415
436
|
*/
|
|
416
437
|
async HandleEntityAIActions(entity, baseType, before, user) {
|
|
438
|
+
// Before the first `await`: after-save dispatch is fire-and-forget, so by the time the task
|
|
439
|
+
// is enqueued the save's transaction may already have settled. See RunAfterCommit.
|
|
440
|
+
const postCommitToken = this.CapturePostCommitToken();
|
|
417
441
|
try {
|
|
418
442
|
if (baseType === 'delete')
|
|
419
443
|
return; // delete not yet supported for AI actions
|
|
@@ -435,7 +459,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
435
459
|
}
|
|
436
460
|
else {
|
|
437
461
|
try {
|
|
438
|
-
this.EnqueueAfterSaveAIAction(p, user);
|
|
462
|
+
this.EnqueueAfterSaveAIAction(p, user, postCommitToken);
|
|
439
463
|
}
|
|
440
464
|
catch (e) {
|
|
441
465
|
LogError(e instanceof Error ? e.message : String(e));
|
|
@@ -453,8 +477,11 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
453
477
|
* Enqueues an after-save AI action for execution. By default, immediately adds
|
|
454
478
|
* to QueueManager. Subclasses with transaction support can override to defer
|
|
455
479
|
* until after transaction commit.
|
|
480
|
+
*
|
|
481
|
+
* @param _postCommitToken The transaction frames open when the save dispatched this action,
|
|
482
|
+
* captured before any `await` — pass it to {@link RunAfterCommit} when deferring.
|
|
456
483
|
*/
|
|
457
|
-
EnqueueAfterSaveAIAction(params, user) {
|
|
484
|
+
EnqueueAfterSaveAIAction(params, user, _postCommitToken) {
|
|
458
485
|
QueueManager.AddTask('Entity AI Action', params, null, user);
|
|
459
486
|
}
|
|
460
487
|
/**************************************************************************/
|
|
@@ -749,6 +776,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
749
776
|
description: options.description,
|
|
750
777
|
ignoreLogging: options.ignoreLogging,
|
|
751
778
|
isMutation: options.isMutation,
|
|
779
|
+
ignoreAmbientTransaction: options.ignoreAmbientTransaction,
|
|
752
780
|
} : undefined;
|
|
753
781
|
const promises = queries.map((query, index) => {
|
|
754
782
|
const queryParams = parameters?.[index];
|
|
@@ -915,6 +943,16 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
915
943
|
const pkValues = entity.PrimaryKey?.KeyValuePairs?.map((p) => p.Value) ?? [];
|
|
916
944
|
return this.allocateSaveCallSuffixForPk(entity.TransactionGroup, entity.EntityInfo.SchemaName, entity.EntityInfo.BaseTable, pkValues);
|
|
917
945
|
}
|
|
946
|
+
/**
|
|
947
|
+
* Optional replay form of a CREATE for the SQL log only (never executed). Dialects that
|
|
948
|
+
* record saves for migration replay (SQL Server's Metadata_Sync migrations) override
|
|
949
|
+
* this to emit a create-or-update guarded on the primary key, so replaying the
|
|
950
|
+
* recording on a database that already holds the row converges instead of failing
|
|
951
|
+
* (MemberJunction/MJ#4503). Default: no replay form, the plain save SQL is logged.
|
|
952
|
+
*/
|
|
953
|
+
RenderReplaySaveSQL(_binding, _entity, _fieldValues) {
|
|
954
|
+
return undefined;
|
|
955
|
+
}
|
|
918
956
|
/**
|
|
919
957
|
* Concrete implementation of the abstract save-SQL builder defined on
|
|
920
958
|
* `DatabaseProviderBase`. Iterates fields via the single `IsSPParameter`
|
|
@@ -978,7 +1016,11 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
978
1016
|
// record-change-free form to fall back to.
|
|
979
1017
|
const baseSaveSQL = this.WrapSaveCallForResult(binding, entity, spName);
|
|
980
1018
|
let saveSQL = baseSaveSQL;
|
|
981
|
-
|
|
1019
|
+
// A CREATE's logged form is guarded on the primary key so a migration replay of
|
|
1020
|
+
// the recording converges on a database that already holds the row (#4503).
|
|
1021
|
+
// Updates and dialects without a replay form log the plain save SQL.
|
|
1022
|
+
const replaySQL = isNew ? this.RenderReplaySaveSQL(binding, entity, fieldValueMap) : undefined;
|
|
1023
|
+
const simpleSQL = replaySQL ?? baseSaveSQL.sql;
|
|
982
1024
|
// 5. Optionally wrap with record-change emission.
|
|
983
1025
|
let overlappingChangeData;
|
|
984
1026
|
// Per-save suppression: a high-volume machine writer (integration sync) opts out of the
|
|
@@ -1941,8 +1983,22 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
1941
1983
|
sUserSearchSQL += ' OR ';
|
|
1942
1984
|
sUserSearchSQL += `(${this.QuoteIdentifier(field.Name)} ${sParam})`;
|
|
1943
1985
|
}
|
|
1944
|
-
if (sUserSearchSQL.length > 0)
|
|
1986
|
+
if (sUserSearchSQL.length > 0) {
|
|
1945
1987
|
sUserSearchSQL = '(' + sUserSearchSQL + ')';
|
|
1988
|
+
}
|
|
1989
|
+
else if (userSearchString && userSearchString.trim().length > 0 && entityInfo.HasSearchFields) {
|
|
1990
|
+
// A term was supplied and this entity DOES declare searchable fields, but every one of
|
|
1991
|
+
// them dropped out of the loop above — denied by field-level security, or not a sensible
|
|
1992
|
+
// text-search target. Returning the whole table would imply the search ran when it did
|
|
1993
|
+
// not, and in the FLS case would hand back rows the caller tried to narrow by a field
|
|
1994
|
+
// they cannot see. So return an unsatisfiable predicate.
|
|
1995
|
+
//
|
|
1996
|
+
// An entity that declares NO searchable field at all is a DIFFERENT case and stays a
|
|
1997
|
+
// no-op. The caller asked to filter by a surface the entity does not have; nothing was
|
|
1998
|
+
// withheld from them, and blanking a generic grid is the wrong answer. That no-op is
|
|
1999
|
+
// pinned by integration check runview-matrix.RVM9. See MJ#4581.
|
|
2000
|
+
sUserSearchSQL = '(1=0)';
|
|
2001
|
+
}
|
|
1946
2002
|
}
|
|
1947
2003
|
return sUserSearchSQL;
|
|
1948
2004
|
}
|
|
@@ -4318,6 +4374,16 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4318
4374
|
/**************************************************************************/
|
|
4319
4375
|
// GetDatasetByName — Shared Implementation
|
|
4320
4376
|
/**************************************************************************/
|
|
4377
|
+
/**
|
|
4378
|
+
* Whether a dataset's reads run on the pool regardless of the ambient transaction. The
|
|
4379
|
+
* metadata dataset is read by a timer-driven refresh that is not part of any caller's unit of
|
|
4380
|
+
* work, so it must never land on a transaction's connection beside its COMMIT (#4514). Every
|
|
4381
|
+
* other dataset keeps joining the ambient transaction: a caller that writes and then loads a
|
|
4382
|
+
* dataset inside one transaction expects to see its own rows.
|
|
4383
|
+
*/
|
|
4384
|
+
datasetReadsOnPool(datasetName) {
|
|
4385
|
+
return datasetName === GenericDatabaseProvider._mjMetadataDatasetName;
|
|
4386
|
+
}
|
|
4321
4387
|
/**
|
|
4322
4388
|
* Builds a parameter placeholder for parameterized queries.
|
|
4323
4389
|
* Default: PG-style ($1, $2, ...). SQL Server overrides to @p0, @p1, etc.
|
|
@@ -4345,7 +4411,8 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4345
4411
|
`INNER JOIN ${provider.QuoteSchemaAndView(schema, 'vwDatasetItems')} di ON d.${provider.QuoteIdentifier('ID')} = di.${provider.QuoteIdentifier('DatasetID')} ` +
|
|
4346
4412
|
`INNER JOIN ${provider.QuoteSchemaAndView(schema, 'vwEntities')} e ON di.${provider.QuoteIdentifier('EntityID')} = e.${provider.QuoteIdentifier('ID')} ` +
|
|
4347
4413
|
`WHERE d.${provider.QuoteIdentifier('Name')} = ${provider.BuildParameterPlaceholder(0)}`;
|
|
4348
|
-
const
|
|
4414
|
+
const readOptions = { ignoreAmbientTransaction: this.datasetReadsOnPool(datasetName) };
|
|
4415
|
+
const items = await provider.ExecuteSQL(sSQL, [datasetName], readOptions, contextUser);
|
|
4349
4416
|
if (!items || items.length === 0) {
|
|
4350
4417
|
return {
|
|
4351
4418
|
DatasetID: '',
|
|
@@ -4448,13 +4515,21 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4448
4515
|
}
|
|
4449
4516
|
// Phase 2: Execute SQL only for cache misses
|
|
4450
4517
|
let batchResults = [];
|
|
4518
|
+
// A batch that throws is a FAILED read, not an empty one. Falling through with empty
|
|
4519
|
+
// results made every uncached item report Success with zero rows, the dataset report
|
|
4520
|
+
// Success overall, and — for MJ_Metadata — GetAllMetadata replace a good metadata cache
|
|
4521
|
+
// with an empty one, after which every EntityByName in the process fails until restart.
|
|
4522
|
+
// One dropped connection during a background refresh did exactly that (#4486). The
|
|
4523
|
+
// error is carried on each affected item and on the dataset so callers can keep what
|
|
4524
|
+
// they already have.
|
|
4525
|
+
let batchError = null;
|
|
4451
4526
|
if (uncachedQueries.length > 0) {
|
|
4452
4527
|
try {
|
|
4453
|
-
batchResults = await provider.ExecuteSQLBatch(uncachedQueries, undefined,
|
|
4528
|
+
batchResults = await provider.ExecuteSQLBatch(uncachedQueries, undefined, { ignoreAmbientTransaction: readOptions.ignoreAmbientTransaction }, contextUser);
|
|
4454
4529
|
}
|
|
4455
4530
|
catch (err) {
|
|
4456
|
-
|
|
4457
|
-
|
|
4531
|
+
batchError = err instanceof Error ? err.message : String(err);
|
|
4532
|
+
LogError(`GetDatasetByName("${datasetName}"): Batch execution failed: ${batchError}`);
|
|
4458
4533
|
}
|
|
4459
4534
|
}
|
|
4460
4535
|
// Phase 3: Process SQL results and write-through to cache
|
|
@@ -4465,6 +4540,20 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4465
4540
|
const entityID = String(item['EntityID']);
|
|
4466
4541
|
const code = String(item['Code']);
|
|
4467
4542
|
const dateFieldToCheck = String(item['DateFieldToCheck'] ?? '__mj_UpdatedAt');
|
|
4543
|
+
if (batchError !== null) {
|
|
4544
|
+
// Nothing is written through to the cache for a failed read: an empty slot
|
|
4545
|
+
// would be served as a genuine empty result until it expired.
|
|
4546
|
+
sqlResults.push({
|
|
4547
|
+
EntityID: entityID,
|
|
4548
|
+
EntityName: entityName,
|
|
4549
|
+
Code: code,
|
|
4550
|
+
Results: [],
|
|
4551
|
+
LatestUpdateDate: new Date(0),
|
|
4552
|
+
Success: false,
|
|
4553
|
+
Status: batchError,
|
|
4554
|
+
});
|
|
4555
|
+
continue;
|
|
4556
|
+
}
|
|
4468
4557
|
let itemData = batchResults[i] || [];
|
|
4469
4558
|
// Post-process rows for encryption/datetime
|
|
4470
4559
|
if (itemData.length > 0) {
|
|
@@ -4517,8 +4606,10 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4517
4606
|
message: `📊 [Dataset] GetDatasetByName("${datasetName}"): ${cacheHitCount} cache hits, ${cacheMissCount} cache misses, ${errorResults.length} errors — ${elapsedMs}ms`,
|
|
4518
4607
|
verboseOnly: true
|
|
4519
4608
|
});
|
|
4520
|
-
// Aggregate results
|
|
4609
|
+
// Aggregate results. A failed item fails the dataset, and its error becomes the
|
|
4610
|
+
// dataset's Status so the caller sees WHY rather than an empty success.
|
|
4521
4611
|
const bSuccess = results.every(result => result.Success);
|
|
4612
|
+
const firstFailure = results.find(result => !result.Success);
|
|
4522
4613
|
const latestUpdateDate = results.reduce((acc, result) => {
|
|
4523
4614
|
if (result?.LatestUpdateDate) {
|
|
4524
4615
|
const theDate = new Date(result.LatestUpdateDate);
|
|
@@ -4531,7 +4622,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4531
4622
|
DatasetID: String(items[0]['DatasetID']),
|
|
4532
4623
|
DatasetName: datasetName,
|
|
4533
4624
|
Success: bSuccess,
|
|
4534
|
-
Status: '',
|
|
4625
|
+
Status: bSuccess ? '' : (firstFailure?.Status ?? 'One or more dataset items failed to load'),
|
|
4535
4626
|
LatestUpdateDate: latestUpdateDate,
|
|
4536
4627
|
Results: results,
|
|
4537
4628
|
};
|
|
@@ -4557,7 +4648,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4557
4648
|
`INNER JOIN ${provider.QuoteSchemaAndView(schema, 'vwDatasetItems')} di ON d.${provider.QuoteIdentifier('ID')} = di.${provider.QuoteIdentifier('DatasetID')} ` +
|
|
4558
4649
|
`INNER JOIN ${provider.QuoteSchemaAndView(schema, 'vwEntities')} e ON di.${provider.QuoteIdentifier('EntityID')} = e.${provider.QuoteIdentifier('ID')} ` +
|
|
4559
4650
|
`WHERE d.${provider.QuoteIdentifier('Name')} = ${provider.BuildParameterPlaceholder(0)}`;
|
|
4560
|
-
const items = await provider.ExecuteSQL(sSQL, [datasetName],
|
|
4651
|
+
const items = await provider.ExecuteSQL(sSQL, [datasetName], { ignoreAmbientTransaction: this.datasetReadsOnPool(datasetName) }, contextUser);
|
|
4561
4652
|
if (!items || items.length === 0) {
|
|
4562
4653
|
return {
|
|
4563
4654
|
DatasetID: '',
|
|
@@ -4862,6 +4953,25 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4862
4953
|
* — outermost begin has depth 1 before the handle is published, and
|
|
4863
4954
|
* concurrent reads on SQL Server legitimately use the pool in that window.
|
|
4864
4955
|
*/
|
|
4956
|
+
/**
|
|
4957
|
+
* A debounced metadata refresh is timer-driven, so it can fire at any point of a caller's
|
|
4958
|
+
* unit of work — including the microtask window while the ambient transaction is being
|
|
4959
|
+
* committed. Joining that transaction puts the metadata batch on the transaction's single
|
|
4960
|
+
* connection alongside the COMMIT, which tedious rejects (EINVALIDSTATE) or drops (ECLOSE)
|
|
4961
|
+
* once the handle is torn down, and a transactional query is deliberately never retried.
|
|
4962
|
+
* Metadata reads are not part of anyone's unit of work, so wait for the transaction to end
|
|
4963
|
+
* before starting one (#4486).
|
|
4964
|
+
*
|
|
4965
|
+
* This narrows the window rather than closing it: the check runs when the timer fires, and
|
|
4966
|
+
* the batch is issued several round trips later, so a transaction that begins in between
|
|
4967
|
+
* is still joined. That case is now harmless to the process — the batch fails, the dataset
|
|
4968
|
+
* reports it, and the loaded metadata stays — but the refresh itself is lost until the next
|
|
4969
|
+
* member write. Running the metadata batch on the pool regardless of the ambient
|
|
4970
|
+
* transaction is #4514 (alongside #4454, the commit-side half of the same window).
|
|
4971
|
+
*/
|
|
4972
|
+
get MetadataMemberRefreshMustWait() {
|
|
4973
|
+
return this.CurrentTransactionDepth > 0 || this.HasPhysicalTransaction;
|
|
4974
|
+
}
|
|
4865
4975
|
AssertAmbientTransactionUsable() {
|
|
4866
4976
|
if (this._doomed) {
|
|
4867
4977
|
throw new DoomedTransactionError(`SQL issued at depth ${this._transactionDepth} while the ambient transaction is doomed would autocommit on the pool`);
|
|
@@ -4900,8 +5010,132 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4900
5010
|
}
|
|
4901
5011
|
}
|
|
4902
5012
|
/**
|
|
4903
|
-
*
|
|
4904
|
-
*
|
|
5013
|
+
* Queue `task` until the outermost commit of the ambient transaction, or start it now when
|
|
5014
|
+
* there is none. See {@link DatabaseProviderBase.RunAfterCommit} for the contract.
|
|
5015
|
+
*
|
|
5016
|
+
* - Queued tasks run once, in registration order, after the outermost commit succeeds and the
|
|
5017
|
+
* transaction lock is released — so a task may begin its own transaction. The committer
|
|
5018
|
+
* awaits them; a failing task is logged and does not stop later tasks or reject the commit.
|
|
5019
|
+
* - Outermost rollback, a failed commit, a doomed/abandoned handle, and
|
|
5020
|
+
* {@link ResetTransactionState} discard the queue.
|
|
5021
|
+
* - A savepoint release keeps its tasks (they now belong to the enclosing frame); a savepoint
|
|
5022
|
+
* rollback discards only the tasks registered inside that savepoint.
|
|
5023
|
+
* - With a `token`, the task follows the transaction the token was captured in: it runs once
|
|
5024
|
+
* that transaction has committed; it is dropped if that transaction, or any savepoint the
|
|
5025
|
+
* token was captured in, rolled back — including a savepoint rolled back inside a transaction
|
|
5026
|
+
* that went on to commit — or if the token matches nothing this provider knows; otherwise it
|
|
5027
|
+
* is queued at the deepest captured frame that is still open. A token captured outside any
|
|
5028
|
+
* transaction always runs. "Runs" means immediately when this provider is idle, and otherwise
|
|
5029
|
+
* once it is: a task must never have its own writes rolled back by an unrelated transaction.
|
|
5030
|
+
*/
|
|
5031
|
+
RunAfterCommit(task, description = 'post-commit task', token) {
|
|
5032
|
+
if (token) {
|
|
5033
|
+
this.registerPostCommitTaskWithToken(task, description, token);
|
|
5034
|
+
return;
|
|
5035
|
+
}
|
|
5036
|
+
if (this._transactionDepth === 0 && !this.HasPhysicalTransaction) {
|
|
5037
|
+
super.RunAfterCommit(task, description);
|
|
5038
|
+
return;
|
|
5039
|
+
}
|
|
5040
|
+
this._postCommitTasks.push({ Task: task, Description: description, Depth: this._transactionDepth });
|
|
5041
|
+
}
|
|
5042
|
+
/**
|
|
5043
|
+
* Snapshot of the open transaction frames. Synchronous, and never `undefined` on this provider:
|
|
5044
|
+
* outside a transaction it returns a token whose epoch is `null`, which says the work is already
|
|
5045
|
+
* durable rather than saying nothing. See {@link DatabaseProviderBase.CapturePostCommitToken}.
|
|
5046
|
+
*/
|
|
5047
|
+
CapturePostCommitToken() {
|
|
5048
|
+
return this._frameTracker.Capture();
|
|
5049
|
+
}
|
|
5050
|
+
registerPostCommitTaskWithToken(task, description, token) {
|
|
5051
|
+
const resolution = this._frameTracker.Resolve(token, this._doomed);
|
|
5052
|
+
switch (resolution.Kind) {
|
|
5053
|
+
case 'run':
|
|
5054
|
+
this.runDetachedTask(task, description);
|
|
5055
|
+
return;
|
|
5056
|
+
case 'queue':
|
|
5057
|
+
this._postCommitTasks.push({ Task: task, Description: description, Depth: resolution.Depth });
|
|
5058
|
+
return;
|
|
5059
|
+
case 'drop':
|
|
5060
|
+
if (resolution.Unknown) {
|
|
5061
|
+
// Not a rollback: durable work is being dropped because its transaction cannot be
|
|
5062
|
+
// identified. That is data loss, so it must not read as routine housekeeping.
|
|
5063
|
+
LogError(`Dropped post-commit task '${description}': ${resolution.Reason}`);
|
|
5064
|
+
}
|
|
5065
|
+
else {
|
|
5066
|
+
LogStatus(`Dropped post-commit task '${description}': ${resolution.Reason}`);
|
|
5067
|
+
}
|
|
5068
|
+
return;
|
|
5069
|
+
}
|
|
5070
|
+
}
|
|
5071
|
+
/** Number of tasks waiting for the outermost commit. */
|
|
5072
|
+
get PendingPostCommitTaskCount() {
|
|
5073
|
+
return this._postCommitTasks.length;
|
|
5074
|
+
}
|
|
5075
|
+
/** Number of tasks waiting only for this provider to go idle. */
|
|
5076
|
+
get PendingIdlePostCommitTaskCount() {
|
|
5077
|
+
return this._idlePostCommitTasks.length;
|
|
5078
|
+
}
|
|
5079
|
+
/**
|
|
5080
|
+
* Run work whose own transaction has already settled. Immediate when this provider is idle;
|
|
5081
|
+
* otherwise held until it is, so the task's writes cannot join — and be rolled back with — a
|
|
5082
|
+
* transaction it has nothing to do with.
|
|
5083
|
+
*/
|
|
5084
|
+
runDetachedTask(task, description) {
|
|
5085
|
+
if (this._transactionDepth === 0 && !this.HasPhysicalTransaction) {
|
|
5086
|
+
super.RunAfterCommit(task, description);
|
|
5087
|
+
return;
|
|
5088
|
+
}
|
|
5089
|
+
this._idlePostCommitTasks.push({ Task: task, Description: description, Depth: 0 });
|
|
5090
|
+
}
|
|
5091
|
+
/** Run everything that was waiting for this provider to go idle. Never throws. */
|
|
5092
|
+
async drainIdlePostCommitTasks() {
|
|
5093
|
+
if (this._idlePostCommitTasks.length === 0 || this._transactionDepth > 0 || this.HasPhysicalTransaction) {
|
|
5094
|
+
return;
|
|
5095
|
+
}
|
|
5096
|
+
const tasks = this._idlePostCommitTasks;
|
|
5097
|
+
this._idlePostCommitTasks = [];
|
|
5098
|
+
LogStatus(`Running ${tasks.length} post-commit task(s) held back by an unrelated transaction`);
|
|
5099
|
+
for (const entry of tasks) {
|
|
5100
|
+
await this.RunPostCommitTaskSafely(entry.Task, entry.Description);
|
|
5101
|
+
}
|
|
5102
|
+
}
|
|
5103
|
+
/** Run tasks detached from a committed transaction, one at a time, in order. Never throws. */
|
|
5104
|
+
async runPostCommitTasks(tasks) {
|
|
5105
|
+
if (tasks.length === 0) {
|
|
5106
|
+
return;
|
|
5107
|
+
}
|
|
5108
|
+
LogStatus(`Running ${tasks.length} post-commit task(s) after transaction commit`);
|
|
5109
|
+
for (const entry of tasks) {
|
|
5110
|
+
await this.RunPostCommitTaskSafely(entry.Task, entry.Description);
|
|
5111
|
+
}
|
|
5112
|
+
}
|
|
5113
|
+
/** Detach the whole queue (outermost commit succeeded). */
|
|
5114
|
+
takePostCommitTasks() {
|
|
5115
|
+
const tasks = this._postCommitTasks;
|
|
5116
|
+
this._postCommitTasks = [];
|
|
5117
|
+
return tasks;
|
|
5118
|
+
}
|
|
5119
|
+
/** Drop every task owned by `depth` or deeper; they belonged to work that will never commit. */
|
|
5120
|
+
discardPostCommitTasks(depth, reason) {
|
|
5121
|
+
const kept = this._postCommitTasks.filter((entry) => entry.Depth < depth);
|
|
5122
|
+
const dropped = this._postCommitTasks.length - kept.length;
|
|
5123
|
+
this._postCommitTasks = kept;
|
|
5124
|
+
if (dropped > 0) {
|
|
5125
|
+
LogStatus(`Cleared ${dropped} post-commit task(s): ${reason}`);
|
|
5126
|
+
}
|
|
5127
|
+
}
|
|
5128
|
+
/** A released savepoint's tasks now belong to the enclosing frame. */
|
|
5129
|
+
promotePostCommitTasks(releasedDepth) {
|
|
5130
|
+
for (const entry of this._postCommitTasks) {
|
|
5131
|
+
if (entry.Depth >= releasedDepth) {
|
|
5132
|
+
entry.Depth = releasedDepth - 1;
|
|
5133
|
+
}
|
|
5134
|
+
}
|
|
5135
|
+
}
|
|
5136
|
+
/**
|
|
5137
|
+
* After a successful outermost commit, once depth is 0, the transaction lock is released, and
|
|
5138
|
+
* the {@link RunAfterCommit} queue has been drained. Subclass hook; no-op by default.
|
|
4905
5139
|
*/
|
|
4906
5140
|
async AfterPhysicalCommit() {
|
|
4907
5141
|
/* no-op */
|
|
@@ -4921,6 +5155,8 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4921
5155
|
}
|
|
4922
5156
|
markDoomed() {
|
|
4923
5157
|
this._doomed = true;
|
|
5158
|
+
// A doomed transaction can never commit, so nothing queued for its commit may run.
|
|
5159
|
+
this.discardPostCommitTasks(0, 'the ambient transaction was abandoned');
|
|
4924
5160
|
}
|
|
4925
5161
|
/**
|
|
4926
5162
|
* Drop a dead physical handle and reset depth/stack. Safe to call when
|
|
@@ -4929,29 +5165,34 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4929
5165
|
*/
|
|
4930
5166
|
async ResetTransactionState() {
|
|
4931
5167
|
await this.WithTransactionLock(() => this.abandonDoomedTransaction());
|
|
5168
|
+
await this.drainIdlePostCommitTasks();
|
|
4932
5169
|
}
|
|
4933
5170
|
async BeginTransaction() {
|
|
4934
5171
|
return this.WithTransactionLock(() => this.beginTransactionCore());
|
|
4935
5172
|
}
|
|
4936
5173
|
async CommitTransaction() {
|
|
4937
|
-
|
|
4938
|
-
await this.WithTransactionLock(async () => {
|
|
5174
|
+
// null = not the outermost commit, so nothing drains and the subclass hook does not run.
|
|
5175
|
+
const committedTasks = await this.WithTransactionLock(async () => {
|
|
4939
5176
|
const outermost = this._transactionDepth === 1;
|
|
4940
|
-
await this.commitTransactionCore();
|
|
4941
|
-
|
|
5177
|
+
const tasks = await this.commitTransactionCore();
|
|
5178
|
+
return outermost ? tasks : null;
|
|
4942
5179
|
});
|
|
4943
|
-
if (
|
|
5180
|
+
if (committedTasks) {
|
|
5181
|
+
await this.runPostCommitTasks(committedTasks);
|
|
4944
5182
|
await this.AfterPhysicalCommit();
|
|
4945
5183
|
}
|
|
5184
|
+
await this.drainIdlePostCommitTasks();
|
|
4946
5185
|
}
|
|
4947
5186
|
async RollbackTransaction() {
|
|
4948
|
-
|
|
5187
|
+
await this.WithTransactionLock(() => this.rollbackTransactionCore());
|
|
5188
|
+
await this.drainIdlePostCommitTasks();
|
|
4949
5189
|
}
|
|
4950
5190
|
async beginTransactionCore() {
|
|
4951
5191
|
if (this._doomed) {
|
|
4952
5192
|
throw new DoomedTransactionError();
|
|
4953
5193
|
}
|
|
4954
5194
|
this._transactionDepth++;
|
|
5195
|
+
this._frameTracker.PushFrame();
|
|
4955
5196
|
try {
|
|
4956
5197
|
if (this._transactionDepth === 1) {
|
|
4957
5198
|
this._abandonedByFailedCommit = false;
|
|
@@ -4975,6 +5216,8 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4975
5216
|
catch (e) {
|
|
4976
5217
|
if (this._transactionDepth > 0) {
|
|
4977
5218
|
this._transactionDepth--;
|
|
5219
|
+
// The frame never opened, so it undid nothing; any work captured in it belongs to its parent.
|
|
5220
|
+
this._frameTracker.ReleaseFrame();
|
|
4978
5221
|
}
|
|
4979
5222
|
if (e instanceof DoomedTransactionError || this._doomed) {
|
|
4980
5223
|
throw e;
|
|
@@ -5030,13 +5273,16 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
5030
5273
|
this.clearTransactionState();
|
|
5031
5274
|
await this.OnBeginFailedAtDepthZero();
|
|
5032
5275
|
}
|
|
5276
|
+
/**
|
|
5277
|
+
* Returns the post-commit tasks detached by a successful outermost commit; empty otherwise.
|
|
5278
|
+
*/
|
|
5033
5279
|
async commitTransactionCore() {
|
|
5034
5280
|
if (this._doomed) {
|
|
5035
5281
|
this.popDoomedFrame();
|
|
5036
5282
|
if (this._transactionDepth === 0) {
|
|
5037
5283
|
throw new DoomedTransactionError();
|
|
5038
5284
|
}
|
|
5039
|
-
return;
|
|
5285
|
+
return [];
|
|
5040
5286
|
}
|
|
5041
5287
|
if (!this.HasPhysicalTransaction) {
|
|
5042
5288
|
throw new Error('No active transaction to commit');
|
|
@@ -5055,8 +5301,10 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
5055
5301
|
LogError(e);
|
|
5056
5302
|
throw e;
|
|
5057
5303
|
}
|
|
5304
|
+
this._frameTracker.EndEpoch('committed');
|
|
5305
|
+
const tasks = this.takePostCommitTasks();
|
|
5058
5306
|
this.clearTransactionState();
|
|
5059
|
-
return;
|
|
5307
|
+
return tasks;
|
|
5060
5308
|
}
|
|
5061
5309
|
const savepointName = this._savepointStack[this._savepointStack.length - 1];
|
|
5062
5310
|
if (!savepointName) {
|
|
@@ -5077,8 +5325,11 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
5077
5325
|
throw new DoomedTransactionError(undefined, { cause: e });
|
|
5078
5326
|
}
|
|
5079
5327
|
}
|
|
5328
|
+
this.promotePostCommitTasks(this._transactionDepth);
|
|
5080
5329
|
this._savepointStack.pop();
|
|
5081
5330
|
this._transactionDepth--;
|
|
5331
|
+
this._frameTracker.ReleaseFrame();
|
|
5332
|
+
return [];
|
|
5082
5333
|
}
|
|
5083
5334
|
async rollbackTransactionCore() {
|
|
5084
5335
|
if (this._doomed) {
|
|
@@ -5121,8 +5372,10 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
5121
5372
|
ignoreLogging: true,
|
|
5122
5373
|
});
|
|
5123
5374
|
}
|
|
5375
|
+
this.discardPostCommitTasks(this._transactionDepth, `savepoint ${savepointName} was rolled back`);
|
|
5124
5376
|
this._savepointStack.pop();
|
|
5125
5377
|
this._transactionDepth--;
|
|
5378
|
+
this._frameTracker.RollBackFrame();
|
|
5126
5379
|
}
|
|
5127
5380
|
catch (savepointError) {
|
|
5128
5381
|
await this.HandleFailedSavepointRollback(savepointName, savepointError);
|
|
@@ -5141,15 +5394,22 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
5141
5394
|
}
|
|
5142
5395
|
this._savepointStack.pop();
|
|
5143
5396
|
this._transactionDepth--;
|
|
5397
|
+
this._frameTracker.RollBackFrame();
|
|
5144
5398
|
}
|
|
5145
5399
|
clearSavepointState() {
|
|
5146
5400
|
this._savepointStack = [];
|
|
5147
5401
|
this._savepointCounter = 0;
|
|
5148
5402
|
}
|
|
5403
|
+
/**
|
|
5404
|
+
* Back to depth 0. A successful commit detaches the post-commit queue first, so anything still
|
|
5405
|
+
* queued here belongs to a transaction that rolled back, failed, or was abandoned.
|
|
5406
|
+
*/
|
|
5149
5407
|
clearTransactionState() {
|
|
5150
5408
|
this._transactionDepth = 0;
|
|
5151
5409
|
this._doomed = false;
|
|
5152
5410
|
this.clearSavepointState();
|
|
5411
|
+
this._frameTracker.EndEpoch('rolledBack');
|
|
5412
|
+
this.discardPostCommitTasks(0, 'the transaction ended without committing');
|
|
5153
5413
|
}
|
|
5154
5414
|
}
|
|
5155
5415
|
//# sourceMappingURL=GenericDatabaseProvider.js.map
|