@memberjunction/generic-database-provider 6.2.0-edge.2 → 6.2.0-edge.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/UserCache.js CHANGED
@@ -1,20 +1,59 @@
1
- import { LogError, UserInfo } from '@memberjunction/core';
2
- import { BaseSingleton, UUIDsEqual } from '@memberjunction/global';
1
+ import { BaseEntity, CacheCategory, LocalCacheManager, LogError, LogStatusEx, LogWarning, UserInfo, } from '@memberjunction/core';
2
+ import { BaseSingleton, EscapeSQLString, GroupByUUID, MJEventType, MJGlobal, UUIDsEqual } from '@memberjunction/global';
3
3
  import { SystemUserID } from './systemUser.js';
4
4
  /**
5
- * Server side cache of users and their roles.
5
+ * Key this cache writes to the shared store to tell other processes that users changed. It lives in
6
+ * the default category, which MJAPI publishes as a key-only notice (see `MJServer/src/sharedCache.ts`),
7
+ * so a change costs one small message per server rather than a payload.
8
+ */
9
+ export const USER_CACHE_STAMP_KEY = '__MJ_UserCache_Stamp__';
10
+ /** The entities this cache is built from; a save or delete of either makes it stale. */
11
+ const USERS_ENTITY = 'MJ: Users';
12
+ const USER_ROLES_ENTITY = 'MJ: User Roles';
13
+ const USER_ENTITY_NAMES = new Set([USERS_ENTITY.toLowerCase(), USER_ROLES_ENTITY.toLowerCase()]);
14
+ /**
15
+ * Server-side cache of users and their roles, shared by every consumer in the process.
6
16
  *
7
17
  * Dialect-neutral: {@link UserCache.Refresh} takes a {@link DatabaseProviderBase} and reads through
8
- * `ExecuteSQL` / `QuoteSchemaAndView`, so SQL Server and PostgreSQL processes share one
9
- * implementation rather than each hand-rolling a `vwUsers` + `vwUserRoles` load.
18
+ * `ExecuteSQL` / `QuoteSchemaAndView`, so SQL Server and PostgreSQL share one implementation.
19
+ *
20
+ * It keeps itself current by four independent routes, because each can be bypassed by the next:
10
21
  *
11
- * Uses BaseSingleton to guarantee a single instance across the entire process,
12
- * even if bundlers duplicate this module across multiple execution paths.
22
+ * 1. **Local writes** — refreshes on `MJ: Users` / `MJ: User Roles` save and delete events, so the
23
+ * process making the change does not have to remember to.
24
+ * 2. **Other processes** — a refresh for a local write stamps {@link USER_CACHE_STAMP_KEY} in the
25
+ * shared store, and peers refresh on that notice. Clearing the shared cache (`mj sync push`,
26
+ * `mj codegen`, `mj migrate`) has the same effect.
27
+ * 3. **Writers that bypass both** (raw SQL, another application) —
28
+ * {@link RefreshIfChangedInDatabase} compares two counts and a timestamp against the database and
29
+ * reloads only on a difference. MJAPI runs it on the engine-sweep interval.
30
+ * 4. **A miss is not a negative fact** — {@link FindUser} falls back to an authoritative single-row
31
+ * read, so a user this process has not heard about is looked up rather than denied.
13
32
  *
14
- * NOTE: the class name `UserCache` is load-bearing — `BaseSingleton` keys its global store on the
15
- * constructor name, so renaming it would hand every existing holder a second, empty instance.
33
+ * Extends `BaseSingleton` so bundler duplication cannot produce a second instance. The class NAME is
34
+ * load-bearing: `BaseSingleton` keys its global store on the constructor name, so renaming it hands
35
+ * every existing holder a second, empty instance.
16
36
  */
17
37
  export class UserCache extends BaseSingleton {
38
+ /** How long a burst of user changes is collected before one reload runs. */
39
+ static { this.ChangeDebounceMs = 250; }
40
+ /**
41
+ * Upper bound of the random extra delay before reloading after another server's notice, so a
42
+ * fleet does not query the database in lockstep.
43
+ */
44
+ static { this.PeerNoticeJitterMs = 500; }
45
+ /** How long {@link FindUser} remembers that a lookup found nothing, before it asks again. */
46
+ static { this.MissRetryIntervalMs = 5000; }
47
+ /** How long to wait before re-checking whether the writing transaction has settled. */
48
+ static { this.TransactionWaitMs = 250; }
49
+ /**
50
+ * How many {@link TransactionWaitMs} windows a pending reload waits for an open transaction
51
+ * before giving up. At the defaults that is 15 s; a unit of work still open after that is
52
+ * stuck, and the periodic staleness check will catch whatever it eventually commits.
53
+ */
54
+ static { this.MaxTransactionWaits = 60; }
55
+ /** Upper bound on remembered misses, so a probing attacker cannot grow the map without limit. */
56
+ static { this.MaxRememberedMisses = 500; }
18
57
  /**
19
58
  * Use UserCache.Instance to get the singleton instance.
20
59
  */
@@ -26,6 +65,44 @@ export class UserCache extends BaseSingleton {
26
65
  * `.find()`. Callers already treat a missing system user as `undefined`.
27
66
  */
28
67
  this._users = [];
68
+ /** The provider the last {@link Refresh} read through; every self-refresh reuses it. */
69
+ this._provider = null;
70
+ /** Event subscriptions are made once per process. */
71
+ this._wired = false;
72
+ this._unsubscribeCacheEvents = null;
73
+ this._refreshTimer = null;
74
+ /** Consecutive windows the pending reload has waited for an open transaction. */
75
+ this._transactionWaits = 0;
76
+ /**
77
+ * The providers that raised the pending changes, so the reload waits for THEIR transactions.
78
+ * MJServer builds a provider per request, and a resolver's save runs on that one — not on the
79
+ * process-wide provider this cache reads through, whose depth is always 0. Waiting on the
80
+ * wrong provider is the same as not waiting at all.
81
+ */
82
+ this._pendingWriters = new Set();
83
+ /**
84
+ * Whether the pending reload has a change of OUR OWN to announce. Sticky, because a local
85
+ * change and an incoming peer notice collapse into one reload: carrying the intent on the timer
86
+ * meant whichever event scheduled last decided it, so a peer notice landing inside the debounce
87
+ * window demoted a local write to "someone else's change" and no peer ever heard about it. The
88
+ * transaction wait stretches that window to seconds.
89
+ */
90
+ this._announcePending = false;
91
+ this._stalenessTimer = null;
92
+ /** The periodic full reload. See {@link scheduleAutoRefresh}. */
93
+ this._autoRefreshTimer = null;
94
+ /**
95
+ * The reload interval the host configured, kept so that a later `Refresh(provider)` without one
96
+ * — the authentication miss path, the roles/users sync — re-arms the same schedule instead of
97
+ * silently ending it.
98
+ */
99
+ this._autoRefreshIntervalMs = undefined;
100
+ /** In-flight reload, so a burst of events costs one database read. */
101
+ this._refreshInFlight = null;
102
+ /** What the database reported at the last reload; the staleness check compares against it. */
103
+ this._lastStamp = null;
104
+ /** Lookups that missed both the cache and the database recently, so a retry storm cannot form. */
105
+ this._recentMisses = new Map();
29
106
  }
30
107
  get SYSTEM_USER_ID() {
31
108
  return SystemUserID;
@@ -42,21 +119,30 @@ export class UserCache extends BaseSingleton {
42
119
  return this.Users.find((u) => u.ID.toLowerCase() === UserCache.Instance.SYSTEM_USER_ID.toLowerCase());
43
120
  }
44
121
  /**
45
- * This method will refresh the cache with the latest data from the database
122
+ * This method will refresh the cache with the latest data from the database, and subscribes this
123
+ * process to the changes that make it stale (see the class comment).
46
124
  * @param provider - the configured database provider to read through. Works on any dialect —
47
125
  * the SQL is built with the provider's own quoting and core-schema name.
48
- * @param autoRefreshIntervalMS - optional, if provided, the cache will be refreshed every interval as specified - denominated in milliseconds
126
+ * @param autoRefreshIntervalMS - optional; when set, the whole cache is also reloaded on this
127
+ * interval. The subscriptions make that unnecessary for most hosts;
128
+ * {@link StartStalenessChecks} is the cheaper periodic safety net. **Omit it to
129
+ * keep whatever schedule an earlier call set** — `Refresh` is also called from
130
+ * paths that know nothing about scheduling, and those must not end it. Pass `0`
131
+ * to turn the schedule off.
49
132
  */
50
133
  async Refresh(provider, autoRefreshIntervalMS) {
134
+ this._provider = provider;
135
+ this.wire();
51
136
  try {
52
137
  const users = await this.LoadUsers(provider);
53
138
  if (users) {
54
139
  this._users = users;
55
- // refresh this every interval noted above to ensure we have the latest data
56
- if (autoRefreshIntervalMS && autoRefreshIntervalMS > 0)
57
- setTimeout(() => {
58
- this.Refresh(provider, autoRefreshIntervalMS);
59
- }, autoRefreshIntervalMS);
140
+ this._recentMisses.clear();
141
+ this._lastStamp = await this.readDatabaseStamp(provider);
142
+ if (autoRefreshIntervalMS !== undefined) {
143
+ this._autoRefreshIntervalMs = autoRefreshIntervalMS;
144
+ }
145
+ this.scheduleAutoRefresh(provider, this._autoRefreshIntervalMs);
60
146
  }
61
147
  }
62
148
  catch (err) {
@@ -83,21 +169,71 @@ export class UserCache extends BaseSingleton {
83
169
  */
84
170
  SetUsers(users) {
85
171
  this._users = users;
172
+ this._recentMisses.clear();
86
173
  }
87
174
  /**
88
- * Reads `vwUsers` + `vwUserRoles` through the provider and stitches each user's roles onto it.
175
+ * Reads the users and user-roles base views through the provider and stitches each user's roles
176
+ * onto it.
177
+ *
178
+ * **Why not `RunView`?** `DatabaseProviderBase` is an `IRunViewProvider`, so this could go
179
+ * through the standard read path and inherit its shared-cache invalidation. It deliberately does
180
+ * not, for three reasons:
181
+ * 1. **Bootstrap.** Server-side `RunView` requires a `contextUser` and throws without one
182
+ * (`CheckUserReadPermissions`). This cache is what produces the system user MJAPI then passes
183
+ * to everything else, so at first load there is no `UserInfo` to read as.
184
+ * 2. **It must be unfiltered.** `RunView` applies the reading user's entity permission, row-level
185
+ * security and field-level projection (`buildFieldSecuritySelectList`). This cache is
186
+ * process-global and answers "who is this?" for every request, so a set scoped to whichever
187
+ * user happened to bootstrap — or missing `Email` because a deployment denied that field to
188
+ * their role — would silently break identity for everyone else.
189
+ * 3. **It would put the user table in the shared cache.** `MJ: Users` is cacheable, so a
190
+ * `RunView` load would publish every user row (names, emails, employee links) into Redis,
191
+ * where today nothing about users is stored.
192
+ *
193
+ * The freshness that `RunView` would have brought is provided instead by the subscriptions on
194
+ * this class — see the class comment.
195
+ * @param whereClause - optional predicate on `vwUsers` (already quoted and escaped), for
196
+ * {@link FindUser}'s single-row read.
89
197
  */
90
- async LoadUsers(provider) {
91
- const coreSchema = provider.MJCoreSchemaName;
92
- const users = await provider.ExecuteSQL(`SELECT * FROM ${provider.QuoteSchemaAndView(coreSchema, 'vwUsers')}`);
93
- const roles = await provider.ExecuteSQL(`SELECT * FROM ${provider.QuoteSchemaAndView(coreSchema, 'vwUserRoles')}`);
94
- if (!users)
198
+ async LoadUsers(provider, whereClause) {
199
+ const where = whereClause ? ` WHERE ${whereClause}` : '';
200
+ const users = await provider.ExecuteSQL(`SELECT * FROM ${this.viewFor(provider, USERS_ENTITY, 'vwUsers')}${where}`);
201
+ if (!users) {
95
202
  return undefined;
203
+ }
204
+ // A single-user read must not scan the whole role table: FindUser runs this on every miss,
205
+ // and a login attempt with an unknown address is a miss.
206
+ const rolesWhere = whereClause ? this.rolesForUsersPredicate(provider, users) : '';
207
+ const roles = rolesWhere === null
208
+ ? []
209
+ : await provider.ExecuteSQL(`SELECT * FROM ${this.viewFor(provider, USER_ROLES_ENTITY, 'vwUserRoles')}${rolesWhere}`);
210
+ const rolesByUser = GroupByUUID(roles ?? [], (role) => role.UserID);
96
211
  return users.map((user) => {
97
- user.UserRoles = (roles ?? []).filter((role) => UUIDsEqual(role.UserID, user.ID));
212
+ user.UserRoles = rolesByUser.Get(user.ID) ?? [];
98
213
  return new UserInfo(provider, user);
99
214
  });
100
215
  }
216
+ /**
217
+ * ` WHERE UserID IN (…)` for the users just loaded, or null when there are none (no query at
218
+ * all then). IDs come from the database, and are still shape-checked before interpolation.
219
+ */
220
+ rolesForUsersPredicate(provider, users) {
221
+ const ids = users.map(u => String(u.ID)).filter(id => /^[0-9A-Fa-f-]{1,64}$/.test(id));
222
+ if (ids.length === 0) {
223
+ return null;
224
+ }
225
+ const list = ids.map(id => `'${EscapeSQLString(id)}'`).join(', ');
226
+ return ` WHERE ${provider.QuoteIdentifier('UserID')} IN (${list})`;
227
+ }
228
+ /**
229
+ * The quoted schema and base view for an entity, from metadata when it is loaded (a deployment
230
+ * may point the entity at a different view), falling back to the core schema and the
231
+ * conventional name — this cache is loaded during bootstrap, before metadata on some hosts.
232
+ */
233
+ viewFor(provider, entityName, defaultView) {
234
+ const entity = provider.Entities?.length ? provider.EntityByName(entityName) : undefined;
235
+ return provider.QuoteSchemaAndView(entity?.SchemaName || provider.MJCoreSchemaName, entity?.BaseView || defaultView);
236
+ }
101
237
  static get Instance() {
102
238
  return UserCache.getInstance();
103
239
  }
@@ -120,5 +256,456 @@ export class UserCache extends BaseSingleton {
120
256
  return caseSensitive ? comparisonItem === item : comparisonItem.toLowerCase() === item.toLowerCase();
121
257
  });
122
258
  }
259
+ // ────────────────────────────────────────────────────────────────────────────────────────────
260
+ // Finding a user: a miss is a question for the database, not an answer
261
+ // ────────────────────────────────────────────────────────────────────────────────────────────
262
+ /**
263
+ * Finds a user by ID or email. **Prefer this over `Users.find(...)` on any path that decides
264
+ * whether a request is allowed.** A plain `find` renders "this process has not loaded that user"
265
+ * as "that user does not exist", which is how a newly created account is rejected as invalid
266
+ * until the server restarts.
267
+ *
268
+ * A miss here is checked against the database (one indexed row read) and, when the user is
269
+ * really there, added to the cache so later lookups are free. A user that the database does not
270
+ * have either is remembered as absent for {@link MissRetryIntervalMs}, so a bad credential
271
+ * cannot turn into a query per request.
272
+ *
273
+ * @returns The user, or undefined when neither the cache nor the database has it.
274
+ */
275
+ async FindUser(criteria) {
276
+ const cached = this.findCached(criteria);
277
+ if (cached || !this._provider) {
278
+ return cached;
279
+ }
280
+ const key = this.missKey(criteria);
281
+ if (!key) {
282
+ return undefined;
283
+ }
284
+ const lastMiss = this._recentMisses.get(key);
285
+ if (lastMiss !== undefined && Date.now() - lastMiss < UserCache.MissRetryIntervalMs) {
286
+ return undefined; // asked recently and the database did not have it either
287
+ }
288
+ try {
289
+ const loaded = await this.LoadUsers(this._provider, this.whereFor(criteria));
290
+ const user = loaded?.[0];
291
+ if (!user) {
292
+ this.rememberMiss(key);
293
+ return undefined;
294
+ }
295
+ // Keep the array instance: callers (MJServer auth) hold and push to it.
296
+ const index = this._users.findIndex(u => UUIDsEqual(u.ID, user.ID));
297
+ if (index >= 0) {
298
+ this._users[index] = user;
299
+ }
300
+ else {
301
+ this._users.push(user);
302
+ }
303
+ LogStatusEx({ message: `UserCache: loaded user ${user.ID} on demand — it was created after this process last refreshed`, verboseOnly: true });
304
+ return user;
305
+ }
306
+ catch (e) {
307
+ LogError(`UserCache.FindUser failed: ${e instanceof Error ? e.message : String(e)}`);
308
+ return undefined;
309
+ }
310
+ }
311
+ /**
312
+ * Remembers that the database did not have this lookup either, pruning as it goes: the map is
313
+ * keyed by whatever a caller asked for, so a credential-stuffing run of distinct addresses
314
+ * would otherwise grow it without limit.
315
+ */
316
+ rememberMiss(key) {
317
+ const now = Date.now();
318
+ for (const [k, at] of this._recentMisses) {
319
+ if (now - at >= UserCache.MissRetryIntervalMs) {
320
+ this._recentMisses.delete(k);
321
+ }
322
+ }
323
+ while (this._recentMisses.size >= UserCache.MaxRememberedMisses) {
324
+ const oldest = this._recentMisses.keys().next();
325
+ if (oldest.done) {
326
+ break;
327
+ }
328
+ this._recentMisses.delete(oldest.value);
329
+ }
330
+ this._recentMisses.set(key, now);
331
+ }
332
+ /** The cached answer for {@link FindUser}'s criteria, without touching the database. */
333
+ findCached(criteria) {
334
+ if (criteria.ID) {
335
+ return this._users.find(u => UUIDsEqual(u.ID, criteria.ID));
336
+ }
337
+ const email = criteria.Email?.trim().toLowerCase();
338
+ return email ? this._users.find(u => u.Email?.trim().toLowerCase() === email) : undefined;
339
+ }
340
+ missKey(criteria) {
341
+ if (criteria.ID)
342
+ return `id:${criteria.ID.trim().toLowerCase()}`;
343
+ const email = criteria.Email?.trim().toLowerCase();
344
+ return email ? `email:${email}` : null;
345
+ }
346
+ /** Predicate for the single-row read; values are escaped, and the ID is checked for shape. */
347
+ whereFor(criteria) {
348
+ const provider = this._provider;
349
+ if (criteria.ID) {
350
+ return `${provider.QuoteIdentifier('ID')} = '${EscapeSQLString(criteria.ID.trim())}'`;
351
+ }
352
+ return `LOWER(${provider.QuoteIdentifier('Email')}) = '${EscapeSQLString((criteria.Email ?? '').trim().toLowerCase())}'`;
353
+ }
354
+ // ────────────────────────────────────────────────────────────────────────────────────────────
355
+ // Staying current
356
+ // ────────────────────────────────────────────────────────────────────────────────────────────
357
+ /**
358
+ * Subscribes this process to what makes the cache stale: local writes to the two entities, and
359
+ * shared-cache events from other processes. Runs once.
360
+ */
361
+ wire() {
362
+ if (this._wired) {
363
+ return;
364
+ }
365
+ this._wired = true;
366
+ MJGlobal.Instance.GetEventListener(false).subscribe((mjEvent) => {
367
+ if (mjEvent.event !== MJEventType.ComponentEvent || mjEvent.eventCode !== BaseEntity.BaseEventCode) {
368
+ return;
369
+ }
370
+ this.handleEntityEvent(mjEvent.args);
371
+ });
372
+ this._unsubscribeCacheEvents = LocalCacheManager.Instance.RegisterChangeCallback(USER_CACHE_STAMP_KEY, (event) => this.handleSharedCacheEvent(event));
373
+ }
374
+ /** A user or user-role row changed in THIS process: reload, then tell the others. */
375
+ handleEntityEvent(event) {
376
+ if (!event || (event.type !== 'save' && event.type !== 'delete')) {
377
+ return;
378
+ }
379
+ const entityName = event.baseEntity?.EntityInfo?.Name ?? event.entityName;
380
+ if (!entityName || !USER_ENTITY_NAMES.has(entityName.trim().toLowerCase())) {
381
+ return;
382
+ }
383
+ const writer = this.writerOf(event);
384
+ if (writer) {
385
+ this._pendingWriters.add(writer);
386
+ }
387
+ this.scheduleRefresh(UserCache.ChangeDebounceMs, true);
388
+ }
389
+ /**
390
+ * Another process changed users (the stamp key), or a tool cleared the shared cache after
391
+ * changing the database (a RunView category clear). Either way this cache may be stale.
392
+ */
393
+ handleSharedCacheEvent(event) {
394
+ const isClear = event.Action === 'category_cleared' && event.Category === CacheCategory.RunViewCache;
395
+ const isStamp = event.CacheKey === USER_CACHE_STAMP_KEY && event.Action !== 'category_cleared';
396
+ if (!isClear && !isStamp) {
397
+ return;
398
+ }
399
+ this.scheduleRefresh(UserCache.ChangeDebounceMs + Math.floor(Math.random() * UserCache.PeerNoticeJitterMs), false);
400
+ }
401
+ /**
402
+ * Reloads after `delayMs`, collecting a burst into one read.
403
+ * @param publishToPeers - true when this process made the change, so other processes are told.
404
+ */
405
+ scheduleRefresh(delayMs, publishToPeers) {
406
+ this._announcePending ||= publishToPeers; // never cleared by a later event, only by publishing
407
+ if (this._refreshTimer) {
408
+ clearTimeout(this._refreshTimer);
409
+ }
410
+ const timer = setTimeout(() => {
411
+ this._refreshTimer = null;
412
+ // A save raises its event while the transaction that made it is still open, and this
413
+ // cache's own writers (new-user creation on first login, the magic-link service, SaaS's
414
+ // provisioning handler) all save inside one. Reloading now reads the database WITHOUT the
415
+ // uncommitted row — on PostgreSQL or under RCSI it simply is not there — so the cache
416
+ // would be rebuilt without the very user that triggered it, and the peer notice would make
417
+ // every other server reload too early. Wait for the transaction to settle.
418
+ if (this.transactionStillOpen()) {
419
+ this._transactionWaits++;
420
+ this.scheduleRefresh(UserCache.TransactionWaitMs, false); // the flag already carries the intent
421
+ return;
422
+ }
423
+ this._transactionWaits = 0;
424
+ this._pendingWriters.clear();
425
+ const announce = this._announcePending;
426
+ this.RefreshNow()
427
+ .then(async () => {
428
+ if (announce) {
429
+ await this.publishStamp();
430
+ this._announcePending = false; // cleared only once peers have actually been told
431
+ }
432
+ })
433
+ .catch((e) => LogError(`UserCache refresh failed: ${e instanceof Error ? e.message : String(e)}`));
434
+ }, delayMs);
435
+ if (typeof timer === 'object' && timer !== null && 'unref' in timer) {
436
+ timer.unref();
437
+ }
438
+ this._refreshTimer = timer;
439
+ }
440
+ /**
441
+ * The provider a save or delete was made through: the entity's own, which on a server is the
442
+ * per-request instance. Falls back to the event's provider (`remote-invalidate` carries it
443
+ * there and has no entity).
444
+ */
445
+ writerOf(event) {
446
+ const candidate = event.baseEntity?.ProviderToUse ?? event.provider;
447
+ return this.isDatabaseProvider(candidate) ? candidate : null;
448
+ }
449
+ /** Whether a provider tracks transaction depth, which is all this cache needs from it. */
450
+ isDatabaseProvider(candidate) {
451
+ return !!candidate && typeof candidate.TransactionDepth === 'number';
452
+ }
453
+ /**
454
+ * True while a provider that raised one of the pending changes still has an open transaction,
455
+ * and the reload should keep waiting. Bounded: a transaction that never settles (a leaked
456
+ * handle) must not hold the reload forever — the periodic staleness check is the backstop, and
457
+ * the next user write re-arms this one.
458
+ */
459
+ transactionStillOpen() {
460
+ for (const writer of this._pendingWriters) {
461
+ if ((writer.TransactionDepth ?? 0) <= 0) {
462
+ this._pendingWriters.delete(writer); // settled; stop holding a reference to it
463
+ }
464
+ }
465
+ const depth = this._pendingWriters.size > 0
466
+ ? Math.max(...[...this._pendingWriters].map(w => w.TransactionDepth ?? 0))
467
+ : (this._provider?.TransactionDepth ?? 0);
468
+ if (depth <= 0) {
469
+ return false;
470
+ }
471
+ if (this._transactionWaits >= UserCache.MaxTransactionWaits) {
472
+ LogWarning(`UserCache waited ${this._transactionWaits} windows for an open transaction before reloading anyway; the writing unit of work has not settled`, 'Cache');
473
+ this._transactionWaits = 0;
474
+ this._pendingWriters.clear();
475
+ return false;
476
+ }
477
+ return true;
478
+ }
479
+ /**
480
+ * Reloads the cache from the provider it was last refreshed through. Concurrent calls share one
481
+ * read. Does nothing when this process never had a provider (a host that only calls
482
+ * {@link SetUsers}).
483
+ */
484
+ async RefreshNow() {
485
+ if (!this._provider) {
486
+ return;
487
+ }
488
+ if (this._refreshInFlight) {
489
+ return this._refreshInFlight;
490
+ }
491
+ const provider = this._provider;
492
+ this._refreshInFlight = (async () => {
493
+ try {
494
+ const users = await this.LoadUsers(provider);
495
+ if (users) {
496
+ this._users = users;
497
+ this._recentMisses.clear();
498
+ this._lastStamp = await this.readDatabaseStamp(provider);
499
+ }
500
+ }
501
+ finally {
502
+ this._refreshInFlight = null;
503
+ }
504
+ })();
505
+ return this._refreshInFlight;
506
+ }
507
+ /**
508
+ * Tells other processes that users changed, by writing {@link USER_CACHE_STAMP_KEY} to the
509
+ * shared store. A store that is private to this process publishes nothing, so this is a no-op
510
+ * there. Never throws: failing to notify peers must not fail the write that caused it.
511
+ */
512
+ async publishStamp() {
513
+ const storage = this._provider?.LocalStorageProvider;
514
+ if (!storage?.SharedAcrossProcesses) {
515
+ return;
516
+ }
517
+ try {
518
+ await storage.SetItem(USER_CACHE_STAMP_KEY, new Date().toISOString(), CacheCategory.Default);
519
+ }
520
+ catch (e) {
521
+ LogWarning(`UserCache could not notify other servers that users changed (${e instanceof Error ? e.message : String(e)}); they will see it at their next staleness check (cacheSettings.userCacheCheckIntervalSeconds) — or not until a restart if that check is disabled`, 'Cache');
522
+ }
523
+ }
524
+ // ────────────────────────────────────────────────────────────────────────────────────────────
525
+ // Periodic safety net
526
+ // ────────────────────────────────────────────────────────────────────────────────────────────
527
+ /**
528
+ * Compares the database with what this cache was built from — two counts and the newest
529
+ * `__mj_UpdatedAt` — and reloads only when they differ. Two small aggregate queries, so it is
530
+ * cheap enough to run on an interval. A deleted role row changes a count; a deactivation, or any
531
+ * other edit, moves `__mj_UpdatedAt`.
532
+ *
533
+ * It runs in two situations, and is skipped otherwise:
534
+ *
535
+ * - **`MJ: Users` or `MJ: User Roles` declares `TrustServerCacheCompletely = false`** — rows can
536
+ * change without an event (raw SQL, another application, a restore), and this is the only thing
537
+ * that can find them.
538
+ * - **This process shares its cache with other processes.** Then a change made on a peer reaches
539
+ * this one only as a pub/sub notice, and pub/sub delivers at most once with no replay after a
540
+ * reconnect. A lost notice is harmless for a GRANT — a new user or role is a cache miss, and a
541
+ * miss falls back to an authoritative read in {@link FindUser}. It is not harmless for a
542
+ * REVOCATION: a removed role or a deactivated user is a cache HIT that still carries the old
543
+ * state, and nothing re-reads it. Without this check a dropped notice would leave a revoked user
544
+ * authorised on that peer until the next user write or a restart. Revocation is a security
545
+ * control, so the cost — one cheap query per process per interval — is paid wherever peers
546
+ * exist.
547
+ *
548
+ * A single process with a private cache has no peer whose notice it can miss, so it issues no
549
+ * query — which keeps a serverless database free to pause.
550
+ *
551
+ * @returns true when the cache was reloaded.
552
+ */
553
+ async RefreshIfChangedInDatabase() {
554
+ if (!this._provider || !this.stalenessCheckWarranted()) {
555
+ return false;
556
+ }
557
+ try {
558
+ const stamp = await this.readDatabaseStamp(this._provider);
559
+ if (!stamp || (this._lastStamp && this.stampsMatch(stamp, this._lastStamp))) {
560
+ return false;
561
+ }
562
+ await this.RefreshNow();
563
+ return true;
564
+ }
565
+ catch (e) {
566
+ LogError(`UserCache staleness check failed: ${e instanceof Error ? e.message : String(e)}`);
567
+ return false;
568
+ }
569
+ }
570
+ /**
571
+ * Arms the periodic full reload of users and roles, replacing any previous schedule.
572
+ *
573
+ * The timer ticks every `intervalMs`, but it reads the database **only when `MJ: Users` or
574
+ * `MJ: User Roles` declares `TrustServerCacheCompletely = false`** — see
575
+ * {@link usersMayChangeWithoutAnEvent}. A tick with nothing declared costs one in-memory lookup
576
+ * and issues no query, so an entity marked later is honoured on the next tick without a restart.
577
+ *
578
+ * Why the reload is conditional: a recurring query prevents a serverless database from pausing,
579
+ * and when every mutation flows through `BaseEntity` there is nothing for a reload to discover —
580
+ * a local save raises an event, a save on another process publishes the shared stamp, and
581
+ * {@link FindUser} falls back to an authoritative read on a miss. The reload therefore earns its
582
+ * cost only where rows can appear without an event.
583
+ *
584
+ * `Refresh` may be called more than once in a process (a bootstrap pass, then host
585
+ * configuration); each call re-arms this single timer rather than starting another chain.
586
+ *
587
+ * @param intervalMs Tick interval. `0` or absent leaves the timer off.
588
+ */
589
+ scheduleAutoRefresh(provider, intervalMs) {
590
+ if (this._autoRefreshTimer) {
591
+ clearTimeout(this._autoRefreshTimer);
592
+ this._autoRefreshTimer = null;
593
+ }
594
+ if (!intervalMs || intervalMs <= 0) {
595
+ return;
596
+ }
597
+ const timer = setTimeout(() => {
598
+ this._autoRefreshTimer = null;
599
+ if (this.usersMayChangeWithoutAnEvent()) {
600
+ void this.Refresh(provider, intervalMs); // reloads, and re-arms from there
601
+ }
602
+ else {
603
+ this.scheduleAutoRefresh(provider, intervalMs); // keep ticking, ask the database nothing
604
+ }
605
+ }, intervalMs);
606
+ if (typeof timer === 'object' && timer !== null && 'unref' in timer) {
607
+ timer.unref();
608
+ }
609
+ this._autoRefreshTimer = timer;
610
+ }
611
+ /**
612
+ * Whether {@link RefreshIfChangedInDatabase} should query: rows can change without an event, or
613
+ * peers share this cache and one of their notices could have been lost. See that method for why
614
+ * the second case cannot be left to the event path.
615
+ */
616
+ stalenessCheckWarranted() {
617
+ return this.usersMayChangeWithoutAnEvent() || this.peersShareThisCache();
618
+ }
619
+ /** Whether other processes read and write the same cache store as this one. */
620
+ peersShareThisCache() {
621
+ return this._provider?.LocalStorageProvider?.SharedAcrossProcesses === true;
622
+ }
623
+ /**
624
+ * Whether `MJ: Users` or `MJ: User Roles` has **declared** that its rows can change without
625
+ * firing an event — the only thing a periodic database check can discover.
626
+ *
627
+ * `Entity.TrustServerCacheCompletely` is that declaration: true (the default) means every
628
+ * mutation flows through `BaseEntity.Save()`, which this cache already hears. Polling such an
629
+ * entity buys nothing and costs a recurring query, which on Azure SQL serverless prevents
630
+ * auto-pause outright — the interval cannot fix that, only not running can.
631
+ *
632
+ * Nothing is lost for the case that motivated this cache's rework (a new user unable to log
633
+ * in): a save in any process raises an event, a save in another process publishes the shared
634
+ * stamp, and a lookup that misses still falls back to an authoritative read in `FindUser`. So
635
+ * even a user inserted by raw SQL can authenticate without this poll — it is the backstop for
636
+ * out-of-band writes. It is one of the two conditions under which the staleness check runs; see
637
+ * {@link stalenessCheckWarranted}.
638
+ */
639
+ usersMayChangeWithoutAnEvent() {
640
+ const provider = this._provider;
641
+ if (!provider) {
642
+ return false;
643
+ }
644
+ return [USERS_ENTITY, USER_ROLES_ENTITY]
645
+ .some(name => provider.EntityByName(name)?.TrustServerCacheCompletely === false);
646
+ }
647
+ /** Runs {@link RefreshIfChangedInDatabase} on an interval. `intervalMs <= 0` stops it. */
648
+ StartStalenessChecks(intervalMs) {
649
+ this.StopStalenessChecks();
650
+ if (!intervalMs || intervalMs <= 0) {
651
+ return;
652
+ }
653
+ this._stalenessTimer = setInterval(() => {
654
+ this.RefreshIfChangedInDatabase().catch(() => undefined); // already logged
655
+ }, intervalMs);
656
+ if (typeof this._stalenessTimer === 'object' && this._stalenessTimer !== null && 'unref' in this._stalenessTimer) {
657
+ this._stalenessTimer.unref();
658
+ }
659
+ }
660
+ StopStalenessChecks() {
661
+ if (this._stalenessTimer) {
662
+ clearInterval(this._stalenessTimer);
663
+ this._stalenessTimer = null;
664
+ }
665
+ }
666
+ stampsMatch(a, b) {
667
+ return a.UserCount === b.UserCount && a.RoleCount === b.RoleCount && a.MaxUpdatedAt === b.MaxUpdatedAt;
668
+ }
669
+ /**
670
+ * Row counts and the newest update timestamp across both views. A user row's own
671
+ * `__mj_UpdatedAt` covers edits and deactivations; the counts cover creates and deletes.
672
+ */
673
+ async readDatabaseStamp(provider) {
674
+ try {
675
+ const updatedAt = provider.QuoteIdentifier('__mj_UpdatedAt');
676
+ const count = provider.QuoteIdentifier('RowCount');
677
+ const newest = provider.QuoteIdentifier('MaxUpdatedAt');
678
+ const scope = provider.QuoteIdentifier('Scope');
679
+ // One round trip for both views.
680
+ const rows = await provider.ExecuteSQL(`SELECT 'users' AS ${scope}, COUNT(*) AS ${count}, MAX(${updatedAt}) AS ${newest} FROM ${this.viewFor(provider, USERS_ENTITY, 'vwUsers')}` +
681
+ ` UNION ALL ` +
682
+ `SELECT 'roles' AS ${scope}, COUNT(*) AS ${count}, MAX(${updatedAt}) AS ${newest} FROM ${this.viewFor(provider, USER_ROLES_ENTITY, 'vwUserRoles')}`);
683
+ const users = rows?.find(r => r.Scope === 'users');
684
+ const roles = rows?.find(r => r.Scope === 'roles');
685
+ if (!users || !roles) {
686
+ return null;
687
+ }
688
+ const latest = [users.MaxUpdatedAt, roles.MaxUpdatedAt]
689
+ .map(v => (v instanceof Date ? v.toISOString() : v ? new Date(v).toISOString() : ''))
690
+ .sort()
691
+ .at(-1) ?? '';
692
+ return { UserCount: Number(users.RowCount), RoleCount: Number(roles.RowCount), MaxUpdatedAt: latest };
693
+ }
694
+ catch (e) {
695
+ LogError(`UserCache could not read the user/role stamp: ${e instanceof Error ? e.message : String(e)}`);
696
+ return null;
697
+ }
698
+ }
699
+ /** Stops the timers and event subscriptions this cache owns. For tests and clean shutdown. */
700
+ Dispose() {
701
+ this.StopStalenessChecks();
702
+ if (this._refreshTimer) {
703
+ clearTimeout(this._refreshTimer);
704
+ this._refreshTimer = null;
705
+ }
706
+ this._unsubscribeCacheEvents?.();
707
+ this._unsubscribeCacheEvents = null;
708
+ this._wired = false;
709
+ }
123
710
  }
124
711
  //# sourceMappingURL=UserCache.js.map