Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 | /** * State Reconstructor - ADR-007 Implementation * * Reconstructs aggregate state from event streams. * Implements event sourcing patterns for V3. * * @module v3/shared/events/state-reconstructor */ import { EventStore, type EventSnapshot } from './event-store.js'; import type { DomainEvent } from './domain-events.js'; /** * Aggregate root interface */ export interface AggregateRoot { id: string; version: number; apply(event: DomainEvent): void; getState(): Record<string, unknown>; } /** * Reconstructor options */ export interface ReconstructorOptions { useSnapshots: boolean; snapshotInterval: number; // Create snapshot every N events maxEventsToReplay: number; } /** * State Reconstructor * * Reconstructs aggregate state from event history. * Supports snapshots for performance optimization. */ export class StateReconstructor { private readonly options: ReconstructorOptions; constructor( private readonly eventStore: EventStore, options?: Partial<ReconstructorOptions> ) { this.options = { useSnapshots: true, snapshotInterval: 100, maxEventsToReplay: 10000, ...options, }; } /** * Reconstruct aggregate state from events */ async reconstruct<T extends AggregateRoot>( aggregateId: string, factory: (id: string) => T ): Promise<T> { const aggregate = factory(aggregateId); // Try to load from snapshot first if (this.options.useSnapshots) { const snapshot = await this.eventStore.getSnapshot(aggregateId); if (snapshot) { this.applySnapshot(aggregate, snapshot); } } // Get events after snapshot version (or all if no snapshot) const events = await this.eventStore.getEvents(aggregateId, aggregate.version + 1); // Apply events for (const event of events) { if (events.length > this.options.maxEventsToReplay) { throw new Error(`Too many events to replay (${events.length}). Consider creating a snapshot.`); } aggregate.apply(event); } // Create snapshot if interval reached if (this.options.useSnapshots && aggregate.version % this.options.snapshotInterval === 0) { await this.createSnapshot(aggregate); } return aggregate; } /** * Reconstruct state at a specific point in time */ async reconstructAtTime<T extends AggregateRoot>( aggregateId: string, factory: (id: string) => T, timestamp: Date ): Promise<T> { const aggregate = factory(aggregateId); // Get all events up to timestamp const allEvents = await this.eventStore.getEvents(aggregateId); const events = allEvents.filter((e) => e.timestamp <= timestamp.getTime()); // Apply events for (const event of events) { aggregate.apply(event); } return aggregate; } /** * Reconstruct state at a specific version */ async reconstructAtVersion<T extends AggregateRoot>( aggregateId: string, factory: (id: string) => T, targetVersion: number ): Promise<T> { const aggregate = factory(aggregateId); // Get events up to target version const events = await this.eventStore.getEvents(aggregateId); const limitedEvents = events.filter((e) => e.version <= targetVersion); // Apply events for (const event of limitedEvents) { aggregate.apply(event); } return aggregate; } /** * Apply snapshot to aggregate */ private applySnapshot(aggregate: AggregateRoot, snapshot: EventSnapshot): void { // Type assertion for aggregate that has restoreFromSnapshot const restorable = aggregate as AggregateRoot & { restoreFromSnapshot?(state: unknown): void; }; if (typeof restorable.restoreFromSnapshot === 'function') { restorable.restoreFromSnapshot(snapshot.state); } // Update version (aggregate as any).version = snapshot.version; } /** * Create snapshot for aggregate */ private async createSnapshot(aggregate: AggregateRoot): Promise<void> { const snapshot: EventSnapshot = { aggregateId: aggregate.id, aggregateType: this.getAggregateType(aggregate), version: aggregate.version, state: aggregate.getState(), timestamp: Date.now(), }; await this.eventStore.saveSnapshot(snapshot); } /** * Get aggregate type from instance */ private getAggregateType(aggregate: AggregateRoot): 'agent' | 'task' | 'memory' | 'swarm' { const typeName = aggregate.constructor.name.toLowerCase().replace('aggregate', ''); // Map to valid aggregate types if (typeName === 'agent' || typeName === 'task' || typeName === 'memory' || typeName === 'swarm') { return typeName; } return 'agent'; // Default fallback } } /** * Agent Aggregate - Example implementation */ export class AgentAggregate implements AggregateRoot { id: string; version = 0; private state = { name: '', role: '', status: 'idle' as string, currentTask: null as string | null, completedTasks: [] as string[], capabilities: [] as string[], createdAt: null as Date | null, lastActiveAt: null as Date | null, }; constructor(id: string) { this.id = id; } apply(event: DomainEvent): void { this.version = event.version; switch (event.type) { case 'agent:spawned': this.state.name = event.payload.name as string; this.state.role = event.payload.role as string; this.state.capabilities = (event.payload.capabilities as string[]) ?? []; this.state.status = 'idle'; this.state.createdAt = new Date(event.timestamp); break; case 'agent:started': this.state.status = 'active'; this.state.lastActiveAt = new Date(event.timestamp); break; case 'agent:task-assigned': this.state.currentTask = event.payload.taskId as string; this.state.status = 'busy'; this.state.lastActiveAt = new Date(event.timestamp); break; case 'agent:task-completed': this.state.completedTasks.push(event.payload.taskId as string); this.state.currentTask = null; this.state.status = 'active'; this.state.lastActiveAt = new Date(event.timestamp); break; case 'agent:terminated': this.state.status = 'terminated'; break; } } getState(): Record<string, unknown> { return { ...this.state }; } restoreFromSnapshot(snapshotState: unknown): void { const state = snapshotState as typeof this.state; this.state = { ...state, createdAt: state.createdAt ? new Date(state.createdAt) : null, lastActiveAt: state.lastActiveAt ? new Date(state.lastActiveAt) : null, }; } // Getters for type safety get name(): string { return this.state.name; } get role(): string { return this.state.role; } get status(): string { return this.state.status; } get currentTask(): string | null { return this.state.currentTask; } get completedTasks(): string[] { return [...this.state.completedTasks]; } get capabilities(): string[] { return [...this.state.capabilities]; } } /** * Task Aggregate - Example implementation */ export class TaskAggregate implements AggregateRoot { id: string; version = 0; private state = { title: '', description: '', type: '', priority: 'normal' as string, status: 'pending' as string, assignedAgent: null as string | null, result: null as unknown, createdAt: null as Date | null, startedAt: null as Date | null, completedAt: null as Date | null, }; constructor(id: string) { this.id = id; } apply(event: DomainEvent): void { this.version = event.version; switch (event.type) { case 'task:created': this.state.title = event.payload.title as string; this.state.description = event.payload.description as string; this.state.type = event.payload.taskType as string; this.state.priority = (event.payload.priority as string) ?? 'normal'; this.state.status = 'pending'; this.state.createdAt = new Date(event.timestamp); break; case 'task:started': this.state.assignedAgent = event.payload.agentId as string; this.state.status = 'running'; this.state.startedAt = new Date(event.timestamp); break; case 'task:completed': this.state.result = event.payload.result; this.state.status = 'completed'; this.state.completedAt = new Date(event.timestamp); break; case 'task:failed': this.state.status = 'failed'; this.state.completedAt = new Date(event.timestamp); break; case 'task:cancelled': this.state.status = 'cancelled'; this.state.completedAt = new Date(event.timestamp); break; } } getState(): Record<string, unknown> { return { ...this.state }; } restoreFromSnapshot(snapshotState: unknown): void { const state = snapshotState as typeof this.state; this.state = { ...state, createdAt: state.createdAt ? new Date(state.createdAt) : null, startedAt: state.startedAt ? new Date(state.startedAt) : null, completedAt: state.completedAt ? new Date(state.completedAt) : null, }; } // Getters get title(): string { return this.state.title; } get status(): string { return this.state.status; } get assignedAgent(): string | null { return this.state.assignedAgent; } get result(): unknown { return this.state.result; } } /** * Factory function */ export function createStateReconstructor( eventStore: EventStore, options?: Partial<ReconstructorOptions> ): StateReconstructor { return new StateReconstructor(eventStore, options); } |