bunsane 0.4.0 → 0.5.1
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/CHANGELOG.md +55 -0
- package/core/App.ts +28 -1
- package/core/ArcheType.ts +47 -2
- package/core/Entity.ts +8 -0
- package/core/app/graphqlSetup.ts +10 -16
- package/core/cache/RedisCache.ts +5 -4
- package/core/cache/index.ts +10 -1
- package/core/cache/txInvalidation.ts +183 -0
- package/core/components/BaseComponent.ts +14 -2
- package/core/entity/cacheStrategies.ts +3 -3
- package/core/entity/componentAccess.ts +24 -5
- package/core/entity/getCacheManager.ts +10 -0
- package/core/entity/saveEntity.ts +24 -20
- package/core/health.ts +93 -4
- package/core/remote/StreamConsumer.ts +535 -535
- package/core/validateEnv.ts +10 -0
- package/database/DatabaseHelper.ts +26 -2
- package/database/index.ts +14 -0
- package/database/sqlHelpers.ts +3 -1
- package/gql/index.ts +33 -8
- package/gql/schema/index.ts +15 -4
- package/package.json +1 -1
- package/query/ComponentInclusionNode.ts +5 -1
- package/query/OrNode.ts +2 -14
- package/query/Query.ts +51 -33
- package/service/ServiceRegistry.ts +26 -7
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,61 @@
|
|
|
2
2
|
|
|
3
3
|
All notable changes to bunsane are documented here.
|
|
4
4
|
|
|
5
|
+
## 0.5.1 — 2026-06-16
|
|
6
|
+
|
|
7
|
+
### Added
|
|
8
|
+
|
|
9
|
+
- **Transaction-aware cache invalidation** — component writes made via
|
|
10
|
+
`comp.save(trx, id)` inside the new `transaction()` wrapper now bust the
|
|
11
|
+
component cache on commit, using the same
|
|
12
|
+
`CacheManager.invalidateEntityComponents` path (L1 + L2 + cross-instance
|
|
13
|
+
pub/sub) that `Entity.save` uses. Touched `(entityId, typeId)` pairs are
|
|
14
|
+
tracked automatically (keyed by the transaction handle), then flushed after
|
|
15
|
+
the transaction commits. The `tx` context also exposes `tx.markDirty(entityId,
|
|
16
|
+
component)` for components not saved directly and `tx.onCommit(cb)` for
|
|
17
|
+
post-commit side effects. Exported from `bunsane/core/cache` as `transaction`,
|
|
18
|
+
`txMarkDirty`, `txOnCommit`. No behavior change for `comp.save` outside the
|
|
19
|
+
wrapper — tracking is a no-op there.
|
|
20
|
+
- **`ArcheTypeQuery.select(...fields)`** — opt-in projection for archetype
|
|
21
|
+
queries. Loads data only for the selected component fields instead of every
|
|
22
|
+
component in the archetype, cutting JSONB wire + parse cost for wide
|
|
23
|
+
archetypes read with narrow selections. Membership filtering is unaffected
|
|
24
|
+
(matching still requires all components); unselected fields remain
|
|
25
|
+
lazy-loadable. Backward-compatible — without `select()`, all components load as
|
|
26
|
+
before.
|
|
27
|
+
|
|
28
|
+
### Fixed
|
|
29
|
+
|
|
30
|
+
- **RedisCache test connects on `127.0.0.1`** instead of `localhost`, which
|
|
31
|
+
resolves to IPv6 `::1` first on Windows and times out against an IPv4-only
|
|
32
|
+
Redis. Test-only change.
|
|
33
|
+
|
|
34
|
+
## 0.5.0 — 2026-06-15
|
|
35
|
+
|
|
36
|
+
### Added
|
|
37
|
+
|
|
38
|
+
- **`/health` write probe** — the deep health check now exercises a real write
|
|
39
|
+
through the same `db.transaction()` path `Entity.save` uses (a temp-table
|
|
40
|
+
insert dropped on commit, no persistent side effect), instead of a read-only
|
|
41
|
+
`SELECT 1`. A wedged write pool — one where reads stay healthy but writes hang
|
|
42
|
+
— now fails liveness so orchestrators restart the container instead of it
|
|
43
|
+
serving timeouts indefinitely. Configurable via `HEALTH_DB_WRITE_PROBE`
|
|
44
|
+
(default on) and `DB_HEALTH_WRITE_TIMEOUT` (default 5000 ms). When the probe
|
|
45
|
+
fails or times out, `/health` returns 503.
|
|
46
|
+
- **`DB_DISABLE_PREPARE`** — set to `true` to disable Bun SQL's automatic
|
|
47
|
+
server-side prepared statements (`prepare: false`). **Required behind PgBouncer
|
|
48
|
+
in transaction pooling mode**, where per-connection prepared statements break
|
|
49
|
+
across pooled backends and can wedge the write path. Default behavior is
|
|
50
|
+
unchanged (prepared statements remain on).
|
|
51
|
+
- **`docs/CONFIGURATION.md`** — full environment-variable reference, including a
|
|
52
|
+
PgBouncer deployment section and the health-check/liveness guidance above.
|
|
53
|
+
|
|
54
|
+
### Behavior change
|
|
55
|
+
|
|
56
|
+
- `/health` now performs a database write by default. If you point a liveness
|
|
57
|
+
probe at `/health`, ensure the write path is reachable, or set
|
|
58
|
+
`HEALTH_DB_WRITE_PROBE=false` to keep the previous read-only behavior.
|
|
59
|
+
|
|
5
60
|
## 0.4.0 — 2026-06-11
|
|
6
61
|
|
|
7
62
|
### Performance (2026-06-10 overhaul)
|
package/core/App.ts
CHANGED
|
@@ -11,7 +11,20 @@ import {
|
|
|
11
11
|
} from "../database/DatabaseHelper";
|
|
12
12
|
import { ComponentRegistry } from "./components";
|
|
13
13
|
import { logger as MainLogger } from "./Logger";
|
|
14
|
+
import { readFileSync } from "fs";
|
|
14
15
|
const logger = MainLogger.child({ scope: "App" });
|
|
16
|
+
|
|
17
|
+
// BunSane framework version, read from the package's own package.json at module
|
|
18
|
+
// load. Resolved relative to this module file so it works regardless of cwd or
|
|
19
|
+
// how the consumer installs the package.
|
|
20
|
+
let BUNSANE_VERSION = "unknown";
|
|
21
|
+
try {
|
|
22
|
+
BUNSANE_VERSION = JSON.parse(
|
|
23
|
+
readFileSync(new URL("../package.json", import.meta.url), "utf8")
|
|
24
|
+
).version;
|
|
25
|
+
} catch {
|
|
26
|
+
// version stays "unknown" if package.json can't be read
|
|
27
|
+
}
|
|
15
28
|
import ServiceRegistry from "../service/ServiceRegistry";
|
|
16
29
|
import { type Plugin, createPubSub } from "graphql-yoga";
|
|
17
30
|
import * as path from "path";
|
|
@@ -351,6 +364,20 @@ export default class App {
|
|
|
351
364
|
this.maxRequestBodySize = bytes;
|
|
352
365
|
}
|
|
353
366
|
|
|
367
|
+
/**
|
|
368
|
+
* Re-weave the GraphQL schema from the currently registered services and
|
|
369
|
+
* swap it into the live Yoga instance — no restart, no Yoga recreation.
|
|
370
|
+
* The next request observes the new schema (Yoga reads it via a factory).
|
|
371
|
+
*
|
|
372
|
+
* Phase 0 primitive for runtime schema mutation: register/modify a service
|
|
373
|
+
* (or its @GraphQLOperation metadata), then call this to reflect it live.
|
|
374
|
+
* Returns the new schema version number (monotonic, starts at 1).
|
|
375
|
+
*/
|
|
376
|
+
public rebuildGraphQLSchema(): number {
|
|
377
|
+
ServiceRegistry.rebuildSchema();
|
|
378
|
+
return ServiceRegistry.getSchemaVersion();
|
|
379
|
+
}
|
|
380
|
+
|
|
354
381
|
private async warmUpPreparedStatementCache(): Promise<void> {
|
|
355
382
|
return warmUpPreparedStatementCacheFn(this);
|
|
356
383
|
}
|
|
@@ -396,7 +423,7 @@ export default class App {
|
|
|
396
423
|
`Server is running on ${new URL(
|
|
397
424
|
this.yoga?.graphqlEndpoint || "/graphql",
|
|
398
425
|
`http://${this.server.hostname}:${this.server.port}`
|
|
399
|
-
)}`
|
|
426
|
+
)} (BunSane v${BUNSANE_VERSION})`
|
|
400
427
|
);
|
|
401
428
|
|
|
402
429
|
// Signal handlers now registered in init() via registerProcessHandlers()
|
package/core/ArcheType.ts
CHANGED
|
@@ -160,6 +160,7 @@ export class ArcheTypeQuery<T extends BaseArcheType> {
|
|
|
160
160
|
private innerQuery: Query<any>;
|
|
161
161
|
private archetypeInstance: T;
|
|
162
162
|
private archetypeCtor: new () => T;
|
|
163
|
+
private selectedFields: string[] | null = null;
|
|
163
164
|
|
|
164
165
|
constructor(archetypeCtor: new () => T) {
|
|
165
166
|
this.archetypeCtor = archetypeCtor;
|
|
@@ -241,6 +242,50 @@ export class ArcheTypeQuery<T extends BaseArcheType> {
|
|
|
241
242
|
return this;
|
|
242
243
|
}
|
|
243
244
|
|
|
245
|
+
/**
|
|
246
|
+
* Project: load data only for the given archetype fields (components).
|
|
247
|
+
*
|
|
248
|
+
* Membership filtering is unaffected — matching the archetype still requires
|
|
249
|
+
* all its components. This only limits which component DATA is fetched, so a
|
|
250
|
+
* wide archetype read with a narrow selection skips the JSONB wire+parse cost
|
|
251
|
+
* of unselected components. Unselected fields are absent from results; they
|
|
252
|
+
* remain lazy-loadable later via entity.get() under a request scope.
|
|
253
|
+
*
|
|
254
|
+
* Backward-compatible: without select(), exec()/first() load all components.
|
|
255
|
+
*
|
|
256
|
+
* @example
|
|
257
|
+
* ```typescript
|
|
258
|
+
* const players = await Player.query().select('position', 'health').exec();
|
|
259
|
+
* // only position + health component data loaded; velocity etc. skipped
|
|
260
|
+
* ```
|
|
261
|
+
*/
|
|
262
|
+
public select<K extends keyof ArcheTypeOwnProperties<T>>(...fields: K[]): this {
|
|
263
|
+
this.selectedFields = fields.map((f) => {
|
|
264
|
+
const name = String(f);
|
|
265
|
+
if (!this.archetypeInstance.componentMap[name]) {
|
|
266
|
+
throw new Error(`Field '${name}' is not a component field on this archetype`);
|
|
267
|
+
}
|
|
268
|
+
return name;
|
|
269
|
+
});
|
|
270
|
+
return this;
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
private selectedComponentCtors(): Array<new () => BaseComponent> {
|
|
274
|
+
return (this.selectedFields ?? []).map(
|
|
275
|
+
(f) => this.archetypeInstance.componentMap[f] as unknown as new () => BaseComponent
|
|
276
|
+
);
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
/**
|
|
280
|
+
* Apply the load strategy: projected (eager-load selected components) when
|
|
281
|
+
* select() was used, otherwise populate() all archetype components.
|
|
282
|
+
*/
|
|
283
|
+
private withLoadStrategy(): Query<any> {
|
|
284
|
+
return this.selectedFields
|
|
285
|
+
? this.innerQuery.eagerLoadComponents(this.selectedComponentCtors())
|
|
286
|
+
: this.innerQuery.populate();
|
|
287
|
+
}
|
|
288
|
+
|
|
244
289
|
/**
|
|
245
290
|
* Enable populate mode to load all component data
|
|
246
291
|
*/
|
|
@@ -261,7 +306,7 @@ export class ArcheTypeQuery<T extends BaseArcheType> {
|
|
|
261
306
|
* Execute the query and return typed archetype results
|
|
262
307
|
*/
|
|
263
308
|
public async exec(): Promise<ArcheTypeResult<T>[]> {
|
|
264
|
-
const entities = await this.
|
|
309
|
+
const entities = await this.withLoadStrategy().exec();
|
|
265
310
|
return entities.map(entity => this.wrapAsArchetype(entity as Entity));
|
|
266
311
|
}
|
|
267
312
|
|
|
@@ -269,7 +314,7 @@ export class ArcheTypeQuery<T extends BaseArcheType> {
|
|
|
269
314
|
* Execute the query and return the first result (or null)
|
|
270
315
|
*/
|
|
271
316
|
public async first(): Promise<ArcheTypeResult<T> | null> {
|
|
272
|
-
const results = await this.
|
|
317
|
+
const results = await this.withLoadStrategy().take(1).exec();
|
|
273
318
|
return results[0] ? this.wrapAsArchetype(results[0] as Entity) : null;
|
|
274
319
|
}
|
|
275
320
|
|
package/core/Entity.ts
CHANGED
|
@@ -20,6 +20,14 @@ export class Entity implements IEntity {
|
|
|
20
20
|
// This persists after save() so resolvers can detect removed components
|
|
21
21
|
/** @internal Promoted from private for the core/entity/ submodule split (RFC §3.2). Not part of the public API. */
|
|
22
22
|
public savedRemovedComponents: Set<string> = new Set<string>();
|
|
23
|
+
/**
|
|
24
|
+
* @internal Type IDs confirmed absent from the DB during this entity's
|
|
25
|
+
* lifetime. Used as a negative cache in loadComponent() so repeated
|
|
26
|
+
* get() probes for optional components skip the SELECT. Invalidated
|
|
27
|
+
* whenever a component is added (addComponent) or the entity is
|
|
28
|
+
* reloaded. Not part of the public API.
|
|
29
|
+
*/
|
|
30
|
+
public _missingComponents: Set<string> = new Set<string>();
|
|
23
31
|
protected _dirty: boolean = false;
|
|
24
32
|
|
|
25
33
|
constructor(id?: string) {
|
package/core/app/graphqlSetup.ts
CHANGED
|
@@ -4,7 +4,10 @@ import { createYogaInstance } from "../../gql";
|
|
|
4
4
|
import { createRequestContextPlugin } from "../RequestContext";
|
|
5
5
|
|
|
6
6
|
export function setupGraphQL(app: any): void {
|
|
7
|
-
|
|
7
|
+
// Provide the schema as a live factory rather than a fixed reference, so
|
|
8
|
+
// ServiceRegistry.rebuildSchema() is observed by the next request without
|
|
9
|
+
// recreating Yoga. Falls back to the static placeholder while null.
|
|
10
|
+
const schemaProvider = () => ServiceRegistry.getSchema();
|
|
8
11
|
|
|
9
12
|
const wrappedContextFactory = app.contextFactory
|
|
10
13
|
? async (yogaContext: any) => {
|
|
@@ -38,19 +41,10 @@ export function setupGraphQL(app: any): void {
|
|
|
38
41
|
? [createRequestContextPlugin(), ...app.yogaPlugins]
|
|
39
42
|
: [...app.yogaPlugins];
|
|
40
43
|
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
);
|
|
48
|
-
} else {
|
|
49
|
-
app.yoga = createYogaInstance(
|
|
50
|
-
undefined,
|
|
51
|
-
effectivePlugins,
|
|
52
|
-
wrappedContextFactory,
|
|
53
|
-
yogaOptions,
|
|
54
|
-
);
|
|
55
|
-
}
|
|
44
|
+
app.yoga = createYogaInstance(
|
|
45
|
+
schemaProvider,
|
|
46
|
+
effectivePlugins,
|
|
47
|
+
wrappedContextFactory,
|
|
48
|
+
yogaOptions,
|
|
49
|
+
);
|
|
56
50
|
}
|
package/core/cache/RedisCache.ts
CHANGED
|
@@ -270,18 +270,19 @@ export class RedisCache implements CacheProvider {
|
|
|
270
270
|
*/
|
|
271
271
|
async setMany<T>(entries: Array<{key: string, value: T, ttl?: number}>): Promise<void> {
|
|
272
272
|
try {
|
|
273
|
+
const compressed = await Promise.all(entries.map(e => CompressionUtils.compressForStorage(e.value)));
|
|
274
|
+
|
|
273
275
|
const pipeline = this.client.pipeline();
|
|
274
276
|
|
|
275
|
-
|
|
277
|
+
entries.forEach((entry, i) => {
|
|
276
278
|
const prefixedKey = this.prefixKey(entry.key);
|
|
277
|
-
const serializedValue =
|
|
278
|
-
|
|
279
|
+
const serializedValue = compressed[i] as string;
|
|
279
280
|
if (entry.ttl) {
|
|
280
281
|
pipeline.setex(prefixedKey, Math.floor(entry.ttl / 1000), serializedValue);
|
|
281
282
|
} else {
|
|
282
283
|
pipeline.set(prefixedKey, serializedValue);
|
|
283
284
|
}
|
|
284
|
-
}
|
|
285
|
+
});
|
|
285
286
|
|
|
286
287
|
await pipeline.exec();
|
|
287
288
|
} catch (error) {
|
package/core/cache/index.ts
CHANGED
|
@@ -3,4 +3,13 @@ export { MemoryCache } from './MemoryCache';
|
|
|
3
3
|
export type { MemoryCacheConfig } from './MemoryCache';
|
|
4
4
|
export { NoOpCache } from './NoOpCache';
|
|
5
5
|
export { CacheManager } from './CacheManager';
|
|
6
|
-
export { CacheFactory } from './CacheFactory';
|
|
6
|
+
export { CacheFactory } from './CacheFactory';
|
|
7
|
+
export {
|
|
8
|
+
transaction,
|
|
9
|
+
markDirty as txMarkDirty,
|
|
10
|
+
registerOnCommit as txOnCommit,
|
|
11
|
+
trackComponentDirty,
|
|
12
|
+
beginTxTracking,
|
|
13
|
+
flushTxTracking,
|
|
14
|
+
} from './txInvalidation';
|
|
15
|
+
export type { TxContext } from './txInvalidation';
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Transaction-aware cache invalidation.
|
|
3
|
+
*
|
|
4
|
+
* `comp.save(trx, id)` writes the DB but does no cache invalidation on its own.
|
|
5
|
+
* Inside a tracked transaction we accumulate the (entityId, typeId) pairs that
|
|
6
|
+
* were touched and, once the transaction COMMITS, run the same invalidation that
|
|
7
|
+
* entity.save() uses (CacheManager.invalidateEntityComponents → deleteMany +
|
|
8
|
+
* cross-instance pub/sub).
|
|
9
|
+
*
|
|
10
|
+
* Bun.SQL exposes no commit hook, so "on commit" means: after the
|
|
11
|
+
* `db.transaction(cb)` promise resolves. The `transaction()` wrapper below owns
|
|
12
|
+
* that boundary. Tracking is keyed by the trx object via a WeakMap, so
|
|
13
|
+
* `trackComponentDirty` is a cheap no-op for any comp.save() that runs outside a
|
|
14
|
+
* tracked transaction (top-level db, or entity.save() which handles its own
|
|
15
|
+
* cache) — zero behavior change for existing callers.
|
|
16
|
+
*/
|
|
17
|
+
import { logger as MainLogger } from '../Logger';
|
|
18
|
+
|
|
19
|
+
const logger = MainLogger.child({ scope: 'TxCacheInvalidation' });
|
|
20
|
+
|
|
21
|
+
/** Anything carrying a component type_id — avoids a hard BaseComponent import (cycle). */
|
|
22
|
+
type ComponentRef = string | { _typeId?: string } | (new (...args: any[]) => any);
|
|
23
|
+
|
|
24
|
+
type SQLLike = Bun.SQL;
|
|
25
|
+
|
|
26
|
+
interface TxState {
|
|
27
|
+
/** entityId -> set of touched component type_ids */
|
|
28
|
+
dirty: Map<string, Set<string>>;
|
|
29
|
+
onCommit: Array<() => void | Promise<void>>;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Tracking state keyed by the transaction's SQL handle. */
|
|
33
|
+
const txRegistry = new WeakMap<SQLLike, TxState>();
|
|
34
|
+
|
|
35
|
+
/** Begin tracking for a transaction handle. Idempotent. */
|
|
36
|
+
export function beginTxTracking(trx: SQLLike): TxState {
|
|
37
|
+
let state = txRegistry.get(trx);
|
|
38
|
+
if (!state) {
|
|
39
|
+
state = { dirty: new Map(), onCommit: [] };
|
|
40
|
+
txRegistry.set(trx, state);
|
|
41
|
+
}
|
|
42
|
+
return state;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export function getTxState(trx: SQLLike): TxState | undefined {
|
|
46
|
+
return txRegistry.get(trx);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Record that a component (entityId + typeId) was written under this trx.
|
|
51
|
+
* No-op when the trx is not tracked (i.e. not inside transaction()).
|
|
52
|
+
*/
|
|
53
|
+
export function trackComponentDirty(trx: SQLLike, entityId: string, typeId: string): void {
|
|
54
|
+
const state = txRegistry.get(trx);
|
|
55
|
+
if (!state || !entityId || !typeId) return;
|
|
56
|
+
let set = state.dirty.get(entityId);
|
|
57
|
+
if (!set) {
|
|
58
|
+
set = new Set();
|
|
59
|
+
state.dirty.set(entityId, set);
|
|
60
|
+
}
|
|
61
|
+
set.add(typeId);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Resolve a component ctor / instance / raw typeId string to its type_id. */
|
|
65
|
+
function resolveTypeId(component: ComponentRef): string | null {
|
|
66
|
+
if (typeof component === 'string') return component;
|
|
67
|
+
// Instance carrying a _typeId (BaseComponent) — duck-typed to avoid an import cycle.
|
|
68
|
+
const instanceTypeId = (component as { _typeId?: string })._typeId;
|
|
69
|
+
if (typeof instanceTypeId === 'string' && instanceTypeId.length > 0) return instanceTypeId;
|
|
70
|
+
// Constructor: derive from class name via metadata.
|
|
71
|
+
if (typeof component === 'function') {
|
|
72
|
+
try {
|
|
73
|
+
const { getMetadataStorage } = require('../metadata');
|
|
74
|
+
return getMetadataStorage().getComponentId(component.name);
|
|
75
|
+
} catch {
|
|
76
|
+
return null;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
return null;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Explicitly mark a component dirty for invalidation on commit.
|
|
84
|
+
* Accepts a component constructor, instance, or raw type_id string.
|
|
85
|
+
*/
|
|
86
|
+
export function markDirty(trx: SQLLike, entityId: string, component: ComponentRef): void {
|
|
87
|
+
const typeId = resolveTypeId(component);
|
|
88
|
+
if (!typeId) {
|
|
89
|
+
logger.warn({ entityId, msg: 'markDirty: could not resolve component type_id; skipping' });
|
|
90
|
+
return;
|
|
91
|
+
}
|
|
92
|
+
trackComponentDirty(trx, entityId, typeId);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** Register a callback to run after the transaction commits. */
|
|
96
|
+
export function registerOnCommit(trx: SQLLike, cb: () => void | Promise<void>): void {
|
|
97
|
+
const state = beginTxTracking(trx);
|
|
98
|
+
state.onCommit.push(cb);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* Flush accumulated invalidations + run onCommit callbacks. Call ONLY after the
|
|
103
|
+
* transaction has committed. Errors are logged, never thrown — a cache flush
|
|
104
|
+
* failure must not surface as a transaction failure (the data is already
|
|
105
|
+
* committed; stale cache is recoverable, a thrown error is not).
|
|
106
|
+
*/
|
|
107
|
+
export async function flushTxTracking(state: TxState | undefined): Promise<void> {
|
|
108
|
+
if (!state) return;
|
|
109
|
+
try {
|
|
110
|
+
if (state.dirty.size > 0) {
|
|
111
|
+
const { CacheManager } = require('./CacheManager');
|
|
112
|
+
const cacheManager = CacheManager.getInstance();
|
|
113
|
+
await Promise.all(
|
|
114
|
+
Array.from(state.dirty.entries()).map(([entityId, typeIds]) =>
|
|
115
|
+
cacheManager
|
|
116
|
+
.invalidateEntityComponents(entityId, Array.from(typeIds), { includeEntityKey: true })
|
|
117
|
+
.catch((error: unknown) =>
|
|
118
|
+
logger.error({ entityId, error, msg: 'Failed to invalidate entity components on commit' }),
|
|
119
|
+
),
|
|
120
|
+
),
|
|
121
|
+
);
|
|
122
|
+
}
|
|
123
|
+
} catch (error) {
|
|
124
|
+
logger.error({ error, msg: 'Error during transaction cache flush' });
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
for (const cb of state.onCommit) {
|
|
128
|
+
try {
|
|
129
|
+
await cb();
|
|
130
|
+
} catch (error) {
|
|
131
|
+
logger.error({ error, msg: 'onCommit callback threw' });
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** Context handed to the transaction() callback for explicit control. */
|
|
137
|
+
export interface TxContext {
|
|
138
|
+
/** Mark a component dirty for invalidation on commit. */
|
|
139
|
+
markDirty(entityId: string, component: ComponentRef): void;
|
|
140
|
+
/** Run a callback after the transaction commits (cache already flushed). */
|
|
141
|
+
onCommit(cb: () => void | Promise<void>): void;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* Run a transaction with automatic, transaction-aware cache invalidation.
|
|
146
|
+
*
|
|
147
|
+
* Any `comp.save(trx, entityId)` performed with the provided `trx` is tracked
|
|
148
|
+
* automatically; on commit, those components are invalidated using the same
|
|
149
|
+
* logic entity.save() uses. The `tx` context adds explicit markDirty/onCommit
|
|
150
|
+
* escape hatches.
|
|
151
|
+
*
|
|
152
|
+
* Invalidation runs inline (awaited) after commit, so when this resolves the
|
|
153
|
+
* cache is already consistent.
|
|
154
|
+
*
|
|
155
|
+
* @example
|
|
156
|
+
* ```typescript
|
|
157
|
+
* await transaction(async (trx, tx) => {
|
|
158
|
+
* await positionComp.save(trx, entityId); // auto-tracked
|
|
159
|
+
* tx.markDirty(entityId, Velocity); // explicit
|
|
160
|
+
* tx.onCommit(() => metrics.bump()); // after commit
|
|
161
|
+
* });
|
|
162
|
+
* ```
|
|
163
|
+
*/
|
|
164
|
+
export async function transaction<T>(
|
|
165
|
+
fn: (trx: SQLLike, tx: TxContext) => Promise<T>,
|
|
166
|
+
): Promise<T> {
|
|
167
|
+
const { getDb } = require('../../database');
|
|
168
|
+
const db: SQLLike = getDb();
|
|
169
|
+
|
|
170
|
+
let state: TxState | undefined;
|
|
171
|
+
const result = await db.transaction(async (trx: SQLLike) => {
|
|
172
|
+
state = beginTxTracking(trx);
|
|
173
|
+
const ctx: TxContext = {
|
|
174
|
+
markDirty: (entityId, component) => markDirty(trx, entityId, component),
|
|
175
|
+
onCommit: (cb) => registerOnCommit(trx, cb),
|
|
176
|
+
};
|
|
177
|
+
return await fn(trx, ctx);
|
|
178
|
+
});
|
|
179
|
+
|
|
180
|
+
// Transaction committed (resolved without throwing) → flush invalidations.
|
|
181
|
+
await flushTxTracking(state);
|
|
182
|
+
return result as T;
|
|
183
|
+
}
|
|
@@ -5,8 +5,13 @@ import ComponentRegistry from "./ComponentRegistry";
|
|
|
5
5
|
import { type ComponentDataType } from './Interfaces';
|
|
6
6
|
import { uuidv7 } from '../../utils/uuid';
|
|
7
7
|
import { getMetadataStorage } from '../metadata';
|
|
8
|
+
import { trackComponentDirty } from '../cache/txInvalidation';
|
|
8
9
|
const logger = MainLogger.child({ scope: "Components" });
|
|
9
10
|
|
|
11
|
+
// Cached property-name arrays keyed by typeId. Metadata is immutable after
|
|
12
|
+
// decorator registration, so allocating once per class is safe.
|
|
13
|
+
const _propNamesCache = new Map<string, string[]>();
|
|
14
|
+
|
|
10
15
|
export class BaseComponent {
|
|
11
16
|
public id: string = "";
|
|
12
17
|
protected _comp_name: string = "";
|
|
@@ -26,10 +31,13 @@ export class BaseComponent {
|
|
|
26
31
|
}
|
|
27
32
|
|
|
28
33
|
properties(): string[] {
|
|
34
|
+
const cached = _propNamesCache.get(this._typeId);
|
|
35
|
+
if (cached) return cached;
|
|
29
36
|
const storage = getMetadataStorage();
|
|
30
37
|
const props = storage.componentProperties.get(this._typeId);
|
|
31
|
-
|
|
32
|
-
|
|
38
|
+
const names = Object.freeze(props ? props.map(p => p.propertyKey) : []) as string[];
|
|
39
|
+
_propNamesCache.set(this._typeId, names);
|
|
40
|
+
return names;
|
|
33
41
|
}
|
|
34
42
|
|
|
35
43
|
/**
|
|
@@ -97,6 +105,10 @@ export class BaseComponent {
|
|
|
97
105
|
await this.insert(trx, entity_id);
|
|
98
106
|
this._persisted = true;
|
|
99
107
|
}
|
|
108
|
+
// Transaction-aware cache invalidation: record this write so the
|
|
109
|
+
// transaction() wrapper can bust the component cache on commit.
|
|
110
|
+
// No-op outside a tracked transaction (cheap WeakMap miss).
|
|
111
|
+
trackComponentDirty(trx, entity_id, this._typeId);
|
|
100
112
|
}
|
|
101
113
|
|
|
102
114
|
async insert(trx: Bun.SQL, entity_id: string) {
|
|
@@ -6,6 +6,7 @@ import { logger } from "../Logger";
|
|
|
6
6
|
import EntityHookManager from "../EntityHookManager";
|
|
7
7
|
import { EntityDeletedEvent } from "../events/EntityLifecycleEvents";
|
|
8
8
|
import type { SQL } from "bun";
|
|
9
|
+
import { getCacheManager } from "./getCacheManager";
|
|
9
10
|
import type { Entity } from "../Entity";
|
|
10
11
|
|
|
11
12
|
/**
|
|
@@ -15,8 +16,7 @@ import type { Entity } from "../Entity";
|
|
|
15
16
|
*/
|
|
16
17
|
export async function handleCacheAfterSave(entity: Entity, changedComponentTypeIds: string[], removedComponentTypeIds: string[], context?: { loaders?: { componentsByEntityType?: any }; trx?: SQL; signal?: AbortSignal }): Promise<void> {
|
|
17
18
|
try {
|
|
18
|
-
|
|
19
|
-
const { CacheManager } = await import('../cache/CacheManager');
|
|
19
|
+
const CacheManager = getCacheManager();
|
|
20
20
|
const cacheManager = CacheManager.getInstance();
|
|
21
21
|
const config = cacheManager.getConfig();
|
|
22
22
|
|
|
@@ -81,7 +81,7 @@ export async function runPostDeleteSideEffects(entity: Entity, softDelete: boole
|
|
|
81
81
|
}
|
|
82
82
|
|
|
83
83
|
try {
|
|
84
|
-
const
|
|
84
|
+
const CacheManager = getCacheManager();
|
|
85
85
|
const cacheManager = CacheManager.getInstance();
|
|
86
86
|
const config = cacheManager.getConfig();
|
|
87
87
|
|
|
@@ -14,10 +14,15 @@ import { getMetadataStorage } from "../metadata";
|
|
|
14
14
|
import { ComponentAddedEvent, ComponentUpdatedEvent, ComponentRemovedEvent } from "../events/EntityLifecycleEvents";
|
|
15
15
|
import { getRequestScope } from "../requestScope";
|
|
16
16
|
import { trackCacheOp } from "./pendingOps";
|
|
17
|
+
import { getCacheManager } from "./getCacheManager";
|
|
17
18
|
import type { Entity } from "../Entity";
|
|
18
19
|
|
|
19
20
|
export function addComponent(entity: Entity, component: BaseComponent): Entity {
|
|
20
|
-
|
|
21
|
+
const typeId = component.getTypeID();
|
|
22
|
+
entity.components.set(typeId, component);
|
|
23
|
+
// A component that just arrived can never be "missing" — clear any
|
|
24
|
+
// previously recorded absence so future get() calls see the new data.
|
|
25
|
+
entity._missingComponents.delete(typeId);
|
|
21
26
|
return entity;
|
|
22
27
|
}
|
|
23
28
|
|
|
@@ -55,8 +60,6 @@ export function add<T extends BaseComponent>(entity: Entity, ctor: new (...args:
|
|
|
55
60
|
const instance = new ctor();
|
|
56
61
|
if (data) {
|
|
57
62
|
Object.assign(instance, data);
|
|
58
|
-
} else {
|
|
59
|
-
Object.assign(instance, {});
|
|
60
63
|
}
|
|
61
64
|
addComponent(entity, instance);
|
|
62
65
|
entity.setDirty(true);
|
|
@@ -109,7 +112,7 @@ export async function set<T extends BaseComponent>(entity: Entity, ctor: new (..
|
|
|
109
112
|
// App.shutdown can await it (H-CACHE-1).
|
|
110
113
|
trackCacheOp((async () => {
|
|
111
114
|
try {
|
|
112
|
-
const
|
|
115
|
+
const CacheManager = getCacheManager();
|
|
113
116
|
const cacheManager = CacheManager.getInstance();
|
|
114
117
|
const config = cacheManager.getConfig();
|
|
115
118
|
|
|
@@ -167,7 +170,7 @@ export function remove<T extends BaseComponent>(entity: Entity, ctor: new (...ar
|
|
|
167
170
|
// (H-CACHE-1).
|
|
168
171
|
trackCacheOp((async () => {
|
|
169
172
|
try {
|
|
170
|
-
const
|
|
173
|
+
const CacheManager = getCacheManager();
|
|
171
174
|
const cacheManager = CacheManager.getInstance();
|
|
172
175
|
const config = cacheManager.getConfig();
|
|
173
176
|
|
|
@@ -222,6 +225,7 @@ export async function reload(entity: Entity, opts?: { trx?: SQL; signal?: AbortS
|
|
|
222
225
|
entity.components.clear();
|
|
223
226
|
entity.removedComponents.clear();
|
|
224
227
|
entity.savedRemovedComponents.clear();
|
|
228
|
+
entity._missingComponents.clear();
|
|
225
229
|
|
|
226
230
|
const dbConn = opts?.trx ?? db;
|
|
227
231
|
const rows = await runWithSignal<any[]>(
|
|
@@ -291,6 +295,15 @@ async function loadComponent<T extends BaseComponent>(entity: Entity, ctor: new
|
|
|
291
295
|
// just to read the type id.
|
|
292
296
|
const typeId = typeIdOf(ctor);
|
|
293
297
|
|
|
298
|
+
// Negative-cache short-circuit: if we previously confirmed this component
|
|
299
|
+
// is absent from the DB (and no explicit transaction is in scope that
|
|
300
|
+
// could see a different snapshot), skip the SELECT entirely.
|
|
301
|
+
// Skipped when a trx is provided — within a transaction the visibility
|
|
302
|
+
// horizon may differ from the outer read (stale-read hazard).
|
|
303
|
+
if (!context?.trx && entity._missingComponents.has(typeId)) {
|
|
304
|
+
return null;
|
|
305
|
+
}
|
|
306
|
+
|
|
294
307
|
// Use transaction if provided, otherwise use default db
|
|
295
308
|
const dbConn = context?.trx ?? db;
|
|
296
309
|
|
|
@@ -353,6 +366,12 @@ async function loadComponent<T extends BaseComponent>(entity: Entity, ctor: new
|
|
|
353
366
|
addComponent(entity, comp);
|
|
354
367
|
return comp as T;
|
|
355
368
|
} else {
|
|
369
|
+
// Record the confirmed absence so repeated probes skip the DB.
|
|
370
|
+
// Only when no explicit trx — within a transaction the caller
|
|
371
|
+
// may insert the component and probe again in the same scope.
|
|
372
|
+
if (!context?.trx) {
|
|
373
|
+
entity._missingComponents.add(typeId);
|
|
374
|
+
}
|
|
356
375
|
return null;
|
|
357
376
|
}
|
|
358
377
|
} catch (error) {
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
// Static import of CacheManager for hot-path use in componentAccess and
|
|
2
|
+
// cacheStrategies. CacheManager's imports are all type-only references back
|
|
3
|
+
// to core/Entity, so there is no runtime circular dependency — static import
|
|
4
|
+
// is safe and avoids the microtask + Promise allocation of a dynamic import
|
|
5
|
+
// on every set/remove/save/delete call.
|
|
6
|
+
import { CacheManager } from '../cache/CacheManager';
|
|
7
|
+
|
|
8
|
+
export function getCacheManager(): typeof CacheManager {
|
|
9
|
+
return CacheManager;
|
|
10
|
+
}
|