@memberjunction/integration-engine 6.2.0-edge.5 → 6.2.0-edge.7
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 +45 -0
- package/dist/ActionMetadataGenerator.d.ts.map +1 -1
- package/dist/ActionMetadataGenerator.js +75 -5
- package/dist/ActionMetadataGenerator.js.map +1 -1
- package/dist/AdaptiveConcurrency.d.ts +15 -0
- package/dist/AdaptiveConcurrency.d.ts.map +1 -1
- package/dist/AdaptiveConcurrency.js +21 -0
- package/dist/AdaptiveConcurrency.js.map +1 -1
- package/dist/BaseIntegrationConnector.d.ts +70 -0
- package/dist/BaseIntegrationConnector.d.ts.map +1 -1
- package/dist/BaseIntegrationConnector.js +112 -9
- package/dist/BaseIntegrationConnector.js.map +1 -1
- package/dist/BaseRESTIntegrationConnector.d.ts +2 -2
- package/dist/BaseRESTIntegrationConnector.d.ts.map +1 -1
- package/dist/BaseRESTIntegrationConnector.js +43 -4
- package/dist/BaseRESTIntegrationConnector.js.map +1 -1
- package/dist/CatalogScope.d.ts +152 -0
- package/dist/CatalogScope.d.ts.map +1 -0
- package/dist/CatalogScope.js +399 -0
- package/dist/CatalogScope.js.map +1 -0
- package/dist/CatalogSource.d.ts +53 -0
- package/dist/CatalogSource.d.ts.map +1 -0
- package/dist/CatalogSource.js +82 -0
- package/dist/CatalogSource.js.map +1 -0
- package/dist/CatalogWriter.d.ts +216 -0
- package/dist/CatalogWriter.d.ts.map +1 -0
- package/dist/CatalogWriter.js +457 -0
- package/dist/CatalogWriter.js.map +1 -0
- package/dist/CompanyIntegrationCatalogStore.d.ts +109 -0
- package/dist/CompanyIntegrationCatalogStore.d.ts.map +1 -0
- package/dist/CompanyIntegrationCatalogStore.js +229 -0
- package/dist/CompanyIntegrationCatalogStore.js.map +1 -0
- package/dist/DeclaredSampleMerge.d.ts +10 -4
- package/dist/DeclaredSampleMerge.d.ts.map +1 -1
- package/dist/DeclaredSampleMerge.js +17 -6
- package/dist/DeclaredSampleMerge.js.map +1 -1
- package/dist/DiscoveryWatchdog.d.ts +38 -1
- package/dist/DiscoveryWatchdog.d.ts.map +1 -1
- package/dist/DiscoveryWatchdog.js +56 -1
- package/dist/DiscoveryWatchdog.js.map +1 -1
- package/dist/IntegrationActionGenerator.d.ts.map +1 -1
- package/dist/IntegrationActionGenerator.js +36 -26
- package/dist/IntegrationActionGenerator.js.map +1 -1
- package/dist/IntegrationConnectorCreationPipeline.d.ts +181 -4
- package/dist/IntegrationConnectorCreationPipeline.d.ts.map +1 -1
- package/dist/IntegrationConnectorCreationPipeline.js +646 -68
- package/dist/IntegrationConnectorCreationPipeline.js.map +1 -1
- package/dist/IntegrationEngine.d.ts +86 -2
- package/dist/IntegrationEngine.d.ts.map +1 -1
- package/dist/IntegrationEngine.js +760 -209
- package/dist/IntegrationEngine.js.map +1 -1
- package/dist/IntegrationSchemaSync.d.ts +97 -0
- package/dist/IntegrationSchemaSync.d.ts.map +1 -1
- package/dist/IntegrationSchemaSync.js +302 -49
- package/dist/IntegrationSchemaSync.js.map +1 -1
- package/dist/MatchEngine.d.ts.map +1 -1
- package/dist/MatchEngine.js +6 -0
- package/dist/MatchEngine.js.map +1 -1
- package/dist/MemoryGovernor.d.ts +183 -0
- package/dist/MemoryGovernor.d.ts.map +1 -0
- package/dist/MemoryGovernor.js +225 -0
- package/dist/MemoryGovernor.js.map +1 -0
- package/dist/ResourcePressure.d.ts +80 -0
- package/dist/ResourcePressure.d.ts.map +1 -0
- package/dist/ResourcePressure.js +143 -0
- package/dist/ResourcePressure.js.map +1 -0
- package/dist/RunMemoryControl.d.ts +122 -0
- package/dist/RunMemoryControl.d.ts.map +1 -0
- package/dist/RunMemoryControl.js +237 -0
- package/dist/RunMemoryControl.js.map +1 -0
- package/dist/SchemaPersistCounts.d.ts +29 -0
- package/dist/SchemaPersistCounts.d.ts.map +1 -0
- package/dist/SchemaPersistCounts.js +27 -0
- package/dist/SchemaPersistCounts.js.map +1 -0
- package/dist/SyncLogger.d.ts +21 -0
- package/dist/SyncLogger.d.ts.map +1 -1
- package/dist/SyncLogger.js +92 -1
- package/dist/SyncLogger.js.map +1 -1
- package/dist/WatermarkService.d.ts.map +1 -1
- package/dist/WatermarkService.js +1 -0
- package/dist/WatermarkService.js.map +1 -1
- package/dist/index.d.ts +12 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +8 -0
- package/dist/index.js.map +1 -1
- package/dist/types.d.ts +46 -0
- package/dist/types.d.ts.map +1 -1
- package/package.json +7 -7
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
2
|
+
import { RefreshCatalogScope, RunInWarmedCatalogScope, UnpinCatalogObjects, WarmCatalogObject } from './CatalogScope.js';
|
|
2
3
|
import { CompositeKey, DatabaseProviderBase, LogStatusEx, Metadata, RunView, EntitySaveOptions, EntityDeleteOptions } from '@memberjunction/core';
|
|
3
4
|
import { RunOwnershipLostError, RunOwnershipService } from './RunOwnershipService.js';
|
|
4
|
-
import { BaseSingleton, UUIDsEqual } from '@memberjunction/global';
|
|
5
|
+
import { BaseSingleton, NormalizeUUID, UUIDsEqual } from '@memberjunction/global';
|
|
5
6
|
import { IntegrationEngineBase } from '@memberjunction/integration-engine-base';
|
|
6
7
|
import { ClassifyError, IsRetryableError } from './types.js';
|
|
7
8
|
import { WithRetry } from './RetryRunner.js';
|
|
@@ -12,6 +13,8 @@ import { FieldMappingEngine } from './FieldMappingEngine.js';
|
|
|
12
13
|
import { MatchEngine } from './MatchEngine.js';
|
|
13
14
|
import { WatermarkService } from './WatermarkService.js';
|
|
14
15
|
import { SyncLogger } from './SyncLogger.js';
|
|
16
|
+
import { ReadResourcePressure, EvaluatePressure } from './ResourcePressure.js';
|
|
17
|
+
import { RunMemoryControl } from './RunMemoryControl.js';
|
|
15
18
|
import { CONTENT_HASH_COLUMN, ComputeContentHash } from './ContentHash.js';
|
|
16
19
|
import { RecordMapBatch } from './RecordMapBatch.js';
|
|
17
20
|
import { BuildContentHashPrefetchFilter, QuoteTextLiteral } from './prefetchFilter.js';
|
|
@@ -434,6 +437,20 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
434
437
|
}
|
|
435
438
|
/** In-process lock map to prevent concurrent syncs for the same CompanyIntegration */
|
|
436
439
|
static { this.activeSyncs = new Map(); }
|
|
440
|
+
/**
|
|
441
|
+
* Live progress for runs owned by THIS process, keyed like activeSyncs.
|
|
442
|
+
*
|
|
443
|
+
* Progress moved to the run row's ProgressJSON so any process could read it — but that column
|
|
444
|
+
* arrives in MJ 6.1.x, and the in-process map was deleted at the same time. On every earlier
|
|
445
|
+
* tenant that left NO source at all: the async reader silently finds nothing (RunView drops the
|
|
446
|
+
* unknown field) and the synchronous accessor was left returning undefined by contract. A sync
|
|
447
|
+
* could run for an hour with the UI showing nothing running.
|
|
448
|
+
*
|
|
449
|
+
* This is the floor. GetSyncProgressAsync prefers the durable row and falls back here, so a
|
|
450
|
+
* single-process tenant answers correctly today and a multi-process one still answers from the
|
|
451
|
+
* row once the column exists.
|
|
452
|
+
*/
|
|
453
|
+
static { this.liveProgress = new Map(); }
|
|
437
454
|
/**
|
|
438
455
|
* Maintenance locks: while a metadata refresh / schema evolution / RSU pipeline is
|
|
439
456
|
* running for a CompanyIntegration, data syncs MUST NOT start ("locks of sync and scheduled
|
|
@@ -456,6 +473,19 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
456
473
|
IntegrationEngine.maintenanceLocks.set(key, { Reason: reason, AcquiredAt: new Date() });
|
|
457
474
|
return true;
|
|
458
475
|
}
|
|
476
|
+
/**
|
|
477
|
+
* Whether a sync for this connection is executing IN THIS PROCESS right now.
|
|
478
|
+
*
|
|
479
|
+
* Exists so a caller can tell an operator the truth about a cancel. The durable cancel needs
|
|
480
|
+
* a run-row column that only newer tenants have; where it is absent, the in-process registry
|
|
481
|
+
* is the only signal there is, and "we signalled the sync" versus "a sync is running
|
|
482
|
+
* somewhere we cannot reach" are different things to tell someone who just hit pause.
|
|
483
|
+
*
|
|
484
|
+
* Reads the same map RunSync reserves, so it cannot drift from what is actually running.
|
|
485
|
+
*/
|
|
486
|
+
static IsSyncRunningInThisProcess(companyIntegrationID) {
|
|
487
|
+
return IntegrationEngine.activeSyncs.has(companyIntegrationID.toLowerCase());
|
|
488
|
+
}
|
|
459
489
|
/** Releases the maintenance lock (idempotent — safe in a finally). */
|
|
460
490
|
static ReleaseMaintenanceLock(companyIntegrationID) {
|
|
461
491
|
IntegrationEngine.maintenanceLocks.delete(companyIntegrationID.toLowerCase());
|
|
@@ -595,22 +625,30 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
595
625
|
EntityName: 'MJ: Company Integration Runs',
|
|
596
626
|
ExtraFilter: `CompanyIntegrationID='${companyIntegrationID.replace(/'/g, "''")}' AND Status IN ('In Progress','Queued')`,
|
|
597
627
|
OrderBy: 'StartedAt DESC',
|
|
598
|
-
Fields: ['ProgressJSON', 'LeaseExpiresAt', 'StartedAt'],
|
|
628
|
+
Fields: ['ID', 'ProgressJSON', 'LeaseExpiresAt', 'StartedAt'],
|
|
599
629
|
MaxRows: 1,
|
|
630
|
+
SkipTotalRowCount: true,
|
|
600
631
|
ResultType: 'simple',
|
|
601
632
|
BypassCache: true, // live liveness/progress read — must see the current row
|
|
602
633
|
}, contextUser);
|
|
603
634
|
const row = result.Success ? result.Results?.[0] : undefined;
|
|
635
|
+
// No readable row is not proof there is no sync: before MJ 6.1.x the run row has no
|
|
636
|
+
// ProgressJSON column at all, and RunView drops the unknown field silently rather than
|
|
637
|
+
// failing. Fall back to this process's own snapshot.
|
|
604
638
|
if (!row)
|
|
605
|
-
return
|
|
639
|
+
return IntegrationEngine.liveProgress.get(companyIntegrationID.toLowerCase());
|
|
606
640
|
if (row.LeaseExpiresAt != null && new Date(row.LeaseExpiresAt).getTime() < Date.now()) {
|
|
607
641
|
return undefined; // owner's lease lapsed — not live progress
|
|
608
642
|
}
|
|
609
|
-
if (!row.ProgressJSON)
|
|
610
|
-
|
|
643
|
+
if (!row.ProgressJSON) {
|
|
644
|
+
const local = IntegrationEngine.liveProgress.get(companyIntegrationID.toLowerCase());
|
|
645
|
+
// The row is readable even when the column is not, so the id is known here even on a
|
|
646
|
+
// tenant whose snapshot came from this process rather than the database.
|
|
647
|
+
return local ? { ...local, RunID: local.RunID ?? row.ID } : undefined;
|
|
648
|
+
}
|
|
611
649
|
try {
|
|
612
650
|
const snapshot = JSON.parse(row.ProgressJSON);
|
|
613
|
-
return { ...snapshot, StartedAt: new Date(snapshot.StartedAt) };
|
|
651
|
+
return { ...snapshot, StartedAt: new Date(snapshot.StartedAt), RunID: snapshot.RunID ?? row.ID };
|
|
614
652
|
}
|
|
615
653
|
catch {
|
|
616
654
|
return undefined; // corrupt snapshot — treat as no progress rather than throwing at a poller
|
|
@@ -749,170 +787,179 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
749
787
|
* await, and the pool always starts one from a synchronous call site.
|
|
750
788
|
*/
|
|
751
789
|
async resumeOneOrphanedRun(run, prov, rv, contextUser) {
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
let resumeResult;
|
|
766
|
-
IntegrationEngine.activeSyncs.set(lockKey, new Promise(res => { resolveResumeLock = res; }));
|
|
767
|
-
const ownership = new RunOwnershipService(prov, runID, undefined, contextUser);
|
|
768
|
-
try {
|
|
769
|
-
// CLAIM BEFORE ADOPTING (PR 1 item 6): a single atomic UPDATE that succeeds only if the
|
|
770
|
-
// run is still unowned/lapsed. Zero rows = another worker adopted it between our RunView
|
|
771
|
-
// and now — skip, never double-run. A successful claim BUMPS the fence, so if the
|
|
772
|
-
// original owner is actually alive-but-slow it aborts at its next boundary check
|
|
773
|
-
// without writing: the sweep-reclaim is itself the abort signal for the abandoned owner.
|
|
774
|
-
const claimed = await ownership.Claim();
|
|
775
|
-
if (!claimed) {
|
|
776
|
-
console.log(`[IntegrationEngine] Skipping resume of run ${runID.substring(0, 8)} — claim lost (another worker adopted it)`);
|
|
790
|
+
// A resumed run reads the same catalog the original did — its own connection's — in the
|
|
791
|
+
// same warmed scope a fresh run uses (see RunSync).
|
|
792
|
+
return RunInWarmedCatalogScope(run.CompanyIntegrationID, async () => {
|
|
793
|
+
const companyIntegrationID = run.CompanyIntegrationID;
|
|
794
|
+
const runID = run.ID;
|
|
795
|
+
const lockKey = companyIntegrationID.toLowerCase();
|
|
796
|
+
// C1: respect the SAME in-process concurrency lock RunSync uses. If a live sync for this
|
|
797
|
+
// CompanyIntegration is already running (e.g. the scheduler fired during startup), skip the
|
|
798
|
+
// resume — double-running one CI on the shared provider connection corrupts its singular
|
|
799
|
+
// transaction state (exactly what runWriteExclusive guards against WITHIN a run). The
|
|
800
|
+
// get→set pair below has no await between them, so check-and-reserve is atomic on the loop.
|
|
801
|
+
if (IntegrationEngine.activeSyncs.get(lockKey)) {
|
|
802
|
+
console.log(`[IntegrationEngine] Skipping resume of run ${runID.substring(0, 8)} — a live sync for ${lockKey} is already running`);
|
|
777
803
|
return;
|
|
778
804
|
}
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
// completed WITH errors (RecordsErrored>0, no throw) must be re-attempted on resume,
|
|
784
|
-
// otherwise its errored records are silently abandoned.
|
|
785
|
-
const detailsResult = await rv.RunView({
|
|
786
|
-
EntityName: 'MJ: Company Integration Run Details',
|
|
787
|
-
ExtraFilter: `CompanyIntegrationRunID='${runID}'`,
|
|
788
|
-
Fields: ['RecordID', 'IsSuccess'],
|
|
789
|
-
ResultType: 'simple',
|
|
790
|
-
}, contextUser);
|
|
791
|
-
const completedMapIDs = new Set();
|
|
792
|
-
if (detailsResult.Success) {
|
|
793
|
-
for (const d of detailsResult.Results) {
|
|
794
|
-
if (!d.IsSuccess)
|
|
795
|
-
continue; // completed-with-errors → re-attempt on resume
|
|
796
|
-
const m = /^EntityMap:([0-9a-fA-F-]+)\|/.exec(d.RecordID ?? '');
|
|
797
|
-
// Parse-miss falls open (map treated as not-completed → re-runs): at worst a
|
|
798
|
-
// redundant idempotent re-sync, never a silent skip.
|
|
799
|
-
if (m)
|
|
800
|
-
completedMapIDs.add(m[1].toLowerCase());
|
|
801
|
-
}
|
|
802
|
-
}
|
|
803
|
-
console.log(`[IntegrationEngine] Resuming run ${runID.substring(0, 8)}... ` +
|
|
804
|
-
`for ${companyIntegrationID.substring(0, 8)}... ` +
|
|
805
|
-
`(${completedMapIDs.size} entity maps already completed)`);
|
|
806
|
-
// Recover what this run was ASKED to do. Without this the resume rebuilds config from
|
|
807
|
-
// the CompanyIntegration alone, so an adopted run silently loses its options — most
|
|
808
|
-
// damagingly FullSync, which exists precisely to distrust the watermark. An adopted
|
|
809
|
-
// full sync would resume incrementally, fetch nothing, and report Success.
|
|
810
|
-
// Unparseable/absent ConfigData falls back to defaults rather than refusing to resume.
|
|
811
|
-
let resumeOptions;
|
|
812
|
-
let resumeTriggerType = 'Scheduled';
|
|
805
|
+
let resolveResumeLock;
|
|
806
|
+
let resumeResult;
|
|
807
|
+
IntegrationEngine.activeSyncs.set(lockKey, new Promise(res => { resolveResumeLock = res; }));
|
|
808
|
+
const ownership = new RunOwnershipService(prov, runID, undefined, contextUser);
|
|
813
809
|
try {
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
if
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
//
|
|
855
|
-
//
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
};
|
|
859
|
-
const runCtx = {
|
|
860
|
-
provider: prov,
|
|
861
|
-
ownership,
|
|
862
|
-
abortController,
|
|
863
|
-
progressSnapshot,
|
|
864
|
-
cancelRequested: false,
|
|
865
|
-
ownershipLost: false,
|
|
866
|
-
};
|
|
867
|
-
ownership.StartHeartbeat({
|
|
868
|
-
onLost: () => { runCtx.ownershipLost = true; abortController.abort(); },
|
|
869
|
-
onCancelRequested: () => { runCtx.cancelRequested = true; abortController.abort(); },
|
|
870
|
-
progressSupplier: () => JSON.stringify(progressSnapshot),
|
|
871
|
-
});
|
|
872
|
-
const result = await IntegrationEngine.runContext.run(runCtx, async () => {
|
|
873
|
-
const r = await this.executeEntityMaps(config, run, contextUser, undefined, abortController.signal);
|
|
874
|
-
r.RunID = runID;
|
|
875
|
-
await this.finalizeRun(run, r, contextUser);
|
|
876
|
-
return r;
|
|
877
|
-
});
|
|
878
|
-
resumeResult = result;
|
|
879
|
-
console.log(`[IntegrationEngine] Resume complete for ${runID.substring(0, 8)}: ` +
|
|
880
|
-
`${result.RecordsCreated} created, ${result.RecordsUpdated} updated, ` +
|
|
881
|
-
`${result.RecordsErrored} errored`);
|
|
882
|
-
}
|
|
883
|
-
catch (err) {
|
|
884
|
-
const errMsg = err instanceof Error ? err.message : String(err);
|
|
885
|
-
console.error(`[IntegrationEngine] Failed to resume run ${runID.substring(0, 8)}: ${errMsg}`);
|
|
886
|
-
if (err instanceof RunOwnershipLostError) {
|
|
887
|
-
// We were fenced out mid-resume — the NEW owner now owns the run row.
|
|
888
|
-
// Writing 'Failed' here would clobber the live holder's state.
|
|
889
|
-
console.warn(`[IntegrationEngine] Resume of run ${runID.substring(0, 8)} lost ownership — leaving the run row to its new owner`);
|
|
890
|
-
}
|
|
891
|
-
else {
|
|
892
|
-
// Mark as failed so it doesn't get picked up again
|
|
893
|
-
run.EndedAt = new Date();
|
|
894
|
-
run.Status = 'Failed';
|
|
895
|
-
run.ErrorLog = JSON.stringify([{ ErrorMessage: `Resume failed: ${errMsg}` }]);
|
|
896
|
-
ownership.SyncEntityOwnershipFields(run);
|
|
897
|
-
await run.Save();
|
|
810
|
+
// CLAIM BEFORE ADOPTING (PR 1 item 6): a single atomic UPDATE that succeeds only if the
|
|
811
|
+
// run is still unowned/lapsed. Zero rows = another worker adopted it between our RunView
|
|
812
|
+
// and now — skip, never double-run. A successful claim BUMPS the fence, so if the
|
|
813
|
+
// original owner is actually alive-but-slow it aborts at its next boundary check
|
|
814
|
+
// without writing: the sweep-reclaim is itself the abort signal for the abandoned owner.
|
|
815
|
+
const claimed = await ownership.Claim();
|
|
816
|
+
if (!claimed) {
|
|
817
|
+
console.log(`[IntegrationEngine] Skipping resume of run ${runID.substring(0, 8)} — claim lost (another worker adopted it)`);
|
|
818
|
+
return;
|
|
819
|
+
}
|
|
820
|
+
// Find which entity MAPS already completed SUCCESSFULLY in this run. We correlate
|
|
821
|
+
// by EntityMapID (parsed from the detail's RecordID, stamped by CreateRunDetail),
|
|
822
|
+
// not EntityID — two maps can target the same MJ Entity, so keying on EntityID
|
|
823
|
+
// could skip a still-pending sibling map. We also require IsSuccess=1: a map that
|
|
824
|
+
// completed WITH errors (RecordsErrored>0, no throw) must be re-attempted on resume,
|
|
825
|
+
// otherwise its errored records are silently abandoned.
|
|
826
|
+
const detailsResult = await rv.RunView({
|
|
827
|
+
EntityName: 'MJ: Company Integration Run Details',
|
|
828
|
+
ExtraFilter: `CompanyIntegrationRunID='${runID}'`,
|
|
829
|
+
Fields: ['RecordID', 'IsSuccess'],
|
|
830
|
+
ResultType: 'simple',
|
|
831
|
+
}, contextUser);
|
|
832
|
+
const completedMapIDs = new Set();
|
|
833
|
+
if (detailsResult.Success) {
|
|
834
|
+
for (const d of detailsResult.Results) {
|
|
835
|
+
if (!d.IsSuccess)
|
|
836
|
+
continue; // completed-with-errors → re-attempt on resume
|
|
837
|
+
const m = /^EntityMap:([0-9a-fA-F-]+)\|/.exec(d.RecordID ?? '');
|
|
838
|
+
// Parse-miss falls open (map treated as not-completed → re-runs): at worst a
|
|
839
|
+
// redundant idempotent re-sync, never a silent skip.
|
|
840
|
+
if (m)
|
|
841
|
+
completedMapIDs.add(m[1].toLowerCase());
|
|
842
|
+
}
|
|
843
|
+
}
|
|
844
|
+
console.log(`[IntegrationEngine] Resuming run ${runID.substring(0, 8)}... ` +
|
|
845
|
+
`for ${companyIntegrationID.substring(0, 8)}... ` +
|
|
846
|
+
`(${completedMapIDs.size} entity maps already completed)`);
|
|
847
|
+
// Recover what this run was ASKED to do. Without this the resume rebuilds config from
|
|
848
|
+
// the CompanyIntegration alone, so an adopted run silently loses its options — most
|
|
849
|
+
// damagingly FullSync, which exists precisely to distrust the watermark. An adopted
|
|
850
|
+
// full sync would resume incrementally, fetch nothing, and report Success.
|
|
851
|
+
// Unparseable/absent ConfigData falls back to defaults rather than refusing to resume.
|
|
852
|
+
let resumeOptions;
|
|
853
|
+
let resumeTriggerType = 'Scheduled';
|
|
898
854
|
try {
|
|
899
|
-
|
|
855
|
+
const cfg = JSON.parse(run.ConfigData ?? '{}');
|
|
856
|
+
resumeOptions = cfg.options ?? undefined;
|
|
857
|
+
if (cfg.triggerType)
|
|
858
|
+
resumeTriggerType = cfg.triggerType;
|
|
900
859
|
}
|
|
901
|
-
catch {
|
|
860
|
+
catch {
|
|
861
|
+
console.warn(`[IntegrationEngine] Run ${runID.substring(0, 8)} has unparseable ConfigData; resuming with defaults`);
|
|
862
|
+
}
|
|
863
|
+
if (resumeOptions?.FullSync) {
|
|
864
|
+
console.log(`[IntegrationEngine] Run ${runID.substring(0, 8)} was a FULL sync — resuming as full, not incremental`);
|
|
865
|
+
}
|
|
866
|
+
// Load config and filter to only remaining entity maps (by map ID)
|
|
867
|
+
const config = await this.loadRunConfiguration(companyIntegrationID, contextUser, resumeOptions);
|
|
868
|
+
const remainingMaps = config.entityMaps.filter(em => !completedMapIDs.has(em.ID.toLowerCase()));
|
|
869
|
+
if (remainingMaps.length === 0) {
|
|
870
|
+
console.log(`[IntegrationEngine] All entity maps completed for run ${runID.substring(0, 8)}, marking as Success`);
|
|
871
|
+
run.EndedAt = new Date();
|
|
872
|
+
run.Status = 'Success';
|
|
873
|
+
ownership.SyncEntityOwnershipFields(run); // full-row save must not clobber the live claim
|
|
874
|
+
await run.Save();
|
|
875
|
+
await ownership.Release('Success');
|
|
876
|
+
return;
|
|
877
|
+
}
|
|
878
|
+
console.log(`[IntegrationEngine] Resuming ${remainingMaps.length} remaining entity maps (of ${config.entityMaps.length} total)`);
|
|
879
|
+
// Replace entityMaps with only the remaining ones
|
|
880
|
+
config.entityMaps = remainingMaps;
|
|
881
|
+
// Execute remaining maps inside a per-run context: the resume gets its own provider
|
|
882
|
+
// binding, abort controller, and ownership — identical to a fresh RunSync — so the
|
|
883
|
+
// heartbeat renews the lease, the batch boundaries fence-check, and FinalizeRun
|
|
884
|
+
// syncs ownership fields + releases, all through the SAME code paths.
|
|
885
|
+
const abortController = new AbortController();
|
|
886
|
+
const progressSnapshot = {
|
|
887
|
+
StartedAt: new Date(),
|
|
888
|
+
CurrentEntity: '',
|
|
889
|
+
EntityMapsTotal: remainingMaps.length,
|
|
890
|
+
EntityMapsCompleted: 0,
|
|
891
|
+
RecordsProcessed: 0,
|
|
892
|
+
RecordsCreated: 0,
|
|
893
|
+
RecordsUpdated: 0,
|
|
894
|
+
RecordsErrored: 0,
|
|
895
|
+
RecordsSkipped: 0,
|
|
896
|
+
// The run's OWN trigger type, recovered above — not a hardcoded 'Scheduled'. This is
|
|
897
|
+
// what IntegrationGetSyncProgress reports back ("Sync in progress (Manual)"), so a
|
|
898
|
+
// hardcoded value mislabels every adopted run.
|
|
899
|
+
TriggerType: resumeTriggerType,
|
|
900
|
+
};
|
|
901
|
+
// Same reason as the main path: without this a resumed run reports no progress at all
|
|
902
|
+
// on any tenant whose run row has no ProgressJSON column.
|
|
903
|
+
IntegrationEngine.liveProgress.set(lockKey, progressSnapshot);
|
|
904
|
+
const runCtx = {
|
|
905
|
+
provider: prov,
|
|
906
|
+
ownership,
|
|
907
|
+
abortController,
|
|
908
|
+
progressSnapshot,
|
|
909
|
+
cancelRequested: false,
|
|
910
|
+
ownershipLost: false,
|
|
911
|
+
};
|
|
912
|
+
ownership.StartHeartbeat({
|
|
913
|
+
onLost: () => { runCtx.ownershipLost = true; abortController.abort(); },
|
|
914
|
+
onCancelRequested: () => { runCtx.cancelRequested = true; abortController.abort(); },
|
|
915
|
+
progressSupplier: () => JSON.stringify(progressSnapshot),
|
|
916
|
+
});
|
|
917
|
+
const result = await IntegrationEngine.runContext.run(runCtx, async () => {
|
|
918
|
+
const r = await this.executeEntityMaps(config, run, contextUser, undefined, abortController.signal);
|
|
919
|
+
r.RunID = runID;
|
|
920
|
+
await this.finalizeRun(run, r, contextUser);
|
|
921
|
+
return r;
|
|
922
|
+
});
|
|
923
|
+
resumeResult = result;
|
|
924
|
+
console.log(`[IntegrationEngine] Resume complete for ${runID.substring(0, 8)}: ` +
|
|
925
|
+
`${result.RecordsCreated} created, ${result.RecordsUpdated} updated, ` +
|
|
926
|
+
`${result.RecordsErrored} errored`);
|
|
902
927
|
}
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
928
|
+
catch (err) {
|
|
929
|
+
const errMsg = err instanceof Error ? err.message : String(err);
|
|
930
|
+
console.error(`[IntegrationEngine] Failed to resume run ${runID.substring(0, 8)}: ${errMsg}`);
|
|
931
|
+
if (err instanceof RunOwnershipLostError) {
|
|
932
|
+
// We were fenced out mid-resume — the NEW owner now owns the run row.
|
|
933
|
+
// Writing 'Failed' here would clobber the live holder's state.
|
|
934
|
+
console.warn(`[IntegrationEngine] Resume of run ${runID.substring(0, 8)} lost ownership — leaving the run row to its new owner`);
|
|
935
|
+
}
|
|
936
|
+
else {
|
|
937
|
+
// Mark as failed so it doesn't get picked up again
|
|
938
|
+
run.EndedAt = new Date();
|
|
939
|
+
run.Status = 'Failed';
|
|
940
|
+
run.ErrorLog = JSON.stringify([{ ErrorMessage: `Resume failed: ${errMsg}` }]);
|
|
941
|
+
ownership.SyncEntityOwnershipFields(run);
|
|
942
|
+
await run.Save();
|
|
943
|
+
try {
|
|
944
|
+
await ownership.Release('Failed');
|
|
945
|
+
}
|
|
946
|
+
catch { /* lease will simply expire */ }
|
|
947
|
+
}
|
|
948
|
+
}
|
|
949
|
+
finally {
|
|
950
|
+
ownership.StopHeartbeat();
|
|
951
|
+
// Release the C1 lock + unblock any RunSync that began awaiting this resume (RunSync returns
|
|
952
|
+
// `existing`). Resolve with the real result when we have one, else a benign empty result so no
|
|
953
|
+
// waiter hangs. Promise resolve is idempotent and the early-exit `return`s also land here.
|
|
954
|
+
IntegrationEngine.activeSyncs.delete(lockKey);
|
|
955
|
+
IntegrationEngine.liveProgress.delete(lockKey);
|
|
956
|
+
resolveResumeLock(resumeResult ?? {
|
|
957
|
+
Success: false, ErrorMessage: 'Resume produced no result', RecordsProcessed: 0,
|
|
958
|
+
RecordsCreated: 0, RecordsUpdated: 0, RecordsDeleted: 0, RecordsErrored: 0,
|
|
959
|
+
RecordsSkipped: 0, Errors: [], EntityMapResults: [], Duration: 0,
|
|
960
|
+
});
|
|
961
|
+
}
|
|
962
|
+
});
|
|
916
963
|
}
|
|
917
964
|
/**
|
|
918
965
|
* Executes a full sync run for a company integration.
|
|
@@ -927,7 +974,15 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
927
974
|
* @returns Aggregate sync result with record counts and errors
|
|
928
975
|
*/
|
|
929
976
|
async RunSync(companyIntegrationID, contextUser, triggerType = 'Manual', onProgress, onNotification, options, provider) {
|
|
930
|
-
|
|
977
|
+
// The connection's catalog is in scope for the WHOLE run: the DAG, the excluded-field
|
|
978
|
+
// resolution and every connector-side GetCachedObject resolve to this connection's own
|
|
979
|
+
// rows once it has them, and to the shared declared rows until it does.
|
|
980
|
+
//
|
|
981
|
+
// A WARMED scope: the run warms each map's objects before the map reads them (see
|
|
982
|
+
// ExecuteEntityMaps), so inside it a cold read is a missed warm site and throws instead of
|
|
983
|
+
// quietly answering with no fields. Entered synchronously, as before — the catalog itself
|
|
984
|
+
// is loaded at the head of ExecuteEntityMaps, inside the run's own error handling.
|
|
985
|
+
return RunInWarmedCatalogScope(companyIntegrationID, () => this.runWithOwnedContext(companyIntegrationID, contextUser, triggerType, onProgress, onNotification, options, provider));
|
|
931
986
|
}
|
|
932
987
|
/**
|
|
933
988
|
* Worker-mode enqueue (PR 1 item 8): create the run row with `Status='Queued'` and
|
|
@@ -1053,6 +1108,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
1053
1108
|
RecordsCreated: 0,
|
|
1054
1109
|
RecordsUpdated: 0,
|
|
1055
1110
|
RecordsErrored: 0,
|
|
1111
|
+
RecordsSkipped: 0,
|
|
1056
1112
|
TriggerType: triggerType,
|
|
1057
1113
|
};
|
|
1058
1114
|
const runCtx = {
|
|
@@ -1077,11 +1133,13 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
1077
1133
|
// ProviderToUse / write chain / ownership from THIS context, isolated per run.
|
|
1078
1134
|
const syncPromise = IntegrationEngine.runContext.run(runCtx, () => this.executeSyncInternal(companyIntegrationID, contextUser, triggerType, wrappedProgress, onNotification, options, abortController.signal, existingRun));
|
|
1079
1135
|
IntegrationEngine.activeSyncs.set(lockKey, syncPromise);
|
|
1136
|
+
IntegrationEngine.liveProgress.set(lockKey, progressSnapshot);
|
|
1080
1137
|
try {
|
|
1081
1138
|
return await syncPromise;
|
|
1082
1139
|
}
|
|
1083
1140
|
finally {
|
|
1084
1141
|
IntegrationEngine.activeSyncs.delete(lockKey);
|
|
1142
|
+
IntegrationEngine.liveProgress.delete(lockKey);
|
|
1085
1143
|
runCtx.ownership?.StopHeartbeat();
|
|
1086
1144
|
}
|
|
1087
1145
|
}
|
|
@@ -1261,6 +1319,9 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
1261
1319
|
}
|
|
1262
1320
|
}
|
|
1263
1321
|
const summary = this.buildSyncResultBody(config.companyIntegration.Integration, result);
|
|
1322
|
+
// Repeated warnings are rolled up by code (SyncLogger.warning) and the summary is emitted
|
|
1323
|
+
// HERE — before the terminal event, so it lands inside this run's own artifact stream.
|
|
1324
|
+
logger.FlushWarningRollups();
|
|
1264
1325
|
logger.emit('sync.run.complete', {
|
|
1265
1326
|
success: result.Success && result.RecordsErrored === 0,
|
|
1266
1327
|
durationMs: result.Duration,
|
|
@@ -1274,12 +1335,22 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
1274
1335
|
});
|
|
1275
1336
|
// A cancelled run returns normally (no throw) with abortSignal.aborted set — finalize it as
|
|
1276
1337
|
// 'cancelled' (exitReason='aborted'), NOT 'completed', so a stopped run is distinguishable.
|
|
1277
|
-
|
|
1338
|
+
//
|
|
1339
|
+
// MJ-RUN-4: a run that abandoned objects must not read as an unqualified success. It is
|
|
1340
|
+
// still 'completed' — the watermark is held and the unfetched window retries next run,
|
|
1341
|
+
// so this is not a failure — but the message has to name what did not finish, or a
|
|
1342
|
+
// nightly sync that dies on its first page every night looks like an unbroken run of
|
|
1343
|
+
// clean Successes with TotalRecords=0.
|
|
1344
|
+
const completionMessage = BuildRunCompletionMessage(result.IncompleteObjects ?? [], result.ErrorMessage, abortSignal?.aborted === true);
|
|
1345
|
+
await this.finalizeSyncProgress(progress, abortSignal?.aborted ? 'cancelled' : 'completed', completionMessage);
|
|
1278
1346
|
console.log(`[IntegrationEngine] Sync complete:\n${summary}`);
|
|
1279
1347
|
return result;
|
|
1280
1348
|
}
|
|
1281
1349
|
catch (err) {
|
|
1282
1350
|
const errMsg = err instanceof Error ? err.message : String(err);
|
|
1351
|
+
// A failing run is exactly where a warning cascade is most likely, so flush the rollups
|
|
1352
|
+
// on this path too — before the terminal fail event.
|
|
1353
|
+
logger.FlushWarningRollups();
|
|
1283
1354
|
logger.emit('sync.run.fail', { error: errMsg, durationMs: Date.now() - startTime });
|
|
1284
1355
|
// Ownership lost (fence moved / lease reclaimed): the run row now belongs to
|
|
1285
1356
|
// ANOTHER process — writing a terminal status to it here would clobber the new
|
|
@@ -1377,6 +1448,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
1377
1448
|
EntityName: 'MJ: Company Integrations',
|
|
1378
1449
|
ExtraFilter: `ID='${companyIntegrationID}'`,
|
|
1379
1450
|
MaxRows: 1,
|
|
1451
|
+
SkipTotalRowCount: true,
|
|
1380
1452
|
ResultType: 'entity_object',
|
|
1381
1453
|
BypassCache: true,
|
|
1382
1454
|
},
|
|
@@ -1501,6 +1573,13 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
1501
1573
|
if (runCtxForFlags) {
|
|
1502
1574
|
runCtxForFlags.suppressWriteSideEffects = this.readWriteSideEffects(config.companyIntegration) === 'suppressed';
|
|
1503
1575
|
}
|
|
1576
|
+
// This connection's own catalog rows are not resident (MJ-RUN-43): the scope holds what was
|
|
1577
|
+
// read when it was last loaded, memoised for the process. Re-read them here, at the async
|
|
1578
|
+
// head of the run — both the direct and the adopted path come through — for the same reason
|
|
1579
|
+
// the shared catalog is re-read at the head of a run: a discovery since (on this host or
|
|
1580
|
+
// another) must be what this run syncs, not whatever this process first read. Read-then-swap
|
|
1581
|
+
// (MJ-RUN-46), so anything else reading this connection meanwhile never sees it catalog-less.
|
|
1582
|
+
await RefreshCatalogScope(config.companyIntegration.ID, contextUser);
|
|
1504
1583
|
const aggregate = {
|
|
1505
1584
|
Success: true,
|
|
1506
1585
|
RecordsProcessed: 0,
|
|
@@ -1514,6 +1593,8 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
1514
1593
|
};
|
|
1515
1594
|
const totalMaps = config.entityMaps.length;
|
|
1516
1595
|
let globalIndex = 0;
|
|
1596
|
+
/** Pressure codes already reported on this run, so each is said once and not per map. */
|
|
1597
|
+
const pressureWarned = new Set();
|
|
1517
1598
|
// Per-map processing. Extracted so it can run sequentially OR concurrently within a
|
|
1518
1599
|
// dependency layer. Aggregate mutations run when each promise resolves — atomic under
|
|
1519
1600
|
// single-threaded async, so concurrent maps in a layer are safe.
|
|
@@ -1531,9 +1612,18 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
1531
1612
|
direction,
|
|
1532
1613
|
priority: entityMap.Priority ?? null,
|
|
1533
1614
|
});
|
|
1615
|
+
let warmed = [];
|
|
1534
1616
|
try {
|
|
1617
|
+
// Warm the field rows this map reads BEFORE it reads them (MJ-RUN-43), pinned until
|
|
1618
|
+
// it finishes. The readers underneath — connectors' GetCachedFields — are synchronous
|
|
1619
|
+
// and cannot fetch, so the load has to happen here. Per MAP rather than per layer, so
|
|
1620
|
+
// what is pinned is bounded by the maps in flight, not by the width of a layer — and
|
|
1621
|
+
// the pipelined path below gets the same warm site for free.
|
|
1622
|
+
warmed = await this.warmEntityMapCatalog(config, entityMap, depGraph, contextUser);
|
|
1535
1623
|
const mapResult = await this.processSingleEntityMap(config, entityMap, run, contextUser, i, totalMaps, onProgress, abortSignal, logger);
|
|
1624
|
+
const governorShedding = config.memoryControl?.IsShedding === true;
|
|
1536
1625
|
this.mergeResult(aggregate, mapResult);
|
|
1626
|
+
const memoryPressure = await this.warnOnResourcePressure(logger, pressureWarned, governorShedding);
|
|
1537
1627
|
aggregate.EntityMapResults.push(this.buildEntityMapResult(entityMap, mapResult, Date.now() - mapStartTime));
|
|
1538
1628
|
logger?.emit('sync.entity-map.complete', {
|
|
1539
1629
|
externalObjectName: entityMap.ExternalObjectName,
|
|
@@ -1549,7 +1639,17 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
1549
1639
|
recordsErrored: mapResult.RecordsErrored,
|
|
1550
1640
|
});
|
|
1551
1641
|
this.checkSecondLayerEmpty(entityMap, mapResult, depGraph, processedByIoId, ioNameById, ioCategoryById, logger);
|
|
1552
|
-
|
|
1642
|
+
// Host memory pressure enters the SAME AIMD signal a source throttle uses, so it
|
|
1643
|
+
// halves the in-flight cap and ramps back only once maps complete cleanly. That is
|
|
1644
|
+
// the whole adaptive answer to OOM: no per-connector tuning, no advance knowledge of
|
|
1645
|
+
// which connector misbehaves - a connector that returns 10x the requested batch
|
|
1646
|
+
// costs 10x the memory, the reading notices, and the cap follows. Floor is 1, so a
|
|
1647
|
+
// sync always makes progress rather than deadlocking on a full box.
|
|
1648
|
+
// Except while the run's governor is shedding: it has already chosen a lever by
|
|
1649
|
+
// cost and escalates itself if the host stays above the line, so halving here too
|
|
1650
|
+
// would override a hold (no throughput cost) with a halve (half of it). This check
|
|
1651
|
+
// remains the answer when the governor has nothing to act on.
|
|
1652
|
+
return { ok: mapResult.Success, throttled: mapResult.Throttled === true || (memoryPressure && !governorShedding) };
|
|
1553
1653
|
}
|
|
1554
1654
|
catch (err) {
|
|
1555
1655
|
// Ownership loss is NOT a per-map failure to record-and-continue: continuing to the
|
|
@@ -1592,6 +1692,9 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
1592
1692
|
});
|
|
1593
1693
|
return { ok: false, throttled: ClassifyError(err).Code === 'RATE_LIMIT_EXCEEDED' };
|
|
1594
1694
|
}
|
|
1695
|
+
finally {
|
|
1696
|
+
UnpinCatalogObjects(warmed);
|
|
1697
|
+
}
|
|
1595
1698
|
};
|
|
1596
1699
|
// Group maps into dependency layers (parents before children) via the IntegrationObject FK
|
|
1597
1700
|
// graph, then process layers in order. Layers run sequentially — a child never syncs before
|
|
@@ -1608,6 +1711,18 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
1608
1711
|
// Configuration override (IntegrationSetSyncConfig) wins over the connector's MaxConcurrencyHint constant.
|
|
1609
1712
|
const maxConcurrency = Math.max(concurrency, this.getConfigOverrides(config).maxConcurrency ?? config.connector.MaxConcurrencyHint ?? concurrency);
|
|
1610
1713
|
const concController = new AdaptiveConcurrencyController({ start: concurrency, min: 1, max: maxConcurrency });
|
|
1714
|
+
// The governor, scoped to THIS run. Created here because this is the only frame that can
|
|
1715
|
+
// see the concurrency controller; handed down on the config because the decision has to be
|
|
1716
|
+
// taken where a batch lands, several frames below.
|
|
1717
|
+
config.memoryControl = new RunMemoryControl({
|
|
1718
|
+
HoldAdmissions: () => concController.Hold(),
|
|
1719
|
+
ReleaseAdmissions: () => concController.Release(),
|
|
1720
|
+
ReduceConcurrency: () => concController.OnThrottleOrError(),
|
|
1721
|
+
CurrentInFlight: () => concController.Cap,
|
|
1722
|
+
Report: plan => logger?.warning('sync', plan.Exhausted ? 'HOST_MEMORY_EXHAUSTED' : 'HOST_MEMORY_PRESSURE', plan.Exhausted
|
|
1723
|
+
? `This workspace ran short of memory and there was nothing left to slow down — ${plan.Reason}. It needs a larger size for this amount of data.`
|
|
1724
|
+
: `This workspace is short of memory, so the sync is ${plan.Levers.map(l => LEVER_COPY[l.Code] ?? 'easing off').join(' and ')} to keep going — ${plan.Reason}.`, { reason: plan.Reason, levers: plan.Levers.map(l => l.Code), exhausted: plan.Exhausted })
|
|
1725
|
+
}, this.MaxBatchSize);
|
|
1611
1726
|
// Second-layer silent-empty detection state (see checkSecondLayerEmpty): a per-IO running
|
|
1612
1727
|
// record count + the FK dependency graph, so an association/dependent object that fetches
|
|
1613
1728
|
// ZERO records while it HAS parents is surfaced as a structured SyncWarning. Layers run
|
|
@@ -1745,9 +1860,12 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
1745
1860
|
const parentsByIoId = new Map();
|
|
1746
1861
|
for (const ioId of selectedIoIds) {
|
|
1747
1862
|
const set = new Set();
|
|
1748
|
-
// (1) hard FK pointer on a field (RelatedIntegrationObjectID).
|
|
1749
|
-
|
|
1750
|
-
|
|
1863
|
+
// (1) hard FK pointer on a field (RelatedIntegrationObjectID). Asked for as the object's
|
|
1864
|
+
// related ids rather than read off its field rows: on a per-connection catalog those
|
|
1865
|
+
// rows are not resident, and this graph is built before any of them are warmed — it is
|
|
1866
|
+
// what decides the order they are warmed in. The related ids come from the edge set.
|
|
1867
|
+
for (const related of this.GetRelatedIntegrationObjectIDs(ioId)) {
|
|
1868
|
+
const parent = related.toUpperCase();
|
|
1751
1869
|
if (parent && parent !== ioId && selectedIoIds.has(parent))
|
|
1752
1870
|
set.add(parent);
|
|
1753
1871
|
}
|
|
@@ -1784,6 +1902,46 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
1784
1902
|
}
|
|
1785
1903
|
return { mapToIoId, parentsByIoId };
|
|
1786
1904
|
}
|
|
1905
|
+
/**
|
|
1906
|
+
* Warm the field rows one entity map is about to read, pinned until the caller releases them
|
|
1907
|
+
* (MJ-RUN-43). That is the map's own object and its parents in the dependency graph: a child's
|
|
1908
|
+
* nested fetch reads its parent's key fields, and the parent's own map may have finished long
|
|
1909
|
+
* enough ago for its rows to have been evicted.
|
|
1910
|
+
*
|
|
1911
|
+
* Only this connection's OWN objects are warmed — a shared object's fields are resident. A map
|
|
1912
|
+
* whose object is not in the connection's catalog warms nothing; the map's own handling of a
|
|
1913
|
+
* missing object applies further in. Returns the ids it pinned.
|
|
1914
|
+
*/
|
|
1915
|
+
async warmEntityMapCatalog(config, entityMap, depGraph, contextUser) {
|
|
1916
|
+
const companyIntegrationID = config.companyIntegration?.ID;
|
|
1917
|
+
const objectName = entityMap.ExternalObjectName;
|
|
1918
|
+
if (!companyIntegrationID || !objectName)
|
|
1919
|
+
return [];
|
|
1920
|
+
const own = this.Base.GetCompanyIntegrationObject(companyIntegrationID, objectName);
|
|
1921
|
+
if (!own)
|
|
1922
|
+
return [];
|
|
1923
|
+
const ids = [own.ID];
|
|
1924
|
+
const seen = new Set([NormalizeUUID(own.ID)]);
|
|
1925
|
+
for (const parentID of depGraph?.parentsByIoId.get(own.ID.toUpperCase()) ?? []) {
|
|
1926
|
+
const parent = this.Base.GetCompanyIntegrationObjectByID(parentID);
|
|
1927
|
+
if (parent && !seen.has(NormalizeUUID(parent.ID))) {
|
|
1928
|
+
seen.add(NormalizeUUID(parent.ID));
|
|
1929
|
+
ids.push(parent.ID);
|
|
1930
|
+
}
|
|
1931
|
+
}
|
|
1932
|
+
const pinned = [];
|
|
1933
|
+
try {
|
|
1934
|
+
for (const id of ids) {
|
|
1935
|
+
await WarmCatalogObject(id, contextUser);
|
|
1936
|
+
pinned.push(id);
|
|
1937
|
+
}
|
|
1938
|
+
}
|
|
1939
|
+
catch (err) {
|
|
1940
|
+
UnpinCatalogObjects(pinned);
|
|
1941
|
+
throw err;
|
|
1942
|
+
}
|
|
1943
|
+
return pinned;
|
|
1944
|
+
}
|
|
1787
1945
|
/**
|
|
1788
1946
|
* Surfaces the second-layer silent-empty case as a structured warning. An object that HAS FK
|
|
1789
1947
|
* parents (an association/dependent — a "second-layer" object) but fetched ZERO records is the
|
|
@@ -2019,7 +2177,19 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
2019
2177
|
let throttleReported = false;
|
|
2020
2178
|
try {
|
|
2021
2179
|
await this.rateLimit(config);
|
|
2022
|
-
return await this.withFetchGate(config, () => WithRetry(() => WithTimeout(config.connector.FetchChanges(ctx), fetchTimeoutMs, `FetchChanges(${objectName})`), undefined,
|
|
2180
|
+
return await this.withFetchGate(config, () => WithRetry(() => WithTimeout(config.connector.FetchChanges(ctx), fetchTimeoutMs, `FetchChanges(${objectName})`), undefined,
|
|
2181
|
+
// A timeout is NOT retryable here, deliberately: WithTimeout abandons the attempt
|
|
2182
|
+
// without CANCELLING it, so a retry stacks a second full page of vendor requests on
|
|
2183
|
+
// a source already too slow to finish the first. A transport error IS retryable — a
|
|
2184
|
+
// reset socket is worth another go.
|
|
2185
|
+
//
|
|
2186
|
+
// The fleet carried a patch (MJ-MEM-2) that inverted this, because the same rule
|
|
2187
|
+
// abandoned sixteen NetSuite objects for a whole run. That inversion must not be
|
|
2188
|
+
// ported here — it contradicts this decision and the two tests that pin it. What
|
|
2189
|
+
// satisfies both is in ProcessPullSync's fetch-error handler: a KEYSET scan whose page
|
|
2190
|
+
// times out is SUSPENDED and resumes from its persisted key next run, where the page
|
|
2191
|
+
// is retried without stacking on the abandoned attempt.
|
|
2192
|
+
(err) => !(err instanceof OperationTimeoutError) && IsRetryableError(ClassifyError(err).Code), (attempt, err, delayMs) => {
|
|
2023
2193
|
// Report a throttle NOW, not after the retries are spent. ReportThrottle
|
|
2024
2194
|
// freezes the shared bucket for this CompanyIntegration, so every other
|
|
2025
2195
|
// object fetching concurrently backs off too. Once per episode; later
|
|
@@ -2202,6 +2372,47 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
2202
2372
|
// same run reads the value that is actually stored.
|
|
2203
2373
|
entityMap.Configuration = configurationJSON;
|
|
2204
2374
|
}
|
|
2375
|
+
/**
|
|
2376
|
+
* Reports a keyset scan suspended by a page timeout: a warning that says where the next run
|
|
2377
|
+
* resumes, a Warning-severity entry in the run's queryable error log, and the object on the
|
|
2378
|
+
* run's incomplete list (MJ-RUN-4). Warning severity keeps Status='Success' — nothing failed,
|
|
2379
|
+
* and the position is held exactly — but the run must not read as a clean, complete one.
|
|
2380
|
+
*/
|
|
2381
|
+
reportKeysetSuspension(entityMap, batchIndex, recordsApplied, resumeAfterKey, errMsg, result, logger) {
|
|
2382
|
+
const objectName = entityMap.ExternalObjectName ?? entityMap.ID;
|
|
2383
|
+
const resumesFrom = resumeAfterKey
|
|
2384
|
+
? `resumes from ordering key '${resumeAfterKey}'`
|
|
2385
|
+
: 'restarts from the beginning, or from the position an earlier suspended scan saved if one ' +
|
|
2386
|
+
'is on record (a full sync does not clear it; the rows before it were applied by that scan)';
|
|
2387
|
+
const message = `Fetch for '${objectName}' timed out at batch ${batchIndex} and is suspended for the rest of this ` +
|
|
2388
|
+
`run: the page is not re-requested while the abandoned request may still be running. ` +
|
|
2389
|
+
`${recordsApplied} record(s) were applied before it. The scan ${resumesFrom} next run, where ` +
|
|
2390
|
+
`this page is retried. Error: ${errMsg}`;
|
|
2391
|
+
logger?.warning(objectName, 'FETCH_SUSPENDED_TIMEOUT', message, {
|
|
2392
|
+
batchIndex,
|
|
2393
|
+
recordsAppliedBeforeTimeout: recordsApplied,
|
|
2394
|
+
resumeAfterKey: resumeAfterKey ?? null,
|
|
2395
|
+
error: errMsg,
|
|
2396
|
+
});
|
|
2397
|
+
result.Errors.push({
|
|
2398
|
+
ExternalID: '',
|
|
2399
|
+
ChangeType: 'Skip',
|
|
2400
|
+
ErrorMessage: message,
|
|
2401
|
+
ErrorCode: 'CONNECTOR_ERROR',
|
|
2402
|
+
Severity: 'Warning',
|
|
2403
|
+
});
|
|
2404
|
+
this.markIncomplete(result, objectName);
|
|
2405
|
+
}
|
|
2406
|
+
/**
|
|
2407
|
+
* Puts an object on the result's incomplete list once (MJ-RUN-4). One object can be held
|
|
2408
|
+
* incomplete for more than one reason in the same run — a suspended page and overlapping pages,
|
|
2409
|
+
* say — and the run summary names objects, not reasons.
|
|
2410
|
+
*/
|
|
2411
|
+
markIncomplete(result, objectName) {
|
|
2412
|
+
const list = (result.IncompleteObjects ??= []);
|
|
2413
|
+
if (!list.includes(objectName))
|
|
2414
|
+
list.push(objectName);
|
|
2415
|
+
}
|
|
2205
2416
|
/**
|
|
2206
2417
|
* Pull sync: fetch from external → map → match → validate → apply to MJ.
|
|
2207
2418
|
*/
|
|
@@ -2327,11 +2538,40 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
2327
2538
|
let previousBatchFingerprint;
|
|
2328
2539
|
let fetchCompletedCleanly = true; // flipped to false if fetch aborted or errored mid-way
|
|
2329
2540
|
let hadFetchGap = false; // ≥1 page was skipped after a persistent fetch error (offset/page paging)
|
|
2541
|
+
// A HOLE behind the max watermark seen, from a cause other than a skipped page.
|
|
2542
|
+
//
|
|
2543
|
+
// The early-stop branch below persists the max watermark on the reasoning that whole
|
|
2544
|
+
// batches completed, so nothing unwritten lies past it. That reasoning fails when records
|
|
2545
|
+
// were never HANDED to us at all: a shortfall against the source's own total, or pages that
|
|
2546
|
+
// overlapped and therefore skipped. Those missing records can carry timestamps BELOW the max
|
|
2547
|
+
// we saw, so advancing past them skips them permanently — the same reason that branch already
|
|
2548
|
+
// refuses to run when `hadFetchGap`, which its own comment calls 'a HOLE behind this
|
|
2549
|
+
// watermark'. Clearing `fetchCompletedCleanly` alone is NOT enough: it only moves us out of
|
|
2550
|
+
// the clean branch and into this one.
|
|
2551
|
+
let windowHasHole = false;
|
|
2330
2552
|
let watermarkFloorSaved = null; // §8a durability floor last persisted mid-run (null = none)
|
|
2331
2553
|
let fetchGapCount = 0; // CONSECUTIVE skipped pages (reset on any clean fetch)
|
|
2554
|
+
// MJ-RUN-35: the total the SOURCE stated for this object, when it states one.
|
|
2555
|
+
let sourceTotalRecords;
|
|
2556
|
+
// MJ-RUN-36: identities a LATER batch repeated from an EARLIER one. Only meaningful for
|
|
2557
|
+
// position-based paging, where it is evidence the page boundaries moved under us.
|
|
2558
|
+
let crossBatchRepeatCount = 0;
|
|
2559
|
+
const crossBatchRepeatSamples = [];
|
|
2332
2560
|
const MAX_FETCH_GAPS = 25; // give up + hold the watermark if this many pages fail in a row (API down)
|
|
2333
2561
|
let consecutiveEmptyBatches = 0; // P3-D: detect a connector that pages empty-but-HasMore forever
|
|
2334
2562
|
let oversizeBatchWarned = false; // pagination rule: warn ONCE per object that the connector ignored BatchSize
|
|
2563
|
+
// Whether this connector respects the page size it is given. Assumed true until a batch
|
|
2564
|
+
// proves otherwise, because that verdict decides whether asking for smaller pages is the
|
|
2565
|
+
// cheapest lever available under memory pressure or a wasted round trip that frees nothing.
|
|
2566
|
+
let honoursBatchSize = true;
|
|
2567
|
+
/**
|
|
2568
|
+
* The page size THIS run asks for, which the governor may shrink between batches.
|
|
2569
|
+
*
|
|
2570
|
+
* Read fresh per fetch, and captured into a local for the duration of that fetch: the
|
|
2571
|
+
* error-skip path advances the offset by what was REQUESTED, so reading it again after the
|
|
2572
|
+
* governor moved it would skip or re-read a page.
|
|
2573
|
+
*/
|
|
2574
|
+
const askedBatchSize = () => config.memoryControl?.BatchSize ?? this.MaxBatchSize;
|
|
2335
2575
|
const MAX_BATCHES_PER_MAP = 5000;
|
|
2336
2576
|
const EMPTY_BATCH_WARN_THRESHOLD = 5; // warn once after this many empty-but-HasMore batches in a row
|
|
2337
2577
|
const fetchedExternalIDs = new Set(); // Track all IDs seen during this pull for orphan detection
|
|
@@ -2371,11 +2611,24 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
2371
2611
|
fetchCompletedCleanly = false;
|
|
2372
2612
|
break;
|
|
2373
2613
|
}
|
|
2614
|
+
// Captured ONCE per iteration. The governor may shrink the run's page size while this
|
|
2615
|
+
// fetch is in flight, and the error-skip path below advances the offset by what was
|
|
2616
|
+
// asked for — re-reading it there would skip or re-read a page.
|
|
2617
|
+
const requestedThisBatch = askedBatchSize();
|
|
2374
2618
|
const ctx = {
|
|
2375
2619
|
CompanyIntegration: config.companyIntegration,
|
|
2376
2620
|
ObjectName: entityMap.ExternalObjectName,
|
|
2377
|
-
|
|
2378
|
-
|
|
2621
|
+
// The fetch filter is the RUN's start boundary, never the running max.
|
|
2622
|
+
//
|
|
2623
|
+
// `currentWatermark` advances every page for connectors that emit a per-page running
|
|
2624
|
+
// max (netsuite@1.4.1+ does, for resume-friendliness); feeding it back into the next
|
|
2625
|
+
// page's query ratchets the incremental predicate forward MID-SCAN, so every row whose
|
|
2626
|
+
// modstamp trails the max seen so far is silently excluded even though the walk never
|
|
2627
|
+
// visited it. Observed live (ACR dev, 2026-09-07): a Vendor Bill full scan collapsed
|
|
2628
|
+
// to 707 of 23,558 rows — an id-ascending-AND-modstamp-ascending subsequence — with
|
|
2629
|
+
// the run still reporting success. `currentWatermark` remains persistence bookkeeping.
|
|
2630
|
+
WatermarkValue: initialWatermark,
|
|
2631
|
+
BatchSize: requestedThisBatch,
|
|
2379
2632
|
ContextUser: contextUser,
|
|
2380
2633
|
CurrentPage: currentPage,
|
|
2381
2634
|
CurrentOffset: currentOffset,
|
|
@@ -2396,7 +2649,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
2396
2649
|
page: currentPage ?? null,
|
|
2397
2650
|
offset: currentOffset ?? null,
|
|
2398
2651
|
cursor: currentCursor ?? null,
|
|
2399
|
-
batchSize:
|
|
2652
|
+
batchSize: requestedThisBatch,
|
|
2400
2653
|
});
|
|
2401
2654
|
let batch;
|
|
2402
2655
|
const fetchStart = Date.now();
|
|
@@ -2415,6 +2668,12 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
2415
2668
|
batch = await this.governedFetch(config, ctx, entityMap.ExternalObjectName, fetchTimeoutMs, batchCount, logger);
|
|
2416
2669
|
}
|
|
2417
2670
|
this.reportRateOutcome(config); // clean fetch → ramp the adaptive rate back up
|
|
2671
|
+
// MJ-RUN-35: remember what the source said it holds. Last statement wins — the
|
|
2672
|
+
// freshest page is the most current answer — and a page that says nothing must
|
|
2673
|
+
// never erase a total an earlier page gave.
|
|
2674
|
+
if (typeof batch.SourceTotalRecords === 'number' && batch.SourceTotalRecords >= 0) {
|
|
2675
|
+
sourceTotalRecords = batch.SourceTotalRecords;
|
|
2676
|
+
}
|
|
2418
2677
|
fetchGapCount = 0; // clean fetch → reset the consecutive fetch-gap counter
|
|
2419
2678
|
// §10: connector type-driven post-processing hook (default no-op) — enforce/normalize
|
|
2420
2679
|
// record values to their resolved formats before mapping + write.
|
|
@@ -2492,6 +2751,18 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
2492
2751
|
batchIndex: batchCount,
|
|
2493
2752
|
error: errMsg,
|
|
2494
2753
|
});
|
|
2754
|
+
// A KEYSET scan whose page hit our own timeout is SUSPENDED, not skipped. The timed-out
|
|
2755
|
+
// attempt is still running (WithTimeout cannot cancel it), so any further request now
|
|
2756
|
+
// stacks on a source already too slow to finish the first — and the page-skip below
|
|
2757
|
+
// would be exactly that: advancing an offset skips nothing in a seek, so the "next"
|
|
2758
|
+
// page re-requests the SAME key. A keyset scan knows its place (the last key whose
|
|
2759
|
+
// batch was applied), so it stops here, the post-loop save persists that key, and the
|
|
2760
|
+
// next run seeks from it: the timed-out page is retried THERE, never stacked.
|
|
2761
|
+
if (fetchErr instanceof OperationTimeoutError && isKeysetConnector) {
|
|
2762
|
+
fetchCompletedCleanly = false;
|
|
2763
|
+
this.reportKeysetSuspension(entityMap, batchCount, recordsInMap, currentAfterKey, errMsg, result, logger);
|
|
2764
|
+
break;
|
|
2765
|
+
}
|
|
2495
2766
|
// Resilience: a persistent fetch failure on ONE page shouldn't abandon the whole object.
|
|
2496
2767
|
// POSITION-based paging (offset/page) can step past the failed page and keep going; we mark
|
|
2497
2768
|
// the fetch incomplete (so the watermark is HELD below + the orphan/partition sweep is skipped)
|
|
@@ -2515,7 +2786,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
2515
2786
|
`'${entityMap.ExternalObjectName}' (batch ${batchCount}); skipped this page and continued — the ` +
|
|
2516
2787
|
`watermark is held so the window is re-fetched next run. Error: ${errMsg}`, { offset: currentOffset ?? null, page: currentPage ?? null, batchIndex: batchCount, error: errMsg });
|
|
2517
2788
|
if (currentOffset != null)
|
|
2518
|
-
currentOffset +=
|
|
2789
|
+
currentOffset += requestedThisBatch;
|
|
2519
2790
|
else if (currentPage != null)
|
|
2520
2791
|
currentPage += 1;
|
|
2521
2792
|
continue;
|
|
@@ -2547,6 +2818,11 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
2547
2818
|
ErrorCode: 'CONNECTOR_ERROR',
|
|
2548
2819
|
Severity: 'Warning',
|
|
2549
2820
|
});
|
|
2821
|
+
// MJ-RUN-4: an abandoned object must also reach the RUN-level result, not only the
|
|
2822
|
+
// per-object warning above. A caller reading the run summary otherwise sees a clean
|
|
2823
|
+
// completion and has to go mining the event stream to discover that sixteen objects
|
|
2824
|
+
// ended INCOMPLETE.
|
|
2825
|
+
this.markIncomplete(result, entityMap.ExternalObjectName ?? entityMap.ID);
|
|
2550
2826
|
break;
|
|
2551
2827
|
}
|
|
2552
2828
|
logger?.emit('sync.fetch.batch.complete', {
|
|
@@ -2574,9 +2850,28 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
2574
2850
|
// run-event stream, not buried in a console.log nobody reads. Warned ONCE per object (the
|
|
2575
2851
|
// CONSECUTIVE_EMPTY_BATCHES pattern) so a paginating-but-over-size connector doesn't flood
|
|
2576
2852
|
// the artifact with one warning per page.
|
|
2577
|
-
if (batch.Records.length >
|
|
2578
|
-
|
|
2579
|
-
|
|
2853
|
+
if (batch.Records.length > requestedThisBatch) {
|
|
2854
|
+
// The verdict the governor needs: a connector that overshoots its page size cannot
|
|
2855
|
+
// be asked to use less memory by asking for a smaller page.
|
|
2856
|
+
honoursBatchSize = false;
|
|
2857
|
+
if (!oversizeBatchWarned) {
|
|
2858
|
+
oversizeBatchWarned = true;
|
|
2859
|
+
this.warnOversizedBatch(entityMap, batch, batchCount, requestedThisBatch, logger);
|
|
2860
|
+
}
|
|
2861
|
+
}
|
|
2862
|
+
// Decide what to give up, HERE — at the batch, not between tables. A table that fetches
|
|
2863
|
+
// twelve consecutive 2,000-record pages allocates all of it without ever reaching a
|
|
2864
|
+
// between-tables checkpoint, which is how the sandbox reached 3,478 MB of 3,830 MB on
|
|
2865
|
+
// 2026-09-14 with the old check never getting a turn. Never awaited for its answer's
|
|
2866
|
+
// sake and never able to throw: a governor that can fail a run trades an occasional
|
|
2867
|
+
// memory problem for a constant availability one.
|
|
2868
|
+
if (config.memoryControl && batch.Records.length > 0) {
|
|
2869
|
+
await config.memoryControl.NoteBatch({
|
|
2870
|
+
EntityMapID: entityMap.ID,
|
|
2871
|
+
ObservedRecords: batch.Records.length,
|
|
2872
|
+
SampleRecord: batch.Records[0],
|
|
2873
|
+
HonoursBatchSize: honoursBatchSize
|
|
2874
|
+
});
|
|
2580
2875
|
}
|
|
2581
2876
|
if (batch.Records.length > 0) {
|
|
2582
2877
|
const fingerprint = batch.Records.map(r => r.ExternalID).join(',');
|
|
@@ -2589,6 +2884,47 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
2589
2884
|
previousBatchFingerprint = fingerprint;
|
|
2590
2885
|
}
|
|
2591
2886
|
if (!orphanTrackingOverflowed) {
|
|
2887
|
+
// MJ-RUN-36: an identity seen in an EARLIER batch means the pages overlapped.
|
|
2888
|
+
//
|
|
2889
|
+
// `CollapseDuplicateIdentities` below is within-batch only ("already present in the
|
|
2890
|
+
// same batch"), so it cannot see this, and before this check nothing could: a page
|
|
2891
|
+
// that re-served a row another page already gave was written twice, quietly, as an
|
|
2892
|
+
// insert and then an update.
|
|
2893
|
+
//
|
|
2894
|
+
// That matters far beyond the wasted write. Position-based pagination has no
|
|
2895
|
+
// guaranteed order unless the source promises one, so a boundary that moves BACKWARD
|
|
2896
|
+
// to re-serve a row has also moved FORWARD past another — the repeat is the visible
|
|
2897
|
+
// half of an omission. The row count then understates the source while the run
|
|
2898
|
+
// reports success, which is the failure mode with no signal attached to it.
|
|
2899
|
+
//
|
|
2900
|
+
// The set is already accumulated here for orphan detection, so this costs one lookup
|
|
2901
|
+
// per record and no extra memory.
|
|
2902
|
+
// TWO PASSES, and the order is the whole correctness of this check.
|
|
2903
|
+
//
|
|
2904
|
+
// Checking and adding in one loop misattributes a batch's OWN duplicate to page
|
|
2905
|
+
// overlap: by the time the second copy is examined, the first has already been added,
|
|
2906
|
+
// so an in-batch repeat looks exactly like a row an earlier page served. Verified —
|
|
2907
|
+
// page 1 [ext-1, ext-2] then page 2 [ext-3, ext-3] reported BOTH a within-batch
|
|
2908
|
+
// collapse and a page overlap, and only one of them was true.
|
|
2909
|
+
//
|
|
2910
|
+
// So pass one asks only about identities from EARLIER batches, while the set still
|
|
2911
|
+
// holds exactly those. Pass two then adds this batch. No copy of the set is taken —
|
|
2912
|
+
// it can hold hundreds of thousands of ids.
|
|
2913
|
+
//
|
|
2914
|
+
// `positionPaged` is also the batch-1 guard: currentOffset/currentPage are only set
|
|
2915
|
+
// from the PREVIOUS batch's NextOffset/NextPage, so both are null on the first batch
|
|
2916
|
+
// by construction and nothing can be a repeat yet.
|
|
2917
|
+
const positionPaged = currentOffset != null || currentPage != null;
|
|
2918
|
+
if (positionPaged) {
|
|
2919
|
+
for (const rec of batch.Records) {
|
|
2920
|
+
if (fetchedExternalIDs.has(rec.ExternalID)) {
|
|
2921
|
+
crossBatchRepeatCount++;
|
|
2922
|
+
if (crossBatchRepeatSamples.length < 5) {
|
|
2923
|
+
crossBatchRepeatSamples.push(String(rec.ExternalID));
|
|
2924
|
+
}
|
|
2925
|
+
}
|
|
2926
|
+
}
|
|
2927
|
+
}
|
|
2592
2928
|
for (const rec of batch.Records) {
|
|
2593
2929
|
fetchedExternalIDs.add(rec.ExternalID);
|
|
2594
2930
|
}
|
|
@@ -2680,9 +3016,19 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
2680
3016
|
`${offsetInfo} — running totals: ${result.RecordsCreated} created, ${result.RecordsUpdated} updated, ` +
|
|
2681
3017
|
`${result.RecordsSkipped} skipped, ${result.RecordsErrored} errored` +
|
|
2682
3018
|
(batch.HasMore ? ` | more batches pending` : ` | batch complete`));
|
|
2683
|
-
// Update progress on the watermark record so the DB reflects live sync state
|
|
3019
|
+
// Update progress on the watermark record so the DB reflects live sync state.
|
|
3020
|
+
//
|
|
3021
|
+
// RecordsSynced counts RECORDS WRITTEN — created + updated — and nothing else. It used
|
|
3022
|
+
// to be handed `afterApply`, which folds in skipped and errored: an object whose rows
|
|
3023
|
+
// were all content-hash-unchanged reported thousands "synced" while writing nothing,
|
|
3024
|
+
// and an object that errored on every record reported the same number as one that
|
|
3025
|
+
// succeeded on every record. Operators watched that counter climb against a physical
|
|
3026
|
+
// row count that never moved (ACR dev, Vendor Payment: 10,400 "synced" against 3,150
|
|
3027
|
+
// rows). Skipped and errored are still counted — on the run result and the run detail,
|
|
3028
|
+
// where they are named as what they are.
|
|
2684
3029
|
if (batch.HasMore) {
|
|
2685
|
-
|
|
3030
|
+
const writtenSoFar = result.RecordsCreated + result.RecordsUpdated;
|
|
3031
|
+
await this.runWriteForMap(entityMapID, () => this.watermarkService.UpdateProgress(entityMapID, writtenSoFar, contextUser));
|
|
2686
3032
|
}
|
|
2687
3033
|
}
|
|
2688
3034
|
recordsInMap += batch.Records.length;
|
|
@@ -2753,6 +3099,52 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
2753
3099
|
}
|
|
2754
3100
|
hasMore = batch.HasMore === true; // Explicit boolean check — prevents truthy undefined from looping
|
|
2755
3101
|
}
|
|
3102
|
+
// MJ-RUN-35 — check our work against the number the source gave us.
|
|
3103
|
+
//
|
|
3104
|
+
// The cheapest self-check available, and it was never wired: the source states its own total
|
|
3105
|
+
// on every page (Django REST returns `count`), connectors parsed it, and it had nowhere to
|
|
3106
|
+
// go. Comparing it to what a CLEAN fetch produced turns a silently short scan into a failed
|
|
3107
|
+
// one, on every connector that states a total, without knowing anything about the vendor.
|
|
3108
|
+
//
|
|
3109
|
+
// Only on a clean fetch: one that already skipped pages or aborted is KNOWN to be short and
|
|
3110
|
+
// has said so. Only when a total was actually stated — absent means "it did not say", never
|
|
3111
|
+
// zero. And deliberately not an equality check: a total that moves while we page is normal,
|
|
3112
|
+
// and fetching MORE than claimed is not a fault. Fetching FEWER is.
|
|
3113
|
+
if (fetchCompletedCleanly &&
|
|
3114
|
+
typeof sourceTotalRecords === 'number' &&
|
|
3115
|
+
recordsInMap < sourceTotalRecords) {
|
|
3116
|
+
const missing = sourceTotalRecords - recordsInMap;
|
|
3117
|
+
fetchCompletedCleanly = false;
|
|
3118
|
+
windowHasHole = true;
|
|
3119
|
+
this.markIncomplete(result, entityMap.ExternalObjectName ?? entityMap.ID);
|
|
3120
|
+
logger?.warning(entityMap.ExternalObjectName ?? entityMap.ID, 'FETCH_SHORT_OF_SOURCE_TOTAL', `'${entityMap.ExternalObjectName}': the source reports ${sourceTotalRecords} record(s) and the scan ` +
|
|
3121
|
+
`finished with ${recordsInMap}, so ${missing} were never returned to us. No request failed, which ` +
|
|
3122
|
+
`means the shortfall is in how the source paged rather than in any one response — most often a page ` +
|
|
3123
|
+
`boundary that moved mid-scan. This result set is INCOMPLETE; the watermark is held so the window is ` +
|
|
3124
|
+
`re-fetched next run.`, { sourceTotal: sourceTotalRecords, fetched: recordsInMap, missing, batches: batchCount });
|
|
3125
|
+
}
|
|
3126
|
+
// MJ-RUN-36 — pages that overlapped also skipped, so this result set is INCOMPLETE.
|
|
3127
|
+
//
|
|
3128
|
+
// Reported and marked incomplete rather than logged as a curiosity: the repeat is the only
|
|
3129
|
+
// visible symptom of an invisible omission, and the run would otherwise finish Success with a
|
|
3130
|
+
// row count that understates the source.
|
|
3131
|
+
//
|
|
3132
|
+
// `fetchCompletedCleanly = false` is what withholds every consequence of "we saw the complete
|
|
3133
|
+
// set" — the watermark is held, orphan detection is skipped (rows absent from an incomplete
|
|
3134
|
+
// fetch are not proof they are gone at the source), and the partition rollup is not
|
|
3135
|
+
// overwritten.
|
|
3136
|
+
if (crossBatchRepeatCount > 0) {
|
|
3137
|
+
fetchCompletedCleanly = false;
|
|
3138
|
+
windowHasHole = true;
|
|
3139
|
+
this.markIncomplete(result, entityMap.ExternalObjectName ?? entityMap.ID);
|
|
3140
|
+
logger?.warning(entityMap.ExternalObjectName ?? entityMap.ID, 'FETCH_PAGES_OVERLAPPED', `'${entityMap.ExternalObjectName}': ${crossBatchRepeatCount} record(s) were served again by a later ` +
|
|
3141
|
+
`page after an earlier page had already returned them, so the page boundaries moved during the scan. ` +
|
|
3142
|
+
`A boundary that moves back to repeat a row has also moved forward past another, which means records ` +
|
|
3143
|
+
`were MISSED — this result set is INCOMPLETE and its row count understates the source. The watermark ` +
|
|
3144
|
+
`is held so the window is re-fetched next run. This object needs a guaranteed sort order from the ` +
|
|
3145
|
+
`source, or a page size large enough that the scan fits one page. ` +
|
|
3146
|
+
`Sample: ${crossBatchRepeatSamples.join(', ')}`, { repeated: crossBatchRepeatCount, sample: crossBatchRepeatSamples, batches: batchCount });
|
|
3147
|
+
}
|
|
2756
3148
|
// Partition (Merkle) reconcile: the full set is now accumulated — diff it against last sync's
|
|
2757
3149
|
// rollups and deep-apply ONLY the changed/added partitions; the new rollup snapshot is persisted
|
|
2758
3150
|
// inside. Runs only on a CLEAN fetch (a partial set would mis-skip partitions and lose updates).
|
|
@@ -2821,7 +3213,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
2821
3213
|
await this.runWriteForMap(entityMapID, () => this.watermarkService.SaveKeysetPosition(entityMapID, currentAfterKey, contextUser));
|
|
2822
3214
|
result.WatermarkAfter = currentAfterKey;
|
|
2823
3215
|
}
|
|
2824
|
-
else if (!hadFetchGap && currentWatermark && currentWatermark !== initialWatermark) {
|
|
3216
|
+
else if (!hadFetchGap && !windowHasHole && currentWatermark && currentWatermark !== initialWatermark) {
|
|
2825
3217
|
// A WATERMARK-based connector stopped early (cancel / safety limit / duplicate batch /
|
|
2826
3218
|
// schema-not-generated / unskippable fetch error) but whole batches DID complete. Persist the
|
|
2827
3219
|
// max watermark seen so the next run resumes from there instead of re-fetching everything
|
|
@@ -2836,7 +3228,10 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
2836
3228
|
// Deliberately NOT wall-clock "now", even for a full sync: coverage is partial, so advancing
|
|
2837
3229
|
// past the point actually reached would skip the (reached, now] window permanently. And
|
|
2838
3230
|
// deliberately NOT when hadFetchGap — a skipped page leaves a HOLE behind this watermark,
|
|
2839
|
-
// which is why that path holds it for a full re-fetch next run.
|
|
3231
|
+
// which is why that path holds it for a full re-fetch next run. `windowHasHole` is the
|
|
3232
|
+
// same refusal for the two holes that are not skipped pages: a scan that finished short
|
|
3233
|
+
// of the total the source stated, and one whose pages overlapped (and therefore skipped).
|
|
3234
|
+
// In both, records we never received can sit BELOW this value.
|
|
2840
3235
|
const partialWatermark = currentWatermark;
|
|
2841
3236
|
await this.runWriteForMap(entityMapID, () => this.watermarkService.Update(entityMapID, partialWatermark, contextUser, 'Pull'));
|
|
2842
3237
|
result.WatermarkAfter = partialWatermark;
|
|
@@ -2859,6 +3254,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
2859
3254
|
// operator knows this object's data is INCOMPLETE this run (the per-page warnings carry the
|
|
2860
3255
|
// offsets). The watermark was held above, so the skipped window is re-fetched on the next run.
|
|
2861
3256
|
if (hadFetchGap) {
|
|
3257
|
+
this.markIncomplete(result, entityMap.ExternalObjectName ?? entityMap.ID);
|
|
2862
3258
|
logger?.warning(entityMap.ExternalObjectName ?? entityMap.ID, 'FETCH_INCOMPLETE_PAGES_SKIPPED', `'${entityMap.ExternalObjectName}' finished with one or more pages skipped after persistent fetch errors — ` +
|
|
2863
3259
|
`the result set is INCOMPLETE. The watermark was held, so the skipped window is re-fetched next run; ` +
|
|
2864
3260
|
`records on the reachable pages were synced normally.`, { skipped: true });
|
|
@@ -2876,6 +3272,20 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
2876
3272
|
})).sort((a, b) => a.Key.localeCompare(b.Key)),
|
|
2877
3273
|
};
|
|
2878
3274
|
}
|
|
3275
|
+
// FINALISE the counter. The mid-loop write above is gated on `batch.HasMore`, so it never
|
|
3276
|
+
// fires for the LAST batch — and an object that finishes in a single page has no such batch
|
|
3277
|
+
// at all, which left its RecordsSynced at whatever the previous run wrote (0, for every
|
|
3278
|
+
// object that has only ever completed in one page). partitionReconcile never entered that
|
|
3279
|
+
// branch either, because its writes all happen after the fetch loop. One write per map per
|
|
3280
|
+
// run closes both cases; it runs after the watermark branches above so the row it updates
|
|
3281
|
+
// exists by now.
|
|
3282
|
+
//
|
|
3283
|
+
// Only for a fetch that completed cleanly. UpdateProgress also stamps LastSyncAt, and a map
|
|
3284
|
+
// that was cancelled, failed mid-fetch or ended INCOMPLETE breaks out of the loop rather than
|
|
3285
|
+
// returning — stamping it would show a run that stopped short as freshly synced.
|
|
3286
|
+
if (fetchCompletedCleanly) {
|
|
3287
|
+
await this.runWriteForMap(entityMapID, () => this.watermarkService.UpdateProgress(entityMapID, result.RecordsCreated + result.RecordsUpdated, contextUser));
|
|
3288
|
+
}
|
|
2879
3289
|
await this.createRunDetail(run, entityMap, result, contextUser);
|
|
2880
3290
|
return result;
|
|
2881
3291
|
}
|
|
@@ -2918,15 +3328,22 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
2918
3328
|
* IntegrationTailRunEvents) so the pagination-rule violation is visible instead of console-only.
|
|
2919
3329
|
* Never truncates and never fails the sync — the over-size batch is written in chunks either way.
|
|
2920
3330
|
*/
|
|
2921
|
-
warnOversizedBatch(entityMap, batch, batchIndex, logger) {
|
|
3331
|
+
warnOversizedBatch(entityMap, batch, batchIndex, requestedBatchSize, logger) {
|
|
2922
3332
|
const objectName = entityMap.ExternalObjectName ?? entityMap.ID;
|
|
2923
|
-
|
|
3333
|
+
// WHAT WAS ASKED FOR ON THIS PAGE, not `this.MaxBatchSize`. The governor may have shed the
|
|
3334
|
+
// run's page size, and the caller decides a batch is over-size against the shed figure.
|
|
3335
|
+
// Classifying against the un-shed ceiling makes the two disagree in exactly the case the
|
|
3336
|
+
// warning exists for: a 2,000 ceiling shed to 500, a connector returning 800, the caller
|
|
3337
|
+
// marking the connector as not honouring the size — and this returning null, so nothing is
|
|
3338
|
+
// ever reported. `oversizeBatchWarned` latches on that first page, so no later page
|
|
3339
|
+
// reports it either.
|
|
3340
|
+
const verdict = IntegrationEngine.ClassifyOversizedBatch(objectName, batch.Records.length, requestedBatchSize, batchIndex, batch.HasMore);
|
|
2924
3341
|
if (!verdict)
|
|
2925
3342
|
return;
|
|
2926
3343
|
logger?.warning(objectName, verdict.Code, verdict.Message, {
|
|
2927
3344
|
batchIndex,
|
|
2928
3345
|
recordCount: batch.Records.length,
|
|
2929
|
-
requestedBatchSize
|
|
3346
|
+
requestedBatchSize,
|
|
2930
3347
|
hasMore: batch.HasMore ?? null,
|
|
2931
3348
|
unbounded: verdict.Unbounded,
|
|
2932
3349
|
});
|
|
@@ -3143,7 +3560,11 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
3143
3560
|
// Paged: an unpaged read is silently capped at the entity's UserViewMaxRows (1000 by
|
|
3144
3561
|
// default), and a truncated map here makes already-synced records look brand new — so
|
|
3145
3562
|
// the push would re-CREATE them externally as duplicates.
|
|
3146
|
-
|
|
3563
|
+
// Streamed per page into the lookup this path actually uses (MJ record id → external id)
|
|
3564
|
+
// rather than materialising every row object first — see loadAllRecordMaps' STREAMING note.
|
|
3565
|
+
const existingMaps = new Map();
|
|
3566
|
+
const allMaps = await this.loadAllRecordMaps(companyIntegration.ID, entityMap.EntityID, contextUser, page => { for (const m of page)
|
|
3567
|
+
existingMaps.set(m.EntityRecordID, m.ExternalSystemRecordID); });
|
|
3147
3568
|
if (!allMaps.Complete) {
|
|
3148
3569
|
// Refuse rather than push a partial picture: with an incomplete map, every unmapped
|
|
3149
3570
|
// record reads as "not yet in the external system" and gets created a second time.
|
|
@@ -3151,10 +3572,6 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
3151
3572
|
`(${allMaps.Error ?? 'unknown error'}). Refusing to push — an incomplete map would ` +
|
|
3152
3573
|
`re-create already-synced records as duplicates in the external system.`);
|
|
3153
3574
|
}
|
|
3154
|
-
const existingMaps = new Map();
|
|
3155
|
-
for (const m of allMaps.Rows) {
|
|
3156
|
-
existingMaps.set(m.EntityRecordID, m.ExternalSystemRecordID);
|
|
3157
|
-
}
|
|
3158
3575
|
const md = this.ProviderToUse;
|
|
3159
3576
|
const entityInfo = md.EntityByName(entityMap.Entity);
|
|
3160
3577
|
if (!entityInfo) {
|
|
@@ -3196,6 +3613,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
3196
3613
|
ExtraFilter: `EntityRecordID='${change.RecordID}' AND CompanyIntegrationID='${config.companyIntegration.ID}'`,
|
|
3197
3614
|
Fields: ['ExternalSystemRecordID'],
|
|
3198
3615
|
MaxRows: 1,
|
|
3616
|
+
SkipTotalRowCount: true,
|
|
3199
3617
|
ResultType: 'simple',
|
|
3200
3618
|
BypassCache: true, // write-back targets the committed external-id mapping
|
|
3201
3619
|
}, contextUser);
|
|
@@ -3447,17 +3865,26 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
3447
3865
|
// Paged: an unpaged read is silently capped at the entity's UserViewMaxRows (1000 by
|
|
3448
3866
|
// default). A tenant with 5,000 orphans would clear 1,000 per run and the operator would
|
|
3449
3867
|
// see a clean run every time — the truncation was invisible, which is the actual bug.
|
|
3450
|
-
|
|
3868
|
+
//
|
|
3869
|
+
// Streamed: the orphan test is per row and needs nothing from the rows that pass it, so each
|
|
3870
|
+
// page is filtered and dropped. What stays resident is the ORPHANS — normally a handful —
|
|
3871
|
+
// instead of every mapping the entity has (see loadAllRecordMaps' STREAMING note).
|
|
3872
|
+
const orphans = [];
|
|
3873
|
+
const allMaps = await this.loadAllRecordMaps(companyIntegration.ID, entityMap.EntityID, contextUser, page => {
|
|
3874
|
+
for (const m of page) {
|
|
3875
|
+
if (!fetchedExternalIDs.has(m.ExternalSystemRecordID))
|
|
3876
|
+
orphans.push(m);
|
|
3877
|
+
}
|
|
3878
|
+
});
|
|
3451
3879
|
if (!allMaps.Complete) {
|
|
3452
3880
|
// Deleting against a partial map is the dangerous direction: rows we simply failed to
|
|
3453
3881
|
// read are indistinguishable from rows the external system dropped. Skip the sweep and
|
|
3454
3882
|
// say so, rather than archiving live records on incomplete evidence.
|
|
3455
3883
|
logger?.warning(entityMap.ExternalObjectName ?? entityMap.ID, 'ORPHAN_SWEEP_SKIPPED', `Delete-detection was skipped for ${entityMap.Entity}: the record map could not be read completely ` +
|
|
3456
|
-
`(${allMaps.Error ?? 'unknown error'}) after ${allMaps.
|
|
3457
|
-
`Deleting on a partial map would archive live records.`, { rowsRead: allMaps.
|
|
3884
|
+
`(${allMaps.Error ?? 'unknown error'}) after ${allMaps.RowsRead} row(s). No records were deleted. ` +
|
|
3885
|
+
`Deleting on a partial map would archive live records.`, { rowsRead: allMaps.RowsRead });
|
|
3458
3886
|
return;
|
|
3459
3887
|
}
|
|
3460
|
-
const orphans = allMaps.Rows.filter(m => !fetchedExternalIDs.has(m.ExternalSystemRecordID));
|
|
3461
3888
|
if (orphans.length === 0)
|
|
3462
3889
|
return;
|
|
3463
3890
|
// The sweep is a DELETE PATH and must answer to the same policy as every other delete.
|
|
@@ -4646,6 +5073,14 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
4646
5073
|
// 2x margin defended by nothing is not a guard. Same reasoning as baseEngine's own
|
|
4647
5074
|
// IgnoreMaxRows use, and this file documents the identical trap on the push side.
|
|
4648
5075
|
IgnoreMaxRows: true,
|
|
5076
|
+
// L4 — this prefetch runs once per batch and every batch's filter is unique, so the
|
|
5077
|
+
// provider's result cache keeps one entry per batch that is never hit again. Memory
|
|
5078
|
+
// then grows O(records processed) for the lifetime of the run, which is how a
|
|
5079
|
+
// ~500k-record drain killed a 3.8 GB box: the KERNEL oom-killed the process at
|
|
5080
|
+
// ~2.3 GB RSS, twice, BEFORE V8's own ceiling was reached — so no
|
|
5081
|
+
// --max-old-space-size value fixes it and box RAM is the binding constraint.
|
|
5082
|
+
// BypassCache makes the call O(batch), matching LoadAllRecordMaps below.
|
|
5083
|
+
BypassCache: true,
|
|
4649
5084
|
}, contextUser);
|
|
4650
5085
|
if (!res.Success)
|
|
4651
5086
|
return undefined;
|
|
@@ -5093,8 +5528,17 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
5093
5528
|
* silently skipping rows while still reporting `Complete: true`. That is exactly the
|
|
5094
5529
|
* truncation this helper exists to prevent, and the orphan sweep would archive live
|
|
5095
5530
|
* records on the strength of it. Keyset seeks on the last ID seen and cannot shift.
|
|
5531
|
+
*
|
|
5532
|
+
* **STREAMING, when the caller can use it.** Paging bounds the QUERY, not the resident set: with
|
|
5533
|
+
* every page appended to one array, a table with a million mappings for one (CompanyIntegration,
|
|
5534
|
+
* Entity) pair holds a million row objects in the heap for the length of the sweep — and neither
|
|
5535
|
+
* caller wants the rows. The push path wants a `Map` of two of the three columns; the orphan
|
|
5536
|
+
* sweep wants the handful of rows whose external ID is missing from the fetched set. Pass
|
|
5537
|
+
* `onPage` and each page is handed over and dropped: `Rows` comes back EMPTY and `RowsRead`
|
|
5538
|
+
* carries the count. Omit it and the behaviour is exactly as before (rows accumulated), because
|
|
5539
|
+
* the honest reading of "give me everything" is that the caller intends to hold everything.
|
|
5096
5540
|
*/
|
|
5097
|
-
async loadAllRecordMaps(companyIntegrationID, entityID, contextUser) {
|
|
5541
|
+
async loadAllRecordMaps(companyIntegrationID, entityID, contextUser, onPage) {
|
|
5098
5542
|
const PAGE_SIZE = IntegrationEngine.RecordMapPageSize;
|
|
5099
5543
|
// Backstop only: at the default page size this is 50M mappings for one
|
|
5100
5544
|
// (CompanyIntegration, Entity) pair. It exists so a provider that ignores the seek key
|
|
@@ -5103,6 +5547,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
5103
5547
|
const filter = `CompanyIntegrationID='${companyIntegrationID}' AND EntityID='${entityID}'`;
|
|
5104
5548
|
const rv = new RunView();
|
|
5105
5549
|
const rows = [];
|
|
5550
|
+
let rowsRead = 0;
|
|
5106
5551
|
let afterID;
|
|
5107
5552
|
for (let pageNo = 0; pageNo < MAX_PAGES; pageNo++) {
|
|
5108
5553
|
const page = await rv.RunView({
|
|
@@ -5121,14 +5566,18 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
5121
5566
|
BypassCache: true, // sync decisions must reflect committed record-map state
|
|
5122
5567
|
}, contextUser);
|
|
5123
5568
|
if (!page.Success) {
|
|
5124
|
-
return { Rows: rows, Complete: false, Error: page.ErrorMessage ?? 'RunView failed' };
|
|
5569
|
+
return { Rows: rows, RowsRead: rowsRead, Complete: false, Error: page.ErrorMessage ?? 'RunView failed' };
|
|
5125
5570
|
}
|
|
5571
|
+
rowsRead += page.Results.length;
|
|
5572
|
+
if (onPage)
|
|
5573
|
+
onPage(page.Results);
|
|
5126
5574
|
// No spread: push(...rows) passes every row as a call argument and throws
|
|
5127
5575
|
// "Maximum call stack size exceeded" past ~100k rows if a provider returns an oversized page.
|
|
5128
|
-
|
|
5129
|
-
|
|
5576
|
+
else
|
|
5577
|
+
for (const row of page.Results)
|
|
5578
|
+
rows.push(row);
|
|
5130
5579
|
if (page.Results.length < PAGE_SIZE)
|
|
5131
|
-
return { Rows: rows, Complete: true };
|
|
5580
|
+
return { Rows: rows, RowsRead: rowsRead, Complete: true };
|
|
5132
5581
|
afterID = page.Results[page.Results.length - 1].ID;
|
|
5133
5582
|
}
|
|
5134
5583
|
// Fell out of the loop with full pages still coming: either a genuinely enormous map or a
|
|
@@ -5136,8 +5585,9 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
5136
5585
|
// saying so is the whole point of the Complete flag.
|
|
5137
5586
|
return {
|
|
5138
5587
|
Rows: rows,
|
|
5588
|
+
RowsRead: rowsRead,
|
|
5139
5589
|
Complete: false,
|
|
5140
|
-
Error: `Record-map paging exceeded ${MAX_PAGES} pages (${
|
|
5590
|
+
Error: `Record-map paging exceeded ${MAX_PAGES} pages (${rowsRead} rows read) without reaching the end.`,
|
|
5141
5591
|
};
|
|
5142
5592
|
}
|
|
5143
5593
|
/**
|
|
@@ -5181,6 +5631,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
5181
5631
|
ExtraFilter: `CompanyIntegrationID='${companyIntegrationID}' AND EntityID='${entityID}' AND ExternalSystemRecordID=${quotedExternalID}`,
|
|
5182
5632
|
Fields: ['ID', 'EntityRecordID'],
|
|
5183
5633
|
MaxRows: 1,
|
|
5634
|
+
SkipTotalRowCount: true,
|
|
5184
5635
|
ResultType: 'simple',
|
|
5185
5636
|
BypassCache: true, // upsert-by-identity: a stale miss here re-creates a duplicate record map
|
|
5186
5637
|
}, contextUser);
|
|
@@ -5203,6 +5654,11 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
5203
5654
|
recordMap.ExternalSystemRecordID = externalID;
|
|
5204
5655
|
recordMap.EntityID = entityID;
|
|
5205
5656
|
recordMap.EntityRecordID = entityRecordID;
|
|
5657
|
+
// When a batch's write group is active, the map row travels in it with the entity saves
|
|
5658
|
+
// instead of paying its own round trip and commit. Its key is client-generated by
|
|
5659
|
+
// NewRecord(), so the "primary key exists before Submit" rule in enrolInWriteGroup holds.
|
|
5660
|
+
// Outside a group (every current caller) this is a no-op and the save is immediate.
|
|
5661
|
+
this.enrolInWriteGroup(recordMap);
|
|
5206
5662
|
const saved = await recordMap.Save();
|
|
5207
5663
|
if (!saved) {
|
|
5208
5664
|
throw new Error(`Failed to save record map for external ID ${externalID}: ${recordMap.LatestResult?.CompleteMessage ?? 'unknown error'}`);
|
|
@@ -5229,6 +5685,9 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
5229
5685
|
// makes a working sync look like it processed zero maps. Retry transient failures before giving up.
|
|
5230
5686
|
try {
|
|
5231
5687
|
await WithRetry(async () => {
|
|
5688
|
+
// Same rule as the record map: inside an active write group it travels with
|
|
5689
|
+
// the batch; outside one (every current caller) it saves immediately.
|
|
5690
|
+
this.enrolInWriteGroup(detail);
|
|
5232
5691
|
const ok = await detail.Save();
|
|
5233
5692
|
if (!ok)
|
|
5234
5693
|
throw new Error(detail.LatestResult?.CompleteMessage ?? 'detail.Save() returned false');
|
|
@@ -5244,6 +5703,51 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
5244
5703
|
/**
|
|
5245
5704
|
* Merges an entity-map-level result into the aggregate result.
|
|
5246
5705
|
*/
|
|
5706
|
+
/**
|
|
5707
|
+
* Warn on the run's own stream when the host is running out of memory or disk, and report
|
|
5708
|
+
* whether memory pressure is present so the caller can shed load.
|
|
5709
|
+
*
|
|
5710
|
+
* plan.md line 158 wants the user told, and the only moment that is useful is BEFORE the
|
|
5711
|
+
* failure. Emitted at an entity-map boundary because that is a natural checkpoint - the
|
|
5712
|
+
* measurement is cheap but not free, and per-record would be absurd.
|
|
5713
|
+
*
|
|
5714
|
+
* The WARNING is once per code per run - repeating it every map would bury the run's real
|
|
5715
|
+
* events, and the condition does not become more true by being restated. The RETURN VALUE is
|
|
5716
|
+
* not: it reports the CURRENT reading every time, because the AIMD cap has to keep being told.
|
|
5717
|
+
* Telling it once would cut concurrency a single step and then ramp straight back up into the
|
|
5718
|
+
* same wall.
|
|
5719
|
+
*
|
|
5720
|
+
* Measured even with no logger. A sync with nowhere to write warnings is still a sync that can
|
|
5721
|
+
* be killed, and the throttle is what keeps it alive.
|
|
5722
|
+
*/
|
|
5723
|
+
async warnOnResourcePressure(logger, warned, governorShedding = false) {
|
|
5724
|
+
try {
|
|
5725
|
+
const findings = EvaluatePressure(await ReadResourcePressure());
|
|
5726
|
+
let memoryPressure = false;
|
|
5727
|
+
for (const f of findings) {
|
|
5728
|
+
const isMemory = f.Code === 'HOST_MEMORY_PRESSURE';
|
|
5729
|
+
if (isMemory)
|
|
5730
|
+
memoryPressure = true;
|
|
5731
|
+
if (!logger || warned.has(f.Code))
|
|
5732
|
+
continue;
|
|
5733
|
+
warned.add(f.Code);
|
|
5734
|
+
// Carry what we DID, not only what we saw: a customer watching a sync get slower
|
|
5735
|
+
// should be able to tell that the slowdown and the warning are one event, not two
|
|
5736
|
+
// problems. Deliberately a field on the existing warning rather than a new event
|
|
5737
|
+
// type - SyncLogEvent is a closed union every client matches on.
|
|
5738
|
+
logger.warning('sync', f.Code, f.Message, {
|
|
5739
|
+
fraction: f.Fraction,
|
|
5740
|
+
...(isMemory && !governorShedding ? { action: 'reduced-concurrency' } : {}),
|
|
5741
|
+
});
|
|
5742
|
+
}
|
|
5743
|
+
return memoryPressure;
|
|
5744
|
+
}
|
|
5745
|
+
catch {
|
|
5746
|
+
// Measuring headroom must never be the thing that ends a sync - and must never be the
|
|
5747
|
+
// thing that throttles it either, so an unreadable measurement reports no pressure.
|
|
5748
|
+
return false;
|
|
5749
|
+
}
|
|
5750
|
+
}
|
|
5247
5751
|
mergeResult(aggregate, mapResult) {
|
|
5248
5752
|
aggregate.RecordsProcessed += mapResult.RecordsProcessed;
|
|
5249
5753
|
aggregate.RecordsCreated += mapResult.RecordsCreated;
|
|
@@ -5254,10 +5758,35 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
5254
5758
|
// Bound the retained error SAMPLE: only the first MAX_AGGREGATE_ERRORS are ever persisted
|
|
5255
5759
|
// (FinalizeRun slices to 100). Accumulating every per-record error across a multi-million-row
|
|
5256
5760
|
// failing run would hold the whole set in RAM for no gain — RecordsErrored already has the count.
|
|
5761
|
+
// Feed the LIVE snapshot from the same accumulation.
|
|
5762
|
+
//
|
|
5763
|
+
// These four fields existed on the snapshot and on OperationProgressOutput, and the
|
|
5764
|
+
// resolver returned them, but NOTHING ever wrote them — they were initialised to 0 and
|
|
5765
|
+
// stayed 0 for the whole run. That is why the UI showed a bare "+" for created and "~"
|
|
5766
|
+
// for updated with no breakdown: the numbers were always zero, not mis-rendered.
|
|
5767
|
+
//
|
|
5768
|
+
// Here rather than on the progress tick because SyncProgress carries no outcome counts at
|
|
5769
|
+
// all; it only knows position. This is the one place a map's real outcome is folded, and
|
|
5770
|
+
// the aggregate is already monotonic, so the snapshot inherits that for free.
|
|
5771
|
+
const snap = this.currentRunContext?.progressSnapshot;
|
|
5772
|
+
if (snap) {
|
|
5773
|
+
snap.RecordsProcessed = aggregate.RecordsProcessed;
|
|
5774
|
+
snap.RecordsCreated = aggregate.RecordsCreated;
|
|
5775
|
+
snap.RecordsUpdated = aggregate.RecordsUpdated;
|
|
5776
|
+
snap.RecordsErrored = aggregate.RecordsErrored;
|
|
5777
|
+
snap.RecordsSkipped = aggregate.RecordsSkipped;
|
|
5778
|
+
// Persist now as well as on the next tick: the final map has no tick after it, so
|
|
5779
|
+
// without this the run's last counts never reach a reader in another process.
|
|
5780
|
+
void this.currentRunContext?.ownership?.WriteProgress(JSON.stringify(snap));
|
|
5781
|
+
}
|
|
5257
5782
|
if (aggregate.Errors.length < MAX_AGGREGATE_ERRORS && mapResult.Errors.length > 0) {
|
|
5258
5783
|
const room = MAX_AGGREGATE_ERRORS - aggregate.Errors.length;
|
|
5259
5784
|
aggregate.Errors.push(...mapResult.Errors.slice(0, room));
|
|
5260
5785
|
}
|
|
5786
|
+
// MJ-RUN-4: the per-map result is where an object is marked incomplete, and the run total is
|
|
5787
|
+
// what the completion message reads. Without this the list never left the map that set it.
|
|
5788
|
+
for (const name of mapResult.IncompleteObjects ?? [])
|
|
5789
|
+
this.markIncomplete(aggregate, name);
|
|
5261
5790
|
if (mapResult.RecordsErrored > 0) {
|
|
5262
5791
|
aggregate.Success = false;
|
|
5263
5792
|
}
|
|
@@ -5400,18 +5929,18 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
5400
5929
|
if (!detailInfo?.SchemaName || !detailInfo.BaseTable || !ciId)
|
|
5401
5930
|
return;
|
|
5402
5931
|
// Cutoff = StartedAt of the Nth-most-recent run for this CI. If there aren't MORE than
|
|
5403
|
-
// `keep` runs, there's nothing to prune.
|
|
5932
|
+
// `keep` runs, there's nothing to prune. Reads `keep + 1` rows and counts them.
|
|
5404
5933
|
const recent = await new RunView().RunView({
|
|
5405
5934
|
EntityName: runInfo.Name,
|
|
5406
5935
|
ExtraFilter: `CompanyIntegrationID='${String(ciId).replace(/'/g, "''")}'`,
|
|
5407
5936
|
OrderBy: 'StartedAt DESC',
|
|
5408
5937
|
Fields: ['StartedAt'],
|
|
5409
|
-
MaxRows: keep,
|
|
5938
|
+
MaxRows: keep + 1,
|
|
5410
5939
|
ResultType: 'simple',
|
|
5411
5940
|
}, contextUser);
|
|
5412
|
-
if (!recent.Success || (recent.
|
|
5941
|
+
if (!recent.Success || (recent.Results?.length ?? 0) <= keep)
|
|
5413
5942
|
return;
|
|
5414
|
-
const cutoffRaw = recent.Results
|
|
5943
|
+
const cutoffRaw = recent.Results[keep - 1]?.StartedAt;
|
|
5415
5944
|
if (!cutoffRaw)
|
|
5416
5945
|
return;
|
|
5417
5946
|
const provider = md;
|
|
@@ -5604,9 +6133,6 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
5604
6133
|
get EntityMaps() {
|
|
5605
6134
|
return this.Base.EntityMaps;
|
|
5606
6135
|
}
|
|
5607
|
-
get FieldMaps() {
|
|
5608
|
-
return this.Base.FieldMaps;
|
|
5609
|
-
}
|
|
5610
6136
|
get Watermarks() {
|
|
5611
6137
|
return this.Base.Watermarks;
|
|
5612
6138
|
}
|
|
@@ -5626,8 +6152,8 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
5626
6152
|
GetEntityMapsForCompanyIntegration(companyIntegrationID) {
|
|
5627
6153
|
return this.Base.GetEntityMapsForCompanyIntegration(companyIntegrationID);
|
|
5628
6154
|
}
|
|
5629
|
-
|
|
5630
|
-
return this.Base.
|
|
6155
|
+
LoadFieldMapsForEntityMap(entityMapID, contextUser) {
|
|
6156
|
+
return this.Base.LoadFieldMapsForEntityMap(entityMapID, contextUser);
|
|
5631
6157
|
}
|
|
5632
6158
|
GetEnabledEntityMaps(companyIntegrationID) {
|
|
5633
6159
|
return this.Base.GetEnabledEntityMaps(companyIntegrationID);
|
|
@@ -5654,6 +6180,10 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
5654
6180
|
GetIntegrationObjectFields(objectID) {
|
|
5655
6181
|
return this.Base.GetIntegrationObjectFields(objectID);
|
|
5656
6182
|
}
|
|
6183
|
+
/** Delegates to IntegrationEngineBase.GetRelatedIntegrationObjectIDs — an object's FK parents. */
|
|
6184
|
+
GetRelatedIntegrationObjectIDs(objectID) {
|
|
6185
|
+
return this.Base.GetRelatedIntegrationObjectIDs(objectID);
|
|
6186
|
+
}
|
|
5657
6187
|
/**
|
|
5658
6188
|
* Source field names the connector declared as SyncDirective 'Exclude' for one
|
|
5659
6189
|
* integration object, read from IntegrationObjectField.Configuration. Empty set
|
|
@@ -5679,4 +6209,25 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
5679
6209
|
return IntegrationEngine.getInstance();
|
|
5680
6210
|
}
|
|
5681
6211
|
}
|
|
6212
|
+
/**
|
|
6213
|
+
* The message a finished sync run is finalized with.
|
|
6214
|
+
*
|
|
6215
|
+
* MJ-RUN-4: a run that left objects INCOMPLETE says which, after anything the run already had to
|
|
6216
|
+
* say (an error count, for one), rather than in place of it. A cancelled run keeps its own message.
|
|
6217
|
+
*/
|
|
6218
|
+
export function BuildRunCompletionMessage(incomplete, errorMessage, aborted) {
|
|
6219
|
+
if (aborted || incomplete.length === 0)
|
|
6220
|
+
return errorMessage;
|
|
6221
|
+
const names = `${incomplete.slice(0, 10).join(', ')}${incomplete.length > 10 ? ', …' : ''}`;
|
|
6222
|
+
return `${errorMessage ?? 'Sync run complete'} — ${incomplete.length} object(s) INCOMPLETE: ${names}`;
|
|
6223
|
+
}
|
|
6224
|
+
/** What each lever is called in the one sentence a customer reads. */
|
|
6225
|
+
const LEVER_COPY = {
|
|
6226
|
+
HOLD_ADMISSIONS: 'not starting more tables for now',
|
|
6227
|
+
REDUCE_CONCURRENCY: 'syncing fewer tables at once',
|
|
6228
|
+
SHRINK_BATCH: 'reading smaller pages from your source',
|
|
6229
|
+
FLUSH_ACCUMULATOR: 'saving more often',
|
|
6230
|
+
DROP_HASH_PREFETCH: 'skipping an optimisation',
|
|
6231
|
+
PAUSE_OTHER_SYNC: 'pausing another sync'
|
|
6232
|
+
};
|
|
5682
6233
|
//# sourceMappingURL=IntegrationEngine.js.map
|