@memberjunction/integration-engine 6.2.0-edge.0 → 6.2.0-edge.2
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/ActionMetadataGenerator.d.ts +17 -17
- package/dist/ActionMetadataGenerator.js +70 -70
- package/dist/BaseIntegrationConnector.js +6 -6
- package/dist/BaseRESTIntegrationConnector.d.ts +28 -28
- package/dist/BaseRESTIntegrationConnector.js +97 -97
- package/dist/ConflictRecency.d.ts +4 -0
- package/dist/ConflictRecency.d.ts.map +1 -1
- package/dist/ConflictRecency.js +12 -4
- package/dist/ConflictRecency.js.map +1 -1
- package/dist/ConnectorFactory.d.ts +1 -1
- package/dist/ConnectorFactory.js +2 -2
- package/dist/ContentHash.d.ts +6 -0
- package/dist/ContentHash.d.ts.map +1 -1
- package/dist/ContentHash.js +15 -3
- package/dist/ContentHash.js.map +1 -1
- package/dist/CustomColumnPromotion.d.ts +12 -0
- package/dist/CustomColumnPromotion.d.ts.map +1 -1
- package/dist/CustomColumnPromotion.js +32 -8
- package/dist/CustomColumnPromotion.js.map +1 -1
- package/dist/CustomOverflow.d.ts +8 -0
- package/dist/CustomOverflow.d.ts.map +1 -1
- package/dist/CustomOverflow.js +20 -4
- package/dist/CustomOverflow.js.map +1 -1
- package/dist/EnrichSchemaConstraints.d.ts +1 -1
- package/dist/EnrichSchemaConstraints.js +2 -2
- package/dist/FieldMappingEngine.d.ts +3 -3
- package/dist/FieldMappingEngine.js +11 -11
- package/dist/HashDiff.d.ts +8 -0
- package/dist/HashDiff.d.ts.map +1 -1
- package/dist/HashDiff.js +22 -6
- package/dist/HashDiff.js.map +1 -1
- package/dist/IntegrationActionGenerator.d.ts +1 -1
- package/dist/IntegrationActionGenerator.js +2 -2
- package/dist/IntegrationConnectorCreationPipeline.d.ts +6 -6
- package/dist/IntegrationConnectorCreationPipeline.js +14 -14
- package/dist/IntegrationEngine.d.ts +38 -38
- package/dist/IntegrationEngine.js +132 -132
- package/dist/IntegrationSchemaSync.d.ts +47 -4
- package/dist/IntegrationSchemaSync.d.ts.map +1 -1
- package/dist/IntegrationSchemaSync.js +62 -30
- package/dist/IntegrationSchemaSync.js.map +1 -1
- package/dist/KeySerialization.d.ts +2 -0
- package/dist/KeySerialization.d.ts.map +1 -1
- package/dist/KeySerialization.js +5 -1
- package/dist/KeySerialization.js.map +1 -1
- package/dist/MatchEngine.d.ts +11 -11
- package/dist/MatchEngine.js +33 -33
- package/dist/RecordFlatten.d.ts +5 -1
- package/dist/RecordFlatten.d.ts.map +1 -1
- package/dist/RecordFlatten.js +11 -3
- package/dist/RecordFlatten.js.map +1 -1
- package/dist/RecordMapBatch.js +2 -2
- package/dist/StreamingDiscovery.d.ts +11 -0
- package/dist/StreamingDiscovery.d.ts.map +1 -1
- package/dist/StreamingDiscovery.js +22 -6
- package/dist/StreamingDiscovery.js.map +1 -1
- package/dist/SyncLogger.d.ts +15 -3
- package/dist/SyncLogger.d.ts.map +1 -1
- package/dist/SyncLogger.js +33 -9
- package/dist/SyncLogger.js.map +1 -1
- package/dist/WatermarkService.d.ts +2 -2
- package/dist/WatermarkService.js +4 -4
- package/dist/auth-helpers/BasicAuthHeaderBuilder.d.ts +6 -0
- package/dist/auth-helpers/BasicAuthHeaderBuilder.d.ts.map +1 -1
- package/dist/auth-helpers/BasicAuthHeaderBuilder.js +10 -2
- package/dist/auth-helpers/BasicAuthHeaderBuilder.js.map +1 -1
- package/dist/auth-helpers/OAuth1aSigner.d.ts +2 -0
- package/dist/auth-helpers/OAuth1aSigner.d.ts.map +1 -1
- package/dist/auth-helpers/OAuth1aSigner.js +10 -6
- package/dist/auth-helpers/OAuth1aSigner.js.map +1 -1
- package/dist/auth-helpers/OAuth2TokenManager.d.ts +2 -2
- package/dist/auth-helpers/OAuth2TokenManager.js +4 -4
- package/dist/auth-helpers/index.d.ts +2 -2
- package/dist/auth-helpers/index.d.ts.map +1 -1
- package/dist/auth-helpers/index.js +2 -2
- package/dist/auth-helpers/index.js.map +1 -1
- package/dist/index.d.ts +8 -8
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +8 -8
- package/dist/index.js.map +1 -1
- package/dist/prefetchFilter.d.ts +4 -0
- package/dist/prefetchFilter.d.ts.map +1 -1
- package/dist/prefetchFilter.js +10 -2
- package/dist/prefetchFilter.js.map +1 -1
- package/package.json +7 -7
|
@@ -12,14 +12,14 @@ import { FieldMappingEngine } from './FieldMappingEngine.js';
|
|
|
12
12
|
import { MatchEngine } from './MatchEngine.js';
|
|
13
13
|
import { WatermarkService } from './WatermarkService.js';
|
|
14
14
|
import { SyncLogger } from './SyncLogger.js';
|
|
15
|
-
import { CONTENT_HASH_COLUMN,
|
|
15
|
+
import { CONTENT_HASH_COLUMN, ComputeContentHash } from './ContentHash.js';
|
|
16
16
|
import { RecordMapBatch } from './RecordMapBatch.js';
|
|
17
|
-
import {
|
|
18
|
-
import {
|
|
19
|
-
import { CUSTOM_OVERFLOW_COLUMN,
|
|
17
|
+
import { BuildContentHashPrefetchFilter, QuoteTextLiteral } from './prefetchFilter.js';
|
|
18
|
+
import { SerializeKeyValue } from './KeySerialization.js';
|
|
19
|
+
import { CUSTOM_OVERFLOW_COLUMN, ReconcileOverflowValue, FoldCustomKeyStats } from './CustomOverflow.js';
|
|
20
20
|
import { ComputeExcludedSourceNames } from './SyncDirectives.js';
|
|
21
21
|
import { DescribeUnbindableFieldMaps, FindUnbindableFieldMaps } from './FieldMapValidation.js';
|
|
22
|
-
import {
|
|
22
|
+
import { PartitionRecords, PartitionRollupHash, DiffPartitions, PartitionKeyForIdentity } from './HashDiff.js';
|
|
23
23
|
import { RateLimiter } from './RateLimiter.js';
|
|
24
24
|
import { AdaptiveConcurrencyController, RunAdaptive } from './AdaptiveConcurrency.js';
|
|
25
25
|
import { mostRecentWinner } from './ConflictRecency.js';
|
|
@@ -304,7 +304,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
304
304
|
* therefore lands on the proven per-record path: a connection has to ASK for batched writes,
|
|
305
305
|
* and a malformed request is not an ask.
|
|
306
306
|
*/
|
|
307
|
-
|
|
307
|
+
readWriteMode(companyIntegration) {
|
|
308
308
|
try {
|
|
309
309
|
const raw = companyIntegration.Configuration;
|
|
310
310
|
if (!raw)
|
|
@@ -391,7 +391,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
391
391
|
* for absent, unparseable or wrongly-typed configuration — every failure mode keeps the side
|
|
392
392
|
* effects ON. A connection has to ask, and a malformed request is not an ask.
|
|
393
393
|
*/
|
|
394
|
-
|
|
394
|
+
readWriteSideEffects(companyIntegration) {
|
|
395
395
|
try {
|
|
396
396
|
const raw = companyIntegration.Get('Configuration');
|
|
397
397
|
if (!raw)
|
|
@@ -733,7 +733,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
733
733
|
// Bounded rather than unbounded: a workspace is one Node process, so concurrency buys
|
|
734
734
|
// overlap on network waiting and not more CPU, and a boot that adopted fifty runs at once
|
|
735
735
|
// would trade one pathology for another.
|
|
736
|
-
await RunResumesBounded(orphanedRuns.Results, ResumeConcurrency(), run => this.
|
|
736
|
+
await RunResumesBounded(orphanedRuns.Results, ResumeConcurrency(), run => this.resumeOneOrphanedRun(run, prov, rv, contextUser));
|
|
737
737
|
}
|
|
738
738
|
/**
|
|
739
739
|
* Resume ONE orphaned run, end to end: reserve the per-CompanyIntegration lock, claim the run,
|
|
@@ -748,7 +748,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
748
748
|
* atomic with several of these in flight: an async function runs synchronously up to its first
|
|
749
749
|
* await, and the pool always starts one from a synchronous call site.
|
|
750
750
|
*/
|
|
751
|
-
async
|
|
751
|
+
async resumeOneOrphanedRun(run, prov, rv, contextUser) {
|
|
752
752
|
const companyIntegrationID = run.CompanyIntegrationID;
|
|
753
753
|
const runID = run.ID;
|
|
754
754
|
const lockKey = companyIntegrationID.toLowerCase();
|
|
@@ -823,7 +823,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
823
823
|
console.log(`[IntegrationEngine] Run ${runID.substring(0, 8)} was a FULL sync — resuming as full, not incremental`);
|
|
824
824
|
}
|
|
825
825
|
// Load config and filter to only remaining entity maps (by map ID)
|
|
826
|
-
const config = await this.
|
|
826
|
+
const config = await this.loadRunConfiguration(companyIntegrationID, contextUser, resumeOptions);
|
|
827
827
|
const remainingMaps = config.entityMaps.filter(em => !completedMapIDs.has(em.ID.toLowerCase()));
|
|
828
828
|
if (remainingMaps.length === 0) {
|
|
829
829
|
console.log(`[IntegrationEngine] All entity maps completed for run ${runID.substring(0, 8)}, marking as Success`);
|
|
@@ -870,9 +870,9 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
870
870
|
progressSupplier: () => JSON.stringify(progressSnapshot),
|
|
871
871
|
});
|
|
872
872
|
const result = await IntegrationEngine.runContext.run(runCtx, async () => {
|
|
873
|
-
const r = await this.
|
|
873
|
+
const r = await this.executeEntityMaps(config, run, contextUser, undefined, abortController.signal);
|
|
874
874
|
r.RunID = runID;
|
|
875
|
-
await this.
|
|
875
|
+
await this.finalizeRun(run, r, contextUser);
|
|
876
876
|
return r;
|
|
877
877
|
});
|
|
878
878
|
resumeResult = result;
|
|
@@ -1090,7 +1090,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
1090
1090
|
*/
|
|
1091
1091
|
async executeSyncInternal(companyIntegrationID, contextUser, triggerType, onProgress, onNotification, options, abortSignal, existingRun) {
|
|
1092
1092
|
const startTime = Date.now();
|
|
1093
|
-
const logger = new SyncLogger({
|
|
1093
|
+
const logger = new SyncLogger({ CiId: companyIntegrationID, Integration: null });
|
|
1094
1094
|
logger.emit('sync.run.start', {
|
|
1095
1095
|
triggerType,
|
|
1096
1096
|
fullSync: options?.FullSync ?? false,
|
|
@@ -1119,7 +1119,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
1119
1119
|
* IDENTITY, so they rebuild lazily on first read after the swap.
|
|
1120
1120
|
*/
|
|
1121
1121
|
await IntegrationEngineBase.Instance.RefreshCatalog(contextUser);
|
|
1122
|
-
const config = await this.
|
|
1122
|
+
const config = await this.loadRunConfiguration(companyIntegrationID, contextUser, options);
|
|
1123
1123
|
logger.attachIntegrationName(config.companyIntegration.Integration);
|
|
1124
1124
|
logger.emit('sync.config.loaded', {
|
|
1125
1125
|
integration: config.companyIntegration.Integration,
|
|
@@ -1171,7 +1171,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
1171
1171
|
};
|
|
1172
1172
|
}
|
|
1173
1173
|
// Worker mode executes a row that already exists (Status='Queued'); the direct path creates one.
|
|
1174
|
-
const run = existingRun ?? await this.
|
|
1174
|
+
const run = existingRun ?? await this.createRunRecord(config.companyIntegration, triggerType, contextUser, options?.ScheduledJobRunID, options);
|
|
1175
1175
|
logger.attachRunId(run.ID);
|
|
1176
1176
|
// ── Durable-run ownership (PR 1 item 3): claim before the first batch. ──
|
|
1177
1177
|
// The claim is ONE atomic UPDATE (unowned OR expired lease) that bumps FenceToken;
|
|
@@ -1231,13 +1231,13 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
1231
1231
|
catch { /* best-effort */ }
|
|
1232
1232
|
}
|
|
1233
1233
|
try {
|
|
1234
|
-
const result = await this.
|
|
1234
|
+
const result = await this.executeEntityMaps(config, run, contextUser, onProgress, abortSignal, logger);
|
|
1235
1235
|
result.RunID = run.ID;
|
|
1236
1236
|
result.Duration = Date.now() - startTime;
|
|
1237
1237
|
if (result.RecordsErrored > 0) {
|
|
1238
1238
|
result.ErrorMessage = `Sync completed with ${result.RecordsErrored} error(s)`;
|
|
1239
1239
|
}
|
|
1240
|
-
await this.
|
|
1240
|
+
await this.finalizeRun(run, result, contextUser, onNotification, abortSignal?.aborted);
|
|
1241
1241
|
// Post-sync custom-column promotion (gaps.md §2 / M2). Self-gated server-side: a
|
|
1242
1242
|
// customs-free sync does no work. Skipped for an aborted run. Never throws into the sync.
|
|
1243
1243
|
if (!abortSignal?.aborted) {
|
|
@@ -1296,7 +1296,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
1296
1296
|
};
|
|
1297
1297
|
}
|
|
1298
1298
|
await this.finalizeSyncProgress(progress, 'failed', errMsg);
|
|
1299
|
-
await this.
|
|
1299
|
+
await this.failRun(run, err, contextUser, onNotification);
|
|
1300
1300
|
throw err;
|
|
1301
1301
|
}
|
|
1302
1302
|
}
|
|
@@ -1362,7 +1362,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
1362
1362
|
/**
|
|
1363
1363
|
* Loads all configuration needed for a sync run.
|
|
1364
1364
|
*/
|
|
1365
|
-
async
|
|
1365
|
+
async loadRunConfiguration(companyIntegrationID, contextUser, options) {
|
|
1366
1366
|
const rv = new RunView();
|
|
1367
1367
|
// BypassCache on ALL three: this loads the live configuration a sync is about to ACT on — the
|
|
1368
1368
|
// CompanyIntegration toggles, the per-entity-map Configuration (partitionReconcile/Merkle, sync
|
|
@@ -1463,7 +1463,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
1463
1463
|
/**
|
|
1464
1464
|
* Creates a new CompanyIntegrationRun record to track this sync.
|
|
1465
1465
|
*/
|
|
1466
|
-
async
|
|
1466
|
+
async createRunRecord(companyIntegration, triggerType, contextUser, scheduledJobRunID, options) {
|
|
1467
1467
|
const md = this.ProviderToUse;
|
|
1468
1468
|
const run = await md.GetEntityObject('MJ: Company Integration Runs', contextUser);
|
|
1469
1469
|
run.NewRecord();
|
|
@@ -1493,13 +1493,13 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
1493
1493
|
/**
|
|
1494
1494
|
* Processes all entity maps, aggregating results with progress tracking.
|
|
1495
1495
|
*/
|
|
1496
|
-
async
|
|
1496
|
+
async executeEntityMaps(config, run, contextUser, onProgress, abortSignal, logger) {
|
|
1497
1497
|
// Resolve the per-connection side-effect suppression ONCE for the run and stamp it on the
|
|
1498
1498
|
// run context, where CreateRecord/UpdateRecord/DeleteRecord (several frames below, no
|
|
1499
1499
|
// config parameter) read it back. Both run paths — direct and adopted — come through here.
|
|
1500
1500
|
const runCtxForFlags = this.currentRunContext;
|
|
1501
1501
|
if (runCtxForFlags) {
|
|
1502
|
-
runCtxForFlags.suppressWriteSideEffects = this.
|
|
1502
|
+
runCtxForFlags.suppressWriteSideEffects = this.readWriteSideEffects(config.companyIntegration) === 'suppressed';
|
|
1503
1503
|
}
|
|
1504
1504
|
const aggregate = {
|
|
1505
1505
|
Success: true,
|
|
@@ -1532,8 +1532,8 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
1532
1532
|
priority: entityMap.Priority ?? null,
|
|
1533
1533
|
});
|
|
1534
1534
|
try {
|
|
1535
|
-
const mapResult = await this.
|
|
1536
|
-
this.
|
|
1535
|
+
const mapResult = await this.processSingleEntityMap(config, entityMap, run, contextUser, i, totalMaps, onProgress, abortSignal, logger);
|
|
1536
|
+
this.mergeResult(aggregate, mapResult);
|
|
1537
1537
|
aggregate.EntityMapResults.push(this.buildEntityMapResult(entityMap, mapResult, Date.now() - mapStartTime));
|
|
1538
1538
|
logger?.emit('sync.entity-map.complete', {
|
|
1539
1539
|
externalObjectName: entityMap.ExternalObjectName,
|
|
@@ -2176,22 +2176,22 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
2176
2176
|
* - Push: detect MJ changes → map → push to external
|
|
2177
2177
|
* - Bidirectional: pull first, then push
|
|
2178
2178
|
*/
|
|
2179
|
-
async
|
|
2179
|
+
async processSingleEntityMap(config, entityMap, run, contextUser, entityMapIndex, totalEntityMaps, onProgress, abortSignal, logger) {
|
|
2180
2180
|
const direction = config.syncDirection ?? entityMap.SyncDirection ?? 'Pull';
|
|
2181
2181
|
if (direction === 'Pull') {
|
|
2182
|
-
return this.
|
|
2182
|
+
return this.processPullSync(config, entityMap, run, contextUser, entityMapIndex, totalEntityMaps, onProgress, abortSignal, logger);
|
|
2183
2183
|
}
|
|
2184
2184
|
if (direction === 'Push') {
|
|
2185
|
-
return this.
|
|
2185
|
+
return this.processPushSync(config, entityMap, run, contextUser, entityMapIndex, totalEntityMaps, onProgress, abortSignal, logger);
|
|
2186
2186
|
}
|
|
2187
2187
|
// Bidirectional: pull first, then push
|
|
2188
|
-
const pullResult = await this.
|
|
2189
|
-
const pushResult = await this.
|
|
2190
|
-
this.
|
|
2188
|
+
const pullResult = await this.processPullSync(config, entityMap, run, contextUser, entityMapIndex, totalEntityMaps, onProgress, abortSignal, logger);
|
|
2189
|
+
const pushResult = await this.processPushSync(config, entityMap, run, contextUser, entityMapIndex, totalEntityMaps, onProgress, abortSignal, logger);
|
|
2190
|
+
this.mergeResult(pullResult, pushResult);
|
|
2191
2191
|
return pullResult;
|
|
2192
2192
|
}
|
|
2193
2193
|
/** Loads the map fresh and writes its Configuration through Save(), like every other engine write. */
|
|
2194
|
-
async
|
|
2194
|
+
async saveEntityMapConfiguration(entityMap, configurationJSON, contextUser) {
|
|
2195
2195
|
const md = new Metadata(); // global-provider-ok: entity-map bookkeeping — single-provider context
|
|
2196
2196
|
const row = await md.GetEntityObject('MJ: Company Integration Entity Maps', contextUser);
|
|
2197
2197
|
if (!(await row.Load(entityMap.ID)))
|
|
@@ -2205,13 +2205,13 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
2205
2205
|
/**
|
|
2206
2206
|
* Pull sync: fetch from external → map → match → validate → apply to MJ.
|
|
2207
2207
|
*/
|
|
2208
|
-
async
|
|
2208
|
+
async processPullSync(config, entityMap, run, contextUser, entityMapIndex, totalEntityMaps, onProgress, abortSignal, logger) {
|
|
2209
2209
|
const entityMapID = entityMap.ID;
|
|
2210
2210
|
// An object this ACCOUNT cannot serve costs a request, an error event and a retry ladder
|
|
2211
2211
|
// every run, forever, and says nothing new after the first time. While the marker is fresh
|
|
2212
2212
|
// we spend nothing on it; once it ages out the next attempt IS the recheck, so an object
|
|
2213
2213
|
// the account later enables heals itself with no operator action.
|
|
2214
|
-
const fieldMaps = await this.
|
|
2214
|
+
const fieldMaps = await this.loadFieldMaps(entityMapID, contextUser);
|
|
2215
2215
|
// Field-level exclusions declared by the connector (SourceFieldInfo.SyncDirective
|
|
2216
2216
|
// -> IntegrationObjectField.Configuration). Resolved once per map, applied to every
|
|
2217
2217
|
// batch below. Empty set on any lookup miss - exclusion can only ever narrow.
|
|
@@ -2237,7 +2237,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
2237
2237
|
watermarkType: watermark?.WatermarkType ?? null,
|
|
2238
2238
|
fullSync: config.fullSync,
|
|
2239
2239
|
});
|
|
2240
|
-
this.
|
|
2240
|
+
this.warnOnUnbindableFieldMaps(entityMap, fieldMaps, logger);
|
|
2241
2241
|
// A6: Validate watermark before using it — skip entirely when FullSync requested
|
|
2242
2242
|
let initialWatermark = config.fullSync ? null : (watermark?.WatermarkValue ?? null);
|
|
2243
2243
|
// The value the ROW held before this run touched it — the retract target if a mid-run
|
|
@@ -2617,7 +2617,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
2617
2617
|
// Custom-key stats: aggregate unmapped keys for EVERY mapped record here —
|
|
2618
2618
|
// before any skip decision — so candidates + sizing stats exist even when the
|
|
2619
2619
|
// content-hash fast path skips the row (the hash basis deliberately excludes them).
|
|
2620
|
-
|
|
2620
|
+
FoldCustomKeyStats(mapped.map(r => r.UnmappedFields), customKeyAgg);
|
|
2621
2621
|
customKeyTotalRecords += mapped.length;
|
|
2622
2622
|
// Partition (Merkle) reconcile defers match + apply: accumulate mapped records now; the
|
|
2623
2623
|
// partition-diff + selective apply runs once after the full fetch (applyViaPartitionReconcile).
|
|
@@ -2646,7 +2646,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
2646
2646
|
const beforeApply = result.RecordsCreated + result.RecordsUpdated + result.RecordsSkipped + result.RecordsErrored;
|
|
2647
2647
|
try {
|
|
2648
2648
|
if (!partitionReconcile)
|
|
2649
|
-
await this.
|
|
2649
|
+
await this.applyRecords(resolved, config.companyIntegration, entityMap, result, contextUser, logger, this.getSyncConcurrency(config) <= 1, this.getSyncConcurrency(config));
|
|
2650
2650
|
}
|
|
2651
2651
|
catch (applyErr) {
|
|
2652
2652
|
if (applyErr instanceof SchemaNotGeneratedError) {
|
|
@@ -2846,7 +2846,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
2846
2846
|
// whose ExternalID isn't in fetchedExternalIDs is genuinely gone — even one inside an otherwise
|
|
2847
2847
|
// unchanged/skipped partition). Only on a clean fetch — a partial set would delete live records.
|
|
2848
2848
|
if ((config.fullSync || partitionReconcile) && fetchedExternalIDs.size > 0 && fetchCompletedCleanly) {
|
|
2849
|
-
await this.
|
|
2849
|
+
await this.deleteOrphanedRecords(config.companyIntegration, entityMap, fetchedExternalIDs, result, contextUser, logger);
|
|
2850
2850
|
}
|
|
2851
2851
|
else if (orphanTrackingOverflowed && fetchCompletedCleanly) {
|
|
2852
2852
|
// We deliberately stopped tracking IDs to avoid OOM — orphan/delete detection can't run
|
|
@@ -2876,7 +2876,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
2876
2876
|
})).sort((a, b) => a.Key.localeCompare(b.Key)),
|
|
2877
2877
|
};
|
|
2878
2878
|
}
|
|
2879
|
-
await this.
|
|
2879
|
+
await this.createRunDetail(run, entityMap, result, contextUser);
|
|
2880
2880
|
return result;
|
|
2881
2881
|
}
|
|
2882
2882
|
/**
|
|
@@ -2939,10 +2939,10 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
2939
2939
|
* Filters out changes made by the integration engine itself to prevent echo loops.
|
|
2940
2940
|
* For each changed record, calls the connector's CreateRecord/UpdateRecord/DeleteRecord.
|
|
2941
2941
|
*/
|
|
2942
|
-
async
|
|
2942
|
+
async processPushSync(config, entityMap, run, contextUser, _entityMapIndex, _totalEntityMaps, _onProgress, _abortSignal, logger) {
|
|
2943
2943
|
const entityMapID = entityMap.ID;
|
|
2944
|
-
const fieldMaps = await this.
|
|
2945
|
-
this.
|
|
2944
|
+
const fieldMaps = await this.loadFieldMaps(entityMapID, contextUser);
|
|
2945
|
+
this.warnOnUnbindableFieldMaps(entityMap, fieldMaps, logger);
|
|
2946
2946
|
const pushWatermark = await this.watermarkService.Load(entityMapID, contextUser, 'Push');
|
|
2947
2947
|
const lastPushAt = pushWatermark?.WatermarkValue ?? null;
|
|
2948
2948
|
// Check connector write capability
|
|
@@ -2955,12 +2955,12 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
2955
2955
|
supportsCreate: config.connector.SupportsCreate,
|
|
2956
2956
|
supportsUpdate: config.connector.SupportsUpdate,
|
|
2957
2957
|
});
|
|
2958
|
-
return this.
|
|
2958
|
+
return this.emptyResult();
|
|
2959
2959
|
}
|
|
2960
2960
|
// Full push: load ALL records from the MJ entity. Incremental push: only changed records.
|
|
2961
2961
|
const changedRecords = config.fullSync
|
|
2962
|
-
? await this.
|
|
2963
|
-
: await this.
|
|
2962
|
+
? await this.loadAllMJRecords(entityMap, config.companyIntegration, contextUser)
|
|
2963
|
+
: await this.loadChangedMJRecords(entityMap, lastPushAt, contextUser);
|
|
2964
2964
|
if (changedRecords.length === 0) {
|
|
2965
2965
|
console.log(`[IntegrationEngine] Push: no changes for ${entityMap.ExternalObjectName} since ${lastPushAt ?? 'beginning'}`);
|
|
2966
2966
|
logger?.emit('sync.push.candidates', {
|
|
@@ -2969,8 +2969,8 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
2969
2969
|
fullSync: config.fullSync,
|
|
2970
2970
|
sinceLastPushAt: lastPushAt,
|
|
2971
2971
|
});
|
|
2972
|
-
await this.
|
|
2973
|
-
return this.
|
|
2972
|
+
await this.createRunDetail(run, entityMap, this.emptyResult(), contextUser);
|
|
2973
|
+
return this.emptyResult();
|
|
2974
2974
|
}
|
|
2975
2975
|
console.log(`[IntegrationEngine] Push: ${changedRecords.length} changed records for ${entityMap.ExternalObjectName}`);
|
|
2976
2976
|
logger?.emit('sync.push.candidates', {
|
|
@@ -2989,7 +2989,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
2989
2989
|
// If no field maps are configured for push, skip this entity entirely
|
|
2990
2990
|
if (pushFieldMaps.length === 0) {
|
|
2991
2991
|
console.log(`[IntegrationEngine] Push skipped for ${entityMap.ExternalObjectName}: no field maps with push direction`);
|
|
2992
|
-
return this.
|
|
2992
|
+
return this.emptyResult();
|
|
2993
2993
|
}
|
|
2994
2994
|
// Watermark safety: the push watermark must never advance PAST a record that FAILED to
|
|
2995
2995
|
// push, or the next incremental push (which filters ChangedAt > watermark, strictly) would
|
|
@@ -3015,7 +3015,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
3015
3015
|
break;
|
|
3016
3016
|
result.RecordsProcessed++;
|
|
3017
3017
|
try {
|
|
3018
|
-
await this.
|
|
3018
|
+
await this.pushSingleRecord(change, config, entityMap, pushFieldMaps, result, contextUser, logger);
|
|
3019
3019
|
if (change.ChangedAt)
|
|
3020
3020
|
successfulChangeAts.push(change.ChangedAt);
|
|
3021
3021
|
}
|
|
@@ -3055,11 +3055,11 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
3055
3055
|
console.log(`[IntegrationEngine] Push complete for ${entityMap.ExternalObjectName}: ` +
|
|
3056
3056
|
`${result.RecordsCreated} created, ${result.RecordsUpdated} updated, ` +
|
|
3057
3057
|
`${result.RecordsDeleted} deleted, ${result.RecordsErrored} errored`);
|
|
3058
|
-
await this.
|
|
3058
|
+
await this.createRunDetail(run, entityMap, result, contextUser);
|
|
3059
3059
|
return result;
|
|
3060
3060
|
}
|
|
3061
3061
|
/** Loads MJ records changed since the last push watermark, excluding integration-engine changes. */
|
|
3062
|
-
async
|
|
3062
|
+
async loadChangedMJRecords(entityMap, lastPushAt, contextUser) {
|
|
3063
3063
|
const rv = new RunView();
|
|
3064
3064
|
// Query Record Changes for this entity since the last push
|
|
3065
3065
|
let filter = `EntityID='${entityMap.EntityID}'`;
|
|
@@ -3083,7 +3083,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
3083
3083
|
// Normalize to just the value(s) so it matches CompanyIntegrationRecordMap.EntityRecordID.
|
|
3084
3084
|
const latestByRecord = new Map();
|
|
3085
3085
|
for (const r of result.Results) {
|
|
3086
|
-
const normalizedID = this.
|
|
3086
|
+
const normalizedID = this.normalizeRecordChangeID(r.RecordID);
|
|
3087
3087
|
latestByRecord.set(normalizedID, { ...r, RecordID: normalizedID, Fields: {} });
|
|
3088
3088
|
}
|
|
3089
3089
|
// Load current field values for each changed record
|
|
@@ -3101,7 +3101,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
3101
3101
|
continue; // No fields to load for deletes
|
|
3102
3102
|
try {
|
|
3103
3103
|
const entity = await md.GetEntityObject(entityMap.Entity, contextUser);
|
|
3104
|
-
const loaded = await entity.InnerLoad(this.
|
|
3104
|
+
const loaded = await entity.InnerLoad(this.buildEntityPrimaryKey(recordID, pkFields));
|
|
3105
3105
|
if (loaded) {
|
|
3106
3106
|
change.Fields = entity.GetAll();
|
|
3107
3107
|
}
|
|
@@ -3117,7 +3117,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
3117
3117
|
* For each record, checks the record map to determine if it's a Create (no external ID)
|
|
3118
3118
|
* or Update (has external ID) in the external system.
|
|
3119
3119
|
*/
|
|
3120
|
-
async
|
|
3120
|
+
async loadAllMJRecords(entityMap, companyIntegration, contextUser) {
|
|
3121
3121
|
const rv = new RunView();
|
|
3122
3122
|
// Load all records from the MJ entity. OOM SAFETY VALVE: a full push materializes every row of
|
|
3123
3123
|
// the MJ entity in RAM. Past a generous ceiling, fail LOUD + actionable (caught by the per-map
|
|
@@ -3143,7 +3143,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
3143
3143
|
// Paged: an unpaged read is silently capped at the entity's UserViewMaxRows (1000 by
|
|
3144
3144
|
// default), and a truncated map here makes already-synced records look brand new — so
|
|
3145
3145
|
// the push would re-CREATE them externally as duplicates.
|
|
3146
|
-
const allMaps = await this.
|
|
3146
|
+
const allMaps = await this.loadAllRecordMaps(companyIntegration.ID, entityMap.EntityID, contextUser);
|
|
3147
3147
|
if (!allMaps.Complete) {
|
|
3148
3148
|
// Refuse rather than push a partial picture: with an incomplete map, every unmapped
|
|
3149
3149
|
// record reads as "not yet in the external system" and gets created a second time.
|
|
@@ -3165,7 +3165,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
3165
3165
|
return allResult.Results.map(record => {
|
|
3166
3166
|
// '|'-joined across EVERY key column — the shape EntityRecordID is stored in — so the
|
|
3167
3167
|
// existingMaps lookup (Create vs Update) matches a composite key, not just its first column.
|
|
3168
|
-
const recordID = this.
|
|
3168
|
+
const recordID = this.composeEntityRecordID(record, pkFields);
|
|
3169
3169
|
return {
|
|
3170
3170
|
RecordID: recordID,
|
|
3171
3171
|
Type: existingMaps.has(recordID) ? 'Update' : 'Create',
|
|
@@ -3175,7 +3175,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
3175
3175
|
});
|
|
3176
3176
|
}
|
|
3177
3177
|
/** Pushes a single changed MJ record to the external system. */
|
|
3178
|
-
async
|
|
3178
|
+
async pushSingleRecord(change, config, entityMap, pushFieldMaps, result, contextUser, logger) {
|
|
3179
3179
|
// Reverse-map MJ fields to external fields
|
|
3180
3180
|
const externalAttributes = {};
|
|
3181
3181
|
for (const fm of pushFieldMaps) {
|
|
@@ -3273,7 +3273,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
3273
3273
|
}
|
|
3274
3274
|
// Persist the new external ID so future syncs update instead of re-creating
|
|
3275
3275
|
if (createResult.ExternalID) {
|
|
3276
|
-
await this.
|
|
3276
|
+
await this.saveRecordMap(config.companyIntegration.ID, createResult.ExternalID, entityMap.EntityID, change.RecordID, contextUser);
|
|
3277
3277
|
result.RecordsCreated++;
|
|
3278
3278
|
}
|
|
3279
3279
|
else {
|
|
@@ -3417,7 +3417,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
3417
3417
|
const entity = await md.GetEntityObject(entityMap.Entity, contextUser);
|
|
3418
3418
|
const entityInfo = md.EntityByName(entityMap.Entity);
|
|
3419
3419
|
const pkFields = entityInfo?.PrimaryKeys ?? [];
|
|
3420
|
-
const loaded = await entity.InnerLoad(this.
|
|
3420
|
+
const loaded = await entity.InnerLoad(this.buildEntityPrimaryKey(mjRecordID, pkFields));
|
|
3421
3421
|
if (!loaded)
|
|
3422
3422
|
return;
|
|
3423
3423
|
const fields = entity.Fields ?? [];
|
|
@@ -3443,11 +3443,11 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
3443
3443
|
* but were NOT returned by the external system during this full pull.
|
|
3444
3444
|
* These records were deleted externally and should be removed from MJ.
|
|
3445
3445
|
*/
|
|
3446
|
-
async
|
|
3446
|
+
async deleteOrphanedRecords(companyIntegration, entityMap, fetchedExternalIDs, result, contextUser, logger) {
|
|
3447
3447
|
// Paged: an unpaged read is silently capped at the entity's UserViewMaxRows (1000 by
|
|
3448
3448
|
// default). A tenant with 5,000 orphans would clear 1,000 per run and the operator would
|
|
3449
3449
|
// see a clean run every time — the truncation was invisible, which is the actual bug.
|
|
3450
|
-
const allMaps = await this.
|
|
3450
|
+
const allMaps = await this.loadAllRecordMaps(companyIntegration.ID, entityMap.EntityID, contextUser);
|
|
3451
3451
|
if (!allMaps.Complete) {
|
|
3452
3452
|
// Deleting against a partial map is the dangerous direction: rows we simply failed to
|
|
3453
3453
|
// read are indistinguishable from rows the external system dropped. Skip the sweep and
|
|
@@ -3485,7 +3485,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
3485
3485
|
for (const orphan of orphans) {
|
|
3486
3486
|
try {
|
|
3487
3487
|
const entity = await md.GetEntityObject(entityMap.Entity, contextUser);
|
|
3488
|
-
const loaded = await entity.InnerLoad(this.
|
|
3488
|
+
const loaded = await entity.InnerLoad(this.buildEntityPrimaryKey(orphan.EntityRecordID, pkFields));
|
|
3489
3489
|
if (!loaded) {
|
|
3490
3490
|
console.log(`[IntegrationEngine] Orphan ${orphan.EntityRecordID} already deleted from MJ`);
|
|
3491
3491
|
// The map row outlived its record. Nothing anywhere else deletes record-map
|
|
@@ -3493,7 +3493,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
3493
3493
|
// full sync and ORPHANS_DETECTED becomes a cumulative counter of history
|
|
3494
3494
|
// rather than a signal about THIS run — observed live as a count that only
|
|
3495
3495
|
// ever grew, sync after sync.
|
|
3496
|
-
await this.
|
|
3496
|
+
await this.deleteRecordMapRow(orphan.ID, contextUser);
|
|
3497
3497
|
continue;
|
|
3498
3498
|
}
|
|
3499
3499
|
if (entityMap.DeleteBehavior === 'SoftDelete') {
|
|
@@ -3513,7 +3513,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
3513
3513
|
const archived = await entity.Save(this.syncSaveOptions);
|
|
3514
3514
|
if (archived) {
|
|
3515
3515
|
result.RecordsDeleted++;
|
|
3516
|
-
await this.
|
|
3516
|
+
await this.deleteRecordMapRow(orphan.ID, contextUser);
|
|
3517
3517
|
console.log(`[IntegrationEngine] Archived orphan ${entityMap.Entity} ${orphan.EntityRecordID} (external ${orphan.ExternalSystemRecordID} no longer exists)`);
|
|
3518
3518
|
}
|
|
3519
3519
|
else {
|
|
@@ -3525,7 +3525,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
3525
3525
|
const deleted = await entity.Delete(this.syncDeleteOptions);
|
|
3526
3526
|
if (deleted) {
|
|
3527
3527
|
result.RecordsDeleted++;
|
|
3528
|
-
await this.
|
|
3528
|
+
await this.deleteRecordMapRow(orphan.ID, contextUser);
|
|
3529
3529
|
console.log(`[IntegrationEngine] Deleted orphan ${entityMap.Entity} ${orphan.EntityRecordID} (external ${orphan.ExternalSystemRecordID} no longer exists)`);
|
|
3530
3530
|
}
|
|
3531
3531
|
else {
|
|
@@ -3545,7 +3545,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
3545
3545
|
* swallowed: the orphan itself was handled, and the worst consequence of a surviving map
|
|
3546
3546
|
* row is one redundant re-detection on the next full sync.
|
|
3547
3547
|
*/
|
|
3548
|
-
async
|
|
3548
|
+
async deleteRecordMapRow(mapRowID, contextUser) {
|
|
3549
3549
|
try {
|
|
3550
3550
|
const md = this.ProviderToUse;
|
|
3551
3551
|
const mapRow = await md.GetEntityObject('MJ: Company Integration Record Maps', contextUser);
|
|
@@ -3566,14 +3566,14 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
3566
3566
|
* "hs_object_id|465950833372" → "465950833372"
|
|
3567
3567
|
* "contact_id|123||deal_id|456" → "123|456"
|
|
3568
3568
|
*/
|
|
3569
|
-
|
|
3569
|
+
normalizeRecordChangeID(recordID) {
|
|
3570
3570
|
return recordID
|
|
3571
3571
|
.split('||')
|
|
3572
3572
|
.map(part => { const i = part.indexOf('|'); return i >= 0 ? part.substring(i + 1) : part; })
|
|
3573
3573
|
.join('|');
|
|
3574
3574
|
}
|
|
3575
3575
|
/** Returns an empty SyncResult. */
|
|
3576
|
-
|
|
3576
|
+
emptyResult() {
|
|
3577
3577
|
return {
|
|
3578
3578
|
Success: true, RecordsProcessed: 0, RecordsCreated: 0, RecordsUpdated: 0,
|
|
3579
3579
|
RecordsDeleted: 0, RecordsErrored: 0, RecordsSkipped: 0, Errors: [],
|
|
@@ -3598,7 +3598,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
3598
3598
|
/**
|
|
3599
3599
|
* Loads active field maps for a given entity map.
|
|
3600
3600
|
*/
|
|
3601
|
-
async
|
|
3601
|
+
async loadFieldMaps(entityMapID, contextUser) {
|
|
3602
3602
|
const rv = new RunView();
|
|
3603
3603
|
const result = await rv.RunView({
|
|
3604
3604
|
EntityName: 'MJ: Company Integration Field Maps',
|
|
@@ -3648,14 +3648,14 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
3648
3648
|
async applyViaPartitionReconcile(mappedRecords, config, entityMap, fieldMaps, result, contextUser, logger, partitionCount) {
|
|
3649
3649
|
const entityMapID = entityMap.ID;
|
|
3650
3650
|
const idOf = (r) => r.ExternalRecord.ExternalID;
|
|
3651
|
-
const partitionOf = (r) =>
|
|
3651
|
+
const partitionOf = (r) => PartitionKeyForIdentity(idOf(r), partitionCount);
|
|
3652
3652
|
// Bucket + rollup the just-fetched full set.
|
|
3653
|
-
const buckets =
|
|
3653
|
+
const buckets = PartitionRecords(mappedRecords, idOf, partitionOf);
|
|
3654
3654
|
const newRollups = new Map();
|
|
3655
3655
|
for (const [partition, recs] of buckets) {
|
|
3656
3656
|
// Content-hash basis: MAPPED fields only — an unmapped/custom key must never move a
|
|
3657
3657
|
// partition rollup (its capture + promotion is handled out-of-band via CustomKeyStats).
|
|
3658
|
-
newRollups.set(partition,
|
|
3658
|
+
newRollups.set(partition, PartitionRollupHash(recs, r => r.MappedFields));
|
|
3659
3659
|
}
|
|
3660
3660
|
// Diff against last sync's snapshot; only changed/added partitions need a deep apply. On a FORCED
|
|
3661
3661
|
// FULL SYNC, treat the snapshot as empty so EVERY partition is re-applied: fullSync is the operator's
|
|
@@ -3665,7 +3665,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
3665
3665
|
const stored = config.fullSync
|
|
3666
3666
|
? new Map()
|
|
3667
3667
|
: await this.watermarkService.LoadPartitionRollups(entityMapID, contextUser);
|
|
3668
|
-
const diff =
|
|
3668
|
+
const diff = DiffPartitions(newRollups, stored);
|
|
3669
3669
|
const toApply = new Set([...diff.changed, ...diff.added]);
|
|
3670
3670
|
let appliedRecords = 0;
|
|
3671
3671
|
let skippedPartitions = 0;
|
|
@@ -3689,7 +3689,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
3689
3689
|
// connection, so when streams run in parallel (syncConcurrency>1) it must not interleave
|
|
3690
3690
|
// with another stream's open write transaction (else "Transaction in progress" / dirty read).
|
|
3691
3691
|
const resolved = await this.runWriteForMap(entityMap.ID, () => this.matchEngine.Resolve(recs, entityMap, fieldMaps, contextUser));
|
|
3692
|
-
await this.
|
|
3692
|
+
await this.applyRecords(resolved, config.companyIntegration, entityMap, result, contextUser, logger, this.getSyncConcurrency(config) <= 1, this.getSyncConcurrency(config));
|
|
3693
3693
|
appliedRecords += recs.length;
|
|
3694
3694
|
}
|
|
3695
3695
|
}
|
|
@@ -3718,7 +3718,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
3718
3718
|
/**
|
|
3719
3719
|
* Applies resolved records to MJ, handling each individually for error isolation.
|
|
3720
3720
|
*/
|
|
3721
|
-
async
|
|
3721
|
+
async applyRecords(records, companyIntegration, entityMap, result, contextUser, logger,
|
|
3722
3722
|
// OPT-IN concurrency (syncConcurrency>1): when false, the batch is applied WITHOUT a provider
|
|
3723
3723
|
// transaction (per-record auto-commit on pooled connections). Rationale: the provider holds ONE
|
|
3724
3724
|
// global transaction bound to one connection, so a held transaction makes every concurrent
|
|
@@ -3749,7 +3749,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
3749
3749
|
// used to spend three round trips per record establishing a mapping now queues into this
|
|
3750
3750
|
// and the queue is flushed set-based once the batch has settled — the single largest cost
|
|
3751
3751
|
// in a no-change sync.
|
|
3752
|
-
const recordMaps = new RecordMapBatch(this.ProviderToUse, companyIntegration.ID, contextUser, (ciID, extID, entID, recID, user) => this.
|
|
3752
|
+
const recordMaps = new RecordMapBatch(this.ProviderToUse, companyIntegration.ID, contextUser, (ciID, extID, entID, recID, user) => this.saveRecordMap(ciID, extID, entID, recID, user));
|
|
3753
3753
|
for (let i = 0; i < records.length; i += APPLY_BATCH_SIZE) {
|
|
3754
3754
|
const batch = records.slice(i, i + APPLY_BATCH_SIZE);
|
|
3755
3755
|
const batchStartProcessed = result.RecordsProcessed;
|
|
@@ -3789,7 +3789,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
3789
3789
|
// target's whole identity is server-assigned can never enrol a record, so batching it
|
|
3790
3790
|
// would produce an empty group and a non-atomic batch reporting success. See
|
|
3791
3791
|
// entityMapHasIdentityOnlyPK.
|
|
3792
|
-
const batchedWrites = this.
|
|
3792
|
+
const batchedWrites = this.readWriteMode(companyIntegration) === 'batched'
|
|
3793
3793
|
&& !this.entityMapHasIdentityOnlyPK(entityMap);
|
|
3794
3794
|
// NEVER nest `runWriteExclusive`: the inner call waits on a chain that already contains
|
|
3795
3795
|
// the outer one, which deadlocks. Under the outer mutex the writes are already
|
|
@@ -3798,7 +3798,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
3798
3798
|
? (fn) => this.runWriteForMap(entityMap.ID, fn)
|
|
3799
3799
|
: (fn) => fn();
|
|
3800
3800
|
const applyOneBatch = async () => {
|
|
3801
|
-
const precheckHashes = await this.
|
|
3801
|
+
const precheckHashes = await this.prefetchContentHashes(batch, contextUser);
|
|
3802
3802
|
// PKs of records the content-hash fast path skipped this batch — still present and
|
|
3803
3803
|
// confirmed-unchanged on the source. Collected so we can refresh LastReconciledAt for
|
|
3804
3804
|
// all of them in ONE set-based touch after the batch (instead of a frozen-forever stamp).
|
|
@@ -3875,7 +3875,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
3875
3875
|
let enrolledSinceFlush = 0;
|
|
3876
3876
|
for (const record of batch) {
|
|
3877
3877
|
result.RecordsProcessed++;
|
|
3878
|
-
await this.
|
|
3878
|
+
await this.applySingleRecord(record, companyIntegration, entityMap, result, contextUser, logger, precheckHashes, reconciledSkipIds, recordMaps);
|
|
3879
3879
|
if (flushAt === undefined)
|
|
3880
3880
|
continue;
|
|
3881
3881
|
if (++enrolledSinceFlush < flushAt)
|
|
@@ -3985,7 +3985,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
3985
3985
|
try {
|
|
3986
3986
|
// §10 — bounded inline retry for provably-transient save failures (auto-commit per
|
|
3987
3987
|
// record, so no transaction to manage); permanent errors throw straight to dead-letter.
|
|
3988
|
-
await WithRetry(() => this.
|
|
3988
|
+
await WithRetry(() => this.applySingleRecord(record, companyIntegration, entityMap, result, contextUser, logger, precheckHashes, reconciledSkipIds, recordMaps), undefined, (e) => !(e instanceof SchemaNotGeneratedError) && IsRetryableError(ClassifyError(e).Code), (attempt, e, delayMs) => logger?.emit('sync.record.retry', {
|
|
3989
3989
|
phase: 'save',
|
|
3990
3990
|
externalObjectName: entityMap.ExternalObjectName,
|
|
3991
3991
|
externalId: record.ExternalRecord?.ExternalID ?? '',
|
|
@@ -4028,13 +4028,13 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
4028
4028
|
// LastReconciledAt for every content-hash-skipped row in ONE set-based touch.
|
|
4029
4029
|
// Best-effort — a touch failure must never break the sync.
|
|
4030
4030
|
if (reconciledSkipIds.length > 0) {
|
|
4031
|
-
await serializeWrite(() => this.
|
|
4031
|
+
await serializeWrite(() => this.touchLastReconciledAt(entityMap, reconciledSkipIds, contextUser, logger));
|
|
4032
4032
|
}
|
|
4033
4033
|
// Write the batch's record maps set-based, now that the records they point at are
|
|
4034
4034
|
// committed. Deliberately AFTER the transaction rather than inside it: the mapping
|
|
4035
4035
|
// is derived data that the next sync can re-establish by primary key, and keeping
|
|
4036
4036
|
// it out of the write transaction keeps that transaction as short as possible.
|
|
4037
|
-
await serializeWrite(() => this.
|
|
4037
|
+
await serializeWrite(() => this.flushRecordMaps(recordMaps, entityMap, logger));
|
|
4038
4038
|
};
|
|
4039
4039
|
// Batched: overlap freely, serializing only the writes above. Otherwise: the whole
|
|
4040
4040
|
// block stays under the mutex, because it owns a provider transaction throughout.
|
|
@@ -4052,7 +4052,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
4052
4052
|
* worth telling the operator about but is not a reason to mark the record — or the run —
|
|
4053
4053
|
* failed. Flushing itself never throws for the same reason.
|
|
4054
4054
|
*/
|
|
4055
|
-
async
|
|
4055
|
+
async flushRecordMaps(recordMaps, entityMap, logger) {
|
|
4056
4056
|
try {
|
|
4057
4057
|
await recordMaps.Flush();
|
|
4058
4058
|
}
|
|
@@ -4073,7 +4073,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
4073
4073
|
* mirroring PrefetchContentHashes. Keeps the column's "last confirmed present" semantics honest so
|
|
4074
4074
|
* future unseen-since-last-reconcile logic can't misclassify a still-present unchanged record.
|
|
4075
4075
|
*/
|
|
4076
|
-
async
|
|
4076
|
+
async touchLastReconciledAt(entityMap, recordIds, contextUser, logger) {
|
|
4077
4077
|
try {
|
|
4078
4078
|
const md = this.ProviderToUse;
|
|
4079
4079
|
const entityInfo = md.EntityByName(entityMap.Entity ?? '');
|
|
@@ -4158,14 +4158,14 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
4158
4158
|
if (!useProviderTransaction) {
|
|
4159
4159
|
// Auto-commit: never touches shared provider transaction state, so
|
|
4160
4160
|
// concurrent entity maps cannot corrupt each other. See the parameter doc.
|
|
4161
|
-
await this.
|
|
4161
|
+
await this.applySingleRecord(record, companyIntegration, entityMap, result, contextUser, logger, precheckHashes, reconciledSkipIds, recordMaps);
|
|
4162
4162
|
return;
|
|
4163
4163
|
}
|
|
4164
4164
|
// Sequential path, unchanged: apply in its own transaction so a deadlock or
|
|
4165
4165
|
// momentary timeout rolls back and the next attempt starts clean.
|
|
4166
4166
|
await provider.BeginTransaction();
|
|
4167
4167
|
try {
|
|
4168
|
-
await this.
|
|
4168
|
+
await this.applySingleRecord(record, companyIntegration, entityMap, result, contextUser, logger, precheckHashes, reconciledSkipIds, recordMaps);
|
|
4169
4169
|
await provider.CommitTransaction();
|
|
4170
4170
|
}
|
|
4171
4171
|
catch (e) {
|
|
@@ -4220,7 +4220,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
4220
4220
|
/**
|
|
4221
4221
|
* Applies a single record change (Create, Update, Delete, or Skip).
|
|
4222
4222
|
*/
|
|
4223
|
-
async
|
|
4223
|
+
async applySingleRecord(record, companyIntegration, entityMap, result, contextUser, logger, precheckHashes, reconciledSkipIds, recordMaps) {
|
|
4224
4224
|
logger?.emit('sync.record.decision', {
|
|
4225
4225
|
externalId: record.ExternalRecord.ExternalID,
|
|
4226
4226
|
objectType: record.ExternalRecord.ObjectType,
|
|
@@ -4236,7 +4236,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
4236
4236
|
try {
|
|
4237
4237
|
switch (record.ChangeType) {
|
|
4238
4238
|
case 'Create': {
|
|
4239
|
-
const outcome = await this.
|
|
4239
|
+
const outcome = await this.createRecord(record, companyIntegration, entityMap, contextUser, recordMaps, logger, precheckHashes);
|
|
4240
4240
|
if (outcome === 'updated')
|
|
4241
4241
|
result.RecordsUpdated++;
|
|
4242
4242
|
else if (outcome === 'skipped')
|
|
@@ -4246,10 +4246,10 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
4246
4246
|
break;
|
|
4247
4247
|
}
|
|
4248
4248
|
case 'Update':
|
|
4249
|
-
await this.
|
|
4249
|
+
await this.updateRecord(record, companyIntegration, entityMap, result, contextUser, precheckHashes, reconciledSkipIds, recordMaps, logger);
|
|
4250
4250
|
break;
|
|
4251
4251
|
case 'Delete': {
|
|
4252
|
-
const didDelete = await this.
|
|
4252
|
+
const didDelete = await this.deleteRecord(record, entityMap, contextUser);
|
|
4253
4253
|
if (didDelete)
|
|
4254
4254
|
result.RecordsDeleted++;
|
|
4255
4255
|
else
|
|
@@ -4306,7 +4306,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
4306
4306
|
*
|
|
4307
4307
|
* @returns true if an existing row was updated, false if a new row was inserted (so the caller counts correctly).
|
|
4308
4308
|
*/
|
|
4309
|
-
async
|
|
4309
|
+
async createRecord(record, companyIntegration, entityMap, contextUser, recordMaps,
|
|
4310
4310
|
/** Optional — lets the keyless-key guard below surface on the run's event stream. */
|
|
4311
4311
|
keylessLogger,
|
|
4312
4312
|
/** What the batch already proved about its destination rows, if anything. */
|
|
@@ -4332,7 +4332,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
4332
4332
|
// `mappedPK == null` is legitimate ONLY when the destination generates its own key (an
|
|
4333
4333
|
// identity column or a server-assigned UUID), which is why the check is scoped to soft PKs
|
|
4334
4334
|
// rather than applied to every table.
|
|
4335
|
-
const keyless = DecideKeylessRefusal(mappedPK, pkFields, MissingKeyFieldNames(record.MappedFields, pkFields,
|
|
4335
|
+
const keyless = DecideKeylessRefusal(mappedPK, pkFields, MissingKeyFieldNames(record.MappedFields, pkFields, SerializeKeyValue));
|
|
4336
4336
|
if (keyless.Refuse) {
|
|
4337
4337
|
const detail = DescribeKeylessRefusal(record.MJEntityName, keyless.KeyNames);
|
|
4338
4338
|
keylessLogger?.emit('sync.record.error', {
|
|
@@ -4355,7 +4355,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
4355
4355
|
// the load, because a wrong "absent" turns an update into a duplicate insert.
|
|
4356
4356
|
const provablyAbsent = this.isProvablyAbsent(mappedPK, precheck);
|
|
4357
4357
|
const existed = mappedPK != null && !provablyAbsent
|
|
4358
|
-
? await entity.InnerLoad(this.
|
|
4358
|
+
? await entity.InnerLoad(this.buildEntityPrimaryKey(mappedPK, pkFields))
|
|
4359
4359
|
: false;
|
|
4360
4360
|
if (existed) {
|
|
4361
4361
|
// Content-hash fast path (the upsert-path complement to UpdateRecord's matched-path precheck):
|
|
@@ -4371,8 +4371,8 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
4371
4371
|
if (hasHashColumn) {
|
|
4372
4372
|
const storedHash = entity.Get(CONTENT_HASH_COLUMN);
|
|
4373
4373
|
if (typeof storedHash === 'string' && storedHash.length > 0
|
|
4374
|
-
&& storedHash ===
|
|
4375
|
-
await this.
|
|
4374
|
+
&& storedHash === ComputeContentHash(record.MappedFields ?? {})) {
|
|
4375
|
+
await this.queueRecordMap(recordMaps, companyIntegration.ID, record.ExternalRecord.ExternalID, entityMap.EntityID, entity.PrimaryKey.KeyValuePairs.map(kv => String(kv.Value)).join('|'), contextUser);
|
|
4376
4376
|
return 'skipped';
|
|
4377
4377
|
}
|
|
4378
4378
|
}
|
|
@@ -4380,17 +4380,17 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
4380
4380
|
// (dirty tracking after SetEntityFields, BEFORE the always-changing integration metadata),
|
|
4381
4381
|
// re-establish the possibly-cleared record map and SKIP the write — leaving __mj_UpdatedAt
|
|
4382
4382
|
// and the integration LastSynced columns untouched, exactly like the content-hash skip path.
|
|
4383
|
-
this.
|
|
4383
|
+
this.setEntityFields(entity, record.MappedFields);
|
|
4384
4384
|
if (!entity.Dirty && !this.needsSyncStateRepair(entity, entityInfo, record)) {
|
|
4385
|
-
await this.
|
|
4385
|
+
await this.queueRecordMap(recordMaps, companyIntegration.ID, record.ExternalRecord.ExternalID, entityMap.EntityID, entity.PrimaryKey.KeyValuePairs.map(kv => String(kv.Value)).join('|'), contextUser);
|
|
4386
4386
|
return 'skipped';
|
|
4387
4387
|
}
|
|
4388
4388
|
}
|
|
4389
4389
|
else {
|
|
4390
4390
|
entity.NewRecord();
|
|
4391
|
-
this.
|
|
4391
|
+
this.setEntityFields(entity, record.MappedFields);
|
|
4392
4392
|
}
|
|
4393
|
-
this.
|
|
4393
|
+
this.setStandardIntegrationFields(entity, record);
|
|
4394
4394
|
// A5: Pre-write validation
|
|
4395
4395
|
this.validateEntity(entity, record.MJEntityName);
|
|
4396
4396
|
const saved = await entity.Save(this.syncSaveOptions);
|
|
@@ -4418,7 +4418,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
4418
4418
|
if (!existed && mappedPK != null && precheck) {
|
|
4419
4419
|
precheck.Present.add(mappedPK);
|
|
4420
4420
|
}
|
|
4421
|
-
await this.
|
|
4421
|
+
await this.queueRecordMap(recordMaps, companyIntegration.ID, record.ExternalRecord.ExternalID, entityMap.EntityID, entityRecordID, contextUser);
|
|
4422
4422
|
return existed ? 'updated' : 'created';
|
|
4423
4423
|
}
|
|
4424
4424
|
/**
|
|
@@ -4438,7 +4438,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
4438
4438
|
const v = (pk.Name in fields) ? fields[pk.Name] : lower.get(pk.Name.toLowerCase());
|
|
4439
4439
|
// serializeKeyValue mirrors the write-side coercion (objects → JSON, not "[object Object]")
|
|
4440
4440
|
// so the load key equals the value stored in the column for object-valued PKs.
|
|
4441
|
-
const s =
|
|
4441
|
+
const s = SerializeKeyValue(v);
|
|
4442
4442
|
if (s === '')
|
|
4443
4443
|
return null;
|
|
4444
4444
|
values.push(s);
|
|
@@ -4467,12 +4467,12 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
4467
4467
|
* If the record cannot be loaded (e.g. it was deleted or never fully created),
|
|
4468
4468
|
* falls back to CreateRecord (upsert behavior).
|
|
4469
4469
|
*/
|
|
4470
|
-
async
|
|
4470
|
+
async updateRecord(record, companyIntegration, entityMap, result, contextUser, precheckHashes, reconciledSkipIds, recordMaps,
|
|
4471
4471
|
/** Forwarded to CreateRecord's keyless-key guard on the upsert fallback paths. */
|
|
4472
4472
|
logger) {
|
|
4473
4473
|
if (!record.MatchedMJRecordID) {
|
|
4474
4474
|
// No matched ID — upsert by PK (insert; or update/skip if the PK already exists)
|
|
4475
|
-
const outcome = await this.
|
|
4475
|
+
const outcome = await this.createRecord(record, companyIntegration, entityMap, contextUser, recordMaps, logger, precheckHashes);
|
|
4476
4476
|
if (outcome === 'updated')
|
|
4477
4477
|
result.RecordsUpdated++;
|
|
4478
4478
|
else if (outcome === 'skipped')
|
|
@@ -4488,7 +4488,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
4488
4488
|
// below is the fallback for entities without the hash column.
|
|
4489
4489
|
if (precheckHashes) {
|
|
4490
4490
|
const stored = precheckHashes.Hashes.get(record.MatchedMJRecordID);
|
|
4491
|
-
if (stored && stored ===
|
|
4491
|
+
if (stored && stored === ComputeContentHash(record.MappedFields ?? {})) {
|
|
4492
4492
|
result.RecordsSkipped++;
|
|
4493
4493
|
// Re-establish the external↔MJ record map even on the content-hash skip. A record can
|
|
4494
4494
|
// reach UpdateRecord matched by KEY FIELDS / PK (MatchEngine.FindByKeyFields queries the
|
|
@@ -4501,7 +4501,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
4501
4501
|
// (CompanyIntegration, Entity, ExternalID) — idempotent for already-mapped records, and the
|
|
4502
4502
|
// CreateRecord skip branches already do exactly this. MatchedMJRecordID IS the dest PK
|
|
4503
4503
|
// (PrimaryKeys order, '|'-joined), which is the EntityRecordID the map stores.
|
|
4504
|
-
await this.
|
|
4504
|
+
await this.queueRecordMap(recordMaps, companyIntegration.ID, record.ExternalRecord.ExternalID, entityMap.EntityID, record.MatchedMJRecordID, contextUser);
|
|
4505
4505
|
// The record IS still present and confirmed-unchanged on the source — but skipping
|
|
4506
4506
|
// the write here means SetStandardIntegrationFields never runs, so __mj_integration_
|
|
4507
4507
|
// LastReconciledAt would freeze at first-sync time. Record the PK so the batch can
|
|
@@ -4518,10 +4518,10 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
4518
4518
|
this.enrolInWriteGroup(entity);
|
|
4519
4519
|
const entityInfo = md.EntityByName(record.MJEntityName);
|
|
4520
4520
|
const pkFields = entityInfo?.PrimaryKeys ?? [];
|
|
4521
|
-
const loaded = await entity.InnerLoad(this.
|
|
4521
|
+
const loaded = await entity.InnerLoad(this.buildEntityPrimaryKey(record.MatchedMJRecordID, pkFields));
|
|
4522
4522
|
if (!loaded) {
|
|
4523
4523
|
// Matched-ID row vanished — fall back to upsert by PK (insert; or update/skip if PK exists)
|
|
4524
|
-
const outcome = await this.
|
|
4524
|
+
const outcome = await this.createRecord(record, companyIntegration, entityMap, contextUser, recordMaps, logger, precheckHashes);
|
|
4525
4525
|
if (outcome === 'updated')
|
|
4526
4526
|
result.RecordsUpdated++;
|
|
4527
4527
|
else if (outcome === 'skipped')
|
|
@@ -4538,7 +4538,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
4538
4538
|
// clobbering concurrent edits to untouched columns and fabricating a record-change row
|
|
4539
4539
|
// each time. CreateRecord's upsert branch already orders it this way; this is the same
|
|
4540
4540
|
// footprint-clean rule applied to the matched path.
|
|
4541
|
-
this.
|
|
4541
|
+
this.setEntityFields(entity, record.MappedFields);
|
|
4542
4542
|
// Skip unchanged records — if no business field values actually changed, don't write.
|
|
4543
4543
|
// Uses MJ's built-in dirty tracking (zero custom comparison logic). Critical for
|
|
4544
4544
|
// connectors without server-side date filtering (e.g., YM) where every sync re-fetches
|
|
@@ -4549,7 +4549,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
4549
4549
|
// above for the full rationale (a key-field/PK match can land here with no map row, and
|
|
4550
4550
|
// dropping the map silently breaks the 1:1 completeness invariant + orphan detection).
|
|
4551
4551
|
// The entity is loaded here, so use its actual PK as the EntityRecordID. Idempotent upsert.
|
|
4552
|
-
await this.
|
|
4552
|
+
await this.queueRecordMap(recordMaps, companyIntegration.ID, record.ExternalRecord.ExternalID, entityMap.EntityID, entity.PrimaryKey.KeyValuePairs.map(kv => String(kv.Value)).join('|'), contextUser);
|
|
4553
4553
|
// Same reasoning as the content-hash skip: the record IS confirmed present on the
|
|
4554
4554
|
// source, so let the batch refresh LastReconciledAt in one set-based touch rather
|
|
4555
4555
|
// than rewriting the row for a timestamp.
|
|
@@ -4557,7 +4557,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
4557
4557
|
reconciledSkipIds.push(record.MatchedMJRecordID);
|
|
4558
4558
|
return;
|
|
4559
4559
|
}
|
|
4560
|
-
this.
|
|
4560
|
+
this.setStandardIntegrationFields(entity, record);
|
|
4561
4561
|
// A5: Pre-write validation
|
|
4562
4562
|
this.validateEntity(entity, record.MJEntityName);
|
|
4563
4563
|
const saved = await entity.Save(this.syncSaveOptions);
|
|
@@ -4574,7 +4574,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
4574
4574
|
// rows and orphan/delete detection silently degrades. SaveRecordMap is an upsert keyed on
|
|
4575
4575
|
// (CompanyIntegration, Entity, ExternalID), so this is idempotent for already-mapped records.
|
|
4576
4576
|
const entityRecordID = entity.PrimaryKey.KeyValuePairs.map(kv => String(kv.Value)).join('|');
|
|
4577
|
-
await this.
|
|
4577
|
+
await this.queueRecordMap(recordMaps, companyIntegration.ID, record.ExternalRecord.ExternalID, entityMap.EntityID, entityRecordID, contextUser);
|
|
4578
4578
|
result.RecordsUpdated++;
|
|
4579
4579
|
}
|
|
4580
4580
|
/**
|
|
@@ -4586,7 +4586,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
4586
4586
|
* - nothing in the batch is an Update with a matched ID, or
|
|
4587
4587
|
* - the read fails (best-effort — a logging/optimization read must never break a sync).
|
|
4588
4588
|
*/
|
|
4589
|
-
async
|
|
4589
|
+
async prefetchContentHashes(batch, contextUser) {
|
|
4590
4590
|
const entityName = batch[0].MJEntityName;
|
|
4591
4591
|
const entityInfo = this.ProviderToUse.EntityByName(entityName);
|
|
4592
4592
|
if (!entityInfo)
|
|
@@ -4631,7 +4631,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
4631
4631
|
// skip, re-writing every unchanged record each sync. Dialect-aware (SS `[key]`, PG `"key"`)
|
|
4632
4632
|
// so it stays valid on both targets (does NOT reintroduce the SS-brackets-break-PG problem).
|
|
4633
4633
|
const dialect = this.ProviderToUse.Dialect;
|
|
4634
|
-
const extraFilter =
|
|
4634
|
+
const extraFilter = BuildContentHashPrefetchFilter(pkNames, ids, dialect);
|
|
4635
4635
|
const res = await rv.RunView({
|
|
4636
4636
|
EntityName: entityName,
|
|
4637
4637
|
Fields: [...pkNames, CONTENT_HASH_COLUMN],
|
|
@@ -4689,7 +4689,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
4689
4689
|
/**
|
|
4690
4690
|
* Deletes (or soft-deletes) an MJ record based on the entity map's DeleteBehavior.
|
|
4691
4691
|
*/
|
|
4692
|
-
async
|
|
4692
|
+
async deleteRecord(record, entityMap, contextUser) {
|
|
4693
4693
|
if (!record.MatchedMJRecordID) {
|
|
4694
4694
|
console.log(`[IntegrationEngine] Skipping delete for ${record.ExternalRecord.ObjectType} ExternalID=${record.ExternalRecord.ExternalID} — no MJ record map entry (record was never synced)`);
|
|
4695
4695
|
return false;
|
|
@@ -4701,7 +4701,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
4701
4701
|
this.enrolInWriteGroup(entity);
|
|
4702
4702
|
const entityInfo = md.EntityByName(record.MJEntityName);
|
|
4703
4703
|
const pkFields = entityInfo?.PrimaryKeys ?? [];
|
|
4704
|
-
const loaded = await entity.InnerLoad(this.
|
|
4704
|
+
const loaded = await entity.InnerLoad(this.buildEntityPrimaryKey(record.MatchedMJRecordID, pkFields));
|
|
4705
4705
|
if (!loaded) {
|
|
4706
4706
|
console.log(`[IntegrationEngine] Skipping delete for ${record.MJEntityName} ${record.MatchedMJRecordID} — record not found in MJ DB (may have been deleted already)`);
|
|
4707
4707
|
return false;
|
|
@@ -4742,7 +4742,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
4742
4742
|
* is expected to be a '|'-delimited string of values in PK-field sequence order —
|
|
4743
4743
|
* the same format written by BaseRESTIntegrationConnector.ToExternalRecord.
|
|
4744
4744
|
*/
|
|
4745
|
-
|
|
4745
|
+
buildEntityPrimaryKey(recordID, pkFields) {
|
|
4746
4746
|
const key = new CompositeKey();
|
|
4747
4747
|
if (pkFields.length === 0) {
|
|
4748
4748
|
// Never invent an `ID` column: MJ keys can have any name, and a load against a made-up
|
|
@@ -4765,8 +4765,8 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
4765
4765
|
* primary-key column(s), in PK-field order — the shape CompanyIntegrationRecordMap.EntityRecordID
|
|
4766
4766
|
* and a normalized RecordChange.RecordID carry. A single-column key is just its value.
|
|
4767
4767
|
*/
|
|
4768
|
-
|
|
4769
|
-
return pkFields.map(pk =>
|
|
4768
|
+
composeEntityRecordID(row, pkFields) {
|
|
4769
|
+
return pkFields.map(pk => SerializeKeyValue(row[pk.Name])).join('|');
|
|
4770
4770
|
}
|
|
4771
4771
|
/**
|
|
4772
4772
|
* Reports ACTIVE field maps whose MJ column does not exist, once per entity map per run.
|
|
@@ -4776,7 +4776,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
4776
4776
|
* record while the run reports those records as written. Checking it here costs one metadata
|
|
4777
4777
|
* read and happens before the first fetch, so the warning arrives before the wasted work.
|
|
4778
4778
|
*/
|
|
4779
|
-
|
|
4779
|
+
warnOnUnbindableFieldMaps(entityMap, fieldMaps, logger) {
|
|
4780
4780
|
const entityName = entityMap.Entity ?? '';
|
|
4781
4781
|
// Diagnostics must never be able to fail a run: an unresolvable entity/provider is reported
|
|
4782
4782
|
// by the paths that actually need it, and here it simply means there is nothing to check.
|
|
@@ -4796,7 +4796,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
4796
4796
|
/**
|
|
4797
4797
|
* Sets fields on a BaseEntity instance from a field value map.
|
|
4798
4798
|
*/
|
|
4799
|
-
|
|
4799
|
+
setEntityFields(entity, fields) {
|
|
4800
4800
|
// Build a quick lookup of field types so we can coerce values correctly.
|
|
4801
4801
|
// Empty strings and common "null sentinel" values from external systems
|
|
4802
4802
|
// (e.g., Salesforce returns "" for unset lat/lon on some records) MUST
|
|
@@ -4979,7 +4979,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
4979
4979
|
if (record && has(CONTENT_HASH_COLUMN)) {
|
|
4980
4980
|
const storedHash = entity.Get(CONTENT_HASH_COLUMN);
|
|
4981
4981
|
if (typeof storedHash === 'string' && storedHash.length > 0
|
|
4982
|
-
&& storedHash !==
|
|
4982
|
+
&& storedHash !== ComputeContentHash(record.MappedFields ?? {})) {
|
|
4983
4983
|
return true;
|
|
4984
4984
|
}
|
|
4985
4985
|
}
|
|
@@ -4989,7 +4989,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
4989
4989
|
* Sets standard integration columns (__mj_integration_*) on target entities.
|
|
4990
4990
|
* Silently skips if the entity doesn't have these columns (e.g., __mj targets).
|
|
4991
4991
|
*/
|
|
4992
|
-
|
|
4992
|
+
setStandardIntegrationFields(entity, record) {
|
|
4993
4993
|
const fieldNames = entity.Fields?.map(f => f.Name) ?? [];
|
|
4994
4994
|
const hasField = (name) => fieldNames.includes(name);
|
|
4995
4995
|
if (hasField('__mj_integration_LastSyncedAt')) {
|
|
@@ -5019,7 +5019,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
5019
5019
|
// stored hash predates this basis (overflow folded in) mismatch ONCE, rewrite, and
|
|
5020
5020
|
// converge on the new basis.
|
|
5021
5021
|
if (hasField(CONTENT_HASH_COLUMN)) {
|
|
5022
|
-
entity.Set(CONTENT_HASH_COLUMN,
|
|
5022
|
+
entity.Set(CONTENT_HASH_COLUMN, ComputeContentHash(record.MappedFields ?? {}));
|
|
5023
5023
|
}
|
|
5024
5024
|
// Custom-overflow capture (gaps.md §2): park any source keys with no field map as JSON,
|
|
5025
5025
|
// in THIS same row write (no extra round-trip → a customs-free sync stays byte-identical).
|
|
@@ -5032,7 +5032,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
5032
5032
|
// null when there are no extras, clearing a prior overflow; it stays byte-identical for a
|
|
5033
5033
|
// customs-free row (Set(null) on an already-null column is a no-op under dirty tracking).
|
|
5034
5034
|
if (hasField(CUSTOM_OVERFLOW_COLUMN)) {
|
|
5035
|
-
entity.Set(CUSTOM_OVERFLOW_COLUMN,
|
|
5035
|
+
entity.Set(CUSTOM_OVERFLOW_COLUMN, ReconcileOverflowValue(record.UnmappedFields));
|
|
5036
5036
|
}
|
|
5037
5037
|
// ── Per-record sync ledger (plan §2.5) ───────────────────────────────────────
|
|
5038
5038
|
// The external system's version token for optimistic-concurrency on bidirectional
|
|
@@ -5094,7 +5094,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
5094
5094
|
* truncation this helper exists to prevent, and the orphan sweep would archive live
|
|
5095
5095
|
* records on the strength of it. Keyset seeks on the last ID seen and cannot shift.
|
|
5096
5096
|
*/
|
|
5097
|
-
async
|
|
5097
|
+
async loadAllRecordMaps(companyIntegrationID, entityID, contextUser) {
|
|
5098
5098
|
const PAGE_SIZE = IntegrationEngine.RecordMapPageSize;
|
|
5099
5099
|
// Backstop only: at the default page size this is 50M mappings for one
|
|
5100
5100
|
// (CompanyIntegration, Entity) pair. It exists so a provider that ignores the seek key
|
|
@@ -5144,7 +5144,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
5144
5144
|
* decides not to change. The `recordMaps` parameter is optional so that callers outside the
|
|
5145
5145
|
* batched apply pass (and every existing test) keep the original immediate-write behaviour.
|
|
5146
5146
|
*/
|
|
5147
|
-
async
|
|
5147
|
+
async queueRecordMap(recordMaps, companyIntegrationID, externalID, entityID, entityRecordID, contextUser) {
|
|
5148
5148
|
if (recordMaps) {
|
|
5149
5149
|
// Queue only — the apply loop flushes after the batch transaction commits. Writing here
|
|
5150
5150
|
// (or auto-flushing on a full chunk) would put map rows inside a transaction that
|
|
@@ -5152,12 +5152,12 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
5152
5152
|
recordMaps.Queue({ EntityID: entityID, ExternalID: externalID, EntityRecordID: entityRecordID });
|
|
5153
5153
|
return;
|
|
5154
5154
|
}
|
|
5155
|
-
await this.
|
|
5155
|
+
await this.saveRecordMap(companyIntegrationID, externalID, entityID, entityRecordID, contextUser);
|
|
5156
5156
|
}
|
|
5157
5157
|
/**
|
|
5158
5158
|
* Creates or updates a CompanyIntegrationRecordMap entry to track the external↔MJ mapping.
|
|
5159
5159
|
*/
|
|
5160
|
-
async
|
|
5160
|
+
async saveRecordMap(companyIntegrationID, externalID, entityID, entityRecordID, contextUser) {
|
|
5161
5161
|
const md = this.ProviderToUse;
|
|
5162
5162
|
const recordMap = await md.GetEntityObject('MJ: Company Integration Record Maps', contextUser);
|
|
5163
5163
|
// Upsert by identity: one row per (CompanyIntegration, Entity, external record).
|
|
@@ -5168,7 +5168,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
5168
5168
|
// so a value the batch would have found here must be found here too, or the fallback
|
|
5169
5169
|
// re-creates the very duplicate the upsert exists to prevent.
|
|
5170
5170
|
const quotedExternalID = md instanceof DatabaseProviderBase
|
|
5171
|
-
?
|
|
5171
|
+
? QuoteTextLiteral(externalID, md.Dialect)
|
|
5172
5172
|
: `'${externalID.replace(/'/g, "''")}'`;
|
|
5173
5173
|
const rv = new RunView();
|
|
5174
5174
|
const existing = await rv.RunView({
|
|
@@ -5206,7 +5206,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
5206
5206
|
/**
|
|
5207
5207
|
* Creates a CompanyIntegrationRunDetail record for audit/reporting.
|
|
5208
5208
|
*/
|
|
5209
|
-
async
|
|
5209
|
+
async createRunDetail(run, entityMap, result, contextUser) {
|
|
5210
5210
|
const md = this.ProviderToUse;
|
|
5211
5211
|
const detail = await md.GetEntityObject('MJ: Company Integration Run Details', contextUser);
|
|
5212
5212
|
detail.NewRecord();
|
|
@@ -5239,7 +5239,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
5239
5239
|
/**
|
|
5240
5240
|
* Merges an entity-map-level result into the aggregate result.
|
|
5241
5241
|
*/
|
|
5242
|
-
|
|
5242
|
+
mergeResult(aggregate, mapResult) {
|
|
5243
5243
|
aggregate.RecordsProcessed += mapResult.RecordsProcessed;
|
|
5244
5244
|
aggregate.RecordsCreated += mapResult.RecordsCreated;
|
|
5245
5245
|
aggregate.RecordsUpdated += mapResult.RecordsUpdated;
|
|
@@ -5307,7 +5307,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
5307
5307
|
/**
|
|
5308
5308
|
* Finalizes a successful run with aggregate totals and emits a completion notification.
|
|
5309
5309
|
*/
|
|
5310
|
-
async
|
|
5310
|
+
async finalizeRun(run, result, contextUser, onNotification, aborted) {
|
|
5311
5311
|
run.EndedAt = new Date();
|
|
5312
5312
|
run.TotalRecords = result.RecordsProcessed;
|
|
5313
5313
|
// A cancelled run is neither a success nor a failure, and 'Cancelled' is now a first-class
|
|
@@ -5431,7 +5431,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
5431
5431
|
/**
|
|
5432
5432
|
* Marks a run as failed after an unrecoverable error and emits a failure notification.
|
|
5433
5433
|
*/
|
|
5434
|
-
async
|
|
5434
|
+
async failRun(run, err, _contextUser, onNotification) {
|
|
5435
5435
|
run.EndedAt = new Date();
|
|
5436
5436
|
run.Status = 'Failed';
|
|
5437
5437
|
run.ErrorLog = err instanceof Error ? err.message : String(err);
|