@memberjunction/integration-engine 6.3.0-edge.0 → 6.3.0-edge.1
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/README.md +32 -0
- package/dist/BaseIntegrationConnector.d.ts +9 -0
- package/dist/BaseIntegrationConnector.d.ts.map +1 -1
- package/dist/BaseIntegrationConnector.js +15 -0
- package/dist/BaseIntegrationConnector.js.map +1 -1
- package/dist/CustomColumnPromotion.d.ts.map +1 -1
- package/dist/CustomColumnPromotion.js +3 -1
- package/dist/CustomColumnPromotion.js.map +1 -1
- package/dist/IntegrationEngine.d.ts +103 -1
- package/dist/IntegrationEngine.d.ts.map +1 -1
- package/dist/IntegrationEngine.js +366 -82
- package/dist/IntegrationEngine.js.map +1 -1
- package/dist/IntegrationSchemaSync.d.ts +2 -0
- package/dist/IntegrationSchemaSync.d.ts.map +1 -1
- package/dist/IntegrationSchemaSync.js +13 -1
- package/dist/IntegrationSchemaSync.js.map +1 -1
- package/dist/MatchEngine.d.ts.map +1 -1
- package/dist/MatchEngine.js +2 -1
- package/dist/MatchEngine.js.map +1 -1
- package/dist/RecordMapBatch.d.ts +5 -1
- package/dist/RecordMapBatch.d.ts.map +1 -1
- package/dist/RecordMapBatch.js +6 -2
- package/dist/RecordMapBatch.js.map +1 -1
- package/dist/tsconfig.tsbuildinfo +1 -0
- package/dist/types.d.ts +8 -1
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/package.json +7 -7
|
@@ -92,13 +92,18 @@ const FULL_PUSH_MAX_RECORDS = (() => {
|
|
|
92
92
|
* "Could not find stored procedure" errors that drown the run report.
|
|
93
93
|
*/
|
|
94
94
|
export class SchemaNotGeneratedError extends Error {
|
|
95
|
-
constructor(entityName, storedProcedureName) {
|
|
96
|
-
super(
|
|
97
|
-
`'${
|
|
98
|
-
|
|
95
|
+
constructor(entityName, storedProcedureName, reason = 'Missing') {
|
|
96
|
+
super(reason === 'Stale'
|
|
97
|
+
? `Schema out of date for entity '${entityName}': the signature of stored procedure ` +
|
|
98
|
+
`'${storedProcedureName}' does not match the entity's fields. ` +
|
|
99
|
+
`Run CodeGen for this entity to regenerate its procedures, then re-sync.`
|
|
100
|
+
: `Schema not generated for entity '${entityName}': stored procedure ` +
|
|
101
|
+
`'${storedProcedureName}' does not exist in the database. ` +
|
|
102
|
+
`Run CodeGen for this entity to create the destination tables/views/procs, then re-sync.`);
|
|
99
103
|
this.name = 'SchemaNotGeneratedError';
|
|
100
104
|
this.EntityName = entityName;
|
|
101
105
|
this.StoredProcedureName = storedProcedureName;
|
|
106
|
+
this.Reason = reason;
|
|
102
107
|
}
|
|
103
108
|
}
|
|
104
109
|
/**
|
|
@@ -172,17 +177,6 @@ const INTEGER_SQL_BOUNDS = {
|
|
|
172
177
|
integer: { min: -2147483648, max: 2147483647 },
|
|
173
178
|
bigint: { min: -9223372036854775808, max: 9223372036854775807 },
|
|
174
179
|
};
|
|
175
|
-
/**
|
|
176
|
-
* Returns a SchemaNotGeneratedError if the given Save() failure message matches the
|
|
177
|
-
* "CRUD routine doesn't exist yet" pattern for either dialect, otherwise null. When
|
|
178
|
-
* CodeGen hasn't created the spCreate/spUpdate/spDelete for an entity, BaseEntity.Save()
|
|
179
|
-
* returns false and the routine-not-found error lands in LatestResult.CompleteMessage:
|
|
180
|
-
* - SQL Server: `Could not find stored procedure '<schema>.<name>'`
|
|
181
|
-
* - PostgreSQL: `function <schema>.<name>(<args>) does not exist` (SQLSTATE 42883)
|
|
182
|
-
* The PG form is what a connector entity in a custom schema hits before its CRUD
|
|
183
|
-
* functions are generated, so it must be classified too (else the run produces
|
|
184
|
-
* per-record errors instead of one fail-fast SchemaNotGeneratedError).
|
|
185
|
-
*/
|
|
186
180
|
/**
|
|
187
181
|
* The one primary-key shape a TransactionGroup cannot carry: a SINGLE auto-increment column.
|
|
188
182
|
*
|
|
@@ -201,10 +195,30 @@ function IsIdentityOnlyPrimaryKey(primaryKeys) {
|
|
|
201
195
|
const pks = primaryKeys ?? [];
|
|
202
196
|
return pks.length === 1 && pks[0]?.AutoIncrement === true;
|
|
203
197
|
}
|
|
204
|
-
|
|
198
|
+
/**
|
|
199
|
+
* Returns a SchemaNotGeneratedError if the given Save() failure message shows the entity's CRUD
|
|
200
|
+
* routine is missing or stale for either dialect, otherwise null. When CodeGen hasn't created the
|
|
201
|
+
* spCreate/spUpdate/spDelete for an entity, BaseEntity.Save() returns false and the
|
|
202
|
+
* routine-not-found error lands in LatestResult.CompleteMessage:
|
|
203
|
+
* - SQL Server: `Could not find stored procedure '<schema>.<name>'`
|
|
204
|
+
* - PostgreSQL: `function <schema>.<name>(<args>) does not exist` (SQLSTATE 42883)
|
|
205
|
+
* The PG form is what a connector entity in a custom schema hits before its CRUD
|
|
206
|
+
* functions are generated, so it must be classified too (else the run produces
|
|
207
|
+
* per-record errors instead of one fail-fast SchemaNotGeneratedError).
|
|
208
|
+
*
|
|
209
|
+
* A STALE routine (#4433) — one generated before columns were added to or removed from the entity —
|
|
210
|
+
* fails every write identically too, so it is classified the same way (Reason 'Stale'):
|
|
211
|
+
* - SQL Server: `Procedure or function '<name>' has too many arguments specified`
|
|
212
|
+
* - SQL Server: `Procedure or function '<name>' expects parameter '@x', which was not supplied`
|
|
213
|
+
* - PostgreSQL: a wrong-arity call already surfaces as `function ... does not exist` above.
|
|
214
|
+
*/
|
|
215
|
+
export function DetectSchemaNotGenerated(entityName, errorMessage) {
|
|
205
216
|
const sqlServer = errorMessage.match(/Could not find stored procedure '([^']+)'/i);
|
|
206
217
|
if (sqlServer)
|
|
207
218
|
return new SchemaNotGeneratedError(entityName, sqlServer[1]);
|
|
219
|
+
const staleArity = errorMessage.match(/Procedure or function '([^']+)' (?:has too many arguments specified|expects parameter '[^']+', which was not supplied)/i);
|
|
220
|
+
if (staleArity)
|
|
221
|
+
return new SchemaNotGeneratedError(entityName, staleArity[1], 'Stale');
|
|
208
222
|
const postgres = errorMessage.match(/function\s+([^(\s]+)\s*\([^)]*\)\s+does not exist/i);
|
|
209
223
|
if (postgres)
|
|
210
224
|
return new SchemaNotGeneratedError(entityName, postgres[1]);
|
|
@@ -228,6 +242,41 @@ function detectSchemaNotGenerated(entityName, errorMessage) {
|
|
|
228
242
|
export function PositiveInt(v) {
|
|
229
243
|
return typeof v === 'number' && Number.isFinite(v) && v > 0 ? Math.floor(v) : undefined;
|
|
230
244
|
}
|
|
245
|
+
/** The integration tombstone columns; an entity with neither cannot be archived (#3528). */
|
|
246
|
+
export const TOMBSTONE_COLUMNS = ['__mj_integration_IsTombstoned', '__mj_integration_SyncStatus'];
|
|
247
|
+
/** True when an entity has at least one integration tombstone column, so SoftDelete can actually archive it. */
|
|
248
|
+
export function CanArchive(fields) {
|
|
249
|
+
return (fields ?? []).some(f => TOMBSTONE_COLUMNS.includes(f.Name));
|
|
250
|
+
}
|
|
251
|
+
/** Default safety cap on pages fetched per object per run; Configuration `maxBatchesPerMap` overrides it. */
|
|
252
|
+
export const DEFAULT_MAX_BATCHES_PER_MAP = 5000;
|
|
253
|
+
/** Operator message for an object that hit the per-run page cap (#4823). Names the two settings that fix it. */
|
|
254
|
+
export function BuildBatchCapMessage(objectName, cap, batchSize) {
|
|
255
|
+
return `Safety limit reached: ${cap} batches of ${batchSize} for '${objectName}'. The object was not fully ` +
|
|
256
|
+
`fetched, so the run is marked failed; the watermark advances only past the batches that finished. Raise 'batchSize' or 'maxBatchesPerMap' ` +
|
|
257
|
+
`in this connection's Configuration if the object really holds more than ${cap * batchSize} rows.`;
|
|
258
|
+
}
|
|
259
|
+
/**
|
|
260
|
+
* A run failed when any record errored OR any Critical error was recorded. The second half matters
|
|
261
|
+
* for errors that stop a whole object without failing a record — a missing or stale CRUD routine
|
|
262
|
+
* (#4433), or the page cap (#4823) — which previously let the run end `Success`.
|
|
263
|
+
*/
|
|
264
|
+
export function RunFailed(result) {
|
|
265
|
+
return result.RecordsErrored > 0 || result.Errors.some(e => e.Severity === 'Critical');
|
|
266
|
+
}
|
|
267
|
+
/**
|
|
268
|
+
* Moves an ISO timestamp watermark back by `seconds` (#3085). An unparseable value is returned unchanged:
|
|
269
|
+
* the overlap is an optimisation for late commits, never a reason to fail or widen to a full fetch.
|
|
270
|
+
*/
|
|
271
|
+
export function SubtractWatermarkSeconds(watermark, seconds) {
|
|
272
|
+
// A zoneless ISO date-time means UTC, as in the external-data-source connectors (ParseIso8601AsUtc):
|
|
273
|
+
// Date.parse would read it as server-local time and move the filter by the server's offset.
|
|
274
|
+
const zoneless = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?$/.test(watermark);
|
|
275
|
+
const ms = Date.parse(zoneless ? `${watermark}Z` : watermark);
|
|
276
|
+
if (Number.isNaN(ms))
|
|
277
|
+
return watermark;
|
|
278
|
+
return new Date(ms - seconds * 1000).toISOString();
|
|
279
|
+
}
|
|
231
280
|
/**
|
|
232
281
|
* How many deferred writes may accumulate in one batched group before it is submitted and replaced.
|
|
233
282
|
*
|
|
@@ -1725,7 +1774,9 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
1725
1774
|
Report: plan => logger?.warning('sync', plan.Exhausted ? 'HOST_MEMORY_EXHAUSTED' : 'HOST_MEMORY_PRESSURE', plan.Exhausted
|
|
1726
1775
|
? `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.`
|
|
1727
1776
|
: `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 })
|
|
1728
|
-
},
|
|
1777
|
+
},
|
|
1778
|
+
// Configuration `batchSize` (#4823) wins over the engine-wide default.
|
|
1779
|
+
this.getConfigOverrides(config).batchSize ?? this.MaxBatchSize);
|
|
1729
1780
|
// Second-layer silent-empty detection state (see checkSecondLayerEmpty): a per-IO running
|
|
1730
1781
|
// record count + the FK dependency graph, so an association/dependent object that fetches
|
|
1731
1782
|
// ZERO records while it HAS parents is surfaced as a structured SyncWarning. Layers run
|
|
@@ -2273,12 +2324,43 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
2273
2324
|
fetchTimeoutMs: PositiveInt(p.fetchTimeoutMs),
|
|
2274
2325
|
// Ceiling on SIMULTANEOUS vendor fetches for this connection (see getFetchGate).
|
|
2275
2326
|
fetchConcurrency: PositiveInt(p.fetchConcurrency),
|
|
2327
|
+
// Page size asked of the connector for this connection (#4823). Starts the run's
|
|
2328
|
+
// governor here instead of at the engine-wide MaxBatchSize.
|
|
2329
|
+
batchSize: PositiveInt(p.batchSize),
|
|
2330
|
+
// Safety cap on pages per object per run (#4823). Reaching it FAILS the run.
|
|
2331
|
+
maxBatchesPerMap: PositiveInt(p.maxBatchesPerMap),
|
|
2332
|
+
// Overlap for monotonic timestamp watermarks (#3085). 0 is a real value (no overlap).
|
|
2333
|
+
watermarkLookbackSeconds: p.watermarkLookbackSeconds === 0 ? 0 : PositiveInt(p.watermarkLookbackSeconds),
|
|
2276
2334
|
};
|
|
2277
2335
|
}
|
|
2278
2336
|
catch {
|
|
2279
2337
|
return {};
|
|
2280
2338
|
}
|
|
2281
2339
|
}
|
|
2340
|
+
/**
|
|
2341
|
+
* #3085 — the watermark the FETCH filter uses, moved back by the lookback window for a connector
|
|
2342
|
+
* whose watermark is a monotonic max timestamp. Such a connector narrows the next incremental to
|
|
2343
|
+
* exactly the last max seen, so a row that commits late with a LOWER timestamp than that max is
|
|
2344
|
+
* never fetched. Re-reading a short overlap is cheap (the upsert is idempotent and content-hash
|
|
2345
|
+
* skips unchanged rows).
|
|
2346
|
+
*
|
|
2347
|
+
* Source order: Configuration `watermarkLookbackSeconds` → connector `WatermarkLookbackSeconds`.
|
|
2348
|
+
* Non-monotonic connectors and non-timestamp watermarks are returned unchanged.
|
|
2349
|
+
*/
|
|
2350
|
+
applyWatermarkLookback(config, entityMap, watermarkType, watermark) {
|
|
2351
|
+
if (!watermark || !config.connector.MonotonicWatermark)
|
|
2352
|
+
return watermark;
|
|
2353
|
+
const lookbackSeconds = this.getConfigOverrides(config).watermarkLookbackSeconds
|
|
2354
|
+
?? config.connector.WatermarkLookbackSeconds;
|
|
2355
|
+
if (!lookbackSeconds || lookbackSeconds <= 0)
|
|
2356
|
+
return watermark;
|
|
2357
|
+
if (watermarkType !== 'Timestamp') {
|
|
2358
|
+
console.debug(`[IntegrationEngine] ${entityMap.ExternalObjectName}: watermark lookback skipped — ` +
|
|
2359
|
+
`watermark type '${watermarkType}' is not a timestamp.`);
|
|
2360
|
+
return watermark;
|
|
2361
|
+
}
|
|
2362
|
+
return SubtractWatermarkSeconds(watermark, lookbackSeconds);
|
|
2363
|
+
}
|
|
2282
2364
|
getRateLimiter(config) {
|
|
2283
2365
|
const key = config.companyIntegration.ID;
|
|
2284
2366
|
let rl = this._rateLimiters.get(key);
|
|
@@ -2455,6 +2537,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
2455
2537
|
* Pull sync: fetch from external → map → match → validate → apply to MJ.
|
|
2456
2538
|
*/
|
|
2457
2539
|
async processPullSync(config, entityMap, run, contextUser, entityMapIndex, totalEntityMaps, onProgress, abortSignal, logger) {
|
|
2540
|
+
this.softDeleteUnsupportedWarned.delete(entityMap.ID); // SOFT_DELETE_UNSUPPORTED warns once per map per run
|
|
2458
2541
|
const entityMapID = entityMap.ID;
|
|
2459
2542
|
// An object this ACCOUNT cannot serve costs a request, an error event and a retry ladder
|
|
2460
2543
|
// every run, forever, and says nothing new after the first time. While the marker is fresh
|
|
@@ -2565,6 +2648,10 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
2565
2648
|
};
|
|
2566
2649
|
let hasMore = true;
|
|
2567
2650
|
let currentWatermark = initialWatermark;
|
|
2651
|
+
// #3085: the FETCH filter may start a little before the saved watermark so a row that
|
|
2652
|
+
// committed late with a lower timestamp is still picked up. Only the filter moves; the
|
|
2653
|
+
// value compared and persisted below is still `initialWatermark` / `currentWatermark`.
|
|
2654
|
+
const fetchWatermark = this.applyWatermarkLookback(config, entityMap, watermark?.WatermarkType ?? 'Timestamp', initialWatermark);
|
|
2568
2655
|
// §10 — the watermark ALWAYS advances to the max value seen on a clean fetch; it is NEVER held back
|
|
2569
2656
|
// by a per-record failure. A failed record is classified: a PROVABLY-TRANSIENT save error is retried
|
|
2570
2657
|
// inline within the batch (ApplyRecords); a PERMANENT (or retry-exhausted) failure is dead-lettered —
|
|
@@ -2616,7 +2703,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
2616
2703
|
* governor moved it would skip or re-read a page.
|
|
2617
2704
|
*/
|
|
2618
2705
|
const askedBatchSize = () => config.memoryControl?.BatchSize ?? this.MaxBatchSize;
|
|
2619
|
-
const MAX_BATCHES_PER_MAP =
|
|
2706
|
+
const MAX_BATCHES_PER_MAP = this.getConfigOverrides(config).maxBatchesPerMap ?? DEFAULT_MAX_BATCHES_PER_MAP;
|
|
2620
2707
|
const EMPTY_BATCH_WARN_THRESHOLD = 5; // warn once after this many empty-but-HasMore batches in a row
|
|
2621
2708
|
const fetchedExternalIDs = new Set(); // Track all IDs seen during this pull for orphan detection
|
|
2622
2709
|
let orphanTrackingOverflowed = false; // set if the ID set exceeds ORPHAN_DETECTION_MAX_IDS → skip the sweep, don't OOM
|
|
@@ -2650,8 +2737,19 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
2650
2737
|
}
|
|
2651
2738
|
batchCount++;
|
|
2652
2739
|
if (batchCount > MAX_BATCHES_PER_MAP) {
|
|
2653
|
-
|
|
2654
|
-
|
|
2740
|
+
// #4823: this used to log and stop, and the run reported success — a snapshot
|
|
2741
|
+
// connector then restarted from the top every run and never finished the object.
|
|
2742
|
+
// It is now a Critical error, so the run ends Failed; the watermark covers only finished batches.
|
|
2743
|
+
const capMessage = BuildBatchCapMessage(entityMap.ExternalObjectName, MAX_BATCHES_PER_MAP, askedBatchSize());
|
|
2744
|
+
console.error(`[IntegrationEngine] ${capMessage}`);
|
|
2745
|
+
result.Errors.push({
|
|
2746
|
+
ExternalID: entityMap.ExternalObjectName,
|
|
2747
|
+
ChangeType: 'Skip',
|
|
2748
|
+
ErrorMessage: capMessage,
|
|
2749
|
+
ErrorCode: 'BATCH_CAP_REACHED',
|
|
2750
|
+
Severity: 'Critical',
|
|
2751
|
+
});
|
|
2752
|
+
this.markIncomplete(result, entityMap.ExternalObjectName ?? entityMap.ID);
|
|
2655
2753
|
fetchCompletedCleanly = false;
|
|
2656
2754
|
break;
|
|
2657
2755
|
}
|
|
@@ -2671,7 +2769,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
2671
2769
|
// visited it. Observed live (ACR dev, 2026-09-07): a Vendor Bill full scan collapsed
|
|
2672
2770
|
// to 707 of 23,558 rows — an id-ascending-AND-modstamp-ascending subsequence — with
|
|
2673
2771
|
// the run still reporting success. `currentWatermark` remains persistence bookkeeping.
|
|
2674
|
-
WatermarkValue:
|
|
2772
|
+
WatermarkValue: fetchWatermark,
|
|
2675
2773
|
BatchSize: requestedThisBatch,
|
|
2676
2774
|
ContextUser: contextUser,
|
|
2677
2775
|
CurrentPage: currentPage,
|
|
@@ -3736,7 +3834,8 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
3736
3834
|
}
|
|
3737
3835
|
// Persist the new external ID so future syncs update instead of re-creating
|
|
3738
3836
|
if (createResult.ExternalID) {
|
|
3739
|
-
await this.saveRecordMap(config.companyIntegration.ID, createResult.ExternalID, entityMap.EntityID, change.RecordID, contextUser
|
|
3837
|
+
await this.saveRecordMap(config.companyIntegration.ID, createResult.ExternalID, entityMap.EntityID, change.RecordID, contextUser, 'Adopted' // the MJ row existed before this push mapped it
|
|
3838
|
+
);
|
|
3740
3839
|
result.RecordsCreated++;
|
|
3741
3840
|
}
|
|
3742
3841
|
else {
|
|
@@ -3968,26 +4067,26 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
3968
4067
|
await this.deleteRecordMapRow(orphan.ID, contextUser);
|
|
3969
4068
|
continue;
|
|
3970
4069
|
}
|
|
3971
|
-
|
|
3972
|
-
|
|
3973
|
-
|
|
3974
|
-
|
|
3975
|
-
|
|
3976
|
-
|
|
3977
|
-
|
|
3978
|
-
|
|
3979
|
-
if (
|
|
3980
|
-
entity.Set('__mj_integration_LastSyncedAt', new Date().toISOString());
|
|
3981
|
-
if (hasField('__mj_integration_IsTombstoned'))
|
|
3982
|
-
entity.Set('__mj_integration_IsTombstoned', true);
|
|
3983
|
-
if (hasField('__mj_integration_DeletedDetectedAt'))
|
|
3984
|
-
entity.Set('__mj_integration_DeletedDetectedAt', new Date().toISOString());
|
|
3985
|
-
const archived = await entity.Save(this.syncSaveOptions);
|
|
3986
|
-
if (archived) {
|
|
4070
|
+
// #3528 — a row the integration ADOPTED (it existed before the sync matched it) is never
|
|
4071
|
+
// hard-deleted: a source deletion is no proof it may go. It is archived when the entity can
|
|
4072
|
+
// be archived, else left alone with a warning.
|
|
4073
|
+
const adopted = orphan.Origin === 'Adopted';
|
|
4074
|
+
if (entityMap.DeleteBehavior === 'SoftDelete' || adopted) {
|
|
4075
|
+
// The MAP row goes once archived — the mapping's job is done, and keeping it would
|
|
4076
|
+
// re-detect this orphan forever. A refused archive keeps both row and map.
|
|
4077
|
+
const outcome = await this.archiveRecord(entity, entityMap, logger);
|
|
4078
|
+
if (outcome === 'archived') {
|
|
3987
4079
|
result.RecordsDeleted++;
|
|
3988
4080
|
await this.deleteRecordMapRow(orphan.ID, contextUser);
|
|
3989
4081
|
console.log(`[IntegrationEngine] Archived orphan ${entityMap.Entity} ${orphan.EntityRecordID} (external ${orphan.ExternalSystemRecordID} no longer exists)`);
|
|
3990
4082
|
}
|
|
4083
|
+
else if (outcome === 'refused') {
|
|
4084
|
+
result.RecordsSkipped++;
|
|
4085
|
+
if (adopted && entityMap.DeleteBehavior === 'HardDelete') {
|
|
4086
|
+
logger?.warning(entityMap.ExternalObjectName ?? entityMap.ID, 'ADOPTED_ROW_KEPT', `${entityMap.Entity} ${orphan.EntityRecordID} was not created by this integration (it was matched to an existing row), ` +
|
|
4087
|
+
`so it is not hard-deleted, and the entity has no tombstone columns to archive it.`, { entityRecordID: orphan.EntityRecordID, externalID: orphan.ExternalSystemRecordID });
|
|
4088
|
+
}
|
|
4089
|
+
}
|
|
3991
4090
|
else {
|
|
3992
4091
|
const reason = entity.LatestResult?.CompleteMessage ?? 'unknown reason';
|
|
3993
4092
|
console.warn(`[IntegrationEngine] Orphan archive blocked for ${entityMap.Entity} ${orphan.EntityRecordID} — ${reason}`);
|
|
@@ -4017,13 +4116,16 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
4017
4116
|
* swallowed: the orphan itself was handled, and the worst consequence of a surviving map
|
|
4018
4117
|
* row is one redundant re-detection on the next full sync.
|
|
4019
4118
|
*/
|
|
4020
|
-
async deleteRecordMapRow(mapRowID, contextUser) {
|
|
4119
|
+
async deleteRecordMapRow(mapRowID, contextUser, inWriteGroup = false) {
|
|
4021
4120
|
try {
|
|
4022
4121
|
const md = this.ProviderToUse;
|
|
4023
4122
|
const mapRow = await md.GetEntityObject('MJ: Company Integration Record Maps', contextUser);
|
|
4024
4123
|
const loaded = await mapRow.InnerLoad(CompositeKey.FromID(mapRowID));
|
|
4025
4124
|
if (!loaded)
|
|
4026
4125
|
return;
|
|
4126
|
+
// From the apply pass, the prune commits or rolls back with the row delete it follows.
|
|
4127
|
+
if (inWriteGroup)
|
|
4128
|
+
this.enrolInWriteGroup(mapRow);
|
|
4027
4129
|
const ok = await mapRow.Delete();
|
|
4028
4130
|
if (!ok) {
|
|
4029
4131
|
console.warn(`[IntegrationEngine] Record-map prune blocked for ${mapRowID} — ${mapRow.LatestResult?.CompleteMessage ?? 'unknown reason'}`);
|
|
@@ -4175,6 +4277,111 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
4175
4277
|
}
|
|
4176
4278
|
return resolution.Resolved;
|
|
4177
4279
|
}
|
|
4280
|
+
/**
|
|
4281
|
+
* #5202 — true when the source marks this record deleted: the entity map's Configuration names a
|
|
4282
|
+
* `sourceDeleteField` and the record's value for it equals `sourceDeleteValue` (both compared as
|
|
4283
|
+
* trimmed strings). Sources like NetForum flag deletions on a live row instead of dropping it.
|
|
4284
|
+
*/
|
|
4285
|
+
isSourceFlaggedDeleted(record, entityMap) {
|
|
4286
|
+
const flag = this.sourceDeleteFlag(entityMap);
|
|
4287
|
+
if (!flag)
|
|
4288
|
+
return false;
|
|
4289
|
+
const value = record.ExternalRecord.Fields?.[flag.Field];
|
|
4290
|
+
if (value === undefined || value === null)
|
|
4291
|
+
return false;
|
|
4292
|
+
return String(value).trim() === flag.Value;
|
|
4293
|
+
}
|
|
4294
|
+
/** The entity map's source delete flag (#5202), or null when its Configuration does not name one. */
|
|
4295
|
+
sourceDeleteFlag(entityMap) {
|
|
4296
|
+
const cfg = this.parseEntityMapConfig(entityMap);
|
|
4297
|
+
const field = typeof cfg?.sourceDeleteField === 'string' ? cfg.sourceDeleteField.trim() : '';
|
|
4298
|
+
if (!field || cfg?.sourceDeleteValue === undefined || cfg.sourceDeleteValue === null)
|
|
4299
|
+
return null;
|
|
4300
|
+
return { Field: field, Value: String(cfg.sourceDeleteValue).trim() };
|
|
4301
|
+
}
|
|
4302
|
+
/** True when the entity map's Configuration names a source delete flag (#5202). */
|
|
4303
|
+
hasSourceDeleteFlag(entityMap) {
|
|
4304
|
+
return this.sourceDeleteFlag(entityMap) !== null;
|
|
4305
|
+
}
|
|
4306
|
+
/** True when a loaded row already carries the tombstone: IsTombstoned, or SyncStatus 'Archived' without it. */
|
|
4307
|
+
isArchived(entity, has) {
|
|
4308
|
+
if (has('__mj_integration_IsTombstoned'))
|
|
4309
|
+
return entity.Get('__mj_integration_IsTombstoned') === true;
|
|
4310
|
+
if (has('__mj_integration_SyncStatus'))
|
|
4311
|
+
return entity.Get('__mj_integration_SyncStatus') === 'Archived';
|
|
4312
|
+
return true; // nothing to tombstone with — no write can change that
|
|
4313
|
+
}
|
|
4314
|
+
/**
|
|
4315
|
+
* #5202 under HardDelete — the source flags a matched record deleted. The record map's `Origin` decides,
|
|
4316
|
+
* the same way the orphan sweep does (#3528):
|
|
4317
|
+
* - `Created` (the sync inserted the row): delete it and prune its map, so later syncs that still see
|
|
4318
|
+
* the flagged row skip it instead of matching a row that is gone. A row already gone counts as
|
|
4319
|
+
* skipped and its map is pruned too.
|
|
4320
|
+
* - `Adopted`, or no map row (matched by key fields, so it existed before the sync): never hard-deleted.
|
|
4321
|
+
* It is archived, or kept with `ADOPTED_ROW_KEPT` when the entity has no tombstone columns. Its map is
|
|
4322
|
+
* kept, so a row already archived is skipped without a write and a cleared flag brings it back.
|
|
4323
|
+
*/
|
|
4324
|
+
async applySourceFlaggedHardDelete(record, companyIntegration, entityMap, result, contextUser, logger) {
|
|
4325
|
+
if (!record.MatchedMJRecordID) {
|
|
4326
|
+
result.RecordsSkipped++;
|
|
4327
|
+
return;
|
|
4328
|
+
}
|
|
4329
|
+
const mapRow = await this.findRecordMapRow(companyIntegration.ID, entityMap.EntityID, record.ExternalRecord.ExternalID, contextUser);
|
|
4330
|
+
if (mapRow && mapRow.Origin !== 'Adopted') {
|
|
4331
|
+
const outcome = await this.deleteRecord(record, entityMap, contextUser, logger);
|
|
4332
|
+
if (outcome === 'deleted' || outcome === 'gone') {
|
|
4333
|
+
await this.deleteRecordMapRow(mapRow.ID, contextUser, true);
|
|
4334
|
+
}
|
|
4335
|
+
if (outcome === 'deleted')
|
|
4336
|
+
result.RecordsDeleted++;
|
|
4337
|
+
else if (outcome === 'gone' || outcome === 'refused')
|
|
4338
|
+
result.RecordsSkipped++;
|
|
4339
|
+
else
|
|
4340
|
+
result.RecordsErrored++;
|
|
4341
|
+
return;
|
|
4342
|
+
}
|
|
4343
|
+
const md = this.ProviderToUse;
|
|
4344
|
+
const entity = await md.GetEntityObject(record.MJEntityName, contextUser);
|
|
4345
|
+
this.enrolInWriteGroup(entity);
|
|
4346
|
+
const pkFields = md.EntityByName(record.MJEntityName)?.PrimaryKeys ?? [];
|
|
4347
|
+
const loaded = await entity.InnerLoad(this.buildEntityPrimaryKey(record.MatchedMJRecordID, pkFields));
|
|
4348
|
+
const fields = entity.Fields ?? [];
|
|
4349
|
+
if (!loaded || (CanArchive(fields) && this.isArchived(entity, n => fields.some(f => f.Name === n)))) {
|
|
4350
|
+
result.RecordsSkipped++;
|
|
4351
|
+
return;
|
|
4352
|
+
}
|
|
4353
|
+
const outcome = await this.archiveRecord(entity, entityMap, logger);
|
|
4354
|
+
if (outcome === 'archived') {
|
|
4355
|
+
result.RecordsDeleted++;
|
|
4356
|
+
}
|
|
4357
|
+
else if (outcome === 'refused') {
|
|
4358
|
+
result.RecordsSkipped++;
|
|
4359
|
+
logger?.warning(entityMap.ExternalObjectName ?? entityMap.ID, 'ADOPTED_ROW_KEPT', `${record.MJEntityName} ${record.MatchedMJRecordID} was not created by this integration (it was matched to an existing row), ` +
|
|
4360
|
+
`so it is not hard-deleted, and the entity has no tombstone columns to archive it.`, { entityRecordID: record.MatchedMJRecordID, externalID: record.ExternalRecord.ExternalID });
|
|
4361
|
+
}
|
|
4362
|
+
else {
|
|
4363
|
+
result.RecordsErrored++;
|
|
4364
|
+
console.warn(`[IntegrationEngine] Archive of adopted ${record.MJEntityName} ${record.MatchedMJRecordID} failed — ${entity.LatestResult?.CompleteMessage ?? 'unknown reason'}`);
|
|
4365
|
+
}
|
|
4366
|
+
}
|
|
4367
|
+
/** The record map row for one external record, or null when there is none (or the read failed). */
|
|
4368
|
+
async findRecordMapRow(companyIntegrationID, entityID, externalID, contextUser) {
|
|
4369
|
+
const md = this.ProviderToUse;
|
|
4370
|
+
const quotedExternalID = md instanceof DatabaseProviderBase
|
|
4371
|
+
? QuoteTextLiteral(externalID, md.Dialect)
|
|
4372
|
+
: `'${externalID.replace(/'/g, "''")}'`;
|
|
4373
|
+
const rv = new RunView();
|
|
4374
|
+
const existing = await rv.RunView({
|
|
4375
|
+
EntityName: 'MJ: Company Integration Record Maps',
|
|
4376
|
+
ExtraFilter: `CompanyIntegrationID='${companyIntegrationID}' AND EntityID='${entityID}' AND ExternalSystemRecordID=${quotedExternalID}`,
|
|
4377
|
+
Fields: ['ID', 'Origin'],
|
|
4378
|
+
MaxRows: 1,
|
|
4379
|
+
SkipTotalRowCount: true,
|
|
4380
|
+
ResultType: 'simple',
|
|
4381
|
+
BypassCache: true,
|
|
4382
|
+
}, contextUser);
|
|
4383
|
+
return existing.Success && existing.Results.length > 0 ? existing.Results[0] : null;
|
|
4384
|
+
}
|
|
4178
4385
|
/** Opt-in partition (Merkle) reconcile flag from the entity map Configuration (GQL-managed). */
|
|
4179
4386
|
isPartitionReconcileEnabled(entityMap) {
|
|
4180
4387
|
return this.parseEntityMapConfig(entityMap)?.partitionReconcile === true;
|
|
@@ -4303,7 +4510,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
4303
4510
|
// used to spend three round trips per record establishing a mapping now queues into this
|
|
4304
4511
|
// and the queue is flushed set-based once the batch has settled — the single largest cost
|
|
4305
4512
|
// in a no-change sync.
|
|
4306
|
-
const recordMaps = new RecordMapBatch(this.ProviderToUse, companyIntegration.ID, contextUser, (ciID, extID, entID, recID, user) => this.saveRecordMap(ciID, extID, entID, recID, user));
|
|
4513
|
+
const recordMaps = new RecordMapBatch(this.ProviderToUse, companyIntegration.ID, contextUser, (ciID, extID, entID, recID, user, origin) => this.saveRecordMap(ciID, extID, entID, recID, user, origin));
|
|
4307
4514
|
for (let i = 0; i < records.length; i += APPLY_BATCH_SIZE) {
|
|
4308
4515
|
const batch = records.slice(i, i + APPLY_BATCH_SIZE);
|
|
4309
4516
|
const batchStartProcessed = result.RecordsProcessed;
|
|
@@ -4787,6 +4994,25 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
4787
4994
|
c: result.RecordsCreated, u: result.RecordsUpdated,
|
|
4788
4995
|
d: result.RecordsDeleted, s: result.RecordsSkipped,
|
|
4789
4996
|
};
|
|
4997
|
+
// #5202 — the source flags this record deleted. DoNothing writes it as before; SoftDelete writes it
|
|
4998
|
+
// tombstoned (inserting it tombstoned when MJ has no row yet, so history stays queryable); HardDelete
|
|
4999
|
+
// removes an existing row the sync created, archives an adopted one, and skips the insert of a new one.
|
|
5000
|
+
if (record.ChangeType !== 'Delete' && record.ChangeType !== 'Skip' && this.isSourceFlaggedDeleted(record, entityMap)) {
|
|
5001
|
+
if (entityMap.DeleteBehavior === 'HardDelete') {
|
|
5002
|
+
await this.applySourceFlaggedHardDelete(record, companyIntegration, entityMap, result, contextUser, logger);
|
|
5003
|
+
return;
|
|
5004
|
+
}
|
|
5005
|
+
if (entityMap.DeleteBehavior === 'SoftDelete') {
|
|
5006
|
+
// Same rule as the orphan sweep: an entity with no tombstone columns cannot be archived, so
|
|
5007
|
+
// the row is written live and the map warns once per run instead of failing silently.
|
|
5008
|
+
if (CanArchive(this.ProviderToUse.EntityByName(record.MJEntityName)?.Fields)) {
|
|
5009
|
+
record.SourceDeleted = true;
|
|
5010
|
+
}
|
|
5011
|
+
else {
|
|
5012
|
+
this.warnSoftDeleteUnsupported(entityMap, logger);
|
|
5013
|
+
}
|
|
5014
|
+
}
|
|
5015
|
+
}
|
|
4790
5016
|
try {
|
|
4791
5017
|
switch (record.ChangeType) {
|
|
4792
5018
|
case 'Create': {
|
|
@@ -4803,9 +5029,11 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
4803
5029
|
await this.updateRecord(record, companyIntegration, entityMap, result, contextUser, precheckHashes, reconciledSkipIds, recordMaps, logger);
|
|
4804
5030
|
break;
|
|
4805
5031
|
case 'Delete': {
|
|
4806
|
-
const
|
|
4807
|
-
if (
|
|
5032
|
+
const outcome = await this.deleteRecord(record, entityMap, contextUser, logger);
|
|
5033
|
+
if (outcome === 'deleted')
|
|
4808
5034
|
result.RecordsDeleted++;
|
|
5035
|
+
else if (outcome === 'refused' || outcome === 'gone')
|
|
5036
|
+
result.RecordsSkipped++;
|
|
4809
5037
|
else
|
|
4810
5038
|
result.RecordsErrored++;
|
|
4811
5039
|
break;
|
|
@@ -4922,11 +5150,12 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
4922
5150
|
// integration column is the sanctioned access here — these runtime-created tables have no
|
|
4923
5151
|
// generated entity type (the engine already .Set()s the same __mj_integration_* columns).
|
|
4924
5152
|
const hasHashColumn = entityInfo?.Fields.some(f => f.Name === CONTENT_HASH_COLUMN) ?? false;
|
|
4925
|
-
|
|
5153
|
+
// The hash covers mapped fields only, so it cannot see a source delete flag change (#5202).
|
|
5154
|
+
if (hasHashColumn && !this.hasSourceDeleteFlag(entityMap)) {
|
|
4926
5155
|
const storedHash = entity.Get(CONTENT_HASH_COLUMN);
|
|
4927
5156
|
if (typeof storedHash === 'string' && storedHash.length > 0
|
|
4928
5157
|
&& storedHash === ComputeContentHash(record.MappedFields ?? {})) {
|
|
4929
|
-
await this.queueRecordMap(recordMaps, companyIntegration.ID, record.ExternalRecord.ExternalID, entityMap.EntityID, entity.PrimaryKey.KeyValuePairs.map(kv => String(kv.Value)).join('|'), contextUser);
|
|
5158
|
+
await this.queueRecordMap(recordMaps, companyIntegration.ID, record.ExternalRecord.ExternalID, entityMap.EntityID, entity.PrimaryKey.KeyValuePairs.map(kv => String(kv.Value)).join('|'), contextUser, 'Adopted');
|
|
4930
5159
|
return 'skipped';
|
|
4931
5160
|
}
|
|
4932
5161
|
}
|
|
@@ -4936,7 +5165,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
4936
5165
|
// and the integration LastSynced columns untouched, exactly like the content-hash skip path.
|
|
4937
5166
|
this.setEntityFields(entity, record.MappedFields);
|
|
4938
5167
|
if (!entity.Dirty && !this.needsSyncStateRepair(entity, entityInfo, record)) {
|
|
4939
|
-
await this.queueRecordMap(recordMaps, companyIntegration.ID, record.ExternalRecord.ExternalID, entityMap.EntityID, entity.PrimaryKey.KeyValuePairs.map(kv => String(kv.Value)).join('|'), contextUser);
|
|
5168
|
+
await this.queueRecordMap(recordMaps, companyIntegration.ID, record.ExternalRecord.ExternalID, entityMap.EntityID, entity.PrimaryKey.KeyValuePairs.map(kv => String(kv.Value)).join('|'), contextUser, 'Adopted');
|
|
4940
5169
|
return 'skipped';
|
|
4941
5170
|
}
|
|
4942
5171
|
}
|
|
@@ -4950,7 +5179,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
4950
5179
|
const saved = await entity.Save(this.syncSaveOptions);
|
|
4951
5180
|
if (!saved) {
|
|
4952
5181
|
const errMsg = entity.LatestResult?.CompleteMessage ?? 'unknown error';
|
|
4953
|
-
const schemaErr =
|
|
5182
|
+
const schemaErr = DetectSchemaNotGenerated(record.MJEntityName, errMsg);
|
|
4954
5183
|
if (schemaErr)
|
|
4955
5184
|
throw schemaErr;
|
|
4956
5185
|
throw new Error(`Failed to ${existed ? 'update' : 'create'} ${record.MJEntityName} record: ${errMsg}`);
|
|
@@ -4972,7 +5201,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
4972
5201
|
if (!existed && mappedPK != null && precheck) {
|
|
4973
5202
|
precheck.Present.add(mappedPK);
|
|
4974
5203
|
}
|
|
4975
|
-
await this.queueRecordMap(recordMaps, companyIntegration.ID, record.ExternalRecord.ExternalID, entityMap.EntityID, entityRecordID, contextUser);
|
|
5204
|
+
await this.queueRecordMap(recordMaps, companyIntegration.ID, record.ExternalRecord.ExternalID, entityMap.EntityID, entityRecordID, contextUser, existed ? 'Adopted' : 'Created');
|
|
4976
5205
|
return existed ? 'updated' : 'created';
|
|
4977
5206
|
}
|
|
4978
5207
|
/**
|
|
@@ -5040,7 +5269,9 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
5040
5269
|
// computed hash of the incoming mapped fields, the record is provably
|
|
5041
5270
|
// unchanged — skip the per-record DB load AND the write. The dirty-flag check
|
|
5042
5271
|
// below is the fallback for entities without the hash column.
|
|
5043
|
-
|
|
5272
|
+
// Not when the map has a source delete flag (#5202): the hash covers mapped fields only, so a flag
|
|
5273
|
+
// that was set or cleared with no mapped field changing would be skipped here.
|
|
5274
|
+
if (precheckHashes && !this.hasSourceDeleteFlag(entityMap)) {
|
|
5044
5275
|
const stored = precheckHashes.Hashes.get(record.MatchedMJRecordID);
|
|
5045
5276
|
if (stored && stored === ComputeContentHash(record.MappedFields ?? {})) {
|
|
5046
5277
|
result.RecordsSkipped++;
|
|
@@ -5055,7 +5286,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
5055
5286
|
// (CompanyIntegration, Entity, ExternalID) — idempotent for already-mapped records, and the
|
|
5056
5287
|
// CreateRecord skip branches already do exactly this. MatchedMJRecordID IS the dest PK
|
|
5057
5288
|
// (PrimaryKeys order, '|'-joined), which is the EntityRecordID the map stores.
|
|
5058
|
-
await this.queueRecordMap(recordMaps, companyIntegration.ID, record.ExternalRecord.ExternalID, entityMap.EntityID, record.MatchedMJRecordID, contextUser);
|
|
5289
|
+
await this.queueRecordMap(recordMaps, companyIntegration.ID, record.ExternalRecord.ExternalID, entityMap.EntityID, record.MatchedMJRecordID, contextUser, 'Adopted');
|
|
5059
5290
|
// The record IS still present and confirmed-unchanged on the source — but skipping
|
|
5060
5291
|
// the write here means SetStandardIntegrationFields never runs, so __mj_integration_
|
|
5061
5292
|
// LastReconciledAt would freeze at first-sync time. Record the PK so the batch can
|
|
@@ -5103,7 +5334,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
5103
5334
|
// above for the full rationale (a key-field/PK match can land here with no map row, and
|
|
5104
5335
|
// dropping the map silently breaks the 1:1 completeness invariant + orphan detection).
|
|
5105
5336
|
// The entity is loaded here, so use its actual PK as the EntityRecordID. Idempotent upsert.
|
|
5106
|
-
await this.queueRecordMap(recordMaps, companyIntegration.ID, record.ExternalRecord.ExternalID, entityMap.EntityID, entity.PrimaryKey.KeyValuePairs.map(kv => String(kv.Value)).join('|'), contextUser);
|
|
5337
|
+
await this.queueRecordMap(recordMaps, companyIntegration.ID, record.ExternalRecord.ExternalID, entityMap.EntityID, entity.PrimaryKey.KeyValuePairs.map(kv => String(kv.Value)).join('|'), contextUser, 'Adopted');
|
|
5107
5338
|
// Same reasoning as the content-hash skip: the record IS confirmed present on the
|
|
5108
5339
|
// source, so let the batch refresh LastReconciledAt in one set-based touch rather
|
|
5109
5340
|
// than rewriting the row for a timestamp.
|
|
@@ -5117,7 +5348,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
5117
5348
|
const saved = await entity.Save(this.syncSaveOptions);
|
|
5118
5349
|
if (!saved) {
|
|
5119
5350
|
const errMsg = entity.LatestResult?.CompleteMessage ?? 'unknown error';
|
|
5120
|
-
const schemaErr =
|
|
5351
|
+
const schemaErr = DetectSchemaNotGenerated(record.MJEntityName, errMsg);
|
|
5121
5352
|
if (schemaErr)
|
|
5122
5353
|
throw schemaErr;
|
|
5123
5354
|
throw new Error(`Failed to update ${record.MJEntityName} record ${record.MatchedMJRecordID}: ${errMsg}`);
|
|
@@ -5128,7 +5359,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
5128
5359
|
// rows and orphan/delete detection silently degrades. SaveRecordMap is an upsert keyed on
|
|
5129
5360
|
// (CompanyIntegration, Entity, ExternalID), so this is idempotent for already-mapped records.
|
|
5130
5361
|
const entityRecordID = entity.PrimaryKey.KeyValuePairs.map(kv => String(kv.Value)).join('|');
|
|
5131
|
-
await this.queueRecordMap(recordMaps, companyIntegration.ID, record.ExternalRecord.ExternalID, entityMap.EntityID, entityRecordID, contextUser);
|
|
5362
|
+
await this.queueRecordMap(recordMaps, companyIntegration.ID, record.ExternalRecord.ExternalID, entityMap.EntityID, entityRecordID, contextUser, 'Adopted');
|
|
5132
5363
|
result.RecordsUpdated++;
|
|
5133
5364
|
}
|
|
5134
5365
|
/**
|
|
@@ -5250,14 +5481,19 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
5250
5481
|
}
|
|
5251
5482
|
/**
|
|
5252
5483
|
* Deletes (or soft-deletes) an MJ record based on the entity map's DeleteBehavior.
|
|
5484
|
+
*
|
|
5485
|
+
* @returns `deleted` when the row was removed or archived; `refused` when SoftDelete cannot archive
|
|
5486
|
+
* because the entity has no tombstone columns (#3528 — reported once per map per run, not counted as a
|
|
5487
|
+
* delete); `gone` when the matched row no longer exists in MJ (already deleted — nothing to do, not an
|
|
5488
|
+
* error); `failed` otherwise (no map entry, DoNothing, or the write failed).
|
|
5253
5489
|
*/
|
|
5254
|
-
async deleteRecord(record, entityMap, contextUser) {
|
|
5490
|
+
async deleteRecord(record, entityMap, contextUser, logger) {
|
|
5255
5491
|
if (!record.MatchedMJRecordID) {
|
|
5256
5492
|
console.log(`[IntegrationEngine] Skipping delete for ${record.ExternalRecord.ObjectType} ExternalID=${record.ExternalRecord.ExternalID} — no MJ record map entry (record was never synced)`);
|
|
5257
|
-
return
|
|
5493
|
+
return 'failed';
|
|
5258
5494
|
}
|
|
5259
5495
|
if (entityMap.DeleteBehavior === 'DoNothing')
|
|
5260
|
-
return
|
|
5496
|
+
return 'failed';
|
|
5261
5497
|
const md = this.ProviderToUse;
|
|
5262
5498
|
const entity = await md.GetEntityObject(record.MJEntityName, contextUser);
|
|
5263
5499
|
this.enrolInWriteGroup(entity);
|
|
@@ -5266,37 +5502,61 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
5266
5502
|
const loaded = await entity.InnerLoad(this.buildEntityPrimaryKey(record.MatchedMJRecordID, pkFields));
|
|
5267
5503
|
if (!loaded) {
|
|
5268
5504
|
console.log(`[IntegrationEngine] Skipping delete for ${record.MJEntityName} ${record.MatchedMJRecordID} — record not found in MJ DB (may have been deleted already)`);
|
|
5269
|
-
return
|
|
5505
|
+
return 'gone';
|
|
5270
5506
|
}
|
|
5271
|
-
// SoftDelete = mark the mirror row Archived
|
|
5272
|
-
// removed upstream) and keep it; HardDelete physically removes it. (DoNothing
|
|
5273
|
-
// already returned above.) Previously both behaviors hit entity.Delete() — so
|
|
5274
|
-
// SoftDelete was indistinguishable from HardDelete.
|
|
5507
|
+
// SoftDelete = mark the mirror row Archived and keep it; HardDelete physically removes it.
|
|
5275
5508
|
if (entityMap.DeleteBehavior === 'SoftDelete') {
|
|
5276
|
-
const
|
|
5277
|
-
|
|
5278
|
-
if (hasField('__mj_integration_SyncStatus'))
|
|
5279
|
-
entity.Set('__mj_integration_SyncStatus', 'Archived');
|
|
5280
|
-
if (hasField('__mj_integration_LastSyncedAt'))
|
|
5281
|
-
entity.Set('__mj_integration_LastSyncedAt', new Date().toISOString());
|
|
5282
|
-
// Explicit, queryable tombstone (plan §2.5) — distinct from parsing SyncStatus='Archived'.
|
|
5283
|
-
if (hasField('__mj_integration_IsTombstoned'))
|
|
5284
|
-
entity.Set('__mj_integration_IsTombstoned', true);
|
|
5285
|
-
if (hasField('__mj_integration_DeletedDetectedAt'))
|
|
5286
|
-
entity.Set('__mj_integration_DeletedDetectedAt', new Date().toISOString());
|
|
5287
|
-
const archived = await entity.Save(this.syncSaveOptions);
|
|
5288
|
-
if (!archived) {
|
|
5509
|
+
const outcome = await this.archiveRecord(entity, entityMap, logger);
|
|
5510
|
+
if (outcome === 'failed') {
|
|
5289
5511
|
const reason = entity.LatestResult?.CompleteMessage ?? 'unknown reason';
|
|
5290
5512
|
console.warn(`[IntegrationEngine] Soft-delete (archive) failed for ${record.MJEntityName} ${record.MatchedMJRecordID} — ${reason}`);
|
|
5291
5513
|
}
|
|
5292
|
-
return archived;
|
|
5514
|
+
return outcome === 'archived' ? 'deleted' : outcome;
|
|
5293
5515
|
}
|
|
5294
5516
|
const deleted = await entity.Delete(this.syncDeleteOptions);
|
|
5295
5517
|
if (!deleted) {
|
|
5296
5518
|
const reason = entity.LatestResult?.CompleteMessage ?? 'unknown reason';
|
|
5297
5519
|
console.warn(`[IntegrationEngine] Delete blocked for ${record.MJEntityName} ${record.MatchedMJRecordID} — ${reason}`);
|
|
5298
5520
|
}
|
|
5299
|
-
return deleted;
|
|
5521
|
+
return deleted ? 'deleted' : 'failed';
|
|
5522
|
+
}
|
|
5523
|
+
get softDeleteUnsupportedWarned() {
|
|
5524
|
+
return (this._softDeleteUnsupportedWarned ??= new Set());
|
|
5525
|
+
}
|
|
5526
|
+
/**
|
|
5527
|
+
* Archives a loaded row: SyncStatus 'Archived', IsTombstoned, and DeletedDetectedAt stamped once (#3528).
|
|
5528
|
+
*
|
|
5529
|
+
* An entity with none of the tombstone columns cannot be archived — setting nothing and saving a clean
|
|
5530
|
+
* entity used to "succeed" and count a delete that never happened. Such a row is refused: no save, no
|
|
5531
|
+
* count, no record-map prune, and one `SOFT_DELETE_UNSUPPORTED` warning per map per run.
|
|
5532
|
+
*/
|
|
5533
|
+
async archiveRecord(entity, entityMap, logger) {
|
|
5534
|
+
const fields = entity.Fields ?? [];
|
|
5535
|
+
if (!CanArchive(fields)) {
|
|
5536
|
+
this.warnSoftDeleteUnsupported(entityMap, logger);
|
|
5537
|
+
return 'refused';
|
|
5538
|
+
}
|
|
5539
|
+
const hasField = (n) => fields.some(f => f.Name === n);
|
|
5540
|
+
const now = new Date().toISOString();
|
|
5541
|
+
if (hasField('__mj_integration_SyncStatus'))
|
|
5542
|
+
entity.Set('__mj_integration_SyncStatus', 'Archived');
|
|
5543
|
+
if (hasField('__mj_integration_LastSyncedAt'))
|
|
5544
|
+
entity.Set('__mj_integration_LastSyncedAt', now);
|
|
5545
|
+
if (hasField('__mj_integration_IsTombstoned'))
|
|
5546
|
+
entity.Set('__mj_integration_IsTombstoned', true);
|
|
5547
|
+
if (hasField('__mj_integration_DeletedDetectedAt') && !entity.Get('__mj_integration_DeletedDetectedAt')) {
|
|
5548
|
+
entity.Set('__mj_integration_DeletedDetectedAt', now);
|
|
5549
|
+
}
|
|
5550
|
+
return (await entity.Save(this.syncSaveOptions)) ? 'archived' : 'failed';
|
|
5551
|
+
}
|
|
5552
|
+
warnSoftDeleteUnsupported(entityMap, logger) {
|
|
5553
|
+
if (this.softDeleteUnsupportedWarned.has(entityMap.ID))
|
|
5554
|
+
return;
|
|
5555
|
+
this.softDeleteUnsupportedWarned.add(entityMap.ID);
|
|
5556
|
+
const message = `${entityMap.Entity} has no integration tombstone columns, so SoftDelete cannot archive its rows; ` +
|
|
5557
|
+
`nothing was deleted. Set DeleteBehavior to DoNothing or HardDelete, or add the columns.`;
|
|
5558
|
+
console.warn(`[IntegrationEngine] ${message}`);
|
|
5559
|
+
logger?.warning(entityMap.ExternalObjectName ?? entityMap.ID, 'SOFT_DELETE_UNSUPPORTED', message, { entity: entityMap.Entity });
|
|
5300
5560
|
}
|
|
5301
5561
|
/**
|
|
5302
5562
|
* Builds a CompositeKey for a record lookup using the entity's PK field definitions.
|
|
@@ -5518,6 +5778,10 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
5518
5778
|
if (!entityInfo)
|
|
5519
5779
|
return false;
|
|
5520
5780
|
const has = (name) => entityInfo.Fields.some(f => f.Name === name);
|
|
5781
|
+
// #5202 — a source-flagged row needs a write until it is tombstoned, and none once it is. This comes
|
|
5782
|
+
// first: the tombstone and SyncStatus checks below would otherwise rewrite it on every sync.
|
|
5783
|
+
if (record?.SourceDeleted)
|
|
5784
|
+
return !this.isArchived(entity, has);
|
|
5521
5785
|
if (has('__mj_integration_IsTombstoned') && entity.Get('__mj_integration_IsTombstoned') === true)
|
|
5522
5786
|
return true;
|
|
5523
5787
|
if (has('__mj_integration_SyncMessage') && entity.Get('__mj_integration_SyncMessage') != null)
|
|
@@ -5622,11 +5886,27 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
5622
5886
|
if (hasField('__mj_integration_LastWriterDirection')) {
|
|
5623
5887
|
entity.Set('__mj_integration_LastWriterDirection', 'Pull');
|
|
5624
5888
|
}
|
|
5889
|
+
// #5202 — the source flags this record deleted under SoftDelete: write it tombstoned, keeping the
|
|
5890
|
+
// first DeletedDetectedAt across syncs that still see the flag.
|
|
5891
|
+
if (record.SourceDeleted) {
|
|
5892
|
+
if (hasField('__mj_integration_SyncStatus'))
|
|
5893
|
+
entity.Set('__mj_integration_SyncStatus', 'Archived');
|
|
5894
|
+
if (hasField('__mj_integration_IsTombstoned'))
|
|
5895
|
+
entity.Set('__mj_integration_IsTombstoned', true);
|
|
5896
|
+
if (hasField('__mj_integration_DeletedDetectedAt') && !entity.Get('__mj_integration_DeletedDetectedAt')) {
|
|
5897
|
+
entity.Set('__mj_integration_DeletedDetectedAt', new Date().toISOString());
|
|
5898
|
+
}
|
|
5899
|
+
return;
|
|
5900
|
+
}
|
|
5625
5901
|
// A live (non-deleted) record. The soft-delete path flips this to true + stamps
|
|
5626
5902
|
// DeletedDetectedAt — an explicit, queryable tombstone instead of parsing SyncStatus text.
|
|
5903
|
+
// A row coming back to life also clears DeletedDetectedAt, so the tombstone reads as one fact.
|
|
5627
5904
|
if (hasField('__mj_integration_IsTombstoned')) {
|
|
5628
5905
|
entity.Set('__mj_integration_IsTombstoned', false);
|
|
5629
5906
|
}
|
|
5907
|
+
if (hasField('__mj_integration_DeletedDetectedAt') && entity.Get('__mj_integration_DeletedDetectedAt')) {
|
|
5908
|
+
entity.Set('__mj_integration_DeletedDetectedAt', null);
|
|
5909
|
+
}
|
|
5630
5910
|
}
|
|
5631
5911
|
/**
|
|
5632
5912
|
* Reads EVERY record-map row for a (CompanyIntegration, Entity) pair, in pages.
|
|
@@ -5680,7 +5960,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
5680
5960
|
const page = await rv.RunView({
|
|
5681
5961
|
EntityName: 'MJ: Company Integration Record Maps',
|
|
5682
5962
|
ExtraFilter: filter,
|
|
5683
|
-
Fields: ['ID', 'EntityRecordID', 'ExternalSystemRecordID'],
|
|
5963
|
+
Fields: ['ID', 'EntityRecordID', 'ExternalSystemRecordID', 'Origin'],
|
|
5684
5964
|
// Keyset requires the sort to be on the PK alone; it is also what makes the seek
|
|
5685
5965
|
// below well-defined.
|
|
5686
5966
|
OrderBy: 'ID ASC',
|
|
@@ -5726,20 +6006,20 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
5726
6006
|
* decides not to change. The `recordMaps` parameter is optional so that callers outside the
|
|
5727
6007
|
* batched apply pass (and every existing test) keep the original immediate-write behaviour.
|
|
5728
6008
|
*/
|
|
5729
|
-
async queueRecordMap(recordMaps, companyIntegrationID, externalID, entityID, entityRecordID, contextUser) {
|
|
6009
|
+
async queueRecordMap(recordMaps, companyIntegrationID, externalID, entityID, entityRecordID, contextUser, origin) {
|
|
5730
6010
|
if (recordMaps) {
|
|
5731
6011
|
// Queue only — the apply loop flushes after the batch transaction commits. Writing here
|
|
5732
6012
|
// (or auto-flushing on a full chunk) would put map rows inside a transaction that
|
|
5733
6013
|
// Discard() can no longer take back on rollback.
|
|
5734
|
-
recordMaps.Queue({ EntityID: entityID, ExternalID: externalID, EntityRecordID: entityRecordID });
|
|
6014
|
+
recordMaps.Queue({ EntityID: entityID, ExternalID: externalID, EntityRecordID: entityRecordID, Origin: origin });
|
|
5735
6015
|
return;
|
|
5736
6016
|
}
|
|
5737
|
-
await this.saveRecordMap(companyIntegrationID, externalID, entityID, entityRecordID, contextUser);
|
|
6017
|
+
await this.saveRecordMap(companyIntegrationID, externalID, entityID, entityRecordID, contextUser, origin);
|
|
5738
6018
|
}
|
|
5739
6019
|
/**
|
|
5740
6020
|
* Creates or updates a CompanyIntegrationRecordMap entry to track the external↔MJ mapping.
|
|
5741
6021
|
*/
|
|
5742
|
-
async saveRecordMap(companyIntegrationID, externalID, entityID, entityRecordID, contextUser) {
|
|
6022
|
+
async saveRecordMap(companyIntegrationID, externalID, entityID, entityRecordID, contextUser, origin) {
|
|
5743
6023
|
const md = this.ProviderToUse;
|
|
5744
6024
|
const recordMap = await md.GetEntityObject('MJ: Company Integration Record Maps', contextUser);
|
|
5745
6025
|
// Upsert by identity: one row per (CompanyIntegration, Entity, external record).
|
|
@@ -5771,11 +6051,15 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
5771
6051
|
if (existing.Results[0].EntityRecordID === entityRecordID)
|
|
5772
6052
|
return;
|
|
5773
6053
|
const loaded = await recordMap.Load(existing.Results[0].ID);
|
|
5774
|
-
if (!loaded)
|
|
6054
|
+
if (!loaded) {
|
|
5775
6055
|
recordMap.NewRecord();
|
|
6056
|
+
recordMap.Origin = origin;
|
|
6057
|
+
}
|
|
5776
6058
|
}
|
|
5777
6059
|
else {
|
|
5778
6060
|
recordMap.NewRecord();
|
|
6061
|
+
// An existing mapping keeps the origin it was written with (#3528).
|
|
6062
|
+
recordMap.Origin = origin;
|
|
5779
6063
|
}
|
|
5780
6064
|
recordMap.CompanyIntegrationID = companyIntegrationID;
|
|
5781
6065
|
recordMap.ExternalSystemRecordID = externalID;
|
|
@@ -5987,7 +6271,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
5987
6271
|
run.ErrorLog = result.ErrorMessage ?? 'Sync cancelled by user';
|
|
5988
6272
|
}
|
|
5989
6273
|
else {
|
|
5990
|
-
terminalStatus = result
|
|
6274
|
+
terminalStatus = RunFailed(result) ? 'Failed' : 'Success';
|
|
5991
6275
|
if (result.Errors.length > 0) {
|
|
5992
6276
|
run.ErrorLog = JSON.stringify(result.Errors.slice(0, 100));
|
|
5993
6277
|
}
|