bunsane 0.3.2 → 0.5.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 (220) hide show
  1. package/CHANGELOG.md +471 -370
  2. package/core/BatchLoader.ts +56 -32
  3. package/core/Entity.ts +93 -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 +8 -7
  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 +25 -10
  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 +383 -0
  28. package/core/entity/finders.ts +202 -0
  29. package/core/entity/getCacheManager.ts +10 -0
  30. package/core/entity/pendingOps.ts +72 -0
  31. package/core/entity/saveEntity.ts +375 -0
  32. package/core/health.ts +93 -4
  33. package/core/hooks/dispatcher.ts +439 -0
  34. package/core/hooks/guards.ts +155 -0
  35. package/core/hooks/registry.ts +247 -0
  36. package/core/metadata/definitions/Component.ts +1 -1
  37. package/core/metadata/index.ts +15 -4
  38. package/core/middleware/RateLimit.ts +102 -105
  39. package/core/middleware/RequestId.ts +2 -9
  40. package/core/middleware/SecurityHeaders.ts +2 -11
  41. package/core/middleware/headers.ts +28 -0
  42. package/core/remote/OutboxWorker.ts +213 -183
  43. package/core/remote/RemoteManager.ts +401 -400
  44. package/core/remote/StreamConsumer.ts +535 -535
  45. package/core/remote/types.ts +153 -151
  46. package/core/requestScope.ts +34 -0
  47. package/core/scheduler/cronEvaluator.ts +174 -0
  48. package/core/scheduler/lifecycleHooks.ts +21 -0
  49. package/core/scheduler/lockCoordinator.ts +27 -0
  50. package/core/scheduler/metrics.ts +14 -0
  51. package/core/scheduler/taskRunner.ts +420 -0
  52. package/core/validateEnv.ts +10 -0
  53. package/database/DatabaseHelper.ts +128 -101
  54. package/database/IndexingStrategy.ts +72 -2
  55. package/database/PreparedStatementCache.ts +8 -2
  56. package/database/cancellable.ts +35 -22
  57. package/database/index.ts +29 -3
  58. package/database/instrumentedDb.ts +141 -141
  59. package/database/sqlHelpers.ts +3 -1
  60. package/endpoints/archetypes.ts +2 -8
  61. package/endpoints/tables.ts +6 -1
  62. package/gql/index.ts +1 -1
  63. package/gql/schema/index.ts +15 -4
  64. package/gql/visitors/ResolverGeneratorVisitor.ts +25 -4
  65. package/package.json +22 -1
  66. package/query/CTENode.ts +5 -3
  67. package/query/ComponentInclusionNode.ts +245 -14
  68. package/query/OrNode.ts +8 -19
  69. package/query/Query.ts +208 -79
  70. package/query/QueryContext.ts +6 -0
  71. package/query/QueryDAG.ts +7 -2
  72. package/query/membershipSource.ts +66 -0
  73. package/storage/LocalStorageProvider.ts +8 -3
  74. package/studio/dist/assets/index-BMZ67Npg.js +254 -0
  75. package/studio/dist/assets/index-BpbuYz9g.css +1 -0
  76. package/studio/{index.html → dist/index.html} +3 -2
  77. package/swagger/generator.ts +11 -1
  78. package/upload/UploadManager.ts +8 -6
  79. package/utils/uuid.ts +40 -10
  80. package/.claude/scheduled_tasks.lock +0 -1
  81. package/.claude/settings.local.json +0 -47
  82. package/.prettierrc +0 -4
  83. package/.serena/memories/architectural-decision-no-dependency-injection.md +0 -76
  84. package/.serena/memories/architecture.md +0 -154
  85. package/.serena/memories/cache-interface-refactoring-2026-01-24.md +0 -165
  86. package/.serena/memories/code_style_and_conventions.md +0 -76
  87. package/.serena/memories/project_overview.md +0 -43
  88. package/.serena/memories/schema-dsl-plan.md +0 -107
  89. package/.serena/memories/suggested_commands.md +0 -80
  90. package/.serena/memories/typescript-compilation-status.md +0 -54
  91. package/.serena/project.yml +0 -114
  92. package/BunSane.jpg +0 -0
  93. package/CLAUDE.md +0 -198
  94. package/TODO.md +0 -2
  95. package/bun.lock +0 -302
  96. package/bunfig.toml +0 -10
  97. package/docs/RFC_APP_REFACTOR.md +0 -248
  98. package/docs/RFC_REFACTOR_TARGETS.md +0 -251
  99. package/docs/SCALABILITY_PLAN.md +0 -175
  100. package/studio/bun.lock +0 -482
  101. package/studio/package.json +0 -39
  102. package/studio/postcss.config.js +0 -6
  103. package/studio/src/components/DataTable.tsx +0 -211
  104. package/studio/src/components/Layout.tsx +0 -13
  105. package/studio/src/components/PageContainer.tsx +0 -9
  106. package/studio/src/components/PageHeader.tsx +0 -13
  107. package/studio/src/components/SearchBar.tsx +0 -57
  108. package/studio/src/components/Sidebar.tsx +0 -294
  109. package/studio/src/components/ui/button.tsx +0 -56
  110. package/studio/src/components/ui/checkbox.tsx +0 -26
  111. package/studio/src/components/ui/input.tsx +0 -25
  112. package/studio/src/hooks/useDataTable.ts +0 -131
  113. package/studio/src/index.css +0 -36
  114. package/studio/src/lib/api.ts +0 -186
  115. package/studio/src/lib/utils.ts +0 -13
  116. package/studio/src/main.tsx +0 -17
  117. package/studio/src/pages/ArcheType.tsx +0 -239
  118. package/studio/src/pages/Components.tsx +0 -124
  119. package/studio/src/pages/EntityInspector.tsx +0 -302
  120. package/studio/src/pages/QueryRunner.tsx +0 -246
  121. package/studio/src/pages/Table.tsx +0 -94
  122. package/studio/src/pages/Welcome.tsx +0 -241
  123. package/studio/src/routes.tsx +0 -45
  124. package/studio/src/store/archeTypeSettings.ts +0 -30
  125. package/studio/src/store/studio.ts +0 -65
  126. package/studio/src/utils/columnHelpers.tsx +0 -114
  127. package/studio/studio-instructions.md +0 -81
  128. package/studio/tailwind.config.js +0 -77
  129. package/studio/utils.ts +0 -54
  130. package/studio/vite.config.js +0 -19
  131. package/tests/benchmark/BENCHMARK_DATABASES_PLAN.md +0 -338
  132. package/tests/benchmark/bunfig.toml +0 -9
  133. package/tests/benchmark/fixtures/EcommerceComponents.ts +0 -283
  134. package/tests/benchmark/fixtures/EcommerceDataGenerators.ts +0 -301
  135. package/tests/benchmark/fixtures/RelationTracker.ts +0 -159
  136. package/tests/benchmark/fixtures/index.ts +0 -6
  137. package/tests/benchmark/index.ts +0 -22
  138. package/tests/benchmark/noop-preload.ts +0 -3
  139. package/tests/benchmark/query-lateral-benchmark.test.ts +0 -372
  140. package/tests/benchmark/runners/BenchmarkLoader.ts +0 -132
  141. package/tests/benchmark/runners/index.ts +0 -4
  142. package/tests/benchmark/scenarios/query-benchmarks.test.ts +0 -465
  143. package/tests/benchmark/scripts/generate-db.ts +0 -344
  144. package/tests/benchmark/scripts/run-benchmarks.ts +0 -97
  145. package/tests/e2e/http.test.ts +0 -130
  146. package/tests/fixtures/archetypes/TestUserArchetype.ts +0 -21
  147. package/tests/fixtures/components/TestOrder.ts +0 -23
  148. package/tests/fixtures/components/TestProduct.ts +0 -23
  149. package/tests/fixtures/components/TestUser.ts +0 -20
  150. package/tests/fixtures/components/index.ts +0 -6
  151. package/tests/graphql/SchemaGeneration.test.ts +0 -90
  152. package/tests/graphql/builders/ResolverBuilder.test.ts +0 -223
  153. package/tests/graphql/builders/TypeDefBuilder.test.ts +0 -153
  154. package/tests/helpers/MockRedisClient.ts +0 -113
  155. package/tests/helpers/MockRedisStreamServer.ts +0 -448
  156. package/tests/integration/archetype/ArcheType.persistence.test.ts +0 -241
  157. package/tests/integration/cache/CacheInvalidation.test.ts +0 -259
  158. package/tests/integration/entity/Entity.persistence.test.ts +0 -333
  159. package/tests/integration/entity/Entity.saveTimeout.test.ts +0 -110
  160. package/tests/integration/loaders/RequestLoaders.abort.test.ts +0 -82
  161. package/tests/integration/query/Query.abort.test.ts +0 -66
  162. package/tests/integration/query/Query.complexAnalysis.test.ts +0 -557
  163. package/tests/integration/query/Query.edgeCases.test.ts +0 -595
  164. package/tests/integration/query/Query.exec.test.ts +0 -576
  165. package/tests/integration/query/Query.explainAnalyze.test.ts +0 -233
  166. package/tests/integration/query/Query.jsonbArray.test.ts +0 -214
  167. package/tests/integration/remote/dlq.test.ts +0 -175
  168. package/tests/integration/remote/event-dispatch.test.ts +0 -114
  169. package/tests/integration/remote/outbox.test.ts +0 -130
  170. package/tests/integration/remote/rpc.test.ts +0 -177
  171. package/tests/pglite-setup.ts +0 -62
  172. package/tests/setup.ts +0 -164
  173. package/tests/stress/BenchmarkRunner.ts +0 -203
  174. package/tests/stress/DataSeeder.ts +0 -190
  175. package/tests/stress/StressTestReporter.ts +0 -229
  176. package/tests/stress/cursor-perf-test.ts +0 -171
  177. package/tests/stress/fixtures/RealisticComponents.ts +0 -235
  178. package/tests/stress/fixtures/StressTestComponents.ts +0 -58
  179. package/tests/stress/index.ts +0 -7
  180. package/tests/stress/scenarios/query-benchmarks.test.ts +0 -285
  181. package/tests/stress/scenarios/realistic-scenarios.test.ts +0 -1081
  182. package/tests/stress/scenarios/timeout-investigation.test.ts +0 -522
  183. package/tests/unit/BatchLoader.test.ts +0 -196
  184. package/tests/unit/archetype/ArcheType.test.ts +0 -107
  185. package/tests/unit/cache/CacheManager.test.ts +0 -498
  186. package/tests/unit/cache/MemoryCache.test.ts +0 -260
  187. package/tests/unit/cache/RedisCache.test.ts +0 -411
  188. package/tests/unit/database/cancellable.test.ts +0 -81
  189. package/tests/unit/database/instrumentedDb.test.ts +0 -160
  190. package/tests/unit/entity/Entity.components.test.ts +0 -317
  191. package/tests/unit/entity/Entity.drainSideEffects.test.ts +0 -51
  192. package/tests/unit/entity/Entity.reload.test.ts +0 -63
  193. package/tests/unit/entity/Entity.requireComponents.test.ts +0 -72
  194. package/tests/unit/entity/Entity.test.ts +0 -345
  195. package/tests/unit/gql/depthLimit.test.ts +0 -203
  196. package/tests/unit/gql/operationMiddleware.test.ts +0 -293
  197. package/tests/unit/health/Health.test.ts +0 -129
  198. package/tests/unit/middleware/AccessLog.test.ts +0 -37
  199. package/tests/unit/middleware/Middleware.test.ts +0 -98
  200. package/tests/unit/middleware/RequestId.test.ts +0 -54
  201. package/tests/unit/middleware/SecurityHeaders.test.ts +0 -66
  202. package/tests/unit/query/FilterBuilder.test.ts +0 -111
  203. package/tests/unit/query/JsonbArrayBuilder.test.ts +0 -178
  204. package/tests/unit/query/Query.emptyString.test.ts +0 -69
  205. package/tests/unit/query/Query.test.ts +0 -310
  206. package/tests/unit/remote/CircuitBreaker.test.ts +0 -159
  207. package/tests/unit/remote/RemoteError.test.ts +0 -55
  208. package/tests/unit/remote/decorators.test.ts +0 -195
  209. package/tests/unit/remote/metrics.test.ts +0 -115
  210. package/tests/unit/remote/mockRedisStreamServer.test.ts +0 -104
  211. package/tests/unit/scheduler/DistributedLock.test.ts +0 -274
  212. package/tests/unit/scheduler/SchedulerManager.timeBased.test.ts +0 -95
  213. package/tests/unit/schema/schema-integration.test.ts +0 -426
  214. package/tests/unit/schema/schema.test.ts +0 -580
  215. package/tests/unit/storage/S3StorageProvider.test.ts +0 -567
  216. package/tests/unit/upload/RestUpload.test.ts +0 -267
  217. package/tests/unit/validateEnv.test.ts +0 -82
  218. package/tests/utils/entity-tracker.ts +0 -57
  219. package/tests/utils/index.ts +0 -13
  220. package/tests/utils/test-context.ts +0 -149
package/core/Entity.ts CHANGED
@@ -1,60 +1,58 @@
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>();
23
+ /**
24
+ * @internal Type IDs confirmed absent from the DB during this entity's
25
+ * lifetime. Used as a negative cache in loadComponent() so repeated
26
+ * get() probes for optional components skip the SELECT. Invalidated
27
+ * whenever a component is added (addComponent) or the entity is
28
+ * reloaded. Not part of the public API.
29
+ */
30
+ public _missingComponents: Set<string> = new Set<string>();
24
31
  protected _dirty: boolean = false;
25
32
 
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();
33
+ constructor(id?: string) {
34
+ // Use || instead of ?? to also handle empty strings
35
+ this.id = (id && id.trim() !== '') ? id : uuidv7();
36
+ this._dirty = true;
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
+ public static Create(): Entity {
40
+ return new Entity();
41
+ }
42
+
43
+ public static CreateWithId(id: string): Entity {
44
+ return new Entity(id);
45
+ }
46
+
47
+ // --- Drainable background-work delegates (core/entity/pendingOps.ts) ---
41
48
 
42
49
  /**
43
50
  * Await all pending background cache operations. Call during shutdown
44
51
  * after HTTP drain but before cache.disconnect so setImmediate'd cache
45
52
  * writes are not lost. Bounded by `timeoutMs`.
46
53
  */
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
- ]);
54
+ public static drainPendingCacheOps(timeoutMs: number = 5_000): Promise<void> {
55
+ return pendingOps.drainPendingCacheOps(timeoutMs);
58
56
  }
59
57
 
60
58
  /**
@@ -64,82 +62,50 @@ export class Entity implements IEntity {
64
62
  * background work has settled before the next file's saves run. Bounded
65
63
  * by `timeoutMs`. Safe to call repeatedly; no-op when the set is empty.
66
64
  */
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
- ]);
78
- }
79
-
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));
88
- }
89
-
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;
65
+ public static drainPendingSideEffects(timeoutMs: number = 5_000): Promise<void> {
66
+ return pendingOps.drainPendingSideEffects(timeoutMs);
94
67
  }
95
68
 
96
- public static Create(): Entity {
97
- return new Entity();
69
+ /**
70
+ * Track a fire-and-forget cache promise in the drainable set. Public so
71
+ * other framework read paths (e.g. Query.populateComponents cache
72
+ * warming) share the same drain semantics (H-CACHE-1).
73
+ */
74
+ public static trackCacheOp(p: Promise<void>): void {
75
+ pendingOps.trackCacheOp(p);
98
76
  }
99
77
 
100
- public static CreateWithId(id: string): Entity {
101
- return new Entity(id);
102
- }
78
+ // --- Component access (core/entity/componentAccess.ts) ---
103
79
 
104
- protected addComponent(component: BaseComponent): Entity {
105
- this.components.set(component.getTypeID(), component);
106
- return this;
80
+ /** @internal Promoted from protected for the core/entity/ submodule split (RFC §3.2). Query.ts / RequestLoaders.ts already cast to call this. */
81
+ public addComponent(component: BaseComponent): Entity {
82
+ return componentAccess.addComponent(this, component);
107
83
  }
108
84
 
109
85
  public componentList(): BaseComponent[] {
110
- return Array.from(this.components.values());
86
+ return componentAccess.componentList(this);
111
87
  }
112
88
 
113
89
  /**
114
90
  * Synchronously check if a component is already loaded in memory.
115
91
  * 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
92
  */
119
93
  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;
94
+ return componentAccess.getInMemory(this, ctor);
121
95
  }
122
96
 
123
97
  /**
124
98
  * 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
99
  */
128
100
  public hasInMemory<T extends BaseComponent>(ctor: new (...args: any[]) => T): boolean {
129
- return Array.from(this.components.values()).some(comp => comp instanceof ctor);
101
+ return componentAccess.hasInMemory(this, ctor);
130
102
  }
131
103
 
132
104
  /**
133
105
  * 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
106
  */
138
107
  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);
108
+ return componentAccess.wasRemoved(this, ctor);
143
109
  }
144
110
 
145
111
  /**
@@ -147,90 +113,15 @@ export class Entity implements IEntity {
147
113
  * Use like: entity.add(Component, { value: "Test" })
148
114
  */
149
115
  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
-
116
+ componentAccess.add(this, ctor, data);
169
117
  return this;
170
118
  }
171
119
 
172
120
  /**
173
121
  * 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
122
  */
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
- }
123
+ 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> {
124
+ await componentAccess.set(this, ctor, data, context);
234
125
  return this;
235
126
  }
236
127
 
@@ -238,733 +129,86 @@ export class Entity implements IEntity {
238
129
  * Removes a component from the entity.
239
130
  * Use like: entity.remove(Component)
240
131
  * 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
132
  */
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;
133
+ public remove<T extends BaseComponent>(ctor: new (...args: any[]) => T, context?: { loaders?: { componentsByEntityType?: any }; trx?: SQL; signal?: AbortSignal }): boolean {
134
+ return componentAccess.remove(this, ctor, context);
294
135
  }
295
136
 
296
137
  /**
297
138
  * 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
139
  */
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;
140
+ public get<T extends BaseComponent>(ctor: new (...args: any[]) => T, context?: { loaders?: { componentsByEntityType?: any }; trx?: SQL; signal?: AbortSignal }): Promise<ComponentDataType<T> | null> {
141
+ return componentAccess.get(this, ctor, context);
305
142
  }
306
143
 
307
144
  /**
308
145
  * Check if entity has a component (type guard).
309
146
  * 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
147
  */
323
148
  public has<T extends BaseComponent>(ctor: new (...args: any[]) => T): boolean {
324
- return this.hasInMemory(ctor);
149
+ return componentAccess.has(this, ctor);
325
150
  }
326
151
 
327
152
  /**
328
153
  * 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
154
  */
343
- public async getOrThrow<T extends BaseComponent>(
155
+ public getOrThrow<T extends BaseComponent>(
344
156
  ctor: new (...args: any[]) => T,
345
- context?: { loaders?: { componentsByEntityType?: any }; trx?: SQL }
157
+ context?: { loaders?: { componentsByEntityType?: any }; trx?: SQL; signal?: AbortSignal }
346
158
  ): 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;
159
+ return componentAccess.getOrThrow(this, ctor, context);
352
160
  }
353
161
 
354
162
  /**
355
163
  * Get component data synchronously if already loaded in memory.
356
164
  * 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
165
  */
373
166
  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;
167
+ return componentAccess.getCached(this, ctor);
376
168
  }
377
169
 
378
170
  /**
379
171
  * 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
172
  */
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);
173
+ public getInstanceOf<T extends BaseComponent>(ctor: new (...args: any[]) => T, context?: { loaders?: { componentsByEntityType?: any }; trx?: SQL; signal?: AbortSignal }): Promise<T | null> {
174
+ return componentAccess.getInstanceOf(this, ctor, context);
386
175
  }
387
176
 
388
177
  /**
389
178
  * Discard in-memory component state and re-hydrate from the database.
390
179
  * 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
180
+ * on the same instance.
396
181
  */
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);
182
+ public async reload(opts?: { trx?: SQL; signal?: AbortSignal }): Promise<this> {
183
+ await componentAccess.reload(this, opts);
435
184
  return this;
436
185
  }
437
186
 
438
187
  /**
439
188
  * 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
189
+ * componentList. No-op for components already loaded.
449
190
  */
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);
191
+ public requireComponents(ctors: Array<new (...args: any[]) => BaseComponent>): Promise<void> {
192
+ return componentAccess.requireComponents(this, ctors);
461
193
  }
462
194
 
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
- }
195
+ // --- Persistence (core/entity/saveEntity.ts) ---
530
196
 
531
197
  @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
- }
198
+ public save(trx?: SQL, context?: { loaders?: { componentsByEntityType?: any }; trx?: SQL; signal?: AbortSignal }): Promise<boolean> {
199
+ return saveEntity.saveEntity(this, trx, context);
607
200
  }
608
201
 
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;
202
+ public doSave(trx: SQL, signal?: AbortSignal): Promise<boolean> {
203
+ return saveEntity.doSave(this, trx, signal);
885
204
  }
886
205
 
887
206
  public delete(force: boolean = false) {
888
207
  return EntityManager.deleteEntity(this, force);
889
208
  }
890
209
 
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
- }
210
+ public doDelete(force: boolean = false): Promise<boolean> {
211
+ return saveEntity.doDelete(this, force);
968
212
  }
969
213
 
970
214
  public setPersisted(persisted: boolean) {
@@ -975,216 +219,45 @@ export class Entity implements IEntity {
975
219
  this._dirty = dirty;
976
220
  }
977
221
 
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
-
222
+ // --- Loaders / factories / (de)serialization (core/entity/finders.ts) ---
993
223
 
994
224
  @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());
225
+ public static LoadMultiple(ids: string[]): Promise<Entity[]> {
226
+ return finders.loadMultiple(ids);
1036
227
  }
1037
228
 
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
- }
229
+ public static LoadComponents(entities: Entity[], componentIds: string[], skipCache: boolean = false): Promise<void> {
230
+ return finders.loadComponents(entities, componentIds, skipCache);
1072
231
  }
1073
232
 
1074
233
  /**
1075
234
  * 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
235
  */
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;
236
+ public static FindById(id: string, trx?: SQL): Promise<Entity | null> {
237
+ return finders.findById(id, trx);
1091
238
  }
1092
239
 
1093
240
  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;
241
+ return finders.clone(entity);
1106
242
  }
1107
243
 
1108
244
  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;
245
+ return finders.makeRef(entity);
1119
246
  }
1120
247
 
1121
248
  /**
1122
249
  * Serialize the entity with only the currently loaded components
1123
- * @returns Object containing id and components data
1124
250
  */
1125
251
  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
- };
252
+ return finders.serialize(this);
1134
253
  }
1135
254
 
1136
255
  /**
1137
256
  * 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
257
  */
1142
258
  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;
259
+ return finders.deserialize(data);
1185
260
  }
1186
-
1187
-
1188
261
  }
1189
262
 
1190
- export default Entity;
263
+ export default Entity;