masterrecord 1.32.2 → 1.32.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/CHANGES.md +30 -0
- package/context.js +101 -84
- package/package.json +2 -2
package/CHANGES.md
CHANGED
|
@@ -1,5 +1,35 @@
|
|
|
1
1
|
# MasterRecord Changelog
|
|
2
2
|
|
|
3
|
+
## v1.32.4 — a context is freed as soon as nothing uses it
|
|
4
|
+
|
|
5
|
+
**Fix: every context stayed in memory until the current job ended.** Each context registered
|
|
6
|
+
`new WeakRef(this)` for the cross-context dirty check. V8 holds a WeakRef's target strongly until
|
|
7
|
+
control returns to the event loop, so a chain of awaits that never did (synchronous SQLite, a worker
|
|
8
|
+
run driven in microtasks, a test) kept every context it created, closed or not, with all its dbsets.
|
|
9
|
+
For CodeBook's 311-table `KanbanContext` that was about 3 MB a context: its `agent-output-limits`
|
|
10
|
+
test ended with 289 MB on the heap after a full collection, and 58 MB with this fix.
|
|
11
|
+
|
|
12
|
+
- The registry now holds a WeakRef to a small entry that shares the context's dirty index and never
|
|
13
|
+
points at the context. The cross-context warning reads that index, which holds every pending change.
|
|
14
|
+
- `attach()` now also takes the entity out of its old context's change set. Before, the old context's
|
|
15
|
+
`saveChanges()` still flushed an entity that had moved to another context.
|
|
16
|
+
- New `test/context-memory-freed.test.js` builds 40 contexts in one job, closed and dropped, read and
|
|
17
|
+
written, and checks each leaves under 100 KB behind (it was about 640 KB for its 120-table context).
|
|
18
|
+
|
|
19
|
+
## v1.32.3 — building a context is 7 times cheaper
|
|
20
|
+
|
|
21
|
+
**Fix: `dbset()` walked every registered entity each time it ran.** Registering an entity re-resolved
|
|
22
|
+
every foreign key and re-checked every many-to-many in the model, so building a context grew with the
|
|
23
|
+
square of its tables. CodeBook has 311 tables in one context and builds about 6 contexts a second while
|
|
24
|
+
idle: that was about 80% of its idle CPU, with nobody using it.
|
|
25
|
+
|
|
26
|
+
- `dbset()` now looks at the entity it was given, and foreign keys wait by parent name. A context with
|
|
27
|
+
311 entities takes 6 ms to build, down from 43 ms. The model it ends up with is the same.
|
|
28
|
+
- A derived type (`dbset(Model, { extends })`) that declares `manyToMany()` now gets its join entity
|
|
29
|
+
straight away. Before, that only happened if another `dbset()` followed it.
|
|
30
|
+
- New `test/context-build-cost.test.js` checks the same FK types come out in any registration order,
|
|
31
|
+
and that the work grows linearly.
|
|
32
|
+
|
|
3
33
|
## v1.32.2 — re-reads return current data again
|
|
4
34
|
|
|
5
35
|
**Fix: since 1.32.0 a tracked re-read could answer with an old row.** 1.32.0 returned the
|
package/context.js
CHANGED
|
@@ -101,11 +101,22 @@ function _ensurePoolReaper() {
|
|
|
101
101
|
// entity loaded by context A, then call saveChanges() on context B (a different
|
|
102
102
|
// instance), and B silently writes nothing because A owns the change tracking.
|
|
103
103
|
//
|
|
104
|
-
// Leak-safe: the Set holds WeakRefs
|
|
105
|
-
//
|
|
106
|
-
//
|
|
107
|
-
|
|
108
|
-
|
|
104
|
+
// Leak-safe: the Set holds WeakRefs, and a FinalizationRegistry prunes a WeakRef
|
|
105
|
+
// once its target is GC'd. Live contexts are also removed explicitly on close().
|
|
106
|
+
//
|
|
107
|
+
// The WeakRefs point at a small entry ({ dirty: <the context's dirty index> }),
|
|
108
|
+
// never at the context itself. Creating a WeakRef (and every deref()) adds its
|
|
109
|
+
// target to V8's "kept during job" list, which holds it STRONGLY until the
|
|
110
|
+
// current job ends. A job ends only when control returns to the event loop, so
|
|
111
|
+
// in a long chain of awaits that never does (synchronous SQLite, a run driven
|
|
112
|
+
// in microtasks) every context created stayed alive with all its dbsets (about
|
|
113
|
+
// 3 MB for a 311-table context), closed or not. Pinning the entry instead pins
|
|
114
|
+
// only the dirty index, which is empty once the context saved or closed.
|
|
115
|
+
//
|
|
116
|
+
// The global key changed with this shape (v2), so a second copy of the package
|
|
117
|
+
// loaded in the same process never mixes the two kinds of entry.
|
|
118
|
+
const _liveContexts = global.__MR_LIVE_CONTEXTS_V2__ || (global.__MR_LIVE_CONTEXTS_V2__ = new Set());
|
|
119
|
+
const _liveContextFinalizer = global.__MR_LIVE_CTX_FIN_V2__ || (global.__MR_LIVE_CTX_FIN_V2__ =
|
|
109
120
|
new FinalizationRegistry((ref) => { _liveContexts.delete(ref); }));
|
|
110
121
|
|
|
111
122
|
function _poolKey(type, cfg) {
|
|
@@ -407,11 +418,13 @@ class context {
|
|
|
407
418
|
this.__trackedEntitiesMap = new Map(); // Initialize Map for O(1) lookups
|
|
408
419
|
|
|
409
420
|
// Register this instance for cross-context change-tracking detection
|
|
410
|
-
// (see _liveContexts).
|
|
411
|
-
//
|
|
412
|
-
|
|
421
|
+
// (see _liveContexts). The registry holds a WeakRef to an entry that
|
|
422
|
+
// shares this context's dirty index and must never reference the context
|
|
423
|
+
// itself (see _liveContexts for why); removed on close() and pruned on GC.
|
|
424
|
+
this.__liveEntry = { dirty: this.__dirtyEntities };
|
|
425
|
+
this.__liveRef = new WeakRef(this.__liveEntry);
|
|
413
426
|
_liveContexts.add(this.__liveRef);
|
|
414
|
-
_liveContextFinalizer.register(this, this.__liveRef, this.__liveRef);
|
|
427
|
+
_liveContextFinalizer.register(this.__liveEntry, this.__liveRef, this.__liveRef);
|
|
415
428
|
|
|
416
429
|
// Track if this is the first instance of this context class
|
|
417
430
|
// Used to determine if duplicate warnings should be shown
|
|
@@ -1544,13 +1557,13 @@ class context {
|
|
|
1544
1557
|
});
|
|
1545
1558
|
|
|
1546
1559
|
// belongsTo() hardcodes type='integer' before the parent entity is known.
|
|
1547
|
-
// Now that
|
|
1548
|
-
//
|
|
1549
|
-
this.#resolveBelongsToTypes();
|
|
1560
|
+
// Now that this entity is registered, resolve its FK columns and the ones
|
|
1561
|
+
// already waiting for it from the parent's primary-key type. Idempotent.
|
|
1562
|
+
this.#resolveBelongsToTypes(validModel);
|
|
1550
1563
|
|
|
1551
1564
|
// EF 5+ skip navigations: materialize the implicit join entity for every
|
|
1552
|
-
// manyToMany()
|
|
1553
|
-
this.#synthesizeJoinEntities();
|
|
1565
|
+
// manyToMany() this entity declares (idempotent; no-op while synthesizing).
|
|
1566
|
+
this.#synthesizeJoinEntities(validModel);
|
|
1554
1567
|
|
|
1555
1568
|
// Return chainable object with seed() / queryFilter() methods
|
|
1556
1569
|
const chain = {
|
|
@@ -1627,7 +1640,9 @@ class context {
|
|
|
1627
1640
|
get: function() { return tools.createNewInstance(derivedDef, query, this); },
|
|
1628
1641
|
configurable: true, enumerable: true,
|
|
1629
1642
|
});
|
|
1630
|
-
|
|
1643
|
+
// The derived type's columns live on the root now.
|
|
1644
|
+
this.#resolveBelongsToTypes(rootDef);
|
|
1645
|
+
this.#synthesizeJoinEntities(rootDef);
|
|
1631
1646
|
const chain = {
|
|
1632
1647
|
seed: (data) => this.#addSeedData(table, data),
|
|
1633
1648
|
queryFilter: (...a) => { this.queryFilter(model.name, ...a); return chain; },
|
|
@@ -1638,42 +1653,39 @@ class context {
|
|
|
1638
1653
|
// ---- Implicit many-to-many join entities (EF Core 5+ skip navigations) ---
|
|
1639
1654
|
|
|
1640
1655
|
/**
|
|
1641
|
-
* For each `manyToMany()` navigation whose join entity is not registered,
|
|
1656
|
+
* For each `manyToMany()` navigation of `entity` whose join entity is not registered,
|
|
1642
1657
|
* synthesize it exactly as a user-written model would be: an auto PK,
|
|
1643
1658
|
* `belongsTo()` to both sides (FK constraints, ON DELETE CASCADE) and a
|
|
1644
1659
|
* unique composite index on the two FK columns. Registered through dbset()
|
|
1645
1660
|
* so table prefix, validation, FK type resolution, migrations and query
|
|
1646
1661
|
* builders all see it. Idempotent.
|
|
1647
1662
|
*/
|
|
1648
|
-
#synthesizeJoinEntities() {
|
|
1663
|
+
#synthesizeJoinEntities(ent) {
|
|
1649
1664
|
if (this.__synthesizingJoins) return;
|
|
1650
1665
|
const prefix = (this.tablePrefix && typeof this.tablePrefix === 'string') ? this.tablePrefix : '';
|
|
1651
1666
|
const registered = (name) => this.__entities.some(e => e && (e.__name === name || e.__name === prefix + name));
|
|
1652
|
-
for (const
|
|
1653
|
-
|
|
1654
|
-
|
|
1655
|
-
|
|
1656
|
-
|
|
1657
|
-
|
|
1658
|
-
|
|
1659
|
-
|
|
1660
|
-
|
|
1661
|
-
|
|
1662
|
-
|
|
1663
|
-
|
|
1664
|
-
|
|
1665
|
-
if (ownerField === targetField) {
|
|
1666
|
-
throw new Error(`masterrecord: manyToMany join '${joinName}' would have two identical fields '${ownerField}'; pass distinct { foreignKey, otherKey }.`);
|
|
1667
|
-
}
|
|
1668
|
-
const Join = { [joinName]: class { id(db) { db.integer().primary().auto(); } } }[joinName];
|
|
1669
|
-
Object.defineProperty(Join.prototype, ownerField, { value: function(db) { db.belongsTo(ownerName, fkOwner); }, writable: true, configurable: true, enumerable: false });
|
|
1670
|
-
Object.defineProperty(Join.prototype, targetField, { value: function(db) { db.belongsTo(targetName, fkTarget); }, writable: true, configurable: true, enumerable: false });
|
|
1671
|
-
Join.compositeIndexes = [{ columns: [fkOwner, fkTarget], unique: true, name: `ux_${joinName.toLowerCase()}_${fkOwner}_${fkTarget}` }];
|
|
1672
|
-
this.__synthesizingJoins = true;
|
|
1673
|
-
try { this.dbset(Join); } finally { this.__synthesizingJoins = false; }
|
|
1674
|
-
const joinDef = this.__entities.find(e => e && e.__name === prefix + joinName);
|
|
1675
|
-
if (joinDef) Object.defineProperty(joinDef, '__implicitJoin', { value: true, enumerable: false, configurable: true });
|
|
1667
|
+
for (const key of Object.keys(ent)) {
|
|
1668
|
+
const def = ent[key];
|
|
1669
|
+
if (key.startsWith('__') || !def || typeof def !== 'object' || !def.implicitJoin) continue;
|
|
1670
|
+
const joinName = def.foreignTable;
|
|
1671
|
+
if (!joinName || registered(joinName)) continue;
|
|
1672
|
+
const ownerName = (prefix && ent.__name.startsWith(prefix)) ? ent.__name.slice(prefix.length) : ent.__name;
|
|
1673
|
+
const targetName = def.targetTable;
|
|
1674
|
+
const fkOwner = def.joinForeignKey;
|
|
1675
|
+
const fkTarget = def.joinOtherKey;
|
|
1676
|
+
const ownerField = fkOwner.replace(/_id$/i, '') || ownerName.toLowerCase();
|
|
1677
|
+
const targetField = fkTarget.replace(/_id$/i, '') || targetName.toLowerCase();
|
|
1678
|
+
if (ownerField === targetField) {
|
|
1679
|
+
throw new Error(`masterrecord: manyToMany join '${joinName}' would have two identical fields '${ownerField}'; pass distinct { foreignKey, otherKey }.`);
|
|
1676
1680
|
}
|
|
1681
|
+
const Join = { [joinName]: class { id(db) { db.integer().primary().auto(); } } }[joinName];
|
|
1682
|
+
Object.defineProperty(Join.prototype, ownerField, { value: function(db) { db.belongsTo(ownerName, fkOwner); }, writable: true, configurable: true, enumerable: false });
|
|
1683
|
+
Object.defineProperty(Join.prototype, targetField, { value: function(db) { db.belongsTo(targetName, fkTarget); }, writable: true, configurable: true, enumerable: false });
|
|
1684
|
+
Join.compositeIndexes = [{ columns: [fkOwner, fkTarget], unique: true, name: `ux_${joinName.toLowerCase()}_${fkOwner}_${fkTarget}` }];
|
|
1685
|
+
this.__synthesizingJoins = true;
|
|
1686
|
+
try { this.dbset(Join); } finally { this.__synthesizingJoins = false; }
|
|
1687
|
+
const joinDef = this.__entities.find(e => e && e.__name === prefix + joinName);
|
|
1688
|
+
if (joinDef) Object.defineProperty(joinDef, '__implicitJoin', { value: true, enumerable: false, configurable: true });
|
|
1677
1689
|
}
|
|
1678
1690
|
}
|
|
1679
1691
|
|
|
@@ -2395,47 +2407,47 @@ class context {
|
|
|
2395
2407
|
});
|
|
2396
2408
|
}
|
|
2397
2409
|
|
|
2398
|
-
//
|
|
2399
|
-
// '
|
|
2400
|
-
//
|
|
2401
|
-
//
|
|
2402
|
-
//
|
|
2403
|
-
|
|
2404
|
-
|
|
2405
|
-
|
|
2406
|
-
|
|
2407
|
-
|
|
2410
|
+
// For each column of `entity` with relationshipType === 'belongsTo', copy the
|
|
2411
|
+
// parent's primary-key type onto the FK column, now if the parent is registered
|
|
2412
|
+
// and otherwise when it is. Without this, FKs to a string/uuid/bigint PK end up
|
|
2413
|
+
// declared INTEGER, which SQLite tolerates (dynamic typing) but Postgres and
|
|
2414
|
+
// MySQL reject.
|
|
2415
|
+
//
|
|
2416
|
+
// Runs once per registered entity and touches only that entity's columns, so
|
|
2417
|
+
// building a context stays linear in its tables. It used to walk every entity
|
|
2418
|
+
// for every dbset(): 311 tables cost CodeBook 40 ms for each context it built.
|
|
2419
|
+
#resolveBelongsToTypes(entity) {
|
|
2420
|
+
// Case-insensitive lookups — users may write
|
|
2408
2421
|
// db.belongsTo('run') while the class is `Run`.
|
|
2409
|
-
const
|
|
2410
|
-
|
|
2411
|
-
|
|
2412
|
-
|
|
2422
|
+
const parents = this.__fkParents || (this.__fkParents = new Map());
|
|
2423
|
+
const waiting = this.__fkWaiting || (this.__fkWaiting = new Map());
|
|
2424
|
+
const primaryKeyType = (parent) => {
|
|
2425
|
+
for (const pKey of Object.keys(parent)) {
|
|
2426
|
+
const pCol = parent[pKey];
|
|
2427
|
+
if (pCol && typeof pCol === 'object' && pCol.primary === true && pCol.type) return pCol.type;
|
|
2413
2428
|
}
|
|
2414
|
-
|
|
2429
|
+
return null;
|
|
2430
|
+
};
|
|
2431
|
+
const assign = (columns, type) => {
|
|
2432
|
+
if (!type) return;
|
|
2433
|
+
for (const col of columns) if (col.type !== type) col.type = type;
|
|
2434
|
+
};
|
|
2415
2435
|
|
|
2416
|
-
|
|
2417
|
-
|
|
2418
|
-
|
|
2419
|
-
|
|
2420
|
-
|
|
2421
|
-
|
|
2422
|
-
|
|
2423
|
-
|
|
2424
|
-
|
|
2425
|
-
|
|
2426
|
-
|
|
2427
|
-
|
|
2428
|
-
const pCol = parent[pKey];
|
|
2429
|
-
if (!pCol || typeof pCol !== 'object') continue;
|
|
2430
|
-
if (pCol.primary === true && pCol.type) {
|
|
2431
|
-
if (col.type !== pCol.type) {
|
|
2432
|
-
col.type = pCol.type;
|
|
2433
|
-
}
|
|
2434
|
-
break;
|
|
2435
|
-
}
|
|
2436
|
-
}
|
|
2437
|
-
}
|
|
2436
|
+
if (entity.__name) parents.set(entity.__name.toLowerCase(), entity);
|
|
2437
|
+
for (const key of Object.keys(entity)) {
|
|
2438
|
+
const col = entity[key];
|
|
2439
|
+
if (!col || typeof col !== 'object') continue;
|
|
2440
|
+
if (col.relationshipType !== 'belongsTo') continue;
|
|
2441
|
+
if (!col.foreignTable) continue;
|
|
2442
|
+
|
|
2443
|
+
const parentName = String(col.foreignTable).toLowerCase();
|
|
2444
|
+
if (!waiting.has(parentName)) waiting.set(parentName, []);
|
|
2445
|
+
waiting.get(parentName).push(col);
|
|
2446
|
+
const parent = parents.get(parentName);
|
|
2447
|
+
if (parent) assign([col], primaryKeyType(parent));
|
|
2438
2448
|
}
|
|
2449
|
+
// FK columns registered before this entity, and a self-reference.
|
|
2450
|
+
if (entity.__name && waiting.has(entity.__name.toLowerCase())) assign(waiting.get(entity.__name.toLowerCase()), primaryKeyType(entity));
|
|
2439
2451
|
}
|
|
2440
2452
|
|
|
2441
2453
|
/**
|
|
@@ -4016,6 +4028,7 @@ class context {
|
|
|
4016
4028
|
_liveContexts.delete(this.__liveRef);
|
|
4017
4029
|
_liveContextFinalizer.unregister(this.__liveRef);
|
|
4018
4030
|
this.__liveRef = null;
|
|
4031
|
+
this.__liveEntry = null;
|
|
4019
4032
|
}
|
|
4020
4033
|
|
|
4021
4034
|
// Find this instance's pool in the registry and decrement
|
|
@@ -4167,6 +4180,9 @@ class context {
|
|
|
4167
4180
|
if (previous && previous !== this && entity.__ID &&
|
|
4168
4181
|
previous.__trackedEntitiesMap && previous.__trackedEntitiesMap.has(entity.__ID)) {
|
|
4169
4182
|
previous.__trackedEntitiesMap.delete(entity.__ID); // list view follows the map
|
|
4183
|
+
// Leave the old context's dirty index too: it is what the old
|
|
4184
|
+
// context's saveChanges() flushes and what the cross-context check reads.
|
|
4185
|
+
if (previous.__dirtyEntities) previous.__dirtyEntities.delete(entity);
|
|
4170
4186
|
if (typeof previous.__unindexIdentity === 'function') previous.__unindexIdentity(entity);
|
|
4171
4187
|
}
|
|
4172
4188
|
|
|
@@ -4621,12 +4637,13 @@ class context {
|
|
|
4621
4637
|
_foreignDirtyEntities() {
|
|
4622
4638
|
const foreign = [];
|
|
4623
4639
|
for (const ref of _liveContexts) {
|
|
4624
|
-
const
|
|
4625
|
-
if (!
|
|
4626
|
-
if (
|
|
4627
|
-
|
|
4628
|
-
|
|
4629
|
-
|
|
4640
|
+
const entry = ref.deref();
|
|
4641
|
+
if (!entry) { _liveContexts.delete(ref); continue; } // prune dead ref
|
|
4642
|
+
if (entry === this.__liveEntry) { continue; }
|
|
4643
|
+
// The dirty index is the complete set of a context's pending changes
|
|
4644
|
+
// (every dirty transition goes through __markDirty / __track).
|
|
4645
|
+
for (const e of entry.dirty) {
|
|
4646
|
+
if (context._isEntityDirty(e) && !e.__noTracking) { foreign.push(e); }
|
|
4630
4647
|
}
|
|
4631
4648
|
}
|
|
4632
4649
|
return foreign;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "masterrecord",
|
|
3
|
-
"version": "1.32.
|
|
3
|
+
"version": "1.32.4",
|
|
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",
|
|
@@ -88,7 +88,7 @@
|
|
|
88
88
|
"better-sqlite3": ">=12.6.2 <14",
|
|
89
89
|
"commander": "^14.0.3",
|
|
90
90
|
"deep-object-diff": "^1.1.9",
|
|
91
|
-
"glob": "^
|
|
91
|
+
"glob": "^14.0.2",
|
|
92
92
|
"mysql2": "^3.23.2",
|
|
93
93
|
"pg": "^8.22.0"
|
|
94
94
|
},
|