@memberjunction/integration-engine 6.2.0-edge.4 → 6.2.0-edge.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/dist/BaseIntegrationConnector.d.ts.map +1 -1
  2. package/dist/BaseIntegrationConnector.js +22 -4
  3. package/dist/BaseIntegrationConnector.js.map +1 -1
  4. package/dist/BaseRESTIntegrationConnector.d.ts +2 -2
  5. package/dist/BaseRESTIntegrationConnector.d.ts.map +1 -1
  6. package/dist/BaseRESTIntegrationConnector.js +34 -4
  7. package/dist/BaseRESTIntegrationConnector.js.map +1 -1
  8. package/dist/CatalogScope.d.ts +152 -0
  9. package/dist/CatalogScope.d.ts.map +1 -0
  10. package/dist/CatalogScope.js +399 -0
  11. package/dist/CatalogScope.js.map +1 -0
  12. package/dist/CatalogSource.d.ts +53 -0
  13. package/dist/CatalogSource.d.ts.map +1 -0
  14. package/dist/CatalogSource.js +82 -0
  15. package/dist/CatalogSource.js.map +1 -0
  16. package/dist/CatalogWriter.d.ts +216 -0
  17. package/dist/CatalogWriter.d.ts.map +1 -0
  18. package/dist/CatalogWriter.js +457 -0
  19. package/dist/CatalogWriter.js.map +1 -0
  20. package/dist/CompanyIntegrationCatalogStore.d.ts +109 -0
  21. package/dist/CompanyIntegrationCatalogStore.d.ts.map +1 -0
  22. package/dist/CompanyIntegrationCatalogStore.js +229 -0
  23. package/dist/CompanyIntegrationCatalogStore.js.map +1 -0
  24. package/dist/DiscoveryWatchdog.d.ts +38 -1
  25. package/dist/DiscoveryWatchdog.d.ts.map +1 -1
  26. package/dist/DiscoveryWatchdog.js +56 -1
  27. package/dist/DiscoveryWatchdog.js.map +1 -1
  28. package/dist/IntegrationActionGenerator.d.ts.map +1 -1
  29. package/dist/IntegrationActionGenerator.js +33 -26
  30. package/dist/IntegrationActionGenerator.js.map +1 -1
  31. package/dist/IntegrationConnectorCreationPipeline.d.ts +141 -4
  32. package/dist/IntegrationConnectorCreationPipeline.d.ts.map +1 -1
  33. package/dist/IntegrationConnectorCreationPipeline.js +521 -64
  34. package/dist/IntegrationConnectorCreationPipeline.js.map +1 -1
  35. package/dist/IntegrationEngine.d.ts +13 -0
  36. package/dist/IntegrationEngine.d.ts.map +1 -1
  37. package/dist/IntegrationEngine.js +257 -166
  38. package/dist/IntegrationEngine.js.map +1 -1
  39. package/dist/IntegrationSchemaSync.d.ts +97 -0
  40. package/dist/IntegrationSchemaSync.d.ts.map +1 -1
  41. package/dist/IntegrationSchemaSync.js +300 -49
  42. package/dist/IntegrationSchemaSync.js.map +1 -1
  43. package/dist/MatchEngine.d.ts.map +1 -1
  44. package/dist/MatchEngine.js +6 -0
  45. package/dist/MatchEngine.js.map +1 -1
  46. package/dist/index.d.ts +8 -0
  47. package/dist/index.d.ts.map +1 -1
  48. package/dist/index.js +6 -0
  49. package/dist/index.js.map +1 -1
  50. package/dist/types.d.ts +21 -0
  51. package/dist/types.d.ts.map +1 -1
  52. package/package.json +7 -7
@@ -0,0 +1,152 @@
1
+ import { UserInfo } from '@memberjunction/core';
2
+ /**
3
+ * Which connection's catalog the code currently running belongs to.
4
+ *
5
+ * The problem this solves: every read of the integration catalog is keyed by INTEGRATION id, which
6
+ * is shared by every connection of a connector. Threading a connection id down to each of them is
7
+ * not viable — there are twenty-two call sites inside the REST connector base alone, and the
8
+ * connectors that call them live in a separate repository and must keep compiling unchanged.
9
+ *
10
+ * So the connection id travels out of band. An operation that belongs to one connection runs inside
11
+ * `RunInCatalogScope`, and the reads underneath it resolve per-connection without being told.
12
+ *
13
+ * This is the same mechanism the sync loop already uses for its own run context, in this very
14
+ * package — `IntegrationEngine` imports `AsyncLocalStorage` for `runContext` and enters it around
15
+ * each run and each write batch. Async context propagates across `await`, `Promise.all` and timer
16
+ * callbacks, so a scope entered at the top of a run covers everything the run does.
17
+ *
18
+ * WHAT IT DOES NOT COVER, and why that is safe: a callback scheduled OUTSIDE the scope and invoked
19
+ * inside it sees no scope, and so does a task handed to a worker thread or another process. Both
20
+ * fall back to the shared catalog, which is the pre-existing behaviour — over-broad, never wrong
21
+ * about what exists. The failure mode of a missed scope is therefore the old behaviour, not a
22
+ * corrupt one. The failure mode that WOULD be dangerous — a per-connection write landing on the
23
+ * shared rows — cannot happen here, because the write path takes an explicit connection id and
24
+ * never consults this scope.
25
+ */
26
+ export interface CatalogScopeState {
27
+ companyIntegrationID: string;
28
+ /**
29
+ * Set by an owner that warms every object before reading its fields — the sync loop. Inside
30
+ * such a scope a read of a cold object is a missed warm site and throws; everywhere else it
31
+ * answers empty. See {@link RunInWarmedCatalogScope}.
32
+ */
33
+ requireWarmFields?: boolean;
34
+ }
35
+ /** Ceiling on the full field rows held for all connections together. Pinned rows may exceed it. */
36
+ export declare const FIELD_ROW_BUDGET = 10000;
37
+ /**
38
+ * Load a connection's objects and dependency edges into the scope cache, if they are not already.
39
+ *
40
+ * Every async entry to a catalog scope does this — `WithCatalogScope` at entry, the discovery
41
+ * pipeline at the start of its run — because the getters underneath are synchronous and cannot
42
+ * query. The sync loop re-reads instead, with {@link RefreshCatalogScope}.
43
+ */
44
+ export declare function LoadCatalogScope(companyIntegrationID: string, contextUser?: UserInfo): Promise<void>;
45
+ /**
46
+ * Warm one object's full field rows before anything reads them synchronously, and PIN them until
47
+ * {@link UnpinCatalogObjects} releases the pin.
48
+ *
49
+ * Called from the async orchestration points that own a scope — the sync loop, per entity map —
50
+ * because the readers (`GetCachedFields`, in connectors this repository does not own) are
51
+ * synchronous and cannot query. Concurrent warms of one object share one read.
52
+ */
53
+ export declare function WarmCatalogObject(objectID: string, contextUser?: UserInfo): Promise<void>;
54
+ /** Release pins taken by {@link WarmCatalogObject}; the rows stay until the budget needs the room. */
55
+ export declare function UnpinCatalogObjects(objectIDs: readonly string[]): void;
56
+ /**
57
+ * Drop one connection's objects, edges and warm field rows — or everything, with no argument.
58
+ *
59
+ * Inside an OPEN scope this is not a refresh: the getters are synchronous and cannot reload, so a
60
+ * dropped connection reads as having no catalog of its own and falls back to the shared one until
61
+ * something async loads it again. To re-read a connection a scope is using, use
62
+ * {@link RefreshCatalogScope}.
63
+ */
64
+ export declare function EvictCatalogScope(companyIntegrationID?: string): void;
65
+ /**
66
+ * Re-read one connection's catalog INSIDE a scope that is already open (MJ-RUN-46).
67
+ *
68
+ * A scope's catalog is memoised from when it was loaded. A first discovery loads it before the
69
+ * connection has any rows, so it holds none — and Persist then writing 888 rows does not disturb
70
+ * it. The two-pass discovery heal exists to sample the objects that "came into existence in the
71
+ * Persist that follows", and `IntegrationEngineBase.RefreshCatalog` refreshes only the SHARED
72
+ * catalog, which is no longer where a connection's own rows live. So without this the heal re-read
73
+ * an empty catalog and sampled nothing. Observed on the sandbox 2026-09-21: both passes failed
74
+ * with 460+1248 `IntegrationObject not found` AFTER Persist had written all 888 rows; 862 of 888
75
+ * objects ended with no primary key and no fields, and the run reported Success.
76
+ *
77
+ * Eviction alone is not enough: inside an open scope the getters are synchronous and cannot
78
+ * query, so an evicted connection reads as having no catalog of its own and silently falls back
79
+ * to the shared one. This READS FIRST and swaps after, so the previous catalog keeps answering
80
+ * until the fresh one replaces it, and a failed read leaves it in place and throws.
81
+ *
82
+ * The connection's field rows are stale by definition once its catalog has been rewritten, so the
83
+ * ones nobody holds are dropped. A row a running map has pinned is left to that map; it goes at
84
+ * the connection's next refresh, which every sync does at its head.
85
+ *
86
+ * Call sites: the head of every sync run, and the discovery heal, right after it refreshes the
87
+ * shared catalog and before its second Introspect + Persist.
88
+ */
89
+ export declare function RefreshCatalogScope(companyIntegrationID: string, contextUser?: UserInfo): Promise<void>;
90
+ /** What the field cache holds right now — for diagnostics and run events. */
91
+ export declare function CatalogFieldCacheStats(): {
92
+ Objects: number;
93
+ Rows: number;
94
+ Pinned: number;
95
+ };
96
+ /** The connection currently in scope, or undefined when there is none. */
97
+ export declare function CurrentCatalogCI(): string | undefined;
98
+ /**
99
+ * Run `fn` with `companyIntegrationID` in scope.
100
+ *
101
+ * Nesting is allowed and the innermost wins, which is what a batch operation over several
102
+ * connections needs: it enters one scope per connection and each iteration's reads resolve to that
103
+ * connection alone.
104
+ *
105
+ * A synchronous entry cannot load anything: the body reads the connection's catalog only if an
106
+ * async entry has already loaded it, and the shared catalog otherwise. Use {@link WithCatalogScope}
107
+ * when the body reads the catalog.
108
+ */
109
+ export declare function RunInCatalogScope<T>(companyIntegrationID: string, fn: () => T): T;
110
+ /**
111
+ * `RunInCatalogScope` for an owner that WARMS every object before reading its fields — the sync
112
+ * loop, which warms each entity map's object (and its parents) before running the map.
113
+ *
114
+ * Inside it, reading an object of this connection whose fields were never warmed throws
115
+ * PER_CONNECTION_CATALOG_OBJECT_COLD instead of answering `[]`, because there a quiet empty answer
116
+ * would show a connector a table with no columns and a sync would write nothing on a run that
117
+ * reports success. Other owners — discovery, the server's own scopes — have no warm sites yet, so
118
+ * their cold reads stay as quiet as they were before the catalog stopped being resident.
119
+ *
120
+ * Like `RunInCatalogScope` it does not load: the owner loads at a point inside its own error
121
+ * handling (the sync loop does it at the head of the run).
122
+ */
123
+ export declare function RunInWarmedCatalogScope<T>(companyIntegrationID: string, fn: () => T): T;
124
+ /**
125
+ * `RunInCatalogScope` for an async body — the ordinary case. Separate so the return type is a
126
+ * promise rather than a promise-shaped generic, which makes a forgotten `await` a type error, and
127
+ * because this is the async boundary: the connection's objects and edges are loaded here, before
128
+ * the body starts, since the synchronous getters underneath cannot query.
129
+ *
130
+ * @param contextUser The user to load as. Defaults to the one the engine was configured with.
131
+ */
132
+ export declare function WithCatalogScope<T>(companyIntegrationID: string, fn: () => Promise<T>, contextUser?: UserInfo): Promise<T>;
133
+ /**
134
+ * Run `fn` with NO connection in scope, so its reads see the shared catalog.
135
+ *
136
+ * One deliberate caller: action generation. An Action describes the vendor's API, not one tenant's
137
+ * projection of it, so generating actions from whichever connection happened to be in scope would
138
+ * make the generated surface depend on who ran it. Stated here rather than left implicit, because
139
+ * from inside the generator the shared read looks like an oversight.
140
+ */
141
+ export declare function RunOutsideCatalogScope<T>(fn: () => T): T;
142
+ /**
143
+ * Install the scope resolvers on the client-safe engine base.
144
+ *
145
+ * Dependency inversion: `integration-engine-base` is bundled into the Angular client and cannot
146
+ * import a Node built-in, so it declares hooks and this package fills them in — which connection
147
+ * is in scope, and that connection's rows. Called at module load, so importing this package is
148
+ * enough — no ordering requirement on callers, and the client never sets them, leaving every read
149
+ * on the shared catalog exactly as before.
150
+ */
151
+ export declare function InstallCatalogScopeResolver(): void;
152
+ //# sourceMappingURL=CatalogScope.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"CatalogScope.d.ts","sourceRoot":"","sources":["../src/CatalogScope.ts"],"names":[],"mappings":"AACA,OAAO,EAAsC,QAAQ,EAAE,MAAM,sBAAsB,CAAC;AAepF;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,MAAM,WAAW,iBAAiB;IAC9B,oBAAoB,EAAE,MAAM,CAAC;IAC7B;;;;OAIG;IACH,iBAAiB,CAAC,EAAE,OAAO,CAAC;CAC/B;AA2BD,mGAAmG;AACnG,eAAO,MAAM,gBAAgB,QAAS,CAAC;AA6HvC;;;;;;GAMG;AACH,wBAAsB,gBAAgB,CAAC,oBAAoB,EAAE,MAAM,EAAE,WAAW,CAAC,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAG1G;AA2CD;;;;;;;GAOG;AACH,wBAAsB,iBAAiB,CAAC,QAAQ,EAAE,MAAM,EAAE,WAAW,CAAC,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAyB/F;AAED,sGAAsG;AACtG,wBAAgB,mBAAmB,CAAC,SAAS,EAAE,SAAS,MAAM,EAAE,GAAG,IAAI,CAGtE;AAED;;;;;;;GAOG;AACH,wBAAgB,iBAAiB,CAAC,oBAAoB,CAAC,EAAE,MAAM,GAAG,IAAI,CAmBrE;AAED;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,wBAAsB,mBAAmB,CAAC,oBAAoB,EAAE,MAAM,EAAE,WAAW,CAAC,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAU7G;AAED,6EAA6E;AAC7E,wBAAgB,sBAAsB,IAAI;IAAE,OAAO,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,CAE1F;AAgBD,0EAA0E;AAC1E,wBAAgB,gBAAgB,IAAI,MAAM,GAAG,SAAS,CAErD;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,iBAAiB,CAAC,CAAC,EAAE,oBAAoB,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,CAAC,GAAG,CAAC,CAGjF;AAED;;;;;;;;;;;;GAYG;AACH,wBAAgB,uBAAuB,CAAC,CAAC,EAAE,oBAAoB,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,CAAC,GAAG,CAAC,CAGvF;AAED;;;;;;;GAOG;AACH,wBAAsB,gBAAgB,CAAC,CAAC,EAAE,oBAAoB,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,EAAE,WAAW,CAAC,EAAE,QAAQ,GAAG,OAAO,CAAC,CAAC,CAAC,CAIhI;AAED;;;;;;;GAOG;AACH,wBAAgB,sBAAsB,CAAC,CAAC,EAAE,EAAE,EAAE,MAAM,CAAC,GAAG,CAAC,CAExD;AAED;;;;;;;;GAQG;AACH,wBAAgB,2BAA2B,IAAI,IAAI,CAGlD"}
@@ -0,0 +1,399 @@
1
+ import { AsyncLocalStorage } from 'node:async_hooks';
2
+ import { RunView } from '@memberjunction/core';
3
+ import { EscapeSQLString, NormalizeUUID } from '@memberjunction/global';
4
+ import { CATALOG_EDGE_COLUMNS, CATALOG_FIELD_COLUMNS, CATALOG_OBJECT_COLUMNS, ENTITY_COMPANY_INTEGRATION_OBJECTS, ENTITY_COMPANY_INTEGRATION_OBJECT_FIELDS, IntegrationEngineBase, ProjectCatalogObjects, } from '@memberjunction/integration-engine-base';
5
+ import { CompanyIntegrationCatalogReadFailed } from './CatalogWriter.js';
6
+ const storage = new AsyncLocalStorage();
7
+ // ── The per-connection catalog is supplied per scope (MJ-RUN-43) ────────────────────────────────
8
+ //
9
+ // It used to be two boot-time CacheLocal datasets in integration-engine-base, which loaded EVERY
10
+ // connection's objects AND fields as BaseEntity rows and held them for the process lifetime. On a
11
+ // NetForum catalog that is 97,414 field entities and a ~3.8 GB FLOOR on a 4748 MB ceiling, measured
12
+ // on an idle process with nothing running (2026-09-19).
13
+ //
14
+ // Three access patterns were being served by one resident copy, which is why it had to be whole:
15
+ // objects — every consumer walks them; 888 rows, one row each. Cheap. Load them all.
16
+ // edges — ONLY the dependency sort needs every field that points at another object, and only
17
+ // 3 columns of each. Load those as plain rows, never entities.
18
+ // fields — everything else wants ONE object's fields. A row-bounded cache, warmed per object.
19
+ //
20
+ // Measured shape that sets the bound: 888 objects, avg 117 fields, MAX 2,539. A cache counted in
21
+ // OBJECTS worst-cases at ~81k rows when wide objects meet, so the bound is on ROWS. An object being
22
+ // read is pinned so it cannot be evicted by its neighbours mid-flight.
23
+ //
24
+ // Every read below BYPASSES the query cache. These entities' cached answers are not invalidated by
25
+ // the writes a discovery makes, so a cached answer taken before a write keeps being served after it
26
+ // — on tenants whose cache is shared and external to the process, across restarts as well. That is
27
+ // how a first discovery came to see every object as keyless (see CatalogWriter.viewRows), and a
28
+ // scope loaded from the cache would freeze a connection's catalog at whatever was read first.
29
+ /** Ceiling on the full field rows held for all connections together. Pinned rows may exceed it. */
30
+ export const FIELD_ROW_BUDGET = 10_000;
31
+ /** Owner ids per edge-set statement. A large catalog is a handful of statements, not one huge one. */
32
+ const EDGE_READ_CHUNK = 200;
33
+ const catalogCache = new Map();
34
+ const catalogLoads = new Map();
35
+ /** Warm field rows by normalised object id. Map order is recency: the first entry is the oldest. */
36
+ const fieldCache = new Map();
37
+ /** The same rows as `fieldCache`, in the shape the engine base reads. Kept in step with it. */
38
+ const warmRows = new Map();
39
+ const fieldLoads = new Map();
40
+ /** Pin COUNTS, not a set: two maps reading one parent each pin it, and one finishing must not unpin the other. */
41
+ const pins = new Map();
42
+ let fieldRowCount = 0;
43
+ const TELEMETRY = {
44
+ Exempt: true,
45
+ Reason: 'Per-connection catalog read for the catalog scope; a cached answer predates the writes it must observe',
46
+ };
47
+ function engineUser() {
48
+ // BaseEngine keeps the user it was configured with. Scope entry has no user of its own unless
49
+ // the caller passes one, and must not invent one: a catalog read before Config is a bug, not a
50
+ // condition to paper over.
51
+ const user = IntegrationEngineBase.Instance.ContextUser;
52
+ if (!user) {
53
+ throw new Error('PER_CONNECTION_CATALOG_NO_USER: catalog scope entered before IntegrationEngineBase.Config() and without a context user.');
54
+ }
55
+ return user;
56
+ }
57
+ /** A workspace with this code but not the migration has nothing to load — and must not try. */
58
+ function catalogEntitiesRegistered() {
59
+ try {
60
+ // The provider the integration engine was configured with, not the process-global one.
61
+ const md = IntegrationEngineBase.Instance.ProviderToUse;
62
+ return !!md?.EntityByName(ENTITY_COMPANY_INTEGRATION_OBJECTS) && !!md?.EntityByName(ENTITY_COMPANY_INTEGRATION_OBJECT_FIELDS);
63
+ }
64
+ catch {
65
+ return false;
66
+ }
67
+ }
68
+ async function readRows(params, user) {
69
+ const res = await new RunView().RunView({ ...params, BypassCache: true, Telemetry: TELEMETRY }, user);
70
+ // A failed read is an ERROR, never an empty catalog: [] here reads downstream as "this
71
+ // connection has no objects" or "this object has no columns", on a run that reports success.
72
+ if (!res?.Success) {
73
+ const filter = typeof params.ExtraFilter === 'string' ? params.ExtraFilter : '';
74
+ throw new CompanyIntegrationCatalogReadFailed(params.EntityName ?? '', filter, res?.ErrorMessage ?? 'RunView returned no result');
75
+ }
76
+ return res.Results ?? [];
77
+ }
78
+ async function readEdges(objectIDs, user) {
79
+ const edges = [];
80
+ for (let i = 0; i < objectIDs.length; i += EDGE_READ_CHUNK) {
81
+ const list = objectIDs.slice(i, i + EDGE_READ_CHUNK).map(id => `'${EscapeSQLString(id)}'`).join(',');
82
+ const rows = await readRows({
83
+ EntityName: ENTITY_COMPANY_INTEGRATION_OBJECT_FIELDS,
84
+ // Only fields that point at another object. Every reader of the edge set skips the
85
+ // rest, and on a wide catalog the rest is nearly all of it — kept for the life of the
86
+ // process, per connection.
87
+ ExtraFilter: `CompanyIntegrationObjectID IN (${list}) AND RelatedCompanyIntegrationObjectID IS NOT NULL`,
88
+ Fields: [...CATALOG_EDGE_COLUMNS],
89
+ ResultType: 'simple',
90
+ }, user);
91
+ for (const r of rows) {
92
+ edges.push({
93
+ ID: String(r.ID),
94
+ CompanyIntegrationObjectID: String(r.CompanyIntegrationObjectID),
95
+ RelatedCompanyIntegrationObjectID: r.RelatedCompanyIntegrationObjectID == null ? null : String(r.RelatedCompanyIntegrationObjectID),
96
+ });
97
+ }
98
+ }
99
+ return edges;
100
+ }
101
+ async function readCatalog(companyIntegrationID, contextUser) {
102
+ if (!catalogEntitiesRegistered())
103
+ return { Objects: [], Edges: [] };
104
+ const user = contextUser ?? engineUser();
105
+ const Objects = await readRows({
106
+ EntityName: ENTITY_COMPANY_INTEGRATION_OBJECTS,
107
+ ExtraFilter: `CompanyIntegrationID = '${EscapeSQLString(companyIntegrationID)}'`,
108
+ Fields: [...CATALOG_OBJECT_COLUMNS],
109
+ ResultType: 'entity_object',
110
+ }, user);
111
+ // Ids come from the PROJECTION, which reads values through Get(). These entities have no
112
+ // generated subclass, so a loaded row has no `ID` property: `row.ID` is undefined, and an edge
113
+ // filter built from it matches nothing — every dependency edge silently lost. Projecting here
114
+ // also checks the column contract before anything reads the rows.
115
+ const Edges = await readEdges(ProjectCatalogObjects(Objects).map(o => o.ID), user);
116
+ return { Objects, Edges };
117
+ }
118
+ async function loadCatalogFor(companyIntegrationID, contextUser) {
119
+ const key = NormalizeUUID(companyIntegrationID);
120
+ const cached = catalogCache.get(key);
121
+ if (cached)
122
+ return cached;
123
+ const inFlight = catalogLoads.get(key);
124
+ if (inFlight)
125
+ return inFlight;
126
+ const load = readCatalog(companyIntegrationID, contextUser)
127
+ .then(entry => {
128
+ // Only the load still registered may fill the cache: an eviction while it was reading
129
+ // means what it read is already stale.
130
+ if (catalogLoads.get(key) === load)
131
+ catalogCache.set(key, entry);
132
+ return entry;
133
+ })
134
+ .finally(() => {
135
+ if (catalogLoads.get(key) === load)
136
+ catalogLoads.delete(key);
137
+ });
138
+ catalogLoads.set(key, load);
139
+ return load;
140
+ }
141
+ /**
142
+ * Load a connection's objects and dependency edges into the scope cache, if they are not already.
143
+ *
144
+ * Every async entry to a catalog scope does this — `WithCatalogScope` at entry, the discovery
145
+ * pipeline at the start of its run — because the getters underneath are synchronous and cannot
146
+ * query. The sync loop re-reads instead, with {@link RefreshCatalogScope}.
147
+ */
148
+ export async function LoadCatalogScope(companyIntegrationID, contextUser) {
149
+ if (!companyIntegrationID)
150
+ return;
151
+ await loadCatalogFor(companyIntegrationID, contextUser);
152
+ }
153
+ function dropFields(key) {
154
+ const entry = fieldCache.get(key);
155
+ if (!entry)
156
+ return;
157
+ fieldCache.delete(key);
158
+ warmRows.delete(key);
159
+ fieldRowCount -= entry.rows.length;
160
+ }
161
+ function storeFields(key, rows, owner) {
162
+ dropFields(key);
163
+ fieldCache.set(key, { rows, owner });
164
+ warmRows.set(key, rows);
165
+ fieldRowCount += rows.length;
166
+ }
167
+ function evictFieldsToBudget() {
168
+ if (fieldRowCount <= FIELD_ROW_BUDGET)
169
+ return;
170
+ for (const key of [...fieldCache.keys()]) {
171
+ if (fieldRowCount <= FIELD_ROW_BUDGET)
172
+ break;
173
+ if ((pins.get(key) ?? 0) > 0)
174
+ continue;
175
+ dropFields(key);
176
+ }
177
+ }
178
+ function unpinOne(key) {
179
+ const n = pins.get(key) ?? 0;
180
+ if (n <= 1)
181
+ pins.delete(key);
182
+ else
183
+ pins.set(key, n - 1);
184
+ }
185
+ async function readFields(objectID, key, owner, contextUser) {
186
+ const rows = await readRows({
187
+ EntityName: ENTITY_COMPANY_INTEGRATION_OBJECT_FIELDS,
188
+ ExtraFilter: `CompanyIntegrationObjectID = '${EscapeSQLString(objectID)}'`,
189
+ Fields: [...CATALOG_FIELD_COLUMNS],
190
+ ResultType: 'entity_object',
191
+ }, contextUser ?? engineUser());
192
+ storeFields(key, rows, owner);
193
+ evictFieldsToBudget();
194
+ }
195
+ /**
196
+ * Warm one object's full field rows before anything reads them synchronously, and PIN them until
197
+ * {@link UnpinCatalogObjects} releases the pin.
198
+ *
199
+ * Called from the async orchestration points that own a scope — the sync loop, per entity map —
200
+ * because the readers (`GetCachedFields`, in connectors this repository does not own) are
201
+ * synchronous and cannot query. Concurrent warms of one object share one read.
202
+ */
203
+ export async function WarmCatalogObject(objectID, contextUser) {
204
+ const key = NormalizeUUID(objectID);
205
+ if (!key)
206
+ return;
207
+ // Pin FIRST, so an eviction triggered by a concurrent warm cannot take the rows between this
208
+ // read finishing and its caller using them.
209
+ pins.set(key, (pins.get(key) ?? 0) + 1);
210
+ try {
211
+ const warm = fieldCache.get(key);
212
+ if (warm) {
213
+ // Refresh recency: the oldest entry is the first evicted.
214
+ fieldCache.delete(key);
215
+ fieldCache.set(key, warm);
216
+ return;
217
+ }
218
+ let load = fieldLoads.get(key);
219
+ if (!load) {
220
+ load = readFields(objectID, key, NormalizeUUID(CurrentCatalogCI()), contextUser)
221
+ .finally(() => fieldLoads.delete(key));
222
+ fieldLoads.set(key, load);
223
+ }
224
+ await load;
225
+ }
226
+ catch (err) {
227
+ unpinOne(key);
228
+ throw err;
229
+ }
230
+ }
231
+ /** Release pins taken by {@link WarmCatalogObject}; the rows stay until the budget needs the room. */
232
+ export function UnpinCatalogObjects(objectIDs) {
233
+ for (const id of objectIDs)
234
+ unpinOne(NormalizeUUID(id));
235
+ evictFieldsToBudget();
236
+ }
237
+ /**
238
+ * Drop one connection's objects, edges and warm field rows — or everything, with no argument.
239
+ *
240
+ * Inside an OPEN scope this is not a refresh: the getters are synchronous and cannot reload, so a
241
+ * dropped connection reads as having no catalog of its own and falls back to the shared one until
242
+ * something async loads it again. To re-read a connection a scope is using, use
243
+ * {@link RefreshCatalogScope}.
244
+ */
245
+ export function EvictCatalogScope(companyIntegrationID) {
246
+ if (!companyIntegrationID) {
247
+ catalogCache.clear();
248
+ catalogLoads.clear();
249
+ fieldCache.clear();
250
+ warmRows.clear();
251
+ fieldLoads.clear();
252
+ pins.clear();
253
+ fieldRowCount = 0;
254
+ return;
255
+ }
256
+ const owner = NormalizeUUID(companyIntegrationID);
257
+ catalogCache.delete(owner);
258
+ catalogLoads.delete(owner);
259
+ for (const [key, entry] of [...fieldCache]) {
260
+ if (entry.owner !== owner)
261
+ continue;
262
+ dropFields(key);
263
+ pins.delete(key);
264
+ }
265
+ }
266
+ /**
267
+ * Re-read one connection's catalog INSIDE a scope that is already open (MJ-RUN-46).
268
+ *
269
+ * A scope's catalog is memoised from when it was loaded. A first discovery loads it before the
270
+ * connection has any rows, so it holds none — and Persist then writing 888 rows does not disturb
271
+ * it. The two-pass discovery heal exists to sample the objects that "came into existence in the
272
+ * Persist that follows", and `IntegrationEngineBase.RefreshCatalog` refreshes only the SHARED
273
+ * catalog, which is no longer where a connection's own rows live. So without this the heal re-read
274
+ * an empty catalog and sampled nothing. Observed on the sandbox 2026-09-21: both passes failed
275
+ * with 460+1248 `IntegrationObject not found` AFTER Persist had written all 888 rows; 862 of 888
276
+ * objects ended with no primary key and no fields, and the run reported Success.
277
+ *
278
+ * Eviction alone is not enough: inside an open scope the getters are synchronous and cannot
279
+ * query, so an evicted connection reads as having no catalog of its own and silently falls back
280
+ * to the shared one. This READS FIRST and swaps after, so the previous catalog keeps answering
281
+ * until the fresh one replaces it, and a failed read leaves it in place and throws.
282
+ *
283
+ * The connection's field rows are stale by definition once its catalog has been rewritten, so the
284
+ * ones nobody holds are dropped. A row a running map has pinned is left to that map; it goes at
285
+ * the connection's next refresh, which every sync does at its head.
286
+ *
287
+ * Call sites: the head of every sync run, and the discovery heal, right after it refreshes the
288
+ * shared catalog and before its second Introspect + Persist.
289
+ */
290
+ export async function RefreshCatalogScope(companyIntegrationID, contextUser) {
291
+ if (!companyIntegrationID)
292
+ return;
293
+ const key = NormalizeUUID(companyIntegrationID);
294
+ const fresh = await readCatalog(companyIntegrationID, contextUser);
295
+ // An older load still in flight read before this one, so it must not overwrite it.
296
+ catalogLoads.delete(key);
297
+ catalogCache.set(key, fresh);
298
+ for (const [objectKey, entry] of [...fieldCache]) {
299
+ if (entry.owner === key && (pins.get(objectKey) ?? 0) === 0)
300
+ dropFields(objectKey);
301
+ }
302
+ }
303
+ /** What the field cache holds right now — for diagnostics and run events. */
304
+ export function CatalogFieldCacheStats() {
305
+ return { Objects: fieldCache.size, Rows: fieldRowCount, Pinned: pins.size };
306
+ }
307
+ /** Everything the engine-base getters need for the scope in force, or undefined when it is not loaded. */
308
+ function currentCatalogData() {
309
+ const state = storage.getStore();
310
+ if (!state)
311
+ return undefined;
312
+ const entry = catalogCache.get(NormalizeUUID(state.companyIntegrationID));
313
+ if (!entry)
314
+ return undefined;
315
+ return {
316
+ Objects: entry.Objects,
317
+ FieldsByObjectID: warmRows,
318
+ Edges: entry.Edges,
319
+ RequireWarmFields: state.requireWarmFields === true,
320
+ };
321
+ }
322
+ /** The connection currently in scope, or undefined when there is none. */
323
+ export function CurrentCatalogCI() {
324
+ return storage.getStore()?.companyIntegrationID;
325
+ }
326
+ /**
327
+ * Run `fn` with `companyIntegrationID` in scope.
328
+ *
329
+ * Nesting is allowed and the innermost wins, which is what a batch operation over several
330
+ * connections needs: it enters one scope per connection and each iteration's reads resolve to that
331
+ * connection alone.
332
+ *
333
+ * A synchronous entry cannot load anything: the body reads the connection's catalog only if an
334
+ * async entry has already loaded it, and the shared catalog otherwise. Use {@link WithCatalogScope}
335
+ * when the body reads the catalog.
336
+ */
337
+ export function RunInCatalogScope(companyIntegrationID, fn) {
338
+ if (!companyIntegrationID)
339
+ return fn();
340
+ return storage.run({ companyIntegrationID }, fn);
341
+ }
342
+ /**
343
+ * `RunInCatalogScope` for an owner that WARMS every object before reading its fields — the sync
344
+ * loop, which warms each entity map's object (and its parents) before running the map.
345
+ *
346
+ * Inside it, reading an object of this connection whose fields were never warmed throws
347
+ * PER_CONNECTION_CATALOG_OBJECT_COLD instead of answering `[]`, because there a quiet empty answer
348
+ * would show a connector a table with no columns and a sync would write nothing on a run that
349
+ * reports success. Other owners — discovery, the server's own scopes — have no warm sites yet, so
350
+ * their cold reads stay as quiet as they were before the catalog stopped being resident.
351
+ *
352
+ * Like `RunInCatalogScope` it does not load: the owner loads at a point inside its own error
353
+ * handling (the sync loop does it at the head of the run).
354
+ */
355
+ export function RunInWarmedCatalogScope(companyIntegrationID, fn) {
356
+ if (!companyIntegrationID)
357
+ return fn();
358
+ return storage.run({ companyIntegrationID, requireWarmFields: true }, fn);
359
+ }
360
+ /**
361
+ * `RunInCatalogScope` for an async body — the ordinary case. Separate so the return type is a
362
+ * promise rather than a promise-shaped generic, which makes a forgotten `await` a type error, and
363
+ * because this is the async boundary: the connection's objects and edges are loaded here, before
364
+ * the body starts, since the synchronous getters underneath cannot query.
365
+ *
366
+ * @param contextUser The user to load as. Defaults to the one the engine was configured with.
367
+ */
368
+ export async function WithCatalogScope(companyIntegrationID, fn, contextUser) {
369
+ if (!companyIntegrationID)
370
+ return fn();
371
+ await loadCatalogFor(companyIntegrationID, contextUser);
372
+ return storage.run({ companyIntegrationID }, fn);
373
+ }
374
+ /**
375
+ * Run `fn` with NO connection in scope, so its reads see the shared catalog.
376
+ *
377
+ * One deliberate caller: action generation. An Action describes the vendor's API, not one tenant's
378
+ * projection of it, so generating actions from whichever connection happened to be in scope would
379
+ * make the generated surface depend on who ran it. Stated here rather than left implicit, because
380
+ * from inside the generator the shared read looks like an oversight.
381
+ */
382
+ export function RunOutsideCatalogScope(fn) {
383
+ return storage.exit(fn);
384
+ }
385
+ /**
386
+ * Install the scope resolvers on the client-safe engine base.
387
+ *
388
+ * Dependency inversion: `integration-engine-base` is bundled into the Angular client and cannot
389
+ * import a Node built-in, so it declares hooks and this package fills them in — which connection
390
+ * is in scope, and that connection's rows. Called at module load, so importing this package is
391
+ * enough — no ordering requirement on callers, and the client never sets them, leaving every read
392
+ * on the shared catalog exactly as before.
393
+ */
394
+ export function InstallCatalogScopeResolver() {
395
+ IntegrationEngineBase.CatalogScopeResolver = CurrentCatalogCI;
396
+ IntegrationEngineBase.CatalogDataResolver = currentCatalogData;
397
+ }
398
+ InstallCatalogScopeResolver();
399
+ //# sourceMappingURL=CatalogScope.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"CatalogScope.js","sourceRoot":"","sources":["../src/CatalogScope.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AACrD,OAAO,EAAc,OAAO,EAA2B,MAAM,sBAAsB,CAAC;AACpF,OAAO,EAAE,eAAe,EAAE,aAAa,EAAE,MAAM,wBAAwB,CAAC;AACxE,OAAO,EACH,oBAAoB,EACpB,qBAAqB,EACrB,sBAAsB,EAGtB,kCAAkC,EAClC,wCAAwC,EACxC,qBAAqB,EACrB,qBAAqB,GACxB,MAAM,yCAAyC,CAAC;AACjD,OAAO,EAAE,mCAAmC,EAAE,MAAM,oBAAoB,CAAC;AAoCzE,MAAM,OAAO,GAAG,IAAI,iBAAiB,EAAqB,CAAC;AAE3D,mGAAmG;AACnG,EAAE;AACF,iGAAiG;AACjG,kGAAkG;AAClG,oGAAoG;AACpG,wDAAwD;AACxD,EAAE;AACF,iGAAiG;AACjG,uFAAuF;AACvF,iGAAiG;AACjG,2EAA2E;AAC3E,iGAAiG;AACjG,EAAE;AACF,iGAAiG;AACjG,oGAAoG;AACpG,uEAAuE;AACvE,EAAE;AACF,mGAAmG;AACnG,oGAAoG;AACpG,mGAAmG;AACnG,gGAAgG;AAChG,8FAA8F;AAE9F,mGAAmG;AACnG,MAAM,CAAC,MAAM,gBAAgB,GAAG,MAAM,CAAC;AACvC,sGAAsG;AACtG,MAAM,eAAe,GAAG,GAAG,CAAC;AAa5B,MAAM,YAAY,GAAG,IAAI,GAAG,EAAwB,CAAC;AAC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AAU,uBAAuB,CAAI,oBAA4B,EAAE,EAAW;IAChF,IAAI,CAAC,oBAAoB;QAAE,OAAO,EAAE,EAAE,CAAC;IACvC,OAAO,OAAO,CAAC,GAAG,CAAC,EAAE,oBAAoB,EAAE,iBAAiB,EAAE,IAAI,EAAE,EAAE,EAAE,CAAC,CAAC;AAC9E,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,CAAC,KAAK,UAAU,gBAAgB,CAAI,oBAA4B,EAAE,EAAoB,EAAE,WAAsB;IAChH,IAAI,CAAC,oBAAoB;QAAE,OAAO,EAAE,EAAE,CAAC;IACvC,MAAM,cAAc,CAAC,oBAAoB,EAAE,WAAW,CAAC,CAAC;IACxD,OAAO,OAAO,CAAC,GAAG,CAAC,EAAE,oBAAoB,EAAE,EAAE,EAAE,CAAC,CAAC;AACrD,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,UAAU,sBAAsB,CAAI,EAAW;IACjD,OAAO,OAAO,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;AAC5B,CAAC;AAED;;;;;;;;GAQG;AACH,MAAM,UAAU,2BAA2B;IACvC,qBAAqB,CAAC,oBAAoB,GAAG,gBAAgB,CAAC;IAC9D,qBAAqB,CAAC,mBAAmB,GAAG,kBAAkB,CAAC;AACnE,CAAC;AAED,2BAA2B,EAAE,CAAC"}
@@ -0,0 +1,53 @@
1
+ import { IMetadataProvider, UserInfo } from '@memberjunction/core';
2
+ import type { MJCompanyIntegrationEntity } from '@memberjunction/core-entities';
3
+ import { CatalogWriter } from './CatalogWriter.js';
4
+ /**
5
+ * THE ONE PLACE that decides whether a connection reads and writes the shared integration catalog
6
+ * or its own.
7
+ *
8
+ * Deliberately one place. A flag consulted in several is a flag that will eventually disagree with
9
+ * itself, and here the two answers are not merely different — a shared write during a
10
+ * per-connection run puts one tenant's discovery into every other tenant's catalog and reports
11
+ * success.
12
+ *
13
+ * Two levers, in precedence order:
14
+ *
15
+ * 1. `CompanyIntegration.Configuration.catalogSource` — per connection. This is the primary
16
+ * control, and it is per-connection rather than per-process for two reasons: it survives a
17
+ * deploy (an environment variable set on the box does not — a deploy rewrites the env file),
18
+ * and it lets one process run some connections each way at once, which is what makes cutting
19
+ * over one connector at a time possible.
20
+ * 2. `MJ_INTEGRATION_CATALOG_SOURCE` — a global override, and the reason it exists is rollback:
21
+ * it is the only lever that does not require reaching a connection's Configuration through a
22
+ * workspace that may be the thing that is broken. Keep it after the fleet cuts over.
23
+ *
24
+ * Default is 'Shared'. The tables can therefore exist, be backfilled and be verified against live
25
+ * traffic before anything reads or writes them.
26
+ */
27
+ export type CatalogSource = 'Shared' | 'PerConnection';
28
+ /** The global override, or undefined when unset. */
29
+ export declare function GlobalCatalogSourceOverride(): CatalogSource | undefined;
30
+ /**
31
+ * Which catalog this connection uses.
32
+ *
33
+ * An unparseable `Configuration` is treated as "no opinion" rather than as an error: that column
34
+ * carries a dozen unrelated settings, and letting one bad character anywhere in it flip a
35
+ * connection's catalog would be a far worse failure than ignoring it.
36
+ */
37
+ export declare function ResolveCatalogSource(companyIntegration: MJCompanyIntegrationEntity): CatalogSource;
38
+ /**
39
+ * The writer for this connection's catalog.
40
+ *
41
+ * FAIL-LOUD, not fail-safe. A connection set to 'PerConnection' that has entity maps but no
42
+ * per-connection catalog rows has not been backfilled, and answering from the shared catalog would
43
+ * be indistinguishable from success: the sync would run, on a different set of objects, and report
44
+ * nothing wrong. So it refuses, and the message names the connection, what it found, and the way
45
+ * out.
46
+ *
47
+ * The "has entity maps" part matters. A brand-new connection legitimately has neither maps nor
48
+ * catalog rows — that is the state right before its first discovery, not a missing backfill — so
49
+ * requiring rows there would refuse every new connector on the very flag that is supposed to be
50
+ * safe to turn on.
51
+ */
52
+ export declare function BuildCatalogWriter(md: IMetadataProvider, companyIntegration: MJCompanyIntegrationEntity, contextUser: UserInfo, source?: CatalogSource): CatalogWriter;
53
+ //# sourceMappingURL=CatalogSource.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"CatalogSource.d.ts","sourceRoot":"","sources":["../src/CatalogSource.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAY,QAAQ,EAAE,MAAM,sBAAsB,CAAC;AAC7E,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,+BAA+B,CAAC;AAEhF,OAAO,EAAE,aAAa,EAAmD,MAAM,oBAAoB,CAAC;AAEpG;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,MAAM,MAAM,aAAa,GAAG,QAAQ,GAAG,eAAe,CAAC;AAavD,oDAAoD;AACpD,wBAAgB,2BAA2B,IAAI,aAAa,GAAG,SAAS,CAEvE;AAED;;;;;;GAMG;AACH,wBAAgB,oBAAoB,CAAC,kBAAkB,EAAE,0BAA0B,GAAG,aAAa,CAWlG;AAED;;;;;;;;;;;;;GAaG;AACH,wBAAgB,kBAAkB,CAC9B,EAAE,EAAE,iBAAiB,EACrB,kBAAkB,EAAE,0BAA0B,EAC9C,WAAW,EAAE,QAAQ,EACrB,MAAM,CAAC,EAAE,aAAa,GACvB,aAAa,CA+Bf"}