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