masterrecord 1.5.15 → 1.5.17

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/CHANGES.md CHANGED
@@ -1,5 +1,30 @@
1
1
  # MasterRecord Changelog
2
2
 
3
+ ## v1.5.17 — connections stay warm across close/reopen (ADO.NET-style pooling; no reconnect churn)
4
+
5
+ `close()` physically closed a pooled connection the moment its refcount reached zero. So a request-scoped context (or a background job that builds a scope per run and disposes it) reconnected on every cycle whenever it was the sole holder — the exact churn that scoping was supposed to avoid.
6
+
7
+ EF/ADO.NET doesn't do this: disposing a `DbContext` returns its connection to the pool **kept physically open and idle**, and the next context reuses it warm. MasterRecord's `_pools` now behaves the same:
8
+
9
+ - At refcount zero the connection is **kept open and idle** (not closed). The next context that needs the same database reuses the warm connection with no reconnect. Verified: `close()` then `new Ctx()` yields the *same* engine instance.
10
+ - A background **reaper** physically closes connections idle longer than `MR_POOL_IDLE_MS` (default `60000`), so idle connections are reclaimed, not leaked. The reaper timer is `unref()`-ed and never keeps the process alive; `closeAll()` stops it.
11
+ - **`MR_POOL_IDLE_MS=0`** opts out — the old behavior (close immediately at refcount zero).
12
+
13
+ This makes per-request contexts and per-run background scopes genuinely cheap: `new AppContext()` allocates a tracking map and points at the already-open connection; `close()` returns it to the pool warm.
14
+
15
+ New tests: `test/pool-idle-retention.test.js` — a closed connection is reused warm (no reconnect); the reaper closes a connection idle past the timeout; `MR_POOL_IDLE_MS=0` closes immediately. Full suite green (0 fail, 315 pass, 20 gated skipped); 0 lint errors.
16
+
17
+ ## v1.5.16 — context pooling (EF's AddDbContextPool) + reset(); change-tracking/lifetime docs
18
+
19
+ Completes the EF-faithful context-lifetime story so request-scoped contexts are affordable even with many contexts registered.
20
+
21
+ - **`ContextPool`** (EF Core's `AddDbContextPool`): a bounded pool of context instances kept **with their connections warm**. `acquire()` rents an exclusive, reset instance; `release(ctx)` resets it and returns it; `use(fn)` does acquire→run→release (releasing even on error); `drain()` closes idle instances at shutdown. Each request still gets its own instance (no cross-request sharing), but you pay connection/setup cost once instead of per request. Exported as `masterrecord.ContextPool` and `masterrecord/ContextPool`.
22
+ - **`context.reset()`**: the "return to pool" primitive — detaches all tracked entities, clears the dirty index and the query cache, but **keeps the connection open** (distinct from `close()`, which also tears down the connection). This is what lets a pooled instance behave like a fresh per-request context.
23
+
24
+ **Docs:** new **`docs/CHANGE_TRACKING_AND_CONTEXT_LIFETIME.md`** documents the whole model shipped across 1.5.9–1.5.16 — how tracking works, `asNoTracking()`/`asTracking()`, `setQueryTrackingBehavior()`, `clearChangeTracker()`/`detach()`, `reset()`/`close()`, `ContextPool`, why singleton contexts are unsafe, and a 1:1 mapping to Entity Framework Core. The readme's Best Practices now leads with context scoping.
25
+
26
+ New tests: `test/context-pool-and-reset.test.js` — `reset()` clears the unit of work but keeps the connection usable; the pool lends a reset instance and returns it (writes persist across rentals; a new rental starts empty); `use()` releases even when the body throws. Full suite green (0 fail, 312 pass, 20 gated skipped); 0 lint errors.
27
+
3
28
  ## v1.5.15 — close() releases the change tracker (EF Dispose parity for request-scoped contexts)
4
29
 
5
30
  EF Core's bounded-memory model is a short-lived, request-scoped `DbContext` that is **disposed** per unit of work — disposal releases the whole `ChangeTracker`. masterrecord's `close()` did everything *except* that: it dropped the live-context registration and the connection-pool ref, but left the tracked-entity map and dirty index populated, so a scoped context only freed its entities when the context object itself was GC'd.
package/ContextPool.js ADDED
@@ -0,0 +1,121 @@
1
+ /**
2
+ * ContextPool — a bounded pool of reusable context instances, modeled on
3
+ * Entity Framework Core's `AddDbContextPool`.
4
+ *
5
+ * A context is a unit of work and must be scoped per request (it is not safe to
6
+ * share one instance across concurrent requests). Constructing a fresh context
7
+ * per request is correct but pays connection/setup cost every time. A pool keeps
8
+ * a small set of instances — with their database connections warm — and lends an
9
+ * exclusive one per request: `acquire()` rents an instance (reset and ready),
10
+ * `release()` resets its change tracker/cache (NOT the connection) and returns
11
+ * it for reuse. You pay setup once, and each request still gets its own
12
+ * instance, so there is no cross-request sharing.
13
+ *
14
+ * @example
15
+ * const pool = new ContextPool(AppContext, { maxSize: 64 });
16
+ * // per request:
17
+ * const db = await pool.acquire();
18
+ * try {
19
+ * // ... load / mutate / saveChanges, exactly like a scoped context ...
20
+ * } finally {
21
+ * pool.release(db); // reset + return to pool (connection stays open)
22
+ * }
23
+ * // at shutdown: await pool.drain();
24
+ */
25
+ class ContextPool {
26
+ /**
27
+ * @param {Function} ContextCtor - a context class (extends masterrecord.context)
28
+ * @param {object} [options]
29
+ * @param {number} [options.maxSize=128] - max idle instances kept warm; when
30
+ * the pool is at capacity on release, the returned instance is closed
31
+ * instead of pooled. Rentals beyond this still succeed (extra instances are
32
+ * created on demand and simply closed rather than pooled on release).
33
+ */
34
+ constructor(ContextCtor, options = {}) {
35
+ if (typeof ContextCtor !== 'function') {
36
+ throw new Error('ContextPool: first argument must be a context class (constructor).');
37
+ }
38
+ this._ctor = ContextCtor;
39
+ this._maxSize = Number.isInteger(options.maxSize) && options.maxSize > 0 ? options.maxSize : 128;
40
+ this._idle = []; // instances ready to lend (reset, connection warm)
41
+ this._rented = new Set();
42
+ this._drained = false;
43
+ }
44
+
45
+ /**
46
+ * Rent an instance from the pool (or create one if none are idle). The
47
+ * returned context is reset and its connection is ready. Give it back with
48
+ * release() when the unit of work is done.
49
+ */
50
+ async acquire() {
51
+ if (this._drained) throw new Error('ContextPool: cannot acquire from a drained pool.');
52
+ let ctx = this._idle.pop();
53
+ if (!ctx) {
54
+ ctx = new this._ctor();
55
+ }
56
+ // Ensure the connection is initialized before handing it out.
57
+ if (typeof ctx._ensureReady === 'function') {
58
+ await ctx._ensureReady();
59
+ }
60
+ this._rented.add(ctx);
61
+ return ctx;
62
+ }
63
+
64
+ /**
65
+ * Return an instance to the pool. Its unit of work is reset (tracked
66
+ * entities detached, dirty index and query cache cleared) but its connection
67
+ * is kept open for reuse. If the pool is already full, the instance is closed
68
+ * instead of retained.
69
+ */
70
+ release(ctx) {
71
+ if (!ctx) return;
72
+ this._rented.delete(ctx);
73
+ try {
74
+ if (typeof ctx.reset === 'function') ctx.reset();
75
+ } catch (_) { /* fall through to close on a bad reset */ }
76
+
77
+ if (this._drained || this._idle.length >= this._maxSize) {
78
+ // Pool full or shutting down: actually close this one.
79
+ Promise.resolve(typeof ctx.close === 'function' ? ctx.close() : undefined).catch(() => {});
80
+ return;
81
+ }
82
+ this._idle.push(ctx);
83
+ }
84
+
85
+ /**
86
+ * Run `fn(ctx)` with a rented instance and release it automatically —
87
+ * including on error. Returns whatever `fn` returns.
88
+ *
89
+ * @example await pool.use(async (db) => { ...; await db.saveChanges(); });
90
+ */
91
+ async use(fn) {
92
+ const ctx = await this.acquire();
93
+ try {
94
+ return await fn(ctx);
95
+ } finally {
96
+ this.release(ctx);
97
+ }
98
+ }
99
+
100
+ /** Number of idle (pooled) instances currently kept warm. */
101
+ get size() { return this._idle.length; }
102
+ /** Number of instances currently rented out (in flight). */
103
+ get rented() { return this._rented.size; }
104
+
105
+ /**
106
+ * Close every idle instance and stop pooling. Call at application shutdown.
107
+ * Rented instances are left to their holders to release (release() will close
108
+ * them because the pool is drained).
109
+ */
110
+ async drain() {
111
+ this._drained = true;
112
+ const idle = this._idle.splice(0, this._idle.length);
113
+ for (const ctx of idle) {
114
+ if (typeof ctx.close === 'function') {
115
+ try { await ctx.close(); } catch (_) { /* best-effort */ }
116
+ }
117
+ }
118
+ }
119
+ }
120
+
121
+ export default ContextPool;
package/MasterRecord.js CHANGED
@@ -1,11 +1,13 @@
1
1
  // version 1.1.0
2
2
  import context from './context.js';
3
3
  import schema from './Migrations/schema.js';
4
+ import ContextPool from './ContextPool.js';
4
5
 
5
6
  class masterrecord {
6
7
  constructor() {
7
8
  this.context = context;
8
9
  this.schema = schema;
10
+ this.ContextPool = ContextPool; // EF AddDbContextPool equivalent
9
11
  }
10
12
  }
11
13
 
package/context.js CHANGED
@@ -59,6 +59,37 @@ function findAppRoot(){
59
59
 
60
60
  const _pools = global.__MR_POOLS__ || (global.__MR_POOLS__ = new Map());
61
61
 
62
+ // ADO.NET-style connection pooling (what EF sits on top of): when a pooled
63
+ // connection's refCount reaches zero it is NOT physically closed — it is kept
64
+ // OPEN and IDLE so the next context that needs it reuses a warm connection
65
+ // (this is why EF does not reconnect on every scope/DbContext dispose). A
66
+ // background reaper physically closes connections that have been idle longer
67
+ // than the timeout, so idle connections are eventually reclaimed. Set
68
+ // MR_POOL_IDLE_MS=0 to disable retention (close immediately at refCount 0).
69
+ const _POOL_IDLE_MS = process.env.MR_POOL_IDLE_MS !== undefined && Number(process.env.MR_POOL_IDLE_MS) >= 0
70
+ ? Number(process.env.MR_POOL_IDLE_MS)
71
+ : 60_000;
72
+ let _poolReaper = global.__MR_POOL_REAPER__ || null;
73
+ function _ensurePoolReaper() {
74
+ if (_poolReaper || _POOL_IDLE_MS <= 0) return;
75
+ _poolReaper = setInterval(() => {
76
+ const now = Date.now();
77
+ for (const [key, entry] of _pools) {
78
+ if (entry && !entry.promise && entry.refCount <= 0
79
+ && entry.idleSince != null && (now - entry.idleSince) >= _POOL_IDLE_MS) {
80
+ _pools.delete(key);
81
+ try {
82
+ if (entry.engine && typeof entry.engine.close === 'function') {
83
+ Promise.resolve(entry.engine.close()).catch(() => {});
84
+ }
85
+ } catch (_) { /* best-effort */ }
86
+ }
87
+ }
88
+ }, Math.min(Math.max(_POOL_IDLE_MS, 1000), 30_000));
89
+ if (typeof _poolReaper.unref === 'function') _poolReaper.unref(); // never keep the process alive
90
+ global.__MR_POOL_REAPER__ = _poolReaper;
91
+ }
92
+
62
93
  // Registry of live context instances so saveChanges()/close() can detect entities
63
94
  // with unsaved changes that are tracked by a DIFFERENT context instance — the
64
95
  // classic "saveChanges() succeeded but nothing was written" bug: you mutate an
@@ -2660,9 +2691,21 @@ class context {
2660
2691
  if (entry.engine === this._SQLEngine) {
2661
2692
  entry.refCount--;
2662
2693
  if (entry.refCount <= 0) {
2663
- _pools.delete(key);
2664
- if (this._SQLEngine && typeof this._SQLEngine.close === 'function') {
2665
- await this._SQLEngine.close();
2694
+ // ADO.NET-style: do NOT close the physical connection now.
2695
+ // Keep it OPEN and idle so the next context reuses a warm
2696
+ // connection (as EF does — a scoped DbContext dispose returns
2697
+ // its connection to the pool, it is not disconnected). The
2698
+ // reaper closes it only after it has been idle past the
2699
+ // timeout. (MR_POOL_IDLE_MS=0 disables retention -> close now.)
2700
+ entry.refCount = 0;
2701
+ if (_POOL_IDLE_MS <= 0) {
2702
+ _pools.delete(key);
2703
+ if (this._SQLEngine && typeof this._SQLEngine.close === 'function') {
2704
+ await this._SQLEngine.close();
2705
+ }
2706
+ } else {
2707
+ entry.idleSince = Date.now();
2708
+ _ensurePoolReaper();
2666
2709
  }
2667
2710
  }
2668
2711
  this._SQLEngine = null;
@@ -2713,6 +2756,12 @@ class context {
2713
2756
  }
2714
2757
  }
2715
2758
  _pools.clear();
2759
+ // Stop the idle-connection reaper (nothing left to reap).
2760
+ if (_poolReaper) {
2761
+ clearInterval(_poolReaper);
2762
+ _poolReaper = null;
2763
+ global.__MR_POOL_REAPER__ = null;
2764
+ }
2716
2765
  }
2717
2766
 
2718
2767
  /**
@@ -3012,6 +3061,23 @@ class context {
3012
3061
  return this;
3013
3062
  }
3014
3063
 
3064
+ /**
3065
+ * Reset this context's unit of work for REUSE — detach all tracked entities,
3066
+ * clear the dirty index and the query cache — WITHOUT closing the database
3067
+ * connection. This is the "return to pool" primitive behind context pooling
3068
+ * (EF Core resets a pooled DbContext's ChangeTracker on release): the
3069
+ * connection stays warm so the instance can serve the next request cheaply.
3070
+ *
3071
+ * Use `close()` to actually tear down the connection; use `reset()` to make
3072
+ * a kept-alive instance behave like a fresh per-request context.
3073
+ */
3074
+ reset() {
3075
+ this.__clearTracked(); // detach all + clear the dirty index
3076
+ this.clearQueryCache(); // drop cached query results
3077
+ this.__clearErrorHandler(); // clear any pending error handler
3078
+ return this;
3079
+ }
3080
+
3015
3081
  /**
3016
3082
  * Detach a single entity from change tracking. Pending changes on it are
3017
3083
  * dropped and it is no longer part of any future saveChanges().
@@ -0,0 +1,128 @@
1
+ # Change Tracking & Context Lifetime
2
+
3
+ MasterRecord's change tracking follows the **Unit of Work + Identity Map** model that Entity Framework Core uses. This guide covers how tracking works, how to control it, and — most importantly — how to scope a context so it is correct and bounded in memory.
4
+
5
+ > **The one rule that prevents most problems:** a context is a **unit of work**. Scope it **per request**, not as a process-wide singleton. This mirrors EF Core, whose docs state a `DbContext` "is not thread-safe" and "designed to be used for a single unit-of-work." Sharing one context across concurrent requests is unsupported and causes lost writes and unbounded memory.
6
+
7
+ ---
8
+
9
+ ## How tracking works
10
+
11
+ - A **query tracks its results by default**. Loaded entities are registered in the context's identity map, so later edits are detected.
12
+ - Mutating a tracked entity marks it **dirty**; `saveChanges()` flushes the dirty set in one transaction.
13
+ - Each `saveChanges()` commits **only its change set** (the dirty entities). A flush is **O(changes)**, not O(total tracked); an empty save is O(1).
14
+ - After a successful flush, written entities are reset to clean and released; deletes are detached; anything re-mutated mid-flush stays pending.
15
+
16
+ ```javascript
17
+ const user = await db.User.where('u => u.id == $$', id).single(); // tracked
18
+ user.blocked = 1; // dirty
19
+ await db.saveChanges(); // one UPDATE
20
+ ```
21
+
22
+ ---
23
+
24
+ ## Controlling what gets tracked (EF's `QueryTrackingBehavior`)
25
+
26
+ Tracking is the default. For read-only work, opt out so nothing is retained.
27
+
28
+ | API | EF Core equivalent | Effect |
29
+ |---|---|---|
30
+ | `db.Model.asNoTracking().toList()` | `AsNoTracking()` | This query's results are **not** tracked; nothing retained; mutations on them are not saved. |
31
+ | `db.Model.asTracking()...` | `AsTracking()` | Track this query even when the context defaults to no-tracking. |
32
+ | `context.setQueryTrackingBehavior('no-track')` | `ChangeTracker.QueryTrackingBehavior = NoTracking` | Make **every** query no-tracking by default; opt back in per query with `asTracking()`. |
33
+ | `context.setQueryTrackingBehavior('track')` | (default) | Queries track their results. |
34
+
35
+ **Read-only endpoints** (e.g. a listing that `.toList()`s a whole table) should use `asNoTracking()` — it is the direct fix for a growing tracked set:
36
+
37
+ ```javascript
38
+ const users = await db.User.asNoTracking().toList(); // retains nothing
39
+ ```
40
+
41
+ If you set a `no-track` default on a shared/long-lived context, remember every write path must then use `asTracking()` on the query it intends to modify — otherwise its edits won't be tracked. That is an app-wide change; prefer request-scoped contexts (below) if you can.
42
+
43
+ ---
44
+
45
+ ## Managing the tracker
46
+
47
+ | API | EF Core equivalent | Effect |
48
+ |---|---|---|
49
+ | `context.detach(entity)` | `Entry(e).State = Detached` | Stop tracking one entity (drops its pending change). |
50
+ | `context.clearChangeTracker()` | `ChangeTracker.Clear()` | Detach all entities and drop all pending changes. |
51
+ | `context.reset()` | (pool release reset) | Detach all + clear the query cache, but **keep the connection open** — the "reuse this instance" primitive. |
52
+ | `await context.close()` | `Dispose()` | Release the change tracker **and** the connection (decrements the connection-pool ref). |
53
+
54
+ `clearChangeTracker()` drops pending changes, so on a shared context it can destroy another in-flight request's writes — it is not a safe per-request mitigation. Use request-scoped contexts or `asNoTracking()` instead.
55
+
56
+ ---
57
+
58
+ ## Scoping a context (the memory bound)
59
+
60
+ MasterRecord holds tracked entities with **strong references** for the life of the context (as EF does — EF removed weak references in 3.0). Memory is therefore bounded by **context lifetime**, exactly as in EF Core. Two supported patterns:
61
+
62
+ ### 1. Request-scoped context (recommended)
63
+
64
+ Create a context per request and `close()` it when the request ends. Every `load → mutate → saveChanges` handler works unchanged, with no tracking-behavior tweaks and no way to introduce a lost write.
65
+
66
+ `new AppContext()` is cheap — it does **not** open a new connection. Connections are pooled per database (like ADO.NET under EF): `close()` releases the change tracker and returns the connection to the pool **kept open and idle**, so the next context reuses a warm connection with no reconnect. Idle connections are reclaimed by a background reaper after `MR_POOL_IDLE_MS` (default 60000ms; set `0` to close immediately at refcount zero). So per-request contexts — and background jobs that build a scope per run — do not churn connections.
67
+
68
+ ```javascript
69
+ async function handler(req, res) {
70
+ const db = new AppContext();
71
+ try {
72
+ // ... load / mutate / saveChanges ...
73
+ } finally {
74
+ await db.close(); // releases tracker + returns the connection
75
+ }
76
+ }
77
+ ```
78
+
79
+ ### 2. Context pooling (EF's `AddDbContextPool`)
80
+
81
+ If constructing a context per request is too costly (e.g. many contexts, or you want to avoid connection churn), use a `ContextPool`. It keeps a small set of instances **with their connections warm** and lends an exclusive, reset instance per request — you pay setup once, and each request still gets its own instance (no cross-request sharing).
82
+
83
+ ```javascript
84
+ import ContextPool from 'masterrecord/ContextPool';
85
+ // or: const { ContextPool } = masterrecord;
86
+
87
+ const pool = new ContextPool(AppContext, { maxSize: 64 });
88
+
89
+ // per request — automatic acquire/reset/release, even on error:
90
+ await pool.use(async (db) => {
91
+ const user = await db.User.asTracking().where('u => u.id == $$', id).single();
92
+ user.blocked = 1;
93
+ await db.saveChanges();
94
+ });
95
+
96
+ // at shutdown:
97
+ await pool.drain();
98
+ ```
99
+
100
+ `pool.acquire()` / `pool.release(ctx)` are available if you need manual control. `release()` calls `reset()` (detach all + clear cache, connection kept), so the next rental behaves like a fresh context.
101
+
102
+ ---
103
+
104
+ ## Why not a singleton context?
105
+
106
+ A singleton context shared across concurrent requests is the root cause of an entire class of bugs (and is unsupported in EF for the same reasons):
107
+
108
+ - **Lost writes** — one request's `saveChanges()` interacting with another's tracked entities.
109
+ - **Unbounded memory** — read-only queries track results that are never released.
110
+ - **Undefined behavior** under concurrent access (EF: "application crashes and data corruption").
111
+
112
+ MasterRecord hardens against the worst symptoms (each save commits only its own change set; identities are collision-free; the dirty index is complete), but the correct and supported model is a **per-request context** — pooled if you need to amortize setup.
113
+
114
+ ---
115
+
116
+ ## Mapping to Entity Framework Core
117
+
118
+ | MasterRecord | EF Core |
119
+ |---|---|
120
+ | context = unit of work, scoped per request | `DbContext`, registered `Scoped` via `AddDbContext` |
121
+ | `ContextPool` / `pool.use()` | `AddDbContextPool` |
122
+ | `asNoTracking()` / `asTracking()` | `AsNoTracking()` / `AsTracking()` |
123
+ | `setQueryTrackingBehavior('no-track')` | `QueryTrackingBehavior.NoTracking` |
124
+ | `clearChangeTracker()` | `ChangeTracker.Clear()` |
125
+ | `reset()` (pool release) | change-tracker reset on pool return |
126
+ | `close()` | `Dispose()` |
127
+ | dirty index → O(changes) saves | `StateManager` / change detection |
128
+ | strong-ref identity map, freed on dispose | strong references, freed on dispose |
package/package.json CHANGED
@@ -1,12 +1,13 @@
1
1
  {
2
2
  "name": "masterrecord",
3
- "version": "1.5.15",
3
+ "version": "1.5.17",
4
4
  "description": "An Object-relational mapping for the Master framework. Master Record connects classes to relational database tables to establish a database with almost zero-configuration ",
5
5
  "type": "module",
6
6
  "main": "./MasterRecord.js",
7
7
  "exports": {
8
8
  ".": "./MasterRecord.js",
9
9
  "./context": "./context.js",
10
+ "./ContextPool": "./ContextPool.js",
10
11
  "./Tools": "./Tools.js",
11
12
  "./SQLLiteEngine": "./SQLLiteEngine.js",
12
13
  "./mySQLEngine": "./mySQLEngine.js",
package/readme.md CHANGED
@@ -81,6 +81,10 @@
81
81
 
82
82
  ## ⚠️ Best Practices (CRITICAL)
83
83
 
84
+ ### 0. Scope your context per request (not a singleton)
85
+
86
+ A context is a **unit of work** and must be scoped **per request**, like an Entity Framework `DbContext` — never shared as a process-wide singleton across concurrent requests (which causes lost writes and unbounded memory). Create one per request and `close()` it, or use a `ContextPool` (EF's `AddDbContextPool`) to keep instances warm. For read-only queries, use `.asNoTracking()` so nothing is retained. See **[Change Tracking & Context Lifetime](docs/CHANGE_TRACKING_AND_CONTEXT_LIFETIME.md)** for the full model (`asNoTracking` / `asTracking` / `setQueryTrackingBehavior` / `clearChangeTracker` / `reset` / `close` / `ContextPool`).
87
+
84
88
  ### 1. Creating Entity Instances
85
89
 
86
90
  **ALWAYS** use `context.Entity.new()` to create new entity instances: