masterrecord 1.5.14 → 1.5.16

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,24 @@
1
1
  # MasterRecord Changelog
2
2
 
3
+ ## v1.5.16 — context pooling (EF's AddDbContextPool) + reset(); change-tracking/lifetime docs
4
+
5
+ Completes the EF-faithful context-lifetime story so request-scoped contexts are affordable even with many contexts registered.
6
+
7
+ - **`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`.
8
+ - **`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.
9
+
10
+ **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.
11
+
12
+ 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.
13
+
14
+ ## v1.5.15 — close() releases the change tracker (EF Dispose parity for request-scoped contexts)
15
+
16
+ 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.
17
+
18
+ `close()` now calls `__clearTracked()` first — detaching every tracked entity and clearing the dirty index — so a request-scoped context frees all its entities immediately on close. This makes request-scoped contexts the clean, EF-faithful bounded-memory answer: `new AppContext()` per request → work → `await ctx.close()`.
19
+
20
+ No new API; behavior only. Full suite green (0 fail, 309 pass, 20 gated skipped); 0 lint errors.
21
+
3
22
  ## v1.5.14 — context-level query tracking behavior (EF's QueryTrackingBehavior) + asTracking()
4
23
 
5
24
  The remaining memory issue: on a long-lived/singleton context, tracked entities are held with **strong references** for the life of the context, so read-only queries that track their results grow the tracked set without bound. `asNoTracking()` (1.5.13) bounds it only per call site.
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
@@ -2631,6 +2631,13 @@ class context {
2631
2631
  * db.close(); // Close connections
2632
2632
  */
2633
2633
  async close() {
2634
+ // Release the change tracker (EF's Dispose clears the ChangeTracker):
2635
+ // detach every tracked entity and drop the dirty index so a request-
2636
+ // scoped context frees all its entities immediately on close, instead of
2637
+ // only when the context object itself is garbage-collected. This is what
2638
+ // makes scoped contexts the bounded-memory answer.
2639
+ this.__clearTracked();
2640
+
2634
2641
  // Deregister from the live-context registry so it stops appearing in
2635
2642
  // cross-context checks and doesn't linger until GC.
2636
2643
  //
@@ -3005,6 +3012,23 @@ class context {
3005
3012
  return this;
3006
3013
  }
3007
3014
 
3015
+ /**
3016
+ * Reset this context's unit of work for REUSE — detach all tracked entities,
3017
+ * clear the dirty index and the query cache — WITHOUT closing the database
3018
+ * connection. This is the "return to pool" primitive behind context pooling
3019
+ * (EF Core resets a pooled DbContext's ChangeTracker on release): the
3020
+ * connection stays warm so the instance can serve the next request cheaply.
3021
+ *
3022
+ * Use `close()` to actually tear down the connection; use `reset()` to make
3023
+ * a kept-alive instance behave like a fresh per-request context.
3024
+ */
3025
+ reset() {
3026
+ this.__clearTracked(); // detach all + clear the dirty index
3027
+ this.clearQueryCache(); // drop cached query results
3028
+ this.__clearErrorHandler(); // clear any pending error handler
3029
+ return this;
3030
+ }
3031
+
3008
3032
  /**
3009
3033
  * Detach a single entity from change tracking. Pending changes on it are
3010
3034
  * dropped and it is no longer part of any future saveChanges().
@@ -0,0 +1,126 @@
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. Connections are pooled underneath, and `close()` releases the whole change tracker. Every `load → mutate → saveChanges` handler works unchanged, with no tracking-behavior tweaks and no way to introduce a lost write.
65
+
66
+ ```javascript
67
+ async function handler(req, res) {
68
+ const db = new AppContext();
69
+ try {
70
+ // ... load / mutate / saveChanges ...
71
+ } finally {
72
+ await db.close(); // releases tracker + returns the connection
73
+ }
74
+ }
75
+ ```
76
+
77
+ ### 2. Context pooling (EF's `AddDbContextPool`)
78
+
79
+ 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).
80
+
81
+ ```javascript
82
+ import ContextPool from 'masterrecord/ContextPool';
83
+ // or: const { ContextPool } = masterrecord;
84
+
85
+ const pool = new ContextPool(AppContext, { maxSize: 64 });
86
+
87
+ // per request — automatic acquire/reset/release, even on error:
88
+ await pool.use(async (db) => {
89
+ const user = await db.User.asTracking().where('u => u.id == $$', id).single();
90
+ user.blocked = 1;
91
+ await db.saveChanges();
92
+ });
93
+
94
+ // at shutdown:
95
+ await pool.drain();
96
+ ```
97
+
98
+ `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.
99
+
100
+ ---
101
+
102
+ ## Why not a singleton context?
103
+
104
+ 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):
105
+
106
+ - **Lost writes** — one request's `saveChanges()` interacting with another's tracked entities.
107
+ - **Unbounded memory** — read-only queries track results that are never released.
108
+ - **Undefined behavior** under concurrent access (EF: "application crashes and data corruption").
109
+
110
+ 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.
111
+
112
+ ---
113
+
114
+ ## Mapping to Entity Framework Core
115
+
116
+ | MasterRecord | EF Core |
117
+ |---|---|
118
+ | context = unit of work, scoped per request | `DbContext`, registered `Scoped` via `AddDbContext` |
119
+ | `ContextPool` / `pool.use()` | `AddDbContextPool` |
120
+ | `asNoTracking()` / `asTracking()` | `AsNoTracking()` / `AsTracking()` |
121
+ | `setQueryTrackingBehavior('no-track')` | `QueryTrackingBehavior.NoTracking` |
122
+ | `clearChangeTracker()` | `ChangeTracker.Clear()` |
123
+ | `reset()` (pool release) | change-tracker reset on pool return |
124
+ | `close()` | `Dispose()` |
125
+ | dirty index → O(changes) saves | `StateManager` / change detection |
126
+ | 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.14",
3
+ "version": "1.5.16",
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: