bunsane 0.3.1 → 0.4.0

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.
Files changed (224) hide show
  1. package/CHANGELOG.md +445 -318
  2. package/config/cache.config.ts +35 -1
  3. package/core/App.ts +24 -1064
  4. package/core/ArcheType.ts +78 -2110
  5. package/core/BatchLoader.ts +56 -32
  6. package/core/Entity.ts +85 -1043
  7. package/core/EntityHookManager.ts +52 -754
  8. package/core/Logger.ts +10 -0
  9. package/core/RequestContext.ts +64 -6
  10. package/core/RequestLoaders.ts +187 -36
  11. package/core/SchedulerManager.ts +28 -600
  12. package/core/app/bootstrap.ts +133 -0
  13. package/core/app/cors.ts +85 -0
  14. package/core/app/graphqlSetup.ts +56 -0
  15. package/core/app/healthEndpoints.ts +31 -0
  16. package/core/app/metricsCollector.ts +27 -0
  17. package/core/app/preparedStatementWarmup.ts +15 -0
  18. package/core/app/processHandlers.ts +43 -0
  19. package/core/app/requestRouter.ts +310 -0
  20. package/core/app/restRegistry.ts +80 -0
  21. package/core/app/shutdown.ts +97 -0
  22. package/core/app/studioRouter.ts +83 -0
  23. package/core/archetype/customTypes.ts +100 -0
  24. package/core/archetype/decorators.ts +171 -0
  25. package/core/archetype/fieldResolvers.ts +666 -0
  26. package/core/archetype/helpers.ts +29 -0
  27. package/core/archetype/relationLoader.ts +161 -0
  28. package/core/archetype/schemaBuilder.ts +141 -0
  29. package/core/archetype/weaver.ts +218 -0
  30. package/core/archetype/zodSchemaBuilder.ts +527 -0
  31. package/core/cache/CacheManager.ts +173 -267
  32. package/core/cache/CompressionUtils.ts +34 -3
  33. package/core/cache/MemoryCache.ts +40 -37
  34. package/core/cache/RedisCache.ts +4 -4
  35. package/core/cache/health.ts +30 -0
  36. package/core/cache/invalidation.ts +96 -0
  37. package/core/cache/strategies/writeInvalidate.ts +111 -0
  38. package/core/cache/strategies/writeThrough.ts +233 -0
  39. package/core/components/BaseComponent.ts +16 -8
  40. package/core/components/ComponentRegistry.ts +28 -0
  41. package/core/decorators/IndexedField.ts +1 -1
  42. package/core/entity/cacheStrategies.ts +97 -0
  43. package/core/entity/componentAccess.ts +364 -0
  44. package/core/entity/finders.ts +202 -0
  45. package/core/entity/pendingOps.ts +72 -0
  46. package/core/entity/saveEntity.ts +377 -0
  47. package/core/hooks/dispatcher.ts +439 -0
  48. package/core/hooks/guards.ts +155 -0
  49. package/core/hooks/registry.ts +247 -0
  50. package/core/metadata/definitions/Component.ts +1 -1
  51. package/core/metadata/index.ts +15 -4
  52. package/core/middleware/AccessLog.ts +8 -1
  53. package/core/middleware/RateLimit.ts +102 -105
  54. package/core/middleware/RequestId.ts +2 -9
  55. package/core/middleware/SecurityHeaders.ts +2 -11
  56. package/core/middleware/headers.ts +28 -0
  57. package/core/remote/OutboxWorker.ts +213 -183
  58. package/core/remote/RemoteManager.ts +401 -400
  59. package/core/remote/types.ts +153 -151
  60. package/core/requestScope.ts +34 -0
  61. package/core/scheduler/cronEvaluator.ts +174 -0
  62. package/core/scheduler/lifecycleHooks.ts +21 -0
  63. package/core/scheduler/lockCoordinator.ts +27 -0
  64. package/core/scheduler/metrics.ts +14 -0
  65. package/core/scheduler/taskRunner.ts +420 -0
  66. package/database/DatabaseHelper.ts +128 -101
  67. package/database/IndexingStrategy.ts +72 -2
  68. package/database/PreparedStatementCache.ts +20 -5
  69. package/database/cancellable.ts +35 -0
  70. package/database/index.ts +15 -3
  71. package/database/instrumentedDb.ts +141 -0
  72. package/endpoints/archetypes.ts +2 -8
  73. package/endpoints/tables.ts +6 -1
  74. package/gql/index.ts +1 -1
  75. package/gql/visitors/ResolverGeneratorVisitor.ts +25 -4
  76. package/package.json +22 -1
  77. package/query/CTENode.ts +5 -3
  78. package/query/ComponentInclusionNode.ts +240 -13
  79. package/query/OrNode.ts +6 -5
  80. package/query/Query.ts +203 -59
  81. package/query/QueryContext.ts +6 -0
  82. package/query/QueryDAG.ts +7 -2
  83. package/query/membershipSource.ts +66 -0
  84. package/storage/LocalStorageProvider.ts +8 -3
  85. package/studio/dist/assets/index-BMZ67Npg.js +254 -0
  86. package/studio/dist/assets/index-BpbuYz9g.css +1 -0
  87. package/studio/{index.html → dist/index.html} +3 -2
  88. package/swagger/generator.ts +11 -1
  89. package/upload/UploadManager.ts +8 -6
  90. package/utils/uuid.ts +40 -10
  91. package/.claude/settings.local.json +0 -47
  92. package/.prettierrc +0 -4
  93. package/.serena/memories/architectural-decision-no-dependency-injection.md +0 -76
  94. package/.serena/memories/architecture.md +0 -154
  95. package/.serena/memories/cache-interface-refactoring-2026-01-24.md +0 -165
  96. package/.serena/memories/code_style_and_conventions.md +0 -76
  97. package/.serena/memories/project_overview.md +0 -43
  98. package/.serena/memories/schema-dsl-plan.md +0 -107
  99. package/.serena/memories/suggested_commands.md +0 -80
  100. package/.serena/memories/typescript-compilation-status.md +0 -54
  101. package/.serena/project.yml +0 -114
  102. package/BunSane.jpg +0 -0
  103. package/CLAUDE.md +0 -198
  104. package/TODO.md +0 -2
  105. package/bun.lock +0 -302
  106. package/bunfig.toml +0 -10
  107. package/docs/SCALABILITY_PLAN.md +0 -175
  108. package/studio/bun.lock +0 -482
  109. package/studio/package.json +0 -39
  110. package/studio/postcss.config.js +0 -6
  111. package/studio/src/components/DataTable.tsx +0 -211
  112. package/studio/src/components/Layout.tsx +0 -13
  113. package/studio/src/components/PageContainer.tsx +0 -9
  114. package/studio/src/components/PageHeader.tsx +0 -13
  115. package/studio/src/components/SearchBar.tsx +0 -57
  116. package/studio/src/components/Sidebar.tsx +0 -294
  117. package/studio/src/components/ui/button.tsx +0 -56
  118. package/studio/src/components/ui/checkbox.tsx +0 -26
  119. package/studio/src/components/ui/input.tsx +0 -25
  120. package/studio/src/hooks/useDataTable.ts +0 -131
  121. package/studio/src/index.css +0 -36
  122. package/studio/src/lib/api.ts +0 -186
  123. package/studio/src/lib/utils.ts +0 -13
  124. package/studio/src/main.tsx +0 -17
  125. package/studio/src/pages/ArcheType.tsx +0 -239
  126. package/studio/src/pages/Components.tsx +0 -124
  127. package/studio/src/pages/EntityInspector.tsx +0 -302
  128. package/studio/src/pages/QueryRunner.tsx +0 -246
  129. package/studio/src/pages/Table.tsx +0 -94
  130. package/studio/src/pages/Welcome.tsx +0 -241
  131. package/studio/src/routes.tsx +0 -45
  132. package/studio/src/store/archeTypeSettings.ts +0 -30
  133. package/studio/src/store/studio.ts +0 -65
  134. package/studio/src/utils/columnHelpers.tsx +0 -114
  135. package/studio/studio-instructions.md +0 -81
  136. package/studio/tailwind.config.js +0 -77
  137. package/studio/utils.ts +0 -54
  138. package/studio/vite.config.js +0 -19
  139. package/tests/benchmark/BENCHMARK_DATABASES_PLAN.md +0 -338
  140. package/tests/benchmark/bunfig.toml +0 -9
  141. package/tests/benchmark/fixtures/EcommerceComponents.ts +0 -283
  142. package/tests/benchmark/fixtures/EcommerceDataGenerators.ts +0 -301
  143. package/tests/benchmark/fixtures/RelationTracker.ts +0 -159
  144. package/tests/benchmark/fixtures/index.ts +0 -6
  145. package/tests/benchmark/index.ts +0 -22
  146. package/tests/benchmark/noop-preload.ts +0 -3
  147. package/tests/benchmark/query-lateral-benchmark.test.ts +0 -372
  148. package/tests/benchmark/runners/BenchmarkLoader.ts +0 -132
  149. package/tests/benchmark/runners/index.ts +0 -4
  150. package/tests/benchmark/scenarios/query-benchmarks.test.ts +0 -465
  151. package/tests/benchmark/scripts/generate-db.ts +0 -344
  152. package/tests/benchmark/scripts/run-benchmarks.ts +0 -97
  153. package/tests/e2e/http.test.ts +0 -130
  154. package/tests/fixtures/archetypes/TestUserArchetype.ts +0 -21
  155. package/tests/fixtures/components/TestOrder.ts +0 -23
  156. package/tests/fixtures/components/TestProduct.ts +0 -23
  157. package/tests/fixtures/components/TestUser.ts +0 -20
  158. package/tests/fixtures/components/index.ts +0 -6
  159. package/tests/graphql/SchemaGeneration.test.ts +0 -90
  160. package/tests/graphql/builders/ResolverBuilder.test.ts +0 -223
  161. package/tests/graphql/builders/TypeDefBuilder.test.ts +0 -153
  162. package/tests/helpers/MockRedisClient.ts +0 -113
  163. package/tests/helpers/MockRedisStreamServer.ts +0 -448
  164. package/tests/integration/archetype/ArcheType.persistence.test.ts +0 -241
  165. package/tests/integration/cache/CacheInvalidation.test.ts +0 -259
  166. package/tests/integration/entity/Entity.persistence.test.ts +0 -333
  167. package/tests/integration/entity/Entity.saveTimeout.test.ts +0 -110
  168. package/tests/integration/query/Query.complexAnalysis.test.ts +0 -557
  169. package/tests/integration/query/Query.edgeCases.test.ts +0 -595
  170. package/tests/integration/query/Query.exec.test.ts +0 -576
  171. package/tests/integration/query/Query.explainAnalyze.test.ts +0 -233
  172. package/tests/integration/query/Query.jsonbArray.test.ts +0 -214
  173. package/tests/integration/remote/dlq.test.ts +0 -175
  174. package/tests/integration/remote/event-dispatch.test.ts +0 -114
  175. package/tests/integration/remote/outbox.test.ts +0 -130
  176. package/tests/integration/remote/rpc.test.ts +0 -177
  177. package/tests/pglite-setup.ts +0 -62
  178. package/tests/setup.ts +0 -164
  179. package/tests/stress/BenchmarkRunner.ts +0 -203
  180. package/tests/stress/DataSeeder.ts +0 -190
  181. package/tests/stress/StressTestReporter.ts +0 -229
  182. package/tests/stress/cursor-perf-test.ts +0 -171
  183. package/tests/stress/fixtures/RealisticComponents.ts +0 -235
  184. package/tests/stress/fixtures/StressTestComponents.ts +0 -58
  185. package/tests/stress/index.ts +0 -7
  186. package/tests/stress/scenarios/query-benchmarks.test.ts +0 -285
  187. package/tests/stress/scenarios/realistic-scenarios.test.ts +0 -1081
  188. package/tests/stress/scenarios/timeout-investigation.test.ts +0 -522
  189. package/tests/unit/BatchLoader.test.ts +0 -196
  190. package/tests/unit/archetype/ArcheType.test.ts +0 -107
  191. package/tests/unit/cache/CacheManager.test.ts +0 -367
  192. package/tests/unit/cache/MemoryCache.test.ts +0 -260
  193. package/tests/unit/cache/RedisCache.test.ts +0 -411
  194. package/tests/unit/entity/Entity.components.test.ts +0 -317
  195. package/tests/unit/entity/Entity.drainSideEffects.test.ts +0 -51
  196. package/tests/unit/entity/Entity.reload.test.ts +0 -63
  197. package/tests/unit/entity/Entity.requireComponents.test.ts +0 -72
  198. package/tests/unit/entity/Entity.test.ts +0 -345
  199. package/tests/unit/gql/depthLimit.test.ts +0 -203
  200. package/tests/unit/gql/operationMiddleware.test.ts +0 -293
  201. package/tests/unit/health/Health.test.ts +0 -129
  202. package/tests/unit/middleware/AccessLog.test.ts +0 -37
  203. package/tests/unit/middleware/Middleware.test.ts +0 -98
  204. package/tests/unit/middleware/RequestId.test.ts +0 -54
  205. package/tests/unit/middleware/SecurityHeaders.test.ts +0 -66
  206. package/tests/unit/query/FilterBuilder.test.ts +0 -111
  207. package/tests/unit/query/JsonbArrayBuilder.test.ts +0 -178
  208. package/tests/unit/query/Query.emptyString.test.ts +0 -69
  209. package/tests/unit/query/Query.test.ts +0 -310
  210. package/tests/unit/remote/CircuitBreaker.test.ts +0 -159
  211. package/tests/unit/remote/RemoteError.test.ts +0 -55
  212. package/tests/unit/remote/decorators.test.ts +0 -195
  213. package/tests/unit/remote/metrics.test.ts +0 -115
  214. package/tests/unit/remote/mockRedisStreamServer.test.ts +0 -104
  215. package/tests/unit/scheduler/DistributedLock.test.ts +0 -274
  216. package/tests/unit/scheduler/SchedulerManager.timeBased.test.ts +0 -95
  217. package/tests/unit/schema/schema-integration.test.ts +0 -426
  218. package/tests/unit/schema/schema.test.ts +0 -580
  219. package/tests/unit/storage/S3StorageProvider.test.ts +0 -567
  220. package/tests/unit/upload/RestUpload.test.ts +0 -267
  221. package/tests/unit/validateEnv.test.ts +0 -82
  222. package/tests/utils/entity-tracker.ts +0 -57
  223. package/tests/utils/index.ts +0 -13
  224. package/tests/utils/test-context.ts +0 -149
package/core/Entity.ts CHANGED
@@ -1,59 +1,50 @@
1
- import type { ComponentDataType, ComponentGetter, BaseComponent } from "./components";
2
- import { logger } from "./Logger";
3
- import db, { QUERY_TIMEOUT_MS } from "../database";
4
- import EntityManager from "./EntityManager";
5
- import ComponentRegistry from "./components/ComponentRegistry";
1
+ import type { ComponentDataType, BaseComponent } from "./components";
6
2
  import { uuidv7 } from "../utils/uuid";
7
- import { sql, SQL } from "bun";
8
- // import Query from "./Query"; // Lazy import to avoid cycle
3
+ import { SQL } from "bun";
9
4
  import { timed } from "./Decorators";
10
- import EntityHookManager from "./EntityHookManager";
11
- import { getMetadataStorage } from "./metadata";
12
- import { EntityCreatedEvent, EntityUpdatedEvent, EntityDeletedEvent, ComponentAddedEvent, ComponentUpdatedEvent, ComponentRemovedEvent } from "./events/EntityLifecycleEvents";
13
5
  import type { IEntity } from "./EntityInterface";
6
+ import EntityManager from "./EntityManager";
7
+ import * as pendingOps from "./entity/pendingOps";
8
+ import * as componentAccess from "./entity/componentAccess";
9
+ import * as saveEntity from "./entity/saveEntity";
10
+ import * as finders from "./entity/finders";
14
11
 
15
12
  export class Entity implements IEntity {
16
13
  id: string;
17
14
  public _persisted: boolean = false;
18
- private components: Map<string, BaseComponent> = new Map<string, BaseComponent>();
19
- private removedComponents: Set<string> = new Set<string>();
15
+ /** @internal Promoted from private for the core/entity/ submodule split (RFC §3.2). Not part of the public API. */
16
+ public components: Map<string, BaseComponent> = new Map<string, BaseComponent>();
17
+ /** @internal Promoted from private for the core/entity/ submodule split (RFC §3.2). Not part of the public API. */
18
+ public removedComponents: Set<string> = new Set<string>();
20
19
  // Track components that were removed and already saved to DB
21
20
  // This persists after save() so resolvers can detect removed components
22
- private savedRemovedComponents: Set<string> = new Set<string>();
21
+ /** @internal Promoted from private for the core/entity/ submodule split (RFC §3.2). Not part of the public API. */
22
+ public savedRemovedComponents: Set<string> = new Set<string>();
23
23
  protected _dirty: boolean = false;
24
24
 
25
- // Drainable set of fire-and-forget cache ops triggered from set/remove.
26
- // App.shutdown can await these to avoid losing writes mid-shutdown
27
- // (H-CACHE-1).
28
- private static pendingCacheOps: Set<Promise<void>> = new Set();
25
+ constructor(id?: string) {
26
+ // Use || instead of ?? to also handle empty strings
27
+ this.id = (id && id.trim() !== '') ? id : uuidv7();
28
+ this._dirty = true;
29
+ }
30
+
31
+ public static Create(): Entity {
32
+ return new Entity();
33
+ }
34
+
35
+ public static CreateWithId(id: string): Entity {
36
+ return new Entity(id);
37
+ }
29
38
 
30
- // Drainable set of post-commit side-effect Promises scheduled via
31
- // queueMicrotask from save(). Includes cache invalidation + lifecycle
32
- // hooks (EntityCreated / EntityUpdated). Hooks may transitively trigger
33
- // more DB work (e.g., entity.save() from a handler), which is why this
34
- // is tracked separately from pendingCacheOps. Tests running against
35
- // PGlite's single-connection pool should drain this between test files
36
- // to prevent background work from prior files queueing behind the
37
- // current file's save and masking visibility of recently-committed
38
- // rows. See BUNSANE-001.
39
- private static pendingSideEffects: Set<Promise<void>> = new Set();
39
+ // --- Drainable background-work delegates (core/entity/pendingOps.ts) ---
40
40
 
41
41
  /**
42
42
  * Await all pending background cache operations. Call during shutdown
43
43
  * after HTTP drain but before cache.disconnect so setImmediate'd cache
44
44
  * writes are not lost. Bounded by `timeoutMs`.
45
45
  */
46
- public static async drainPendingCacheOps(timeoutMs: number = 5_000): Promise<void> {
47
- if (Entity.pendingCacheOps.size === 0) return;
48
- const snapshot = [...Entity.pendingCacheOps];
49
- const drainTimer = new Promise<'timeout'>((resolve) => {
50
- const t = setTimeout(() => resolve('timeout'), timeoutMs);
51
- t.unref?.();
52
- });
53
- await Promise.race([
54
- Promise.allSettled(snapshot).then(() => 'drained' as const),
55
- drainTimer,
56
- ]);
46
+ public static drainPendingCacheOps(timeoutMs: number = 5_000): Promise<void> {
47
+ return pendingOps.drainPendingCacheOps(timeoutMs);
57
48
  }
58
49
 
59
50
  /**
@@ -63,82 +54,50 @@ export class Entity implements IEntity {
63
54
  * background work has settled before the next file's saves run. Bounded
64
55
  * by `timeoutMs`. Safe to call repeatedly; no-op when the set is empty.
65
56
  */
66
- public static async drainPendingSideEffects(timeoutMs: number = 5_000): Promise<void> {
67
- if (Entity.pendingSideEffects.size === 0) return;
68
- const snapshot = [...Entity.pendingSideEffects];
69
- const drainTimer = new Promise<'timeout'>((resolve) => {
70
- const t = setTimeout(() => resolve('timeout'), timeoutMs);
71
- t.unref?.();
72
- });
73
- await Promise.race([
74
- Promise.allSettled(snapshot).then(() => 'drained' as const),
75
- drainTimer,
76
- ]);
57
+ public static drainPendingSideEffects(timeoutMs: number = 5_000): Promise<void> {
58
+ return pendingOps.drainPendingSideEffects(timeoutMs);
77
59
  }
78
60
 
79
- private static trackCacheOp(p: Promise<void>): void {
80
- Entity.pendingCacheOps.add(p);
81
- p.finally(() => Entity.pendingCacheOps.delete(p));
82
- }
83
-
84
- private static trackSideEffect(p: Promise<void>): void {
85
- Entity.pendingSideEffects.add(p);
86
- p.finally(() => Entity.pendingSideEffects.delete(p));
61
+ /**
62
+ * Track a fire-and-forget cache promise in the drainable set. Public so
63
+ * other framework read paths (e.g. Query.populateComponents cache
64
+ * warming) share the same drain semantics (H-CACHE-1).
65
+ */
66
+ public static trackCacheOp(p: Promise<void>): void {
67
+ pendingOps.trackCacheOp(p);
87
68
  }
88
69
 
89
- constructor(id?: string) {
90
- // Use || instead of ?? to also handle empty strings
91
- this.id = (id && id.trim() !== '') ? id : uuidv7();
92
- this._dirty = true;
93
- }
70
+ // --- Component access (core/entity/componentAccess.ts) ---
94
71
 
95
- public static Create(): Entity {
96
- return new Entity();
97
- }
98
-
99
- public static CreateWithId(id: string): Entity {
100
- return new Entity(id);
101
- }
102
-
103
- protected addComponent(component: BaseComponent): Entity {
104
- this.components.set(component.getTypeID(), component);
105
- return this;
72
+ /** @internal Promoted from protected for the core/entity/ submodule split (RFC §3.2). Query.ts / RequestLoaders.ts already cast to call this. */
73
+ public addComponent(component: BaseComponent): Entity {
74
+ return componentAccess.addComponent(this, component);
106
75
  }
107
76
 
108
77
  public componentList(): BaseComponent[] {
109
- return Array.from(this.components.values());
78
+ return componentAccess.componentList(this);
110
79
  }
111
80
 
112
81
  /**
113
82
  * Synchronously check if a component is already loaded in memory.
114
83
  * This does NOT trigger a database fetch - use get() for that.
115
- * @param ctor Component constructor
116
- * @returns Component instance if already in memory, undefined otherwise
117
84
  */
118
85
  public getInMemory<T extends BaseComponent>(ctor: new (...args: any[]) => T): T | undefined {
119
- return Array.from(this.components.values()).find(comp => comp instanceof ctor) as T | undefined;
86
+ return componentAccess.getInMemory(this, ctor);
120
87
  }
121
88
 
122
89
  /**
123
90
  * Check if a component exists in memory (synchronous, no DB fetch).
124
- * @param ctor Component constructor
125
- * @returns true if component is already loaded in memory
126
91
  */
127
92
  public hasInMemory<T extends BaseComponent>(ctor: new (...args: any[]) => T): boolean {
128
- return Array.from(this.components.values()).some(comp => comp instanceof ctor);
93
+ return componentAccess.hasInMemory(this, ctor);
129
94
  }
130
95
 
131
96
  /**
132
97
  * Check if a component was explicitly removed from this entity (pending or already saved deletion).
133
- * Useful in resolvers to avoid returning stale cached data for removed components.
134
- * @param ctor Component constructor
135
- * @returns true if component was removed (pending or saved)
136
98
  */
137
99
  public wasRemoved<T extends BaseComponent>(ctor: new (...args: any[]) => T): boolean {
138
- const temp = new ctor();
139
- const typeId = temp.getTypeID();
140
- // Check both pending removals and already-saved removals
141
- return this.removedComponents.has(typeId) || this.savedRemovedComponents.has(typeId);
100
+ return componentAccess.wasRemoved(this, ctor);
142
101
  }
143
102
 
144
103
  /**
@@ -146,90 +105,15 @@ export class Entity implements IEntity {
146
105
  * Use like: entity.add(Component, { value: "Test" })
147
106
  */
148
107
  public add<T extends BaseComponent>(ctor: new (...args: any[]) => T, data?: Partial<ComponentDataType<T>>): this {
149
- const instance = new ctor();
150
- if (data) {
151
- Object.assign(instance, data);
152
- } else {
153
- Object.assign(instance, {});
154
- }
155
- this.addComponent(instance);
156
- this._dirty = true;
157
- // executeHooks is async; the surrounding try/catch only captures
158
- // synchronous throws. Attach a .catch so an async rejection from a
159
- // hook handler does not escape as an unhandled rejection (H-HOOK-1).
160
- // Add stays sync to preserve the fluent chaining signature; hook
161
- // failures are logged and do not fail the add operation.
162
- Promise.resolve()
163
- .then(() => EntityHookManager.executeHooks(new ComponentAddedEvent(this, instance)))
164
- .catch((error) => {
165
- logger.error(`Error firing component added hook for ${instance.getTypeID()}: ${error}`);
166
- });
167
-
108
+ componentAccess.add(this, ctor, data);
168
109
  return this;
169
110
  }
170
111
 
171
112
  /**
172
113
  * Sets/updates a component on the entity.
173
- * If the component exists, it updates its properties.
174
- * If it doesn't exist, it adds a new component.
175
- * Use like: entity.set(Component, { value: "Test" })
176
114
  */
177
- public async set<T extends BaseComponent>(ctor: new (...args: any[]) => T, data: Partial<ComponentDataType<T>>, context?: { loaders?: { componentsByEntityType?: any }; trx?: SQL }): Promise<this> {
178
- await this.get(ctor, context);
179
-
180
- const component = Array.from(this.components.values()).find(comp => comp instanceof ctor) as T;
181
- if (component) {
182
- // Store old data for the update event
183
- const oldData = { ...component };
184
-
185
- // Update existing component
186
- Object.assign(component, data);
187
- component.setDirty(true);
188
- this._dirty = true;
189
-
190
- // Fire component updated event. Await so a hook rejection is
191
- // captured by this method's try/catch and does not escape as an
192
- // unhandled rejection (H-HOOK-1).
193
- try {
194
- await EntityHookManager.executeHooks(new ComponentUpdatedEvent(this, component, oldData, component));
195
- } catch (error) {
196
- logger.error(`Error firing component updated hook for ${component.getTypeID()}: ${error}`);
197
- // Don't fail the set operation if hooks fail
198
- }
199
-
200
- // Invalidate DataLoader cache if context is provided
201
- if (context?.loaders?.componentsByEntityType) {
202
- context.loaders.componentsByEntityType.clear({
203
- entityId: this.id,
204
- typeId: component.getTypeID()
205
- });
206
- }
207
-
208
- // Fire-and-forget cache update, tracked via drainable set so
209
- // App.shutdown can await it (H-CACHE-1).
210
- Entity.trackCacheOp((async () => {
211
- try {
212
- const { CacheManager } = await import('./cache/CacheManager');
213
- const cacheManager = CacheManager.getInstance();
214
- const config = cacheManager.getConfig();
215
-
216
- if (config.enabled && config.component?.enabled) {
217
- if (config.strategy === 'write-through') {
218
- await cacheManager.setComponentWriteThrough(this.id, [component], component.getTypeID(), config.component.ttl);
219
- } else {
220
- await cacheManager.invalidateComponent(this.id, component.getTypeID());
221
- }
222
- }
223
- } catch (error) {
224
- logger.warn({ scope: 'cache', component: 'Entity', msg: 'Cache operation failed after set', err: error });
225
- }
226
- })());
227
- } else {
228
- // Add new component
229
- this.add(ctor, data);
230
- this._dirty = true;
231
- // Note: add() already fires ComponentAddedEvent, so we don't need to fire it again
232
- }
115
+ public async set<T extends BaseComponent>(ctor: new (...args: any[]) => T, data: Partial<ComponentDataType<T>>, context?: { loaders?: { componentsByEntityType?: any }; trx?: SQL; signal?: AbortSignal }): Promise<this> {
116
+ await componentAccess.set(this, ctor, data, context);
233
117
  return this;
234
118
  }
235
119
 
@@ -237,757 +121,86 @@ export class Entity implements IEntity {
237
121
  * Removes a component from the entity.
238
122
  * Use like: entity.remove(Component)
239
123
  * WARNING: This will delete the component from the database upon saving the entity.
240
- * If you want to keep the component in the database but just remove it from the entity instance,
241
- * consider implementing a different method.
242
124
  */
243
- public remove<T extends BaseComponent>(ctor: new (...args: any[]) => T, context?: { loaders?: { componentsByEntityType?: any }; trx?: SQL }): boolean {
244
- const component = Array.from(this.components.values()).find(comp => comp instanceof ctor) as T;
245
-
246
- if (component) {
247
- const typeId = component.getTypeID();
248
-
249
- // Track the component type for database deletion
250
- this.removedComponents.add(typeId);
251
-
252
- // Remove the component from the map
253
- this.components.delete(typeId);
254
- this._dirty = true;
255
-
256
- // Fire component removed event. remove() stays sync to preserve
257
- // the boolean return signature used by callers; attach .catch so
258
- // async hook rejections do not escape (H-HOOK-1).
259
- Promise.resolve()
260
- .then(() => EntityHookManager.executeHooks(new ComponentRemovedEvent(this, component)))
261
- .catch((error) => {
262
- logger.error(`Error firing component removed hook for ${typeId}: ${error}`);
263
- });
264
-
265
- // Invalidate DataLoader cache if context is provided
266
- if (context?.loaders?.componentsByEntityType) {
267
- context.loaders.componentsByEntityType.clear({
268
- entityId: this.id,
269
- typeId: typeId
270
- });
271
- }
272
-
273
- // Fire-and-forget cache invalidation, tracked for shutdown drain
274
- // (H-CACHE-1).
275
- Entity.trackCacheOp((async () => {
276
- try {
277
- const { CacheManager } = await import('./cache/CacheManager');
278
- const cacheManager = CacheManager.getInstance();
279
- const config = cacheManager.getConfig();
280
-
281
- if (config.enabled && config.component?.enabled) {
282
- await cacheManager.invalidateComponent(this.id, typeId);
283
- }
284
- } catch (error) {
285
- logger.warn({ scope: 'cache', component: 'Entity', msg: 'Cache invalidation failed after remove', err: error });
286
- }
287
- })());
288
-
289
- return true;
290
- }
291
-
292
- return false;
125
+ public remove<T extends BaseComponent>(ctor: new (...args: any[]) => T, context?: { loaders?: { componentsByEntityType?: any }; trx?: SQL; signal?: AbortSignal }): boolean {
126
+ return componentAccess.remove(this, ctor, context);
293
127
  }
294
128
 
295
129
  /**
296
130
  * Get component data from entity. Loads from DB if not cached.
297
- * @param ctor Component constructor
298
- * @param context Optional DataLoader context and/or transaction
299
- * @returns Component data or null
300
131
  */
301
- public async get<T extends BaseComponent>(ctor: new (...args: any[]) => T, context?: { loaders?: { componentsByEntityType?: any }; trx?: SQL }): Promise<ComponentDataType<T> | null> {
302
- const comp = await this._loadComponent(ctor, context);
303
- return comp ? (comp as ComponentGetter<T>).data() : null;
132
+ public get<T extends BaseComponent>(ctor: new (...args: any[]) => T, context?: { loaders?: { componentsByEntityType?: any }; trx?: SQL; signal?: AbortSignal }): Promise<ComponentDataType<T> | null> {
133
+ return componentAccess.get(this, ctor, context);
304
134
  }
305
135
 
306
136
  /**
307
137
  * Check if entity has a component (type guard).
308
138
  * Uses in-memory check only - does not query database.
309
- * Useful for runtime checks before accessing component data.
310
- *
311
- * @example
312
- * ```typescript
313
- * if (entity.has(Health)) {
314
- * // TypeScript knows entity has Health component
315
- * const health = entity.getCached(Health); // guaranteed to exist
316
- * }
317
- * ```
318
- *
319
- * @param ctor Component constructor
320
- * @returns true if component exists in memory
321
139
  */
322
140
  public has<T extends BaseComponent>(ctor: new (...args: any[]) => T): boolean {
323
- return this.hasInMemory(ctor);
141
+ return componentAccess.has(this, ctor);
324
142
  }
325
143
 
326
144
  /**
327
145
  * Get component data or throw if not found.
328
- * Use this when you know the component must exist (e.g., after a query that included it).
329
- *
330
- * @example
331
- * ```typescript
332
- * // After query that included Position
333
- * const pos = await entity.getOrThrow(Position);
334
- * // pos is guaranteed to be ComponentDataType<Position>, not null
335
- * ```
336
- *
337
- * @param ctor Component constructor
338
- * @param context Optional DataLoader context and/or transaction
339
- * @returns Component data (never null)
340
- * @throws Error if component not found
341
146
  */
342
- public async getOrThrow<T extends BaseComponent>(
147
+ public getOrThrow<T extends BaseComponent>(
343
148
  ctor: new (...args: any[]) => T,
344
- context?: { loaders?: { componentsByEntityType?: any }; trx?: SQL }
149
+ context?: { loaders?: { componentsByEntityType?: any }; trx?: SQL; signal?: AbortSignal }
345
150
  ): Promise<ComponentDataType<T>> {
346
- const data = await this.get(ctor, context);
347
- if (data === null) {
348
- throw new Error(`Entity ${this.id} is missing required component ${ctor.name}`);
349
- }
350
- return data;
151
+ return componentAccess.getOrThrow(this, ctor, context);
351
152
  }
352
153
 
353
154
  /**
354
155
  * Get component data synchronously if already loaded in memory.
355
156
  * Does NOT trigger a database fetch - returns undefined if not cached.
356
- *
357
- * Use this for performance-critical code paths when you know
358
- * the component was already loaded (e.g., via query populate).
359
- *
360
- * @example
361
- * ```typescript
362
- * // After query with .populate()
363
- * const pos = entity.getCached(Position);
364
- * if (pos) {
365
- * console.log(pos.x, pos.y);
366
- * }
367
- * ```
368
- *
369
- * @param ctor Component constructor
370
- * @returns Component data if in memory, undefined otherwise
371
157
  */
372
158
  public getCached<T extends BaseComponent>(ctor: new (...args: any[]) => T): ComponentDataType<T> | undefined {
373
- const comp = this.getInMemory(ctor);
374
- return comp ? (comp as ComponentGetter<T>).data() : undefined;
159
+ return componentAccess.getCached(this, ctor);
375
160
  }
376
161
 
377
162
  /**
378
163
  * Get component instance from entity. Loads from DB if not cached.
379
- * @param ctor Constructor of the component to fetch
380
- * @param context Optional DataLoader context and/or transaction
381
- * @returns Component instance or null
382
164
  */
383
- public async getInstanceOf<T extends BaseComponent>(ctor: new (...args: any[]) => T, context?: { loaders?: { componentsByEntityType?: any }; trx?: SQL }): Promise<T | null> {
384
- return this._loadComponent(ctor, context);
165
+ public getInstanceOf<T extends BaseComponent>(ctor: new (...args: any[]) => T, context?: { loaders?: { componentsByEntityType?: any }; trx?: SQL; signal?: AbortSignal }): Promise<T | null> {
166
+ return componentAccess.getInstanceOf(this, ctor, context);
385
167
  }
386
168
 
387
169
  /**
388
170
  * Discard in-memory component state and re-hydrate from the database.
389
171
  * Preserves entity identity — callers holding a reference see fresh data
390
- * on the same instance. Use after a raw-SQL write that bypassed
391
- * `entity.set`/`entity.save`, or when a different `Entity` instance with
392
- * the same id mutated persisted data.
393
- *
394
- * @param opts Optional transaction
172
+ * on the same instance.
395
173
  */
396
- public async reload(opts?: { trx?: SQL }): Promise<this> {
397
- if (!this.id || this.id.trim() === '') {
398
- return this;
399
- }
400
- this.components.clear();
401
- this.removedComponents.clear();
402
- this.savedRemovedComponents.clear();
403
-
404
- const dbConn = opts?.trx ?? db;
405
- const rows = await dbConn`
406
- SELECT c.id, c.type_id, c.data
407
- FROM components c
408
- WHERE c.entity_id = ${this.id} AND c.deleted_at IS NULL
409
- `;
410
-
411
- const storage = getMetadataStorage();
412
- for (const row of rows) {
413
- const ctor = ComponentRegistry.getConstructor(row.type_id);
414
- if (!ctor) continue;
415
- const comp: any = new ctor();
416
- const parsed = typeof row.data === 'string' ? JSON.parse(row.data) : row.data;
417
- Object.assign(comp, parsed);
418
- comp.id = row.id;
419
- const props = storage.componentProperties.get(row.type_id);
420
- if (props) {
421
- for (const prop of props) {
422
- if (prop.propertyType === Date && typeof comp[prop.propertyKey] === 'string') {
423
- comp[prop.propertyKey] = new Date(comp[prop.propertyKey]);
424
- }
425
- }
426
- }
427
- comp.setPersisted(true);
428
- comp.setDirty(false);
429
- this.addComponent(comp);
430
- }
431
-
432
- this.setPersisted(true);
433
- this.setDirty(false);
174
+ public async reload(opts?: { trx?: SQL; signal?: AbortSignal }): Promise<this> {
175
+ await componentAccess.reload(this, opts);
434
176
  return this;
435
177
  }
436
178
 
437
179
  /**
438
180
  * Ensure the given components are hydrated on this entity's in-memory
439
- * componentList. No-op for components already loaded. Batched: one SQL
440
- * call for all missing components.
441
- *
442
- * Required when a later `entity.set(...)` + `entity.save()` may trigger
443
- * a `@ComponentTargetHook` whose `includeComponents` lists tag
444
- * components. Hook matching reads `componentList()` (in-memory only), so
445
- * tags must be loaded first for the hook to fire.
446
- *
447
- * @param ctors Component constructors to ensure are loaded
181
+ * componentList. No-op for components already loaded.
448
182
  */
449
- public async requireComponents(ctors: Array<new (...args: any[]) => BaseComponent>): Promise<void> {
450
- if (ctors.length === 0) return;
451
- const missing: string[] = [];
452
- for (const ctor of ctors) {
453
- const existing = Array.from(this.components.values()).find(c => c instanceof ctor);
454
- if (existing) continue;
455
- const typeId = new ctor().getTypeID();
456
- missing.push(typeId);
457
- }
458
- if (missing.length === 0) return;
459
- await Entity.LoadComponents([this], missing);
183
+ public requireComponents(ctors: Array<new (...args: any[]) => BaseComponent>): Promise<void> {
184
+ return componentAccess.requireComponents(this, ctors);
460
185
  }
461
186
 
462
- private async _loadComponent<T extends BaseComponent>(ctor: new (...args: any[]) => T, context?: { loaders?: { componentsByEntityType?: any }; trx?: SQL }): Promise<T | null> {
463
- const comp = Array.from(this.components.values()).find(comp => comp instanceof ctor) as T | undefined;
464
- if (typeof comp !== "undefined") {
465
- return comp;
466
- }
467
-
468
- // Validate entity ID before database query
469
- if (!this.id || this.id.trim() === '') {
470
- logger.warn(`Cannot load component ${ctor.name}: entity id is empty`);
471
- return null;
472
- }
473
-
474
- const temp = new ctor();
475
- const typeId = temp.getTypeID();
476
-
477
- // Use transaction if provided, otherwise use default db
478
- const dbConn = context?.trx ?? db;
479
-
480
- try {
481
- let componentData: any = null;
482
- let componentId: string | null = null;
483
-
484
- if (context?.loaders?.componentsByEntityType) {
485
- const loaderResult = await context.loaders.componentsByEntityType.load({
486
- entityId: this.id,
487
- typeId: typeId
488
- });
489
- if (loaderResult) {
490
- componentData = loaderResult.data;
491
- componentId = loaderResult.id;
492
- }
493
- } else {
494
- const rows = await dbConn`SELECT id, data FROM components WHERE entity_id = ${this.id} AND type_id = ${typeId} AND deleted_at IS NULL`;
495
- if (rows.length > 0) {
496
- componentData = rows[0].data;
497
- componentId = rows[0].id;
498
- }
499
- }
500
-
501
- if (componentData !== null) {
502
- const comp: any = new ctor();
503
- if (componentId) {
504
- comp.id = componentId;
505
- }
506
- const parsedData = typeof componentData === 'string' ? JSON.parse(componentData) : componentData;
507
- Object.assign(comp, parsedData);
508
- const storage = getMetadataStorage();
509
- const props = storage.componentProperties.get(typeId);
510
- if (props) {
511
- for (const prop of props) {
512
- if (prop.propertyType === Date && typeof comp[prop.propertyKey] === 'string') {
513
- comp[prop.propertyKey] = new Date(comp[prop.propertyKey]);
514
- }
515
- }
516
- }
517
- comp.setPersisted(true);
518
- comp.setDirty(false);
519
- this.addComponent(comp);
520
- return comp as T;
521
- } else {
522
- return null;
523
- }
524
- } catch (error) {
525
- logger.error(`Failed to fetch component ${ctor.name}: ${error}`);
526
- return null;
527
- }
528
- }
187
+ // --- Persistence (core/entity/saveEntity.ts) ---
529
188
 
530
189
  @timed("Entity.save")
531
- public async save(trx?: SQL, context?: { loaders?: { componentsByEntityType?: any }; trx?: SQL }): Promise<boolean> {
532
- // Capture pre-save state BEFORE doSave mutates persisted/dirty flags.
533
- const wasNew = !this._persisted;
534
- const changedComponentTypeIds = this.getDirtyComponents();
535
- const removedComponentTypeIds = Array.from(this.removedComponents);
536
-
537
- // Pre-flight: await ComponentRegistry readiness for every component on
538
- // this entity BEFORE opening the transaction. Previously doSave awaited
539
- // ComponentRegistry.getReadyPromise inside the executeSave loop, so a
540
- // slow DDL (partition creation) would keep the PG transaction open and
541
- // idle-in-transaction waiting on registry state. (H-DB-4).
542
- for (const comp of this.components.values()) {
543
- const compName = comp.constructor.name;
544
- if (!ComponentRegistry.isComponentReady(compName)) {
545
- await ComponentRegistry.getReadyPromise(compName);
546
- }
547
- }
548
-
549
- const profile = process.env.DB_SAVE_PROFILE === 'true';
550
- const phaseStart = profile ? performance.now() : 0;
551
- const phases: Record<string, number> = {};
552
-
553
- // AbortController cancels in-flight queries and propagates ROLLBACK
554
- // when the wall-clock timer fires. Throwing from inside the transaction
555
- // callback triggers Bun SQL's auto-ROLLBACK, releasing the pooled connection.
556
- const controller = new AbortController();
557
- const timeoutMs = QUERY_TIMEOUT_MS;
558
- const timeoutHandle = setTimeout(() => {
559
- const err = new Error(`Entity save timeout for entity ${this.id} after ${timeoutMs}ms`);
560
- logger.error({ scope: 'Entity.save', entityId: this.id, timeoutMs }, err.message);
561
- controller.abort(err);
562
- }, timeoutMs);
563
-
564
- try {
565
- const dbStart = profile ? performance.now() : 0;
566
- if (trx) {
567
- await this.doSave(trx, controller.signal);
568
- } else {
569
- await db.transaction(async (newTrx) => {
570
- await this.doSave(newTrx, controller.signal);
571
- });
572
- }
573
- if (profile) phases.db = performance.now() - dbStart;
574
-
575
- clearTimeout(timeoutHandle);
576
-
577
- // Post-commit side effects are fire-and-forget so Redis / hook
578
- // latency cannot consume the save budget or block the caller.
579
- // Tracked in pendingSideEffects so tests/shutdown can drain
580
- // background work before asserting or tearing down.
581
- const sideEffectPromise = new Promise<void>((resolve) => {
582
- queueMicrotask(() => {
583
- this.runPostCommitSideEffects(
584
- wasNew,
585
- changedComponentTypeIds,
586
- removedComponentTypeIds,
587
- context,
588
- profile ? phases : undefined,
589
- profile ? phaseStart : undefined,
590
- ).finally(() => resolve());
591
- });
592
- });
593
- Entity.trackSideEffect(sideEffectPromise);
594
-
595
- return true;
596
- } catch (error) {
597
- clearTimeout(timeoutHandle);
598
- if (controller.signal.aborted) {
599
- throw controller.signal.reason ?? error;
600
- }
601
- throw error;
602
- } finally {
603
- // Ensure AbortController listeners are released even on success.
604
- if (!controller.signal.aborted) controller.abort();
605
- }
190
+ public save(trx?: SQL, context?: { loaders?: { componentsByEntityType?: any }; trx?: SQL; signal?: AbortSignal }): Promise<boolean> {
191
+ return saveEntity.saveEntity(this, trx, context);
606
192
  }
607
193
 
608
- /**
609
- * Fire-and-forget post-commit work: cache invalidation + lifecycle hooks.
610
- * Runs outside the save budget. Errors are logged and swallowed so cache
611
- * or hook failures never surface as save failures.
612
- */
613
- private async runPostCommitSideEffects(
614
- wasNew: boolean,
615
- changedComponentTypeIds: string[],
616
- removedComponentTypeIds: string[],
617
- context: { loaders?: { componentsByEntityType?: any }; trx?: SQL } | undefined,
618
- phases: Record<string, number> | undefined,
619
- phaseStart: number | undefined,
620
- ): Promise<void> {
621
- const profile = phases !== undefined && phaseStart !== undefined;
622
-
623
- const cacheStart = profile ? performance.now() : 0;
624
- try {
625
- await this.handleCacheAfterSave(changedComponentTypeIds, removedComponentTypeIds, context);
626
- } catch (err) {
627
- logger.warn({ scope: 'cache', entityId: this.id, err }, 'post-commit cache invalidation failed');
628
- }
629
- if (profile) phases!.cache = performance.now() - cacheStart;
630
-
631
- const hookStart = profile ? performance.now() : 0;
632
- try {
633
- if (wasNew) {
634
- await EntityHookManager.executeHooks(new EntityCreatedEvent(this));
635
- } else if (changedComponentTypeIds.length > 0) {
636
- await EntityHookManager.executeHooks(new EntityUpdatedEvent(this, changedComponentTypeIds));
637
- }
638
- } catch (err) {
639
- logger.error({ scope: 'hooks', entityId: this.id, err }, 'post-commit lifecycle hooks failed');
640
- }
641
- if (profile) phases!.hooks = performance.now() - hookStart;
642
-
643
- if (profile) {
644
- phases!.total = performance.now() - phaseStart!;
645
- logger.info({ scope: 'Entity.save.profile', entityId: this.id, phases }, 'Entity.save phase timings');
646
- }
647
- }
648
-
649
- /**
650
- * Handle cache operations after successful save
651
- * @param changedComponentTypeIds - Component type IDs that were dirty before save (captured before doSave clears flags)
652
- * @param removedComponentTypeIds - Component type IDs that were removed (captured before doSave clears the set)
653
- */
654
- private async handleCacheAfterSave(changedComponentTypeIds: string[], removedComponentTypeIds: string[], context?: { loaders?: { componentsByEntityType?: any }; trx?: SQL }): Promise<void> {
655
- try {
656
- // Import CacheManager dynamically to avoid circular dependency
657
- const { CacheManager } = await import('./cache/CacheManager');
658
- const cacheManager = CacheManager.getInstance();
659
- const config = cacheManager.getConfig();
660
-
661
- if (config.enabled && config.entity?.enabled) {
662
- // Always update entity existence cache
663
- if (config.strategy === 'write-through') {
664
- await cacheManager.setEntityWriteThrough(this, config.entity.ttl);
665
- } else {
666
- await cacheManager.invalidateEntity(this.id);
667
- }
668
- }
669
-
670
- // Handle component cache invalidation with granular approach
671
- if (config.enabled && config.component?.enabled) {
672
- // Use the pre-captured lists instead of re-querying (dirty flags are already cleared by doSave)
673
-
674
- // Invalidate cache for changed components
675
- for (const typeId of changedComponentTypeIds) {
676
- if (config.strategy === 'write-through') {
677
- // Update component cache with new data
678
- const component = this.components.get(typeId);
679
- if (component) {
680
- await cacheManager.setComponentWriteThrough(this.id, [component], typeId, config.component.ttl);
681
- }
682
- } else {
683
- // Invalidate component cache
684
- await cacheManager.invalidateComponent(this.id, typeId);
685
- }
686
-
687
- // Invalidate DataLoader cache for changed component
688
- if (context?.loaders?.componentsByEntityType) {
689
- context.loaders.componentsByEntityType.clear({
690
- entityId: this.id,
691
- typeId: typeId
692
- });
693
- }
694
- }
695
-
696
- // Invalidate cache for removed components
697
- for (const typeId of removedComponentTypeIds) {
698
- await cacheManager.invalidateComponent(this.id, typeId);
699
-
700
- // Invalidate DataLoader cache for removed component
701
- if (context?.loaders?.componentsByEntityType) {
702
- context.loaders.componentsByEntityType.clear({
703
- entityId: this.id,
704
- typeId: typeId
705
- });
706
- }
707
- }
708
- }
709
- } catch (error) {
710
- logger.warn({ scope: 'cache', component: 'Entity', msg: 'Cache operation failed after save', error });
711
- }
712
- }
713
-
714
- public async doSave(trx: SQL, signal?: AbortSignal): Promise<boolean> {
715
- // Validate entity ID to prevent PostgreSQL UUID parsing errors
716
- if (!this.id || this.id.trim() === '') {
717
- logger.error(`Cannot save entity: id is empty or invalid`);
718
- throw new Error(`Cannot save entity: id is empty or invalid`);
719
- }
720
-
721
- if (!this._dirty) {
722
- let dirtyComponents: string[] = [];
723
- try {
724
- dirtyComponents = this.getDirtyComponents();
725
- } catch {
726
- // best-effort diagnostics only
727
- }
728
-
729
- const removedTypeIds = Array.from(this.removedComponents);
730
- const entityType = (this as any)?.constructor?.name ?? "Entity";
731
- const dirtyComponentPreview = dirtyComponents.slice(0, 10).map((component) => {
732
- const anyComponent = component as any;
733
- return {
734
- type: anyComponent?.constructor?.name ?? "Component",
735
- typeId: typeof anyComponent?.getTypeID === "function" ? anyComponent.getTypeID() : undefined,
736
- id: anyComponent?.id,
737
- persisted: anyComponent?._persisted,
738
- dirty: anyComponent?._dirty,
739
- };
740
- });
741
-
742
- logger.trace(
743
- {
744
- component: "Entity",
745
- entity: {
746
- type: entityType,
747
- id: this.id,
748
- persisted: this._persisted,
749
- dirty: this._dirty,
750
- },
751
- components: {
752
- total: this.components.size,
753
- dirtyCount: dirtyComponents.length,
754
- dirtyPreview: dirtyComponentPreview,
755
- },
756
- removedComponents: {
757
- count: removedTypeIds.length,
758
- typeIdsPreview: removedTypeIds.slice(0, 10),
759
- },
760
- },
761
- "[Entity.doSave] Skipping save because entity is not dirty"
762
- );
763
- return true;
764
- }
765
-
766
- // Execute a Bun SQL query with AbortSignal support. On abort, the
767
- // in-flight query is cancelled (SQL.Query.cancel()) which causes the
768
- // transaction callback to throw, triggering Bun's automatic ROLLBACK
769
- // and releasing the pooled backend connection. Without this, a wall-
770
- // clock timeout leaks backends into `idle in transaction` state —
771
- // fatal under pgbouncer transaction-mode pooling.
772
- const run = async <T>(q: any): Promise<T> => {
773
- if (!signal) return await q;
774
- if (signal.aborted) {
775
- try { q.cancel?.(); } catch { /* ignore */ }
776
- throw signal.reason ?? new Error('Entity.save aborted');
777
- }
778
- const onAbort = () => { try { q.cancel?.(); } catch { /* ignore */ } };
779
- signal.addEventListener('abort', onAbort, { once: true });
780
- try {
781
- return await q;
782
- } finally {
783
- signal.removeEventListener('abort', onAbort);
784
- }
785
- };
786
-
787
- const executeSave = async (saveTrx: SQL) => {
788
- if (!this._persisted) {
789
- await run(saveTrx`INSERT INTO entities (id) VALUES (${this.id}) ON CONFLICT DO NOTHING`);
790
- this._persisted = true;
791
- }
792
-
793
- // Delete removed components from database
794
- if (this.removedComponents.size > 0) {
795
- const typeIds = Array.from(this.removedComponents);
796
- await run(saveTrx`DELETE FROM components WHERE entity_id = ${this.id} AND type_id IN ${sql(typeIds)}`);
797
- await run(saveTrx`DELETE FROM entity_components WHERE entity_id = ${this.id} AND type_id IN ${sql(typeIds)}`);
798
- // Move to savedRemovedComponents so resolvers can still detect removed components
799
- // This is needed because DataLoader may have stale cached data for this request
800
- for (const typeId of typeIds) {
801
- this.savedRemovedComponents.add(typeId);
802
- }
803
- this.removedComponents.clear();
804
- }
805
-
806
- if (this.components.size === 0) {
807
- logger.trace(`No components to save for entity ${this.id}`);
808
- return;
809
- }
810
-
811
- // Batch inserts and updates for better performance
812
- const componentsToInsert = [];
813
- const entityComponentsToInsert = [];
814
- const componentsToUpdate = [];
815
-
816
- for (const comp of this.components.values()) {
817
- const compName = comp.constructor.name;
818
- // Registry readiness is pre-flighted in save() before the
819
- // transaction starts (H-DB-4). This assert catches a
820
- // theoretical race if a caller skipped save() and jumped
821
- // straight to doSave — we refuse to await inside the txn so
822
- // a slow DDL cannot hold a pg session idle in transaction.
823
- if (!ComponentRegistry.isComponentReady(compName)) {
824
- throw new Error(`Component ${compName} not ready; call save() (not doSave) or await registry readiness before the transaction.`);
825
- }
826
-
827
- if (!(comp as any)._persisted) {
828
- if (comp.id === "") {
829
- comp.id = uuidv7();
830
- }
831
- componentsToInsert.push({
832
- id: comp.id,
833
- entity_id: this.id,
834
- name: compName,
835
- type_id: comp.getTypeID(),
836
- data: comp.serializableData()
837
- });
838
- entityComponentsToInsert.push({
839
- entity_id: this.id,
840
- type_id: comp.getTypeID(),
841
- component_id: comp.id
842
- });
843
- (comp as any).setPersisted(true);
844
- (comp as any).setDirty(false);
845
- } else if ((comp as any)._dirty) {
846
- componentsToUpdate.push({
847
- id: comp.id,
848
- data: comp.serializableData()
849
- });
850
- (comp as any).setDirty(false);
851
- }
852
- }
853
-
854
- // Perform batch inserts
855
- if (componentsToInsert.length > 0) {
856
- await run(saveTrx`INSERT INTO components ${sql(componentsToInsert, 'id', 'entity_id', 'name', 'type_id', 'data')}`);
857
- await run(saveTrx`INSERT INTO entity_components ${sql(entityComponentsToInsert, 'entity_id', 'type_id', 'component_id')} ON CONFLICT DO NOTHING`);
858
- }
859
-
860
- // Insert entity_components for existing components if entity is new
861
- if (!this._persisted) {
862
- const existingEntityComponents = [];
863
- for (const comp of this.components.values()) {
864
- if ((comp as any)._persisted) {
865
- existingEntityComponents.push({
866
- entity_id: this.id,
867
- type_id: comp.getTypeID(),
868
- component_id: comp.id
869
- });
870
- }
871
- }
872
- if (existingEntityComponents.length > 0) {
873
- await run(saveTrx`INSERT INTO entity_components ${sql(existingEntityComponents, 'entity_id', 'type_id', 'component_id')} ON CONFLICT DO NOTHING`);
874
- }
875
- }
876
-
877
- // Perform batch updates
878
- if (componentsToUpdate.length > 0) {
879
- for (const comp of componentsToUpdate) {
880
- // Validate component ID to prevent PostgreSQL UUID parsing errors
881
- if (!comp.id || comp.id.trim() === '') {
882
- logger.error(`Cannot update component: id is empty or invalid. Component data: ${JSON.stringify(comp.data).substring(0, 200)}`);
883
- throw new Error(`Cannot update component: component id is empty or invalid`);
884
- }
885
- logger.trace({ componentId: comp.id, data: comp.data }, `[Entity.doSave] Updating component`);
886
- await run(saveTrx`UPDATE components SET data = ${comp.data} WHERE id = ${comp.id}`);
887
- }
888
- }
889
- };
890
-
891
- await executeSave(trx);
892
-
893
- this._dirty = false;
894
-
895
- return true;
194
+ public doSave(trx: SQL, signal?: AbortSignal): Promise<boolean> {
195
+ return saveEntity.doSave(this, trx, signal);
896
196
  }
897
197
 
898
198
  public delete(force: boolean = false) {
899
199
  return EntityManager.deleteEntity(this, force);
900
200
  }
901
201
 
902
- public async doDelete(force: boolean = false): Promise<boolean> {
903
- if (!this._persisted) {
904
- logger.warn("Entity is not persisted, cannot delete.");
905
- return false;
906
- }
907
-
908
- // AbortController cancels in-flight queries on wall-clock timeout so a
909
- // hanging DELETE cannot leak backends into `idle in transaction` under
910
- // pgbouncer transaction pool mode. Same pattern as Entity.save.
911
- const controller = new AbortController();
912
- const timeoutMs = QUERY_TIMEOUT_MS;
913
- const timeoutHandle = setTimeout(() => {
914
- const err = new Error(`Entity delete timeout for entity ${this.id} after ${timeoutMs}ms`);
915
- logger.error({ scope: 'Entity.doDelete', entityId: this.id, timeoutMs }, err.message);
916
- controller.abort(err);
917
- }, timeoutMs);
918
-
919
- const signal = controller.signal;
920
- const run = async <T>(q: any): Promise<T> => {
921
- if (signal.aborted) {
922
- try { q.cancel?.(); } catch { /* ignore */ }
923
- throw signal.reason ?? new Error('Entity.doDelete aborted');
924
- }
925
- const onAbort = () => { try { q.cancel?.(); } catch { /* ignore */ } };
926
- signal.addEventListener('abort', onAbort, { once: true });
927
- try {
928
- return await q;
929
- } finally {
930
- signal.removeEventListener('abort', onAbort);
931
- }
932
- };
933
-
934
- try {
935
- await db.transaction(async (trx) => {
936
- if (force) {
937
- await run(trx`DELETE FROM entity_components WHERE entity_id = ${this.id}`);
938
- await run(trx`DELETE FROM components WHERE entity_id = ${this.id}`);
939
- await run(trx`DELETE FROM entities WHERE id = ${this.id}`);
940
- } else {
941
- await run(trx`UPDATE entities SET deleted_at = CURRENT_TIMESTAMP WHERE id = ${this.id} AND deleted_at IS NULL`);
942
- await run(trx`UPDATE entity_components SET deleted_at = CURRENT_TIMESTAMP WHERE entity_id = ${this.id} AND deleted_at IS NULL`);
943
- await run(trx`UPDATE components SET deleted_at = CURRENT_TIMESTAMP WHERE entity_id = ${this.id} AND deleted_at IS NULL`);
944
- }
945
- });
946
- clearTimeout(timeoutHandle);
947
-
948
- // Fire-and-forget post-commit side effects: lifecycle hooks + cache
949
- // invalidation. Errors are logged, never propagate to caller.
950
- queueMicrotask(() => this.runPostDeleteSideEffects(!force));
951
-
952
- return true;
953
- } catch (error) {
954
- clearTimeout(timeoutHandle);
955
- if (signal.aborted) {
956
- logger.error({ scope: 'Entity.doDelete', entityId: this.id }, `Entity delete aborted: ${signal.reason ?? error}`);
957
- } else {
958
- logger.error({ scope: 'Entity.doDelete', entityId: this.id, err: error }, 'Failed to delete entity');
959
- }
960
- // Re-throw so callers can distinguish DB failures (pool exhausted,
961
- // lock timeout, etc.) from "entity not found" / not persisted,
962
- // which still returns `false`. Previously any error produced the
963
- // same `false` return, hiding infrastructure problems (H-OBS-4).
964
- throw error instanceof Error ? error : new Error(String(error));
965
- } finally {
966
- if (!signal.aborted) controller.abort();
967
- }
968
- }
969
-
970
- private async runPostDeleteSideEffects(softDelete: boolean): Promise<void> {
971
- try {
972
- await EntityHookManager.executeHooks(new EntityDeletedEvent(this, softDelete));
973
- } catch (err) {
974
- logger.error({ scope: 'hooks', entityId: this.id, err }, 'post-delete lifecycle hooks failed');
975
- }
976
-
977
- try {
978
- const { CacheManager } = await import('./cache/CacheManager');
979
- const cacheManager = CacheManager.getInstance();
980
- const config = cacheManager.getConfig();
981
-
982
- if (config.enabled && config.entity?.enabled) {
983
- await cacheManager.invalidateEntity(this.id);
984
- }
985
- if (config.enabled && config.component?.enabled) {
986
- await cacheManager.invalidateAllEntityComponents(this.id);
987
- }
988
- } catch (err) {
989
- logger.warn({ scope: 'cache', entityId: this.id, err }, 'post-delete cache invalidation failed');
990
- }
202
+ public doDelete(force: boolean = false): Promise<boolean> {
203
+ return saveEntity.doDelete(this, force);
991
204
  }
992
205
 
993
206
  public setPersisted(persisted: boolean) {
@@ -998,216 +211,45 @@ export class Entity implements IEntity {
998
211
  this._dirty = dirty;
999
212
  }
1000
213
 
1001
- /**
1002
- * Get list of component type IDs that are dirty
1003
- */
1004
- private getDirtyComponents(): string[] {
1005
- const dirtyComponents: string[] = [];
1006
- for (const component of this.components.values()) {
1007
- // Include both dirty (modified) components AND new (not persisted) components
1008
- // New components need to be cached after save, not just modified ones
1009
- if ((component as any)._dirty || !(component as any)._persisted) {
1010
- dirtyComponents.push(component.getTypeID());
1011
- }
1012
- }
1013
- return dirtyComponents;
1014
- }
1015
-
214
+ // --- Loaders / factories / (de)serialization (core/entity/finders.ts) ---
1016
215
 
1017
216
  @timed("Entity.LoadMultiple")
1018
- public static async LoadMultiple(ids: string[]): Promise<Entity[]> {
1019
- if (ids.length === 0) return [];
1020
-
1021
- // Filter out empty/invalid IDs to prevent PostgreSQL UUID parsing errors
1022
- const validIds = ids.filter(id => id && id.trim() !== '');
1023
- if (validIds.length === 0) return [];
1024
- if (validIds.length !== ids.length) {
1025
- logger.warn(`LoadMultiple: Filtered out ${ids.length - validIds.length} invalid entity IDs`);
1026
- }
1027
-
1028
- const components = await db`
1029
- SELECT c.id, c.entity_id, c.type_id, c.data
1030
- FROM components c
1031
- WHERE c.entity_id IN ${sql(validIds)} AND c.deleted_at IS NULL
1032
- `;
1033
-
1034
- const entitiesMap = new Map<string, Entity>();
1035
-
1036
- for (const id of validIds) {
1037
- const entity = new Entity();
1038
- entity.id = id;
1039
- entity.setPersisted(true);
1040
- entity.setDirty(false);
1041
- entitiesMap.set(id, entity);
1042
- }
1043
-
1044
- for (const row of components) {
1045
- const { id, entity_id, type_id, data } = row;
1046
- const ctor = ComponentRegistry.getConstructor(type_id);
1047
- if (ctor) {
1048
- const comp = new ctor();
1049
- const componentData = typeof data === 'string' ? JSON.parse(data) : data;
1050
- Object.assign(comp, componentData);
1051
- comp.id = id;
1052
- comp.setPersisted(true);
1053
- comp.setDirty(false);
1054
- entitiesMap.get(entity_id)?.addComponent(comp);
1055
- }
1056
- }
1057
-
1058
- return Array.from(entitiesMap.values());
217
+ public static LoadMultiple(ids: string[]): Promise<Entity[]> {
218
+ return finders.loadMultiple(ids);
1059
219
  }
1060
220
 
1061
- public static async LoadComponents(entities: Entity[], componentIds: string[], skipCache: boolean = false): Promise<void> {
1062
- if (entities.length === 0 || componentIds.length === 0) return;
1063
-
1064
- // Filter out entities with empty/invalid IDs to prevent PostgreSQL UUID parsing errors
1065
- const validEntities = entities.filter(e => e.id && e.id.trim() !== '');
1066
- if (validEntities.length === 0) return;
1067
-
1068
- const entityIds = validEntities.map(e => e.id);
1069
-
1070
- const components = await db`
1071
- SELECT c.id, c.entity_id, c.type_id, c.data
1072
- FROM components c
1073
- WHERE c.entity_id IN ${sql(entityIds)} AND c.type_id IN ${sql(componentIds)} AND c.deleted_at IS NULL
1074
- `;
1075
-
1076
- // Use Map for O(1) lookups instead of O(n) find() - fixes O(n²) performance issue
1077
- const entityMap = new Map<string, Entity>(validEntities.map(e => [e.id, e]));
1078
-
1079
- for (const row of components) {
1080
- const { id, entity_id, type_id, data } = row;
1081
- const entity = entityMap.get(entity_id); // O(1) instead of O(n)
1082
- if (entity) {
1083
- const ctor = ComponentRegistry.getConstructor(type_id);
1084
- if (ctor) {
1085
- const comp = new ctor();
1086
- const componentData = typeof data === 'string' ? JSON.parse(data) : data;
1087
- Object.assign(comp, componentData);
1088
- comp.id = id;
1089
- comp.setPersisted(true);
1090
- comp.setDirty(false);
1091
- entity.addComponent(comp);
1092
- }
1093
- }
1094
- }
221
+ public static LoadComponents(entities: Entity[], componentIds: string[], skipCache: boolean = false): Promise<void> {
222
+ return finders.loadComponents(entities, componentIds, skipCache);
1095
223
  }
1096
224
 
1097
225
  /**
1098
226
  * Find an entity by its ID. Returning populated with all components. Or null if not found.
1099
- * @param id Entity ID
1100
- * @returns Entity | null
1101
227
  */
1102
- public static async FindById(id: string, trx?: SQL): Promise<Entity | null> {
1103
- // Validate ID to prevent PostgreSQL UUID parsing errors
1104
- if (!id || typeof id !== 'string' || id.trim() === '') {
1105
- logger.warn(`FindById called with invalid id: "${id}"`);
1106
- return null;
1107
- }
1108
- const { Query } = await import("../query/Query");
1109
- const entities = await new Query(trx).findById(id).populate().exec()
1110
- if(entities.length === 1) {
1111
- return entities[0]!;
1112
- }
1113
- return null;
228
+ public static FindById(id: string, trx?: SQL): Promise<Entity | null> {
229
+ return finders.findById(id, trx);
1114
230
  }
1115
231
 
1116
232
  public static Clone(entity: Entity): Entity {
1117
- const clone = new Entity();
1118
- clone._dirty = true;
1119
- clone._persisted = false;
1120
- for (const comp of entity.components.values()) {
1121
- const newComp = new (comp.constructor as any)();
1122
- Object.assign(newComp, comp.data());
1123
- newComp.id = uuidv7();
1124
- newComp.setDirty(true);
1125
- newComp.setPersisted(false);
1126
- clone.addComponent(newComp);
1127
- }
1128
- return clone;
233
+ return finders.clone(entity);
1129
234
  }
1130
235
 
1131
236
  public static MakeRef(entity: Entity): Entity {
1132
- const ref = new Entity();
1133
- ref._dirty = true;
1134
- ref._persisted = false;
1135
- for (const comp of entity.components.values()) {
1136
- const refComp = comp;
1137
- refComp.setDirty(false);
1138
- refComp.setPersisted(true);
1139
- ref.addComponent(refComp);
1140
- }
1141
- return ref;
237
+ return finders.makeRef(entity);
1142
238
  }
1143
239
 
1144
240
  /**
1145
241
  * Serialize the entity with only the currently loaded components
1146
- * @returns Object containing id and components data
1147
242
  */
1148
243
  public serialize(): { id: string; components: Record<string, any> } {
1149
- const components: Record<string, any> = {};
1150
- for (const comp of this.components.values()) {
1151
- components[comp.constructor.name] = comp.serializableData();
1152
- }
1153
- return {
1154
- id: this.id,
1155
- components
1156
- };
244
+ return finders.serialize(this);
1157
245
  }
1158
246
 
1159
247
  /**
1160
248
  * Deserialize/reconstitute an Entity from cached/serialized data.
1161
- * Handles both serialized format { id, components } and raw Entity-like objects.
1162
- * @param data Serialized entity data or Entity-like plain object
1163
- * @returns Reconstituted Entity instance
1164
249
  */
1165
250
  public static deserialize(data: any): Entity {
1166
- if (data instanceof Entity) {
1167
- return data;
1168
- }
1169
-
1170
- const entity = new Entity(data.id);
1171
- entity._persisted = true;
1172
- entity._dirty = false;
1173
-
1174
- // Handle serialized format: { id, components: { ComponentName: {...data} } }
1175
- if (data.components && typeof data.components === 'object') {
1176
- const storage = getMetadataStorage();
1177
-
1178
- for (const [componentName, componentData] of Object.entries(data.components)) {
1179
- // Find the component constructor by name
1180
- const ComponentCtor = ComponentRegistry.getConstructorByName(componentName);
1181
- if (!ComponentCtor) {
1182
- logger.warn(`Cannot deserialize component: constructor not found for ${componentName}`);
1183
- continue;
1184
- }
1185
-
1186
- const comp = new ComponentCtor();
1187
- const parsedData = typeof componentData === 'string' ? JSON.parse(componentData) : componentData;
1188
- Object.assign(comp, parsedData);
1189
-
1190
- // Restore Date objects
1191
- const typeId = comp.getTypeID();
1192
- const props = storage.componentProperties.get(typeId);
1193
- if (props) {
1194
- for (const prop of props) {
1195
- if (prop.propertyType === Date && typeof (comp as any)[prop.propertyKey] === 'string') {
1196
- (comp as any)[prop.propertyKey] = new Date((comp as any)[prop.propertyKey]);
1197
- }
1198
- }
1199
- }
1200
-
1201
- comp.setPersisted(true);
1202
- comp.setDirty(false);
1203
- entity.addComponent(comp);
1204
- }
1205
- }
1206
-
1207
- return entity;
251
+ return finders.deserialize(data);
1208
252
  }
1209
-
1210
-
1211
253
  }
1212
254
 
1213
- export default Entity;
255
+ export default Entity;