@memberjunction/integration-engine 6.2.2 → 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 +137 -1
- package/dist/IntegrationEngine.d.ts.map +1 -1
- package/dist/IntegrationEngine.js +499 -89
- 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 +48 -10
- 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/RecordFilter.d.ts +53 -0
- package/dist/RecordFilter.d.ts.map +1 -0
- package/dist/RecordFilter.js +64 -0
- package/dist/RecordFilter.js.map +1 -0
- 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/ReferenceResolver.d.ts +71 -0
- package/dist/ReferenceResolver.d.ts.map +1 -0
- package/dist/ReferenceResolver.js +145 -0
- package/dist/ReferenceResolver.js.map +1 -0
- package/dist/SyncLogger.d.ts +1 -1
- package/dist/SyncLogger.d.ts.map +1 -1
- package/dist/SyncLogger.js.map +1 -1
- package/dist/index.d.ts +5 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -1
- package/dist/index.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
|
@@ -2,7 +2,7 @@ import { AsyncLocalStorage } from 'node:async_hooks';
|
|
|
2
2
|
import { RefreshCatalogScope, RunInWarmedCatalogScope, UnpinCatalogObjects, WarmCatalogObject } from './CatalogScope.js';
|
|
3
3
|
import { CompositeKey, DatabaseProviderBase, LogStatusEx, Metadata, RunView, EntitySaveOptions, EntityDeleteOptions } from '@memberjunction/core';
|
|
4
4
|
import { RunOwnershipLostError, RunOwnershipService } from './RunOwnershipService.js';
|
|
5
|
-
import { BaseSingleton, NormalizeUUID, UUIDsEqual } from '@memberjunction/global';
|
|
5
|
+
import { BaseSingleton, EscapeSQLString, NormalizeUUID, UUIDsEqual } from '@memberjunction/global';
|
|
6
6
|
import { IntegrationEngineBase } from '@memberjunction/integration-engine-base';
|
|
7
7
|
import { ClassifyError, IsRetryableError } from './types.js';
|
|
8
8
|
import { WithRetry } from './RetryRunner.js';
|
|
@@ -29,6 +29,8 @@ import { AdaptiveConcurrencyController, RunAdaptive } from './AdaptiveConcurrenc
|
|
|
29
29
|
import { mostRecentWinner } from './ConflictRecency.js';
|
|
30
30
|
import { IntegrationProgressEmitter } from '@memberjunction/integration-progress-artifacts';
|
|
31
31
|
import { CollapseDuplicateIdentities } from './BatchIdentity.js';
|
|
32
|
+
import { ApplyRecordFilter, ParseRecordFilter } from './RecordFilter.js';
|
|
33
|
+
import { ApplyResolvedReferences, DescribeUnresolvedReference, LoadReferenceLookups, ParseReferenceFields, } from './ReferenceResolver.js';
|
|
32
34
|
import { WriteSerializer } from './WriteSerializer.js';
|
|
33
35
|
import { ResumeConcurrency, RunResumesBounded } from './ResumeConcurrency.js';
|
|
34
36
|
/** Default batch size for fetching records from external systems */
|
|
@@ -90,13 +92,18 @@ const FULL_PUSH_MAX_RECORDS = (() => {
|
|
|
90
92
|
* "Could not find stored procedure" errors that drown the run report.
|
|
91
93
|
*/
|
|
92
94
|
export class SchemaNotGeneratedError extends Error {
|
|
93
|
-
constructor(entityName, storedProcedureName) {
|
|
94
|
-
super(
|
|
95
|
-
`'${
|
|
96
|
-
|
|
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.`);
|
|
97
103
|
this.name = 'SchemaNotGeneratedError';
|
|
98
104
|
this.EntityName = entityName;
|
|
99
105
|
this.StoredProcedureName = storedProcedureName;
|
|
106
|
+
this.Reason = reason;
|
|
100
107
|
}
|
|
101
108
|
}
|
|
102
109
|
/**
|
|
@@ -170,17 +177,6 @@ const INTEGER_SQL_BOUNDS = {
|
|
|
170
177
|
integer: { min: -2147483648, max: 2147483647 },
|
|
171
178
|
bigint: { min: -9223372036854775808, max: 9223372036854775807 },
|
|
172
179
|
};
|
|
173
|
-
/**
|
|
174
|
-
* Returns a SchemaNotGeneratedError if the given Save() failure message matches the
|
|
175
|
-
* "CRUD routine doesn't exist yet" pattern for either dialect, otherwise null. When
|
|
176
|
-
* CodeGen hasn't created the spCreate/spUpdate/spDelete for an entity, BaseEntity.Save()
|
|
177
|
-
* returns false and the routine-not-found error lands in LatestResult.CompleteMessage:
|
|
178
|
-
* - SQL Server: `Could not find stored procedure '<schema>.<name>'`
|
|
179
|
-
* - PostgreSQL: `function <schema>.<name>(<args>) does not exist` (SQLSTATE 42883)
|
|
180
|
-
* The PG form is what a connector entity in a custom schema hits before its CRUD
|
|
181
|
-
* functions are generated, so it must be classified too (else the run produces
|
|
182
|
-
* per-record errors instead of one fail-fast SchemaNotGeneratedError).
|
|
183
|
-
*/
|
|
184
180
|
/**
|
|
185
181
|
* The one primary-key shape a TransactionGroup cannot carry: a SINGLE auto-increment column.
|
|
186
182
|
*
|
|
@@ -199,10 +195,30 @@ function IsIdentityOnlyPrimaryKey(primaryKeys) {
|
|
|
199
195
|
const pks = primaryKeys ?? [];
|
|
200
196
|
return pks.length === 1 && pks[0]?.AutoIncrement === true;
|
|
201
197
|
}
|
|
202
|
-
|
|
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) {
|
|
203
216
|
const sqlServer = errorMessage.match(/Could not find stored procedure '([^']+)'/i);
|
|
204
217
|
if (sqlServer)
|
|
205
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');
|
|
206
222
|
const postgres = errorMessage.match(/function\s+([^(\s]+)\s*\([^)]*\)\s+does not exist/i);
|
|
207
223
|
if (postgres)
|
|
208
224
|
return new SchemaNotGeneratedError(entityName, postgres[1]);
|
|
@@ -226,6 +242,41 @@ function detectSchemaNotGenerated(entityName, errorMessage) {
|
|
|
226
242
|
export function PositiveInt(v) {
|
|
227
243
|
return typeof v === 'number' && Number.isFinite(v) && v > 0 ? Math.floor(v) : undefined;
|
|
228
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
|
+
}
|
|
229
280
|
/**
|
|
230
281
|
* How many deferred writes may accumulate in one batched group before it is submitted and replaced.
|
|
231
282
|
*
|
|
@@ -1723,7 +1774,9 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
1723
1774
|
Report: plan => logger?.warning('sync', plan.Exhausted ? 'HOST_MEMORY_EXHAUSTED' : 'HOST_MEMORY_PRESSURE', plan.Exhausted
|
|
1724
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.`
|
|
1725
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 })
|
|
1726
|
-
},
|
|
1777
|
+
},
|
|
1778
|
+
// Configuration `batchSize` (#4823) wins over the engine-wide default.
|
|
1779
|
+
this.getConfigOverrides(config).batchSize ?? this.MaxBatchSize);
|
|
1727
1780
|
// Second-layer silent-empty detection state (see checkSecondLayerEmpty): a per-IO running
|
|
1728
1781
|
// record count + the FK dependency graph, so an association/dependent object that fetches
|
|
1729
1782
|
// ZERO records while it HAS parents is surfaced as a structured SyncWarning. Layers run
|
|
@@ -2271,12 +2324,43 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
2271
2324
|
fetchTimeoutMs: PositiveInt(p.fetchTimeoutMs),
|
|
2272
2325
|
// Ceiling on SIMULTANEOUS vendor fetches for this connection (see getFetchGate).
|
|
2273
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),
|
|
2274
2334
|
};
|
|
2275
2335
|
}
|
|
2276
2336
|
catch {
|
|
2277
2337
|
return {};
|
|
2278
2338
|
}
|
|
2279
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
|
+
}
|
|
2280
2364
|
getRateLimiter(config) {
|
|
2281
2365
|
const key = config.companyIntegration.ID;
|
|
2282
2366
|
let rl = this._rateLimiters.get(key);
|
|
@@ -2414,16 +2498,54 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
2414
2498
|
if (!list.includes(objectName))
|
|
2415
2499
|
list.push(objectName);
|
|
2416
2500
|
}
|
|
2501
|
+
/**
|
|
2502
|
+
* The result for a pull map that has no active field maps, returned BEFORE anything is fetched.
|
|
2503
|
+
*
|
|
2504
|
+
* Such a map cannot write a single column, so everything fetched for it is wasted: a soft-key
|
|
2505
|
+
* table refuses every record (`KEYLESS_RECORD_REFUSED`, because the key is the first field the
|
|
2506
|
+
* engine finds unmapped) and any other table gets rows with nothing in them. Observed on a
|
|
2507
|
+
* per-connection NetForum catalog: 292 maps were created with no field maps, and the first sync
|
|
2508
|
+
* that reached them fetched and refused 307,843 records until the refusals ran the API out of heap.
|
|
2509
|
+
*
|
|
2510
|
+
* The skip is reported where the run keeps its history, not only on the event stream: one
|
|
2511
|
+
* Critical `CONFIGURATION_ERROR` (the run's ErrorLog is written from `Errors`) and the object on
|
|
2512
|
+
* the incomplete list. No record is counted, because none was read.
|
|
2513
|
+
*/
|
|
2514
|
+
skipMapWithoutFieldMaps(entityMap, logger) {
|
|
2515
|
+
const objectName = entityMap.ExternalObjectName ?? entityMap.ID;
|
|
2516
|
+
const message = `'${objectName}' has no active field maps, so nothing fetched for it could be written. It was ` +
|
|
2517
|
+
`skipped without fetching. Apply this object again for the connection to create its field maps.`;
|
|
2518
|
+
logger?.Emit('sync.entity-map.skipped', {
|
|
2519
|
+
externalObjectName: entityMap.ExternalObjectName,
|
|
2520
|
+
skippedReason: 'ENTITY_MAP_HAS_NO_FIELD_MAPS',
|
|
2521
|
+
message,
|
|
2522
|
+
});
|
|
2523
|
+
logger?.Warning(objectName, 'ENTITY_MAP_HAS_NO_FIELD_MAPS', message, { entityMapID: entityMap.ID });
|
|
2524
|
+
console.error(`[IntegrationEngine] ENTITY_MAP_HAS_NO_FIELD_MAPS: ${message}`);
|
|
2525
|
+
const result = this.emptyResult();
|
|
2526
|
+
result.Errors.push({
|
|
2527
|
+
ExternalID: '',
|
|
2528
|
+
ChangeType: 'Skip',
|
|
2529
|
+
ErrorMessage: message,
|
|
2530
|
+
ErrorCode: 'CONFIGURATION_ERROR',
|
|
2531
|
+
Severity: 'Critical',
|
|
2532
|
+
});
|
|
2533
|
+
this.markIncomplete(result, objectName);
|
|
2534
|
+
return result;
|
|
2535
|
+
}
|
|
2417
2536
|
/**
|
|
2418
2537
|
* Pull sync: fetch from external → map → match → validate → apply to MJ.
|
|
2419
2538
|
*/
|
|
2420
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
|
|
2421
2541
|
const entityMapID = entityMap.ID;
|
|
2422
2542
|
// An object this ACCOUNT cannot serve costs a request, an error event and a retry ladder
|
|
2423
2543
|
// every run, forever, and says nothing new after the first time. While the marker is fresh
|
|
2424
2544
|
// we spend nothing on it; once it ages out the next attempt IS the recheck, so an object
|
|
2425
2545
|
// the account later enables heals itself with no operator action.
|
|
2426
2546
|
const fieldMaps = await this.loadFieldMaps(entityMapID, contextUser);
|
|
2547
|
+
if (fieldMaps.length === 0)
|
|
2548
|
+
return this.skipMapWithoutFieldMaps(entityMap, logger);
|
|
2427
2549
|
// Field-level exclusions declared by the connector (SourceFieldInfo.SyncDirective
|
|
2428
2550
|
// -> IntegrationObjectField.Configuration). Resolved once per map, applied to every
|
|
2429
2551
|
// batch below. Empty set on any lookup miss - exclusion can only ever narrow.
|
|
@@ -2450,6 +2572,10 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
2450
2572
|
fullSync: config.fullSync,
|
|
2451
2573
|
});
|
|
2452
2574
|
this.warnOnUnbindableFieldMaps(entityMap, fieldMaps, logger);
|
|
2575
|
+
// Record filter and reference resolution are read once per map; a malformed declaration
|
|
2576
|
+
// throws here and fails this map only, before anything is fetched or written.
|
|
2577
|
+
const recordFilter = this.resolveRecordFilter(entityMap);
|
|
2578
|
+
const references = this.resolveReferenceFields(entityMap);
|
|
2453
2579
|
// A6: Validate watermark before using it — skip entirely when FullSync requested
|
|
2454
2580
|
let initialWatermark = config.fullSync ? null : (watermark?.WatermarkValue ?? null);
|
|
2455
2581
|
// The value the ROW held before this run touched it — the retract target if a mid-run
|
|
@@ -2522,6 +2648,10 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
2522
2648
|
};
|
|
2523
2649
|
let hasMore = true;
|
|
2524
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);
|
|
2525
2655
|
// §10 — the watermark ALWAYS advances to the max value seen on a clean fetch; it is NEVER held back
|
|
2526
2656
|
// by a per-record failure. A failed record is classified: a PROVABLY-TRANSIENT save error is retried
|
|
2527
2657
|
// inline within the batch (ApplyRecords); a PERMANENT (or retry-exhausted) failure is dead-lettered —
|
|
@@ -2573,7 +2703,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
2573
2703
|
* governor moved it would skip or re-read a page.
|
|
2574
2704
|
*/
|
|
2575
2705
|
const askedBatchSize = () => config.memoryControl?.BatchSize ?? this.MaxBatchSize;
|
|
2576
|
-
const MAX_BATCHES_PER_MAP =
|
|
2706
|
+
const MAX_BATCHES_PER_MAP = this.getConfigOverrides(config).maxBatchesPerMap ?? DEFAULT_MAX_BATCHES_PER_MAP;
|
|
2577
2707
|
const EMPTY_BATCH_WARN_THRESHOLD = 5; // warn once after this many empty-but-HasMore batches in a row
|
|
2578
2708
|
const fetchedExternalIDs = new Set(); // Track all IDs seen during this pull for orphan detection
|
|
2579
2709
|
let orphanTrackingOverflowed = false; // set if the ID set exceeds ORPHAN_DETECTION_MAX_IDS → skip the sweep, don't OOM
|
|
@@ -2607,8 +2737,19 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
2607
2737
|
}
|
|
2608
2738
|
batchCount++;
|
|
2609
2739
|
if (batchCount > MAX_BATCHES_PER_MAP) {
|
|
2610
|
-
|
|
2611
|
-
|
|
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);
|
|
2612
2753
|
fetchCompletedCleanly = false;
|
|
2613
2754
|
break;
|
|
2614
2755
|
}
|
|
@@ -2628,7 +2769,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
2628
2769
|
// visited it. Observed live (ACR dev, 2026-09-07): a Vendor Bill full scan collapsed
|
|
2629
2770
|
// to 707 of 23,558 rows — an id-ascending-AND-modstamp-ascending subsequence — with
|
|
2630
2771
|
// the run still reporting success. `currentWatermark` remains persistence bookkeeping.
|
|
2631
|
-
WatermarkValue:
|
|
2772
|
+
WatermarkValue: fetchWatermark,
|
|
2632
2773
|
BatchSize: requestedThisBatch,
|
|
2633
2774
|
ContextUser: contextUser,
|
|
2634
2775
|
CurrentPage: currentPage,
|
|
@@ -2950,7 +3091,8 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
2950
3091
|
+ `identity are one source record observed twice; writing both would insert duplicate rows that `
|
|
2951
3092
|
+ `no later sync could reconcile. Sample: ${identity.SampleIDs.join(', ')}`, { object: entityMap.ExternalObjectName, collapsed: identity.Collapsed, sample: identity.SampleIDs });
|
|
2952
3093
|
}
|
|
2953
|
-
const
|
|
3094
|
+
const kept = this.applyRecordFilter(identity.Records, recordFilter, entityMap, result, logger);
|
|
3095
|
+
const mapped = await this.resolveReferences(this.fieldMappingEngine.Apply(kept, fieldMaps, entityMap.Entity, excludedSourceNames), references, config, entityMap, result, contextUser, logger);
|
|
2954
3096
|
// Custom-key stats: aggregate unmapped keys for EVERY mapped record here —
|
|
2955
3097
|
// before any skip decision — so candidates + sizing stats exist even when the
|
|
2956
3098
|
// content-hash fast path skips the row (the hash basis deliberately excludes them).
|
|
@@ -3692,7 +3834,8 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
3692
3834
|
}
|
|
3693
3835
|
// Persist the new external ID so future syncs update instead of re-creating
|
|
3694
3836
|
if (createResult.ExternalID) {
|
|
3695
|
-
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
|
+
);
|
|
3696
3839
|
result.RecordsCreated++;
|
|
3697
3840
|
}
|
|
3698
3841
|
else {
|
|
@@ -3924,26 +4067,26 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
3924
4067
|
await this.deleteRecordMapRow(orphan.ID, contextUser);
|
|
3925
4068
|
continue;
|
|
3926
4069
|
}
|
|
3927
|
-
|
|
3928
|
-
|
|
3929
|
-
|
|
3930
|
-
|
|
3931
|
-
|
|
3932
|
-
|
|
3933
|
-
|
|
3934
|
-
|
|
3935
|
-
if (
|
|
3936
|
-
entity.Set('__mj_integration_LastSyncedAt', new Date().toISOString());
|
|
3937
|
-
if (hasField('__mj_integration_IsTombstoned'))
|
|
3938
|
-
entity.Set('__mj_integration_IsTombstoned', true);
|
|
3939
|
-
if (hasField('__mj_integration_DeletedDetectedAt'))
|
|
3940
|
-
entity.Set('__mj_integration_DeletedDetectedAt', new Date().toISOString());
|
|
3941
|
-
const archived = await entity.Save(this.syncSaveOptions);
|
|
3942
|
-
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') {
|
|
3943
4079
|
result.RecordsDeleted++;
|
|
3944
4080
|
await this.deleteRecordMapRow(orphan.ID, contextUser);
|
|
3945
4081
|
console.log(`[IntegrationEngine] Archived orphan ${entityMap.Entity} ${orphan.EntityRecordID} (external ${orphan.ExternalSystemRecordID} no longer exists)`);
|
|
3946
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
|
+
}
|
|
3947
4090
|
else {
|
|
3948
4091
|
const reason = entity.LatestResult?.CompleteMessage ?? 'unknown reason';
|
|
3949
4092
|
console.warn(`[IntegrationEngine] Orphan archive blocked for ${entityMap.Entity} ${orphan.EntityRecordID} — ${reason}`);
|
|
@@ -3973,13 +4116,16 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
3973
4116
|
* swallowed: the orphan itself was handled, and the worst consequence of a surviving map
|
|
3974
4117
|
* row is one redundant re-detection on the next full sync.
|
|
3975
4118
|
*/
|
|
3976
|
-
async deleteRecordMapRow(mapRowID, contextUser) {
|
|
4119
|
+
async deleteRecordMapRow(mapRowID, contextUser, inWriteGroup = false) {
|
|
3977
4120
|
try {
|
|
3978
4121
|
const md = this.ProviderToUse;
|
|
3979
4122
|
const mapRow = await md.GetEntityObject('MJ: Company Integration Record Maps', contextUser);
|
|
3980
4123
|
const loaded = await mapRow.InnerLoad(CompositeKey.FromID(mapRowID));
|
|
3981
4124
|
if (!loaded)
|
|
3982
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);
|
|
3983
4129
|
const ok = await mapRow.Delete();
|
|
3984
4130
|
if (!ok) {
|
|
3985
4131
|
console.warn(`[IntegrationEngine] Record-map prune blocked for ${mapRowID} — ${mapRow.LatestResult?.CompleteMessage ?? 'unknown reason'}`);
|
|
@@ -4025,17 +4171,25 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
4025
4171
|
}
|
|
4026
4172
|
/**
|
|
4027
4173
|
* Loads active field maps for a given entity map.
|
|
4174
|
+
*
|
|
4175
|
+
* @throws FIELD_MAPS_UNREADABLE when the read fails. An empty answer would read as a map that
|
|
4176
|
+
* HAS no field maps, which the pull path skips as a configuration error and the push path
|
|
4177
|
+
* skips as having nothing to push: a transient read failure must not be reported as either.
|
|
4028
4178
|
*/
|
|
4029
4179
|
async loadFieldMaps(entityMapID, contextUser) {
|
|
4030
4180
|
const rv = new RunView();
|
|
4031
4181
|
const result = await rv.RunView({
|
|
4032
4182
|
EntityName: 'MJ: Company Integration Field Maps',
|
|
4033
|
-
ExtraFilter: `EntityMapID='${entityMapID}' AND Status='Active'`,
|
|
4183
|
+
ExtraFilter: `EntityMapID='${EscapeSQLString(entityMapID)}' AND Status='Active'`,
|
|
4034
4184
|
OrderBy: 'Priority ASC',
|
|
4035
4185
|
ResultType: 'entity_object',
|
|
4036
4186
|
BypassCache: true, // field maps drive value mapping; a sync must see freshly-applied maps
|
|
4037
4187
|
}, contextUser);
|
|
4038
|
-
|
|
4188
|
+
if (!result.Success) {
|
|
4189
|
+
throw new Error(`FIELD_MAPS_UNREADABLE: could not read the field maps of entity map ${entityMapID}: ` +
|
|
4190
|
+
`${result.ErrorMessage ?? 'unknown error'}`);
|
|
4191
|
+
}
|
|
4192
|
+
return result.Results;
|
|
4039
4193
|
}
|
|
4040
4194
|
/** Parses the entity map's Configuration JSON (best-effort) for engine-side feature toggles. */
|
|
4041
4195
|
parseEntityMapConfig(entityMap) {
|
|
@@ -4043,12 +4197,191 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
4043
4197
|
if (!raw)
|
|
4044
4198
|
return null;
|
|
4045
4199
|
try {
|
|
4046
|
-
|
|
4200
|
+
const parsed = JSON.parse(raw);
|
|
4201
|
+
return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : null;
|
|
4047
4202
|
}
|
|
4048
4203
|
catch {
|
|
4049
4204
|
return null;
|
|
4050
4205
|
}
|
|
4051
4206
|
}
|
|
4207
|
+
/** The entity map's record filter (`Configuration.recordFilter`); throws when it is malformed. */
|
|
4208
|
+
resolveRecordFilter(entityMap) {
|
|
4209
|
+
const parsed = ParseRecordFilter(this.parseEntityMapConfig(entityMap));
|
|
4210
|
+
if (parsed.Problems.length > 0) {
|
|
4211
|
+
throw new Error(`Entity map ${entityMap.ExternalObjectName} → ${entityMap.Entity}: ${parsed.Problems.join(' ')}`);
|
|
4212
|
+
}
|
|
4213
|
+
return parsed.Conditions;
|
|
4214
|
+
}
|
|
4215
|
+
/**
|
|
4216
|
+
* The destination fields to resolve from external to MJ ids (`Configuration.resolveReferences`),
|
|
4217
|
+
* each with the entity it points at (ID for the record-map read, name for error messages, both
|
|
4218
|
+
* looked up here once per map rather than per unresolved row). Throws when a field is not a foreign key on the target entity:
|
|
4219
|
+
* without a related entity there is no record map to resolve through.
|
|
4220
|
+
*/
|
|
4221
|
+
resolveReferenceFields(entityMap) {
|
|
4222
|
+
const fields = ParseReferenceFields(this.parseEntityMapConfig(entityMap));
|
|
4223
|
+
if (fields.length === 0)
|
|
4224
|
+
return [];
|
|
4225
|
+
const entityInfo = this.ProviderToUse.EntityByName(entityMap.Entity);
|
|
4226
|
+
if (!entityInfo)
|
|
4227
|
+
throw new Error(`Entity map ${entityMap.ExternalObjectName}: entity ${entityMap.Entity} not found in metadata.`);
|
|
4228
|
+
return fields.map(name => {
|
|
4229
|
+
const field = entityInfo.Fields.find(f => f.Name.toLowerCase() === name.toLowerCase());
|
|
4230
|
+
if (!field?.RelatedEntityID) {
|
|
4231
|
+
throw new Error(`Entity map ${entityMap.ExternalObjectName}: resolveReferences names ${name}, which is not a foreign key on ${entityMap.Entity}.`);
|
|
4232
|
+
}
|
|
4233
|
+
const relatedEntityName = field.RelatedEntity || this.ProviderToUse.EntityByID(field.RelatedEntityID)?.Name || 'parent';
|
|
4234
|
+
return { Field: field.Name, RelatedEntityID: field.RelatedEntityID, RelatedEntityName: relatedEntityName };
|
|
4235
|
+
});
|
|
4236
|
+
}
|
|
4237
|
+
/** Drops the source records the map's filter excludes; each one counts as skipped. */
|
|
4238
|
+
applyRecordFilter(records, conditions, entityMap, result, logger) {
|
|
4239
|
+
const filtered = ApplyRecordFilter(records, conditions);
|
|
4240
|
+
if (filtered.Excluded > 0) {
|
|
4241
|
+
result.RecordsSkipped += filtered.Excluded;
|
|
4242
|
+
logger?.emit('sync.entity-map.filtered', {
|
|
4243
|
+
externalObjectName: entityMap.ExternalObjectName,
|
|
4244
|
+
excluded: filtered.Excluded,
|
|
4245
|
+
kept: filtered.Kept.length,
|
|
4246
|
+
});
|
|
4247
|
+
}
|
|
4248
|
+
return filtered.Kept;
|
|
4249
|
+
}
|
|
4250
|
+
/**
|
|
4251
|
+
* Swaps each configured reference's external id for the parent's MJ id, through this connection's
|
|
4252
|
+
* record maps. A record whose parent has no record map is reported as an error and not written.
|
|
4253
|
+
*/
|
|
4254
|
+
async resolveReferences(mapped, references, config, entityMap, result, contextUser, logger) {
|
|
4255
|
+
if (references.length === 0 || mapped.length === 0)
|
|
4256
|
+
return mapped;
|
|
4257
|
+
const lookups = await this.runWriteForMap(entityMap.ID, () => LoadReferenceLookups(this.ProviderToUse, config.companyIntegration.ID, references, mapped, contextUser));
|
|
4258
|
+
const resolution = ApplyResolvedReferences(mapped, references.map(r => r.Field), lookups);
|
|
4259
|
+
for (const miss of resolution.Unresolved) {
|
|
4260
|
+
const parentName = references.find(r => r.Field === miss.Field)?.RelatedEntityName ?? 'parent';
|
|
4261
|
+
const message = DescribeUnresolvedReference(miss, parentName);
|
|
4262
|
+
result.RecordsErrored++;
|
|
4263
|
+
result.Errors.push({
|
|
4264
|
+
ExternalID: miss.Record.ExternalRecord.ExternalID,
|
|
4265
|
+
ChangeType: miss.Record.ChangeType,
|
|
4266
|
+
ErrorMessage: message,
|
|
4267
|
+
ErrorCode: 'MATCH_RESOLUTION_ERROR',
|
|
4268
|
+
Severity: 'Warning',
|
|
4269
|
+
ExternalRecord: miss.Record.ExternalRecord,
|
|
4270
|
+
});
|
|
4271
|
+
logger?.emit('sync.record.error', {
|
|
4272
|
+
phase: 'resolve-references',
|
|
4273
|
+
externalObjectName: entityMap.ExternalObjectName,
|
|
4274
|
+
externalID: miss.Record.ExternalRecord.ExternalID,
|
|
4275
|
+
error: message,
|
|
4276
|
+
});
|
|
4277
|
+
}
|
|
4278
|
+
return resolution.Resolved;
|
|
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
|
+
}
|
|
4052
4385
|
/** Opt-in partition (Merkle) reconcile flag from the entity map Configuration (GQL-managed). */
|
|
4053
4386
|
isPartitionReconcileEnabled(entityMap) {
|
|
4054
4387
|
return this.parseEntityMapConfig(entityMap)?.partitionReconcile === true;
|
|
@@ -4177,7 +4510,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
4177
4510
|
// used to spend three round trips per record establishing a mapping now queues into this
|
|
4178
4511
|
// and the queue is flushed set-based once the batch has settled — the single largest cost
|
|
4179
4512
|
// in a no-change sync.
|
|
4180
|
-
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));
|
|
4181
4514
|
for (let i = 0; i < records.length; i += APPLY_BATCH_SIZE) {
|
|
4182
4515
|
const batch = records.slice(i, i + APPLY_BATCH_SIZE);
|
|
4183
4516
|
const batchStartProcessed = result.RecordsProcessed;
|
|
@@ -4661,6 +4994,25 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
4661
4994
|
c: result.RecordsCreated, u: result.RecordsUpdated,
|
|
4662
4995
|
d: result.RecordsDeleted, s: result.RecordsSkipped,
|
|
4663
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
|
+
}
|
|
4664
5016
|
try {
|
|
4665
5017
|
switch (record.ChangeType) {
|
|
4666
5018
|
case 'Create': {
|
|
@@ -4677,9 +5029,11 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
4677
5029
|
await this.updateRecord(record, companyIntegration, entityMap, result, contextUser, precheckHashes, reconciledSkipIds, recordMaps, logger);
|
|
4678
5030
|
break;
|
|
4679
5031
|
case 'Delete': {
|
|
4680
|
-
const
|
|
4681
|
-
if (
|
|
5032
|
+
const outcome = await this.deleteRecord(record, entityMap, contextUser, logger);
|
|
5033
|
+
if (outcome === 'deleted')
|
|
4682
5034
|
result.RecordsDeleted++;
|
|
5035
|
+
else if (outcome === 'refused' || outcome === 'gone')
|
|
5036
|
+
result.RecordsSkipped++;
|
|
4683
5037
|
else
|
|
4684
5038
|
result.RecordsErrored++;
|
|
4685
5039
|
break;
|
|
@@ -4796,11 +5150,12 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
4796
5150
|
// integration column is the sanctioned access here — these runtime-created tables have no
|
|
4797
5151
|
// generated entity type (the engine already .Set()s the same __mj_integration_* columns).
|
|
4798
5152
|
const hasHashColumn = entityInfo?.Fields.some(f => f.Name === CONTENT_HASH_COLUMN) ?? false;
|
|
4799
|
-
|
|
5153
|
+
// The hash covers mapped fields only, so it cannot see a source delete flag change (#5202).
|
|
5154
|
+
if (hasHashColumn && !this.hasSourceDeleteFlag(entityMap)) {
|
|
4800
5155
|
const storedHash = entity.Get(CONTENT_HASH_COLUMN);
|
|
4801
5156
|
if (typeof storedHash === 'string' && storedHash.length > 0
|
|
4802
5157
|
&& storedHash === ComputeContentHash(record.MappedFields ?? {})) {
|
|
4803
|
-
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');
|
|
4804
5159
|
return 'skipped';
|
|
4805
5160
|
}
|
|
4806
5161
|
}
|
|
@@ -4810,7 +5165,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
4810
5165
|
// and the integration LastSynced columns untouched, exactly like the content-hash skip path.
|
|
4811
5166
|
this.setEntityFields(entity, record.MappedFields);
|
|
4812
5167
|
if (!entity.Dirty && !this.needsSyncStateRepair(entity, entityInfo, record)) {
|
|
4813
|
-
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');
|
|
4814
5169
|
return 'skipped';
|
|
4815
5170
|
}
|
|
4816
5171
|
}
|
|
@@ -4824,7 +5179,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
4824
5179
|
const saved = await entity.Save(this.syncSaveOptions);
|
|
4825
5180
|
if (!saved) {
|
|
4826
5181
|
const errMsg = entity.LatestResult?.CompleteMessage ?? 'unknown error';
|
|
4827
|
-
const schemaErr =
|
|
5182
|
+
const schemaErr = DetectSchemaNotGenerated(record.MJEntityName, errMsg);
|
|
4828
5183
|
if (schemaErr)
|
|
4829
5184
|
throw schemaErr;
|
|
4830
5185
|
throw new Error(`Failed to ${existed ? 'update' : 'create'} ${record.MJEntityName} record: ${errMsg}`);
|
|
@@ -4846,7 +5201,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
4846
5201
|
if (!existed && mappedPK != null && precheck) {
|
|
4847
5202
|
precheck.Present.add(mappedPK);
|
|
4848
5203
|
}
|
|
4849
|
-
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');
|
|
4850
5205
|
return existed ? 'updated' : 'created';
|
|
4851
5206
|
}
|
|
4852
5207
|
/**
|
|
@@ -4914,7 +5269,9 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
4914
5269
|
// computed hash of the incoming mapped fields, the record is provably
|
|
4915
5270
|
// unchanged — skip the per-record DB load AND the write. The dirty-flag check
|
|
4916
5271
|
// below is the fallback for entities without the hash column.
|
|
4917
|
-
|
|
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)) {
|
|
4918
5275
|
const stored = precheckHashes.Hashes.get(record.MatchedMJRecordID);
|
|
4919
5276
|
if (stored && stored === ComputeContentHash(record.MappedFields ?? {})) {
|
|
4920
5277
|
result.RecordsSkipped++;
|
|
@@ -4929,7 +5286,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
4929
5286
|
// (CompanyIntegration, Entity, ExternalID) — idempotent for already-mapped records, and the
|
|
4930
5287
|
// CreateRecord skip branches already do exactly this. MatchedMJRecordID IS the dest PK
|
|
4931
5288
|
// (PrimaryKeys order, '|'-joined), which is the EntityRecordID the map stores.
|
|
4932
|
-
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');
|
|
4933
5290
|
// The record IS still present and confirmed-unchanged on the source — but skipping
|
|
4934
5291
|
// the write here means SetStandardIntegrationFields never runs, so __mj_integration_
|
|
4935
5292
|
// LastReconciledAt would freeze at first-sync time. Record the PK so the batch can
|
|
@@ -4977,7 +5334,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
4977
5334
|
// above for the full rationale (a key-field/PK match can land here with no map row, and
|
|
4978
5335
|
// dropping the map silently breaks the 1:1 completeness invariant + orphan detection).
|
|
4979
5336
|
// The entity is loaded here, so use its actual PK as the EntityRecordID. Idempotent upsert.
|
|
4980
|
-
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');
|
|
4981
5338
|
// Same reasoning as the content-hash skip: the record IS confirmed present on the
|
|
4982
5339
|
// source, so let the batch refresh LastReconciledAt in one set-based touch rather
|
|
4983
5340
|
// than rewriting the row for a timestamp.
|
|
@@ -4991,7 +5348,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
4991
5348
|
const saved = await entity.Save(this.syncSaveOptions);
|
|
4992
5349
|
if (!saved) {
|
|
4993
5350
|
const errMsg = entity.LatestResult?.CompleteMessage ?? 'unknown error';
|
|
4994
|
-
const schemaErr =
|
|
5351
|
+
const schemaErr = DetectSchemaNotGenerated(record.MJEntityName, errMsg);
|
|
4995
5352
|
if (schemaErr)
|
|
4996
5353
|
throw schemaErr;
|
|
4997
5354
|
throw new Error(`Failed to update ${record.MJEntityName} record ${record.MatchedMJRecordID}: ${errMsg}`);
|
|
@@ -5002,7 +5359,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
5002
5359
|
// rows and orphan/delete detection silently degrades. SaveRecordMap is an upsert keyed on
|
|
5003
5360
|
// (CompanyIntegration, Entity, ExternalID), so this is idempotent for already-mapped records.
|
|
5004
5361
|
const entityRecordID = entity.PrimaryKey.KeyValuePairs.map(kv => String(kv.Value)).join('|');
|
|
5005
|
-
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');
|
|
5006
5363
|
result.RecordsUpdated++;
|
|
5007
5364
|
}
|
|
5008
5365
|
/**
|
|
@@ -5124,14 +5481,19 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
5124
5481
|
}
|
|
5125
5482
|
/**
|
|
5126
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).
|
|
5127
5489
|
*/
|
|
5128
|
-
async deleteRecord(record, entityMap, contextUser) {
|
|
5490
|
+
async deleteRecord(record, entityMap, contextUser, logger) {
|
|
5129
5491
|
if (!record.MatchedMJRecordID) {
|
|
5130
5492
|
console.log(`[IntegrationEngine] Skipping delete for ${record.ExternalRecord.ObjectType} ExternalID=${record.ExternalRecord.ExternalID} — no MJ record map entry (record was never synced)`);
|
|
5131
|
-
return
|
|
5493
|
+
return 'failed';
|
|
5132
5494
|
}
|
|
5133
5495
|
if (entityMap.DeleteBehavior === 'DoNothing')
|
|
5134
|
-
return
|
|
5496
|
+
return 'failed';
|
|
5135
5497
|
const md = this.ProviderToUse;
|
|
5136
5498
|
const entity = await md.GetEntityObject(record.MJEntityName, contextUser);
|
|
5137
5499
|
this.enrolInWriteGroup(entity);
|
|
@@ -5140,37 +5502,61 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
5140
5502
|
const loaded = await entity.InnerLoad(this.buildEntityPrimaryKey(record.MatchedMJRecordID, pkFields));
|
|
5141
5503
|
if (!loaded) {
|
|
5142
5504
|
console.log(`[IntegrationEngine] Skipping delete for ${record.MJEntityName} ${record.MatchedMJRecordID} — record not found in MJ DB (may have been deleted already)`);
|
|
5143
|
-
return
|
|
5505
|
+
return 'gone';
|
|
5144
5506
|
}
|
|
5145
|
-
// SoftDelete = mark the mirror row Archived
|
|
5146
|
-
// removed upstream) and keep it; HardDelete physically removes it. (DoNothing
|
|
5147
|
-
// already returned above.) Previously both behaviors hit entity.Delete() — so
|
|
5148
|
-
// SoftDelete was indistinguishable from HardDelete.
|
|
5507
|
+
// SoftDelete = mark the mirror row Archived and keep it; HardDelete physically removes it.
|
|
5149
5508
|
if (entityMap.DeleteBehavior === 'SoftDelete') {
|
|
5150
|
-
const
|
|
5151
|
-
|
|
5152
|
-
if (hasField('__mj_integration_SyncStatus'))
|
|
5153
|
-
entity.Set('__mj_integration_SyncStatus', 'Archived');
|
|
5154
|
-
if (hasField('__mj_integration_LastSyncedAt'))
|
|
5155
|
-
entity.Set('__mj_integration_LastSyncedAt', new Date().toISOString());
|
|
5156
|
-
// Explicit, queryable tombstone (plan §2.5) — distinct from parsing SyncStatus='Archived'.
|
|
5157
|
-
if (hasField('__mj_integration_IsTombstoned'))
|
|
5158
|
-
entity.Set('__mj_integration_IsTombstoned', true);
|
|
5159
|
-
if (hasField('__mj_integration_DeletedDetectedAt'))
|
|
5160
|
-
entity.Set('__mj_integration_DeletedDetectedAt', new Date().toISOString());
|
|
5161
|
-
const archived = await entity.Save(this.syncSaveOptions);
|
|
5162
|
-
if (!archived) {
|
|
5509
|
+
const outcome = await this.archiveRecord(entity, entityMap, logger);
|
|
5510
|
+
if (outcome === 'failed') {
|
|
5163
5511
|
const reason = entity.LatestResult?.CompleteMessage ?? 'unknown reason';
|
|
5164
5512
|
console.warn(`[IntegrationEngine] Soft-delete (archive) failed for ${record.MJEntityName} ${record.MatchedMJRecordID} — ${reason}`);
|
|
5165
5513
|
}
|
|
5166
|
-
return archived;
|
|
5514
|
+
return outcome === 'archived' ? 'deleted' : outcome;
|
|
5167
5515
|
}
|
|
5168
5516
|
const deleted = await entity.Delete(this.syncDeleteOptions);
|
|
5169
5517
|
if (!deleted) {
|
|
5170
5518
|
const reason = entity.LatestResult?.CompleteMessage ?? 'unknown reason';
|
|
5171
5519
|
console.warn(`[IntegrationEngine] Delete blocked for ${record.MJEntityName} ${record.MatchedMJRecordID} — ${reason}`);
|
|
5172
5520
|
}
|
|
5173
|
-
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 });
|
|
5174
5560
|
}
|
|
5175
5561
|
/**
|
|
5176
5562
|
* Builds a CompositeKey for a record lookup using the entity's PK field definitions.
|
|
@@ -5323,9 +5709,9 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
5323
5709
|
}
|
|
5324
5710
|
if (this.isBooleanSqlType(targetType)) {
|
|
5325
5711
|
const lower = trimmed.toLowerCase();
|
|
5326
|
-
if (lower === 'true' || lower === '1' || lower === 'yes')
|
|
5712
|
+
if (lower === 'true' || lower === '1' || lower === 'yes' || lower === 't')
|
|
5327
5713
|
return true;
|
|
5328
|
-
if (lower === 'false' || lower === '0' || lower === 'no')
|
|
5714
|
+
if (lower === 'false' || lower === '0' || lower === 'no' || lower === 'f')
|
|
5329
5715
|
return false;
|
|
5330
5716
|
return null;
|
|
5331
5717
|
}
|
|
@@ -5392,6 +5778,10 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
5392
5778
|
if (!entityInfo)
|
|
5393
5779
|
return false;
|
|
5394
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);
|
|
5395
5785
|
if (has('__mj_integration_IsTombstoned') && entity.Get('__mj_integration_IsTombstoned') === true)
|
|
5396
5786
|
return true;
|
|
5397
5787
|
if (has('__mj_integration_SyncMessage') && entity.Get('__mj_integration_SyncMessage') != null)
|
|
@@ -5496,11 +5886,27 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
5496
5886
|
if (hasField('__mj_integration_LastWriterDirection')) {
|
|
5497
5887
|
entity.Set('__mj_integration_LastWriterDirection', 'Pull');
|
|
5498
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
|
+
}
|
|
5499
5901
|
// A live (non-deleted) record. The soft-delete path flips this to true + stamps
|
|
5500
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.
|
|
5501
5904
|
if (hasField('__mj_integration_IsTombstoned')) {
|
|
5502
5905
|
entity.Set('__mj_integration_IsTombstoned', false);
|
|
5503
5906
|
}
|
|
5907
|
+
if (hasField('__mj_integration_DeletedDetectedAt') && entity.Get('__mj_integration_DeletedDetectedAt')) {
|
|
5908
|
+
entity.Set('__mj_integration_DeletedDetectedAt', null);
|
|
5909
|
+
}
|
|
5504
5910
|
}
|
|
5505
5911
|
/**
|
|
5506
5912
|
* Reads EVERY record-map row for a (CompanyIntegration, Entity) pair, in pages.
|
|
@@ -5554,7 +5960,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
5554
5960
|
const page = await rv.RunView({
|
|
5555
5961
|
EntityName: 'MJ: Company Integration Record Maps',
|
|
5556
5962
|
ExtraFilter: filter,
|
|
5557
|
-
Fields: ['ID', 'EntityRecordID', 'ExternalSystemRecordID'],
|
|
5963
|
+
Fields: ['ID', 'EntityRecordID', 'ExternalSystemRecordID', 'Origin'],
|
|
5558
5964
|
// Keyset requires the sort to be on the PK alone; it is also what makes the seek
|
|
5559
5965
|
// below well-defined.
|
|
5560
5966
|
OrderBy: 'ID ASC',
|
|
@@ -5600,20 +6006,20 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
5600
6006
|
* decides not to change. The `recordMaps` parameter is optional so that callers outside the
|
|
5601
6007
|
* batched apply pass (and every existing test) keep the original immediate-write behaviour.
|
|
5602
6008
|
*/
|
|
5603
|
-
async queueRecordMap(recordMaps, companyIntegrationID, externalID, entityID, entityRecordID, contextUser) {
|
|
6009
|
+
async queueRecordMap(recordMaps, companyIntegrationID, externalID, entityID, entityRecordID, contextUser, origin) {
|
|
5604
6010
|
if (recordMaps) {
|
|
5605
6011
|
// Queue only — the apply loop flushes after the batch transaction commits. Writing here
|
|
5606
6012
|
// (or auto-flushing on a full chunk) would put map rows inside a transaction that
|
|
5607
6013
|
// Discard() can no longer take back on rollback.
|
|
5608
|
-
recordMaps.Queue({ EntityID: entityID, ExternalID: externalID, EntityRecordID: entityRecordID });
|
|
6014
|
+
recordMaps.Queue({ EntityID: entityID, ExternalID: externalID, EntityRecordID: entityRecordID, Origin: origin });
|
|
5609
6015
|
return;
|
|
5610
6016
|
}
|
|
5611
|
-
await this.saveRecordMap(companyIntegrationID, externalID, entityID, entityRecordID, contextUser);
|
|
6017
|
+
await this.saveRecordMap(companyIntegrationID, externalID, entityID, entityRecordID, contextUser, origin);
|
|
5612
6018
|
}
|
|
5613
6019
|
/**
|
|
5614
6020
|
* Creates or updates a CompanyIntegrationRecordMap entry to track the external↔MJ mapping.
|
|
5615
6021
|
*/
|
|
5616
|
-
async saveRecordMap(companyIntegrationID, externalID, entityID, entityRecordID, contextUser) {
|
|
6022
|
+
async saveRecordMap(companyIntegrationID, externalID, entityID, entityRecordID, contextUser, origin) {
|
|
5617
6023
|
const md = this.ProviderToUse;
|
|
5618
6024
|
const recordMap = await md.GetEntityObject('MJ: Company Integration Record Maps', contextUser);
|
|
5619
6025
|
// Upsert by identity: one row per (CompanyIntegration, Entity, external record).
|
|
@@ -5645,11 +6051,15 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
5645
6051
|
if (existing.Results[0].EntityRecordID === entityRecordID)
|
|
5646
6052
|
return;
|
|
5647
6053
|
const loaded = await recordMap.Load(existing.Results[0].ID);
|
|
5648
|
-
if (!loaded)
|
|
6054
|
+
if (!loaded) {
|
|
5649
6055
|
recordMap.NewRecord();
|
|
6056
|
+
recordMap.Origin = origin;
|
|
6057
|
+
}
|
|
5650
6058
|
}
|
|
5651
6059
|
else {
|
|
5652
6060
|
recordMap.NewRecord();
|
|
6061
|
+
// An existing mapping keeps the origin it was written with (#3528).
|
|
6062
|
+
recordMap.Origin = origin;
|
|
5653
6063
|
}
|
|
5654
6064
|
recordMap.CompanyIntegrationID = companyIntegrationID;
|
|
5655
6065
|
recordMap.ExternalSystemRecordID = externalID;
|
|
@@ -5861,7 +6271,7 @@ export class IntegrationEngine extends BaseSingleton {
|
|
|
5861
6271
|
run.ErrorLog = result.ErrorMessage ?? 'Sync cancelled by user';
|
|
5862
6272
|
}
|
|
5863
6273
|
else {
|
|
5864
|
-
terminalStatus = result
|
|
6274
|
+
terminalStatus = RunFailed(result) ? 'Failed' : 'Success';
|
|
5865
6275
|
if (result.Errors.length > 0) {
|
|
5866
6276
|
run.ErrorLog = JSON.stringify(result.Errors.slice(0, 100));
|
|
5867
6277
|
}
|