@memberjunction/integration-engine 6.2.0-edge.4 → 6.2.0-edge.6
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/BaseIntegrationConnector.d.ts.map +1 -1
- package/dist/BaseIntegrationConnector.js +22 -4
- 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 +34 -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/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 +33 -26
- package/dist/IntegrationActionGenerator.js.map +1 -1
- package/dist/IntegrationConnectorCreationPipeline.d.ts +141 -4
- package/dist/IntegrationConnectorCreationPipeline.d.ts.map +1 -1
- package/dist/IntegrationConnectorCreationPipeline.js +521 -64
- package/dist/IntegrationConnectorCreationPipeline.js.map +1 -1
- package/dist/IntegrationEngine.d.ts +13 -0
- package/dist/IntegrationEngine.d.ts.map +1 -1
- package/dist/IntegrationEngine.js +257 -166
- 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 +300 -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/index.d.ts +8 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +6 -0
- package/dist/index.js.map +1 -1
- package/dist/types.d.ts +21 -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';
|
|
@@ -749,170 +750,174 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
749
750
|
* await, and the pool always starts one from a synchronous call site.
|
|
750
751
|
*/
|
|
751
752
|
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)`);
|
|
753
|
+
// A resumed run reads the same catalog the original did — its own connection's — in the
|
|
754
|
+
// same warmed scope a fresh run uses (see RunSync).
|
|
755
|
+
return RunInWarmedCatalogScope(run.CompanyIntegrationID, async () => {
|
|
756
|
+
const companyIntegrationID = run.CompanyIntegrationID;
|
|
757
|
+
const runID = run.ID;
|
|
758
|
+
const lockKey = companyIntegrationID.toLowerCase();
|
|
759
|
+
// C1: respect the SAME in-process concurrency lock RunSync uses. If a live sync for this
|
|
760
|
+
// CompanyIntegration is already running (e.g. the scheduler fired during startup), skip the
|
|
761
|
+
// resume — double-running one CI on the shared provider connection corrupts its singular
|
|
762
|
+
// transaction state (exactly what runWriteExclusive guards against WITHIN a run). The
|
|
763
|
+
// get→set pair below has no await between them, so check-and-reserve is atomic on the loop.
|
|
764
|
+
if (IntegrationEngine.activeSyncs.get(lockKey)) {
|
|
765
|
+
console.log(`[IntegrationEngine] Skipping resume of run ${runID.substring(0, 8)} — a live sync for ${lockKey} is already running`);
|
|
777
766
|
return;
|
|
778
767
|
}
|
|
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';
|
|
768
|
+
let resolveResumeLock;
|
|
769
|
+
let resumeResult;
|
|
770
|
+
IntegrationEngine.activeSyncs.set(lockKey, new Promise(res => { resolveResumeLock = res; }));
|
|
771
|
+
const ownership = new RunOwnershipService(prov, runID, undefined, contextUser);
|
|
813
772
|
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();
|
|
773
|
+
// CLAIM BEFORE ADOPTING (PR 1 item 6): a single atomic UPDATE that succeeds only if the
|
|
774
|
+
// run is still unowned/lapsed. Zero rows = another worker adopted it between our RunView
|
|
775
|
+
// and now — skip, never double-run. A successful claim BUMPS the fence, so if the
|
|
776
|
+
// original owner is actually alive-but-slow it aborts at its next boundary check
|
|
777
|
+
// without writing: the sweep-reclaim is itself the abort signal for the abandoned owner.
|
|
778
|
+
const claimed = await ownership.Claim();
|
|
779
|
+
if (!claimed) {
|
|
780
|
+
console.log(`[IntegrationEngine] Skipping resume of run ${runID.substring(0, 8)} — claim lost (another worker adopted it)`);
|
|
781
|
+
return;
|
|
782
|
+
}
|
|
783
|
+
// Find which entity MAPS already completed SUCCESSFULLY in this run. We correlate
|
|
784
|
+
// by EntityMapID (parsed from the detail's RecordID, stamped by CreateRunDetail),
|
|
785
|
+
// not EntityID — two maps can target the same MJ Entity, so keying on EntityID
|
|
786
|
+
// could skip a still-pending sibling map. We also require IsSuccess=1: a map that
|
|
787
|
+
// completed WITH errors (RecordsErrored>0, no throw) must be re-attempted on resume,
|
|
788
|
+
// otherwise its errored records are silently abandoned.
|
|
789
|
+
const detailsResult = await rv.RunView({
|
|
790
|
+
EntityName: 'MJ: Company Integration Run Details',
|
|
791
|
+
ExtraFilter: `CompanyIntegrationRunID='${runID}'`,
|
|
792
|
+
Fields: ['RecordID', 'IsSuccess'],
|
|
793
|
+
ResultType: 'simple',
|
|
794
|
+
}, contextUser);
|
|
795
|
+
const completedMapIDs = new Set();
|
|
796
|
+
if (detailsResult.Success) {
|
|
797
|
+
for (const d of detailsResult.Results) {
|
|
798
|
+
if (!d.IsSuccess)
|
|
799
|
+
continue; // completed-with-errors → re-attempt on resume
|
|
800
|
+
const m = /^EntityMap:([0-9a-fA-F-]+)\|/.exec(d.RecordID ?? '');
|
|
801
|
+
// Parse-miss falls open (map treated as not-completed → re-runs): at worst a
|
|
802
|
+
// redundant idempotent re-sync, never a silent skip.
|
|
803
|
+
if (m)
|
|
804
|
+
completedMapIDs.add(m[1].toLowerCase());
|
|
805
|
+
}
|
|
806
|
+
}
|
|
807
|
+
console.log(`[IntegrationEngine] Resuming run ${runID.substring(0, 8)}... ` +
|
|
808
|
+
`for ${companyIntegrationID.substring(0, 8)}... ` +
|
|
809
|
+
`(${completedMapIDs.size} entity maps already completed)`);
|
|
810
|
+
// Recover what this run was ASKED to do. Without this the resume rebuilds config from
|
|
811
|
+
// the CompanyIntegration alone, so an adopted run silently loses its options — most
|
|
812
|
+
// damagingly FullSync, which exists precisely to distrust the watermark. An adopted
|
|
813
|
+
// full sync would resume incrementally, fetch nothing, and report Success.
|
|
814
|
+
// Unparseable/absent ConfigData falls back to defaults rather than refusing to resume.
|
|
815
|
+
let resumeOptions;
|
|
816
|
+
let resumeTriggerType = 'Scheduled';
|
|
898
817
|
try {
|
|
899
|
-
|
|
818
|
+
const cfg = JSON.parse(run.ConfigData ?? '{}');
|
|
819
|
+
resumeOptions = cfg.options ?? undefined;
|
|
820
|
+
if (cfg.triggerType)
|
|
821
|
+
resumeTriggerType = cfg.triggerType;
|
|
822
|
+
}
|
|
823
|
+
catch {
|
|
824
|
+
console.warn(`[IntegrationEngine] Run ${runID.substring(0, 8)} has unparseable ConfigData; resuming with defaults`);
|
|
825
|
+
}
|
|
826
|
+
if (resumeOptions?.FullSync) {
|
|
827
|
+
console.log(`[IntegrationEngine] Run ${runID.substring(0, 8)} was a FULL sync — resuming as full, not incremental`);
|
|
828
|
+
}
|
|
829
|
+
// Load config and filter to only remaining entity maps (by map ID)
|
|
830
|
+
const config = await this.loadRunConfiguration(companyIntegrationID, contextUser, resumeOptions);
|
|
831
|
+
const remainingMaps = config.entityMaps.filter(em => !completedMapIDs.has(em.ID.toLowerCase()));
|
|
832
|
+
if (remainingMaps.length === 0) {
|
|
833
|
+
console.log(`[IntegrationEngine] All entity maps completed for run ${runID.substring(0, 8)}, marking as Success`);
|
|
834
|
+
run.EndedAt = new Date();
|
|
835
|
+
run.Status = 'Success';
|
|
836
|
+
ownership.SyncEntityOwnershipFields(run); // full-row save must not clobber the live claim
|
|
837
|
+
await run.Save();
|
|
838
|
+
await ownership.Release('Success');
|
|
839
|
+
return;
|
|
840
|
+
}
|
|
841
|
+
console.log(`[IntegrationEngine] Resuming ${remainingMaps.length} remaining entity maps (of ${config.entityMaps.length} total)`);
|
|
842
|
+
// Replace entityMaps with only the remaining ones
|
|
843
|
+
config.entityMaps = remainingMaps;
|
|
844
|
+
// Execute remaining maps inside a per-run context: the resume gets its own provider
|
|
845
|
+
// binding, abort controller, and ownership — identical to a fresh RunSync — so the
|
|
846
|
+
// heartbeat renews the lease, the batch boundaries fence-check, and FinalizeRun
|
|
847
|
+
// syncs ownership fields + releases, all through the SAME code paths.
|
|
848
|
+
const abortController = new AbortController();
|
|
849
|
+
const progressSnapshot = {
|
|
850
|
+
StartedAt: new Date(),
|
|
851
|
+
CurrentEntity: '',
|
|
852
|
+
EntityMapsTotal: remainingMaps.length,
|
|
853
|
+
EntityMapsCompleted: 0,
|
|
854
|
+
RecordsProcessed: 0,
|
|
855
|
+
RecordsCreated: 0,
|
|
856
|
+
RecordsUpdated: 0,
|
|
857
|
+
RecordsErrored: 0,
|
|
858
|
+
// The run's OWN trigger type, recovered above — not a hardcoded 'Scheduled'. This is
|
|
859
|
+
// what IntegrationGetSyncProgress reports back ("Sync in progress (Manual)"), so a
|
|
860
|
+
// hardcoded value mislabels every adopted run.
|
|
861
|
+
TriggerType: resumeTriggerType,
|
|
862
|
+
};
|
|
863
|
+
const runCtx = {
|
|
864
|
+
provider: prov,
|
|
865
|
+
ownership,
|
|
866
|
+
abortController,
|
|
867
|
+
progressSnapshot,
|
|
868
|
+
cancelRequested: false,
|
|
869
|
+
ownershipLost: false,
|
|
870
|
+
};
|
|
871
|
+
ownership.StartHeartbeat({
|
|
872
|
+
onLost: () => { runCtx.ownershipLost = true; abortController.abort(); },
|
|
873
|
+
onCancelRequested: () => { runCtx.cancelRequested = true; abortController.abort(); },
|
|
874
|
+
progressSupplier: () => JSON.stringify(progressSnapshot),
|
|
875
|
+
});
|
|
876
|
+
const result = await IntegrationEngine.runContext.run(runCtx, async () => {
|
|
877
|
+
const r = await this.executeEntityMaps(config, run, contextUser, undefined, abortController.signal);
|
|
878
|
+
r.RunID = runID;
|
|
879
|
+
await this.finalizeRun(run, r, contextUser);
|
|
880
|
+
return r;
|
|
881
|
+
});
|
|
882
|
+
resumeResult = result;
|
|
883
|
+
console.log(`[IntegrationEngine] Resume complete for ${runID.substring(0, 8)}: ` +
|
|
884
|
+
`${result.RecordsCreated} created, ${result.RecordsUpdated} updated, ` +
|
|
885
|
+
`${result.RecordsErrored} errored`);
|
|
886
|
+
}
|
|
887
|
+
catch (err) {
|
|
888
|
+
const errMsg = err instanceof Error ? err.message : String(err);
|
|
889
|
+
console.error(`[IntegrationEngine] Failed to resume run ${runID.substring(0, 8)}: ${errMsg}`);
|
|
890
|
+
if (err instanceof RunOwnershipLostError) {
|
|
891
|
+
// We were fenced out mid-resume — the NEW owner now owns the run row.
|
|
892
|
+
// Writing 'Failed' here would clobber the live holder's state.
|
|
893
|
+
console.warn(`[IntegrationEngine] Resume of run ${runID.substring(0, 8)} lost ownership — leaving the run row to its new owner`);
|
|
894
|
+
}
|
|
895
|
+
else {
|
|
896
|
+
// Mark as failed so it doesn't get picked up again
|
|
897
|
+
run.EndedAt = new Date();
|
|
898
|
+
run.Status = 'Failed';
|
|
899
|
+
run.ErrorLog = JSON.stringify([{ ErrorMessage: `Resume failed: ${errMsg}` }]);
|
|
900
|
+
ownership.SyncEntityOwnershipFields(run);
|
|
901
|
+
await run.Save();
|
|
902
|
+
try {
|
|
903
|
+
await ownership.Release('Failed');
|
|
904
|
+
}
|
|
905
|
+
catch { /* lease will simply expire */ }
|
|
900
906
|
}
|
|
901
|
-
catch { /* lease will simply expire */ }
|
|
902
907
|
}
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
}
|
|
915
|
-
}
|
|
908
|
+
finally {
|
|
909
|
+
ownership.StopHeartbeat();
|
|
910
|
+
// Release the C1 lock + unblock any RunSync that began awaiting this resume (RunSync returns
|
|
911
|
+
// `existing`). Resolve with the real result when we have one, else a benign empty result so no
|
|
912
|
+
// waiter hangs. Promise resolve is idempotent and the early-exit `return`s also land here.
|
|
913
|
+
IntegrationEngine.activeSyncs.delete(lockKey);
|
|
914
|
+
resolveResumeLock(resumeResult ?? {
|
|
915
|
+
Success: false, ErrorMessage: 'Resume produced no result', RecordsProcessed: 0,
|
|
916
|
+
RecordsCreated: 0, RecordsUpdated: 0, RecordsDeleted: 0, RecordsErrored: 0,
|
|
917
|
+
RecordsSkipped: 0, Errors: [], EntityMapResults: [], Duration: 0,
|
|
918
|
+
});
|
|
919
|
+
}
|
|
920
|
+
});
|
|
916
921
|
}
|
|
917
922
|
/**
|
|
918
923
|
* Executes a full sync run for a company integration.
|
|
@@ -927,7 +932,15 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
927
932
|
* @returns Aggregate sync result with record counts and errors
|
|
928
933
|
*/
|
|
929
934
|
async RunSync(companyIntegrationID, contextUser, triggerType = 'Manual', onProgress, onNotification, options, provider) {
|
|
930
|
-
|
|
935
|
+
// The connection's catalog is in scope for the WHOLE run: the DAG, the excluded-field
|
|
936
|
+
// resolution and every connector-side GetCachedObject resolve to this connection's own
|
|
937
|
+
// rows once it has them, and to the shared declared rows until it does.
|
|
938
|
+
//
|
|
939
|
+
// A WARMED scope: the run warms each map's objects before the map reads them (see
|
|
940
|
+
// ExecuteEntityMaps), so inside it a cold read is a missed warm site and throws instead of
|
|
941
|
+
// quietly answering with no fields. Entered synchronously, as before — the catalog itself
|
|
942
|
+
// is loaded at the head of ExecuteEntityMaps, inside the run's own error handling.
|
|
943
|
+
return RunInWarmedCatalogScope(companyIntegrationID, () => this.runWithOwnedContext(companyIntegrationID, contextUser, triggerType, onProgress, onNotification, options, provider));
|
|
931
944
|
}
|
|
932
945
|
/**
|
|
933
946
|
* Worker-mode enqueue (PR 1 item 8): create the run row with `Status='Queued'` and
|
|
@@ -1501,6 +1514,13 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
1501
1514
|
if (runCtxForFlags) {
|
|
1502
1515
|
runCtxForFlags.suppressWriteSideEffects = this.readWriteSideEffects(config.companyIntegration) === 'suppressed';
|
|
1503
1516
|
}
|
|
1517
|
+
// This connection's own catalog rows are not resident (MJ-RUN-43): the scope holds what was
|
|
1518
|
+
// read when it was last loaded, memoised for the process. Re-read them here, at the async
|
|
1519
|
+
// head of the run — both the direct and the adopted path come through — for the same reason
|
|
1520
|
+
// the shared catalog is re-read at the head of a run: a discovery since (on this host or
|
|
1521
|
+
// another) must be what this run syncs, not whatever this process first read. Read-then-swap
|
|
1522
|
+
// (MJ-RUN-46), so anything else reading this connection meanwhile never sees it catalog-less.
|
|
1523
|
+
await RefreshCatalogScope(config.companyIntegration.ID, contextUser);
|
|
1504
1524
|
const aggregate = {
|
|
1505
1525
|
Success: true,
|
|
1506
1526
|
RecordsProcessed: 0,
|
|
@@ -1531,7 +1551,14 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
1531
1551
|
direction,
|
|
1532
1552
|
priority: entityMap.Priority ?? null,
|
|
1533
1553
|
});
|
|
1554
|
+
let warmed = [];
|
|
1534
1555
|
try {
|
|
1556
|
+
// Warm the field rows this map reads BEFORE it reads them (MJ-RUN-43), pinned until
|
|
1557
|
+
// it finishes. The readers underneath — connectors' GetCachedFields — are synchronous
|
|
1558
|
+
// and cannot fetch, so the load has to happen here. Per MAP rather than per layer, so
|
|
1559
|
+
// what is pinned is bounded by the maps in flight, not by the width of a layer — and
|
|
1560
|
+
// the pipelined path below gets the same warm site for free.
|
|
1561
|
+
warmed = await this.warmEntityMapCatalog(config, entityMap, depGraph, contextUser);
|
|
1535
1562
|
const mapResult = await this.processSingleEntityMap(config, entityMap, run, contextUser, i, totalMaps, onProgress, abortSignal, logger);
|
|
1536
1563
|
this.mergeResult(aggregate, mapResult);
|
|
1537
1564
|
aggregate.EntityMapResults.push(this.buildEntityMapResult(entityMap, mapResult, Date.now() - mapStartTime));
|
|
@@ -1592,6 +1619,9 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
1592
1619
|
});
|
|
1593
1620
|
return { ok: false, throttled: ClassifyError(err).Code === 'RATE_LIMIT_EXCEEDED' };
|
|
1594
1621
|
}
|
|
1622
|
+
finally {
|
|
1623
|
+
UnpinCatalogObjects(warmed);
|
|
1624
|
+
}
|
|
1595
1625
|
};
|
|
1596
1626
|
// Group maps into dependency layers (parents before children) via the IntegrationObject FK
|
|
1597
1627
|
// graph, then process layers in order. Layers run sequentially — a child never syncs before
|
|
@@ -1745,9 +1775,12 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
1745
1775
|
const parentsByIoId = new Map();
|
|
1746
1776
|
for (const ioId of selectedIoIds) {
|
|
1747
1777
|
const set = new Set();
|
|
1748
|
-
// (1) hard FK pointer on a field (RelatedIntegrationObjectID).
|
|
1749
|
-
|
|
1750
|
-
|
|
1778
|
+
// (1) hard FK pointer on a field (RelatedIntegrationObjectID). Asked for as the object's
|
|
1779
|
+
// related ids rather than read off its field rows: on a per-connection catalog those
|
|
1780
|
+
// rows are not resident, and this graph is built before any of them are warmed — it is
|
|
1781
|
+
// what decides the order they are warmed in. The related ids come from the edge set.
|
|
1782
|
+
for (const related of this.GetRelatedIntegrationObjectIDs(ioId)) {
|
|
1783
|
+
const parent = related.toUpperCase();
|
|
1751
1784
|
if (parent && parent !== ioId && selectedIoIds.has(parent))
|
|
1752
1785
|
set.add(parent);
|
|
1753
1786
|
}
|
|
@@ -1784,6 +1817,46 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
1784
1817
|
}
|
|
1785
1818
|
return { mapToIoId, parentsByIoId };
|
|
1786
1819
|
}
|
|
1820
|
+
/**
|
|
1821
|
+
* Warm the field rows one entity map is about to read, pinned until the caller releases them
|
|
1822
|
+
* (MJ-RUN-43). That is the map's own object and its parents in the dependency graph: a child's
|
|
1823
|
+
* nested fetch reads its parent's key fields, and the parent's own map may have finished long
|
|
1824
|
+
* enough ago for its rows to have been evicted.
|
|
1825
|
+
*
|
|
1826
|
+
* Only this connection's OWN objects are warmed — a shared object's fields are resident. A map
|
|
1827
|
+
* whose object is not in the connection's catalog warms nothing; the map's own handling of a
|
|
1828
|
+
* missing object applies further in. Returns the ids it pinned.
|
|
1829
|
+
*/
|
|
1830
|
+
async warmEntityMapCatalog(config, entityMap, depGraph, contextUser) {
|
|
1831
|
+
const companyIntegrationID = config.companyIntegration?.ID;
|
|
1832
|
+
const objectName = entityMap.ExternalObjectName;
|
|
1833
|
+
if (!companyIntegrationID || !objectName)
|
|
1834
|
+
return [];
|
|
1835
|
+
const own = this.Base.GetCompanyIntegrationObject(companyIntegrationID, objectName);
|
|
1836
|
+
if (!own)
|
|
1837
|
+
return [];
|
|
1838
|
+
const ids = [own.ID];
|
|
1839
|
+
const seen = new Set([NormalizeUUID(own.ID)]);
|
|
1840
|
+
for (const parentID of depGraph?.parentsByIoId.get(own.ID.toUpperCase()) ?? []) {
|
|
1841
|
+
const parent = this.Base.GetCompanyIntegrationObjectByID(parentID);
|
|
1842
|
+
if (parent && !seen.has(NormalizeUUID(parent.ID))) {
|
|
1843
|
+
seen.add(NormalizeUUID(parent.ID));
|
|
1844
|
+
ids.push(parent.ID);
|
|
1845
|
+
}
|
|
1846
|
+
}
|
|
1847
|
+
const pinned = [];
|
|
1848
|
+
try {
|
|
1849
|
+
for (const id of ids) {
|
|
1850
|
+
await WarmCatalogObject(id, contextUser);
|
|
1851
|
+
pinned.push(id);
|
|
1852
|
+
}
|
|
1853
|
+
}
|
|
1854
|
+
catch (err) {
|
|
1855
|
+
UnpinCatalogObjects(pinned);
|
|
1856
|
+
throw err;
|
|
1857
|
+
}
|
|
1858
|
+
return pinned;
|
|
1859
|
+
}
|
|
1787
1860
|
/**
|
|
1788
1861
|
* Surfaces the second-layer silent-empty case as a structured warning. An object that HAS FK
|
|
1789
1862
|
* parents (an association/dependent — a "second-layer" object) but fetched ZERO records is the
|
|
@@ -2374,7 +2447,16 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
2374
2447
|
const ctx = {
|
|
2375
2448
|
CompanyIntegration: config.companyIntegration,
|
|
2376
2449
|
ObjectName: entityMap.ExternalObjectName,
|
|
2377
|
-
|
|
2450
|
+
// The fetch filter is the RUN's start boundary, never the running max.
|
|
2451
|
+
//
|
|
2452
|
+
// `currentWatermark` advances every page for connectors that emit a per-page running
|
|
2453
|
+
// max (netsuite@1.4.1+ does, for resume-friendliness); feeding it back into the next
|
|
2454
|
+
// page's query ratchets the incremental predicate forward MID-SCAN, so every row whose
|
|
2455
|
+
// modstamp trails the max seen so far is silently excluded even though the walk never
|
|
2456
|
+
// visited it. Observed live (ACR dev, 2026-09-07): a Vendor Bill full scan collapsed
|
|
2457
|
+
// to 707 of 23,558 rows — an id-ascending-AND-modstamp-ascending subsequence — with
|
|
2458
|
+
// the run still reporting success. `currentWatermark` remains persistence bookkeeping.
|
|
2459
|
+
WatermarkValue: initialWatermark,
|
|
2378
2460
|
BatchSize: this.MaxBatchSize,
|
|
2379
2461
|
ContextUser: contextUser,
|
|
2380
2462
|
CurrentPage: currentPage,
|
|
@@ -5113,7 +5195,9 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
5113
5195
|
// below well-defined.
|
|
5114
5196
|
OrderBy: 'ID ASC',
|
|
5115
5197
|
AfterKey: afterID ? CompositeKey.FromID(afterID) : undefined,
|
|
5116
|
-
|
|
5198
|
+
// An explicit MaxRows already overrides the entity-level UserViewMaxRows cap on a keyset
|
|
5199
|
+
// read. Do NOT add IgnoreMaxRows: it drops MaxRows too, so the first "page" becomes the
|
|
5200
|
+
// whole record map.
|
|
5117
5201
|
MaxRows: PAGE_SIZE,
|
|
5118
5202
|
ResultType: 'simple',
|
|
5119
5203
|
BypassCache: true, // sync decisions must reflect committed record-map state
|
|
@@ -5121,7 +5205,10 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
5121
5205
|
if (!page.Success) {
|
|
5122
5206
|
return { Rows: rows, Complete: false, Error: page.ErrorMessage ?? 'RunView failed' };
|
|
5123
5207
|
}
|
|
5124
|
-
|
|
5208
|
+
// No spread: push(...rows) passes every row as a call argument and throws
|
|
5209
|
+
// "Maximum call stack size exceeded" past ~100k rows if a provider returns an oversized page.
|
|
5210
|
+
for (const row of page.Results)
|
|
5211
|
+
rows.push(row);
|
|
5125
5212
|
if (page.Results.length < PAGE_SIZE)
|
|
5126
5213
|
return { Rows: rows, Complete: true };
|
|
5127
5214
|
afterID = page.Results[page.Results.length - 1].ID;
|
|
@@ -5649,6 +5736,10 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
5649
5736
|
GetIntegrationObjectFields(objectID) {
|
|
5650
5737
|
return this.Base.GetIntegrationObjectFields(objectID);
|
|
5651
5738
|
}
|
|
5739
|
+
/** Delegates to IntegrationEngineBase.GetRelatedIntegrationObjectIDs — an object's FK parents. */
|
|
5740
|
+
GetRelatedIntegrationObjectIDs(objectID) {
|
|
5741
|
+
return this.Base.GetRelatedIntegrationObjectIDs(objectID);
|
|
5742
|
+
}
|
|
5652
5743
|
/**
|
|
5653
5744
|
* Source field names the connector declared as SyncDirective 'Exclude' for one
|
|
5654
5745
|
* integration object, read from IntegrationObjectField.Configuration. Empty set
|