@soulcraft/brainy 3.0.0 → 3.1.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 (270) hide show
  1. package/CHANGELOG.md +53 -3
  2. package/README.md +427 -111
  3. package/bin/brainy.js +340 -62
  4. package/dist/api/ConfigAPI.d.ts +67 -0
  5. package/dist/api/ConfigAPI.js +166 -0
  6. package/dist/api/DataAPI.d.ts +123 -0
  7. package/dist/api/DataAPI.js +391 -0
  8. package/dist/api/SecurityAPI.d.ts +50 -0
  9. package/dist/api/SecurityAPI.js +139 -0
  10. package/dist/api/UniversalImportAPI.d.ts +134 -0
  11. package/dist/api/UniversalImportAPI.js +615 -0
  12. package/dist/augmentationManager.js +12 -7
  13. package/dist/augmentationPipeline.d.ts +0 -61
  14. package/dist/augmentationPipeline.js +0 -87
  15. package/dist/augmentationRegistry.d.ts +1 -1
  16. package/dist/augmentationRegistry.js +1 -1
  17. package/dist/augmentations/apiServerAugmentation.d.ts +27 -1
  18. package/dist/augmentations/apiServerAugmentation.js +290 -9
  19. package/dist/augmentations/auditLogAugmentation.d.ts +109 -0
  20. package/dist/augmentations/auditLogAugmentation.js +358 -0
  21. package/dist/augmentations/batchProcessingAugmentation.d.ts +3 -2
  22. package/dist/augmentations/batchProcessingAugmentation.js +123 -22
  23. package/dist/augmentations/brainyAugmentation.d.ts +142 -8
  24. package/dist/augmentations/brainyAugmentation.js +179 -2
  25. package/dist/augmentations/cacheAugmentation.d.ts +8 -5
  26. package/dist/augmentations/cacheAugmentation.js +116 -17
  27. package/dist/augmentations/conduitAugmentations.d.ts +2 -2
  28. package/dist/augmentations/conduitAugmentations.js +2 -2
  29. package/dist/augmentations/configResolver.d.ts +122 -0
  30. package/dist/augmentations/configResolver.js +440 -0
  31. package/dist/augmentations/connectionPoolAugmentation.d.ts +3 -1
  32. package/dist/augmentations/connectionPoolAugmentation.js +37 -12
  33. package/dist/augmentations/defaultAugmentations.d.ts +14 -10
  34. package/dist/augmentations/defaultAugmentations.js +16 -11
  35. package/dist/augmentations/discovery/catalogDiscovery.d.ts +142 -0
  36. package/dist/augmentations/discovery/catalogDiscovery.js +249 -0
  37. package/dist/augmentations/discovery/localDiscovery.d.ts +84 -0
  38. package/dist/augmentations/discovery/localDiscovery.js +246 -0
  39. package/dist/augmentations/discovery/runtimeLoader.d.ts +97 -0
  40. package/dist/augmentations/discovery/runtimeLoader.js +337 -0
  41. package/dist/augmentations/discovery.d.ts +152 -0
  42. package/dist/augmentations/discovery.js +441 -0
  43. package/dist/augmentations/display/cache.d.ts +130 -0
  44. package/dist/augmentations/display/cache.js +319 -0
  45. package/dist/augmentations/display/fieldPatterns.d.ts +52 -0
  46. package/dist/augmentations/display/fieldPatterns.js +393 -0
  47. package/dist/augmentations/display/iconMappings.d.ts +57 -0
  48. package/dist/augmentations/display/iconMappings.js +68 -0
  49. package/dist/augmentations/display/intelligentComputation.d.ts +109 -0
  50. package/dist/augmentations/display/intelligentComputation.js +462 -0
  51. package/dist/augmentations/display/types.d.ts +203 -0
  52. package/dist/augmentations/display/types.js +7 -0
  53. package/dist/augmentations/entityRegistryAugmentation.d.ts +3 -1
  54. package/dist/augmentations/entityRegistryAugmentation.js +5 -1
  55. package/dist/augmentations/indexAugmentation.d.ts +5 -3
  56. package/dist/augmentations/indexAugmentation.js +5 -2
  57. package/dist/augmentations/intelligentVerbScoringAugmentation.d.ts +24 -7
  58. package/dist/augmentations/intelligentVerbScoringAugmentation.js +111 -27
  59. package/dist/augmentations/manifest.d.ts +176 -0
  60. package/dist/augmentations/manifest.js +8 -0
  61. package/dist/augmentations/marketplace/AugmentationMarketplace.d.ts +168 -0
  62. package/dist/augmentations/marketplace/AugmentationMarketplace.js +329 -0
  63. package/dist/augmentations/marketplace/cli.d.ts +47 -0
  64. package/dist/augmentations/marketplace/cli.js +265 -0
  65. package/dist/augmentations/metricsAugmentation.d.ts +3 -3
  66. package/dist/augmentations/metricsAugmentation.js +2 -2
  67. package/dist/augmentations/monitoringAugmentation.d.ts +3 -3
  68. package/dist/augmentations/monitoringAugmentation.js +2 -2
  69. package/dist/augmentations/neuralImport.d.ts +1 -1
  70. package/dist/augmentations/neuralImport.js +4 -4
  71. package/dist/augmentations/rateLimitAugmentation.d.ts +82 -0
  72. package/dist/augmentations/rateLimitAugmentation.js +321 -0
  73. package/dist/augmentations/requestDeduplicatorAugmentation.d.ts +2 -2
  74. package/dist/augmentations/requestDeduplicatorAugmentation.js +1 -1
  75. package/dist/augmentations/storageAugmentation.d.ts +1 -1
  76. package/dist/augmentations/storageAugmentation.js +2 -2
  77. package/dist/augmentations/storageAugmentations.d.ts +37 -8
  78. package/dist/augmentations/storageAugmentations.js +204 -15
  79. package/dist/augmentations/synapseAugmentation.d.ts +1 -1
  80. package/dist/augmentations/synapseAugmentation.js +35 -16
  81. package/dist/augmentations/typeMatching/brainyTypes.d.ts +83 -0
  82. package/dist/augmentations/typeMatching/brainyTypes.js +425 -0
  83. package/dist/augmentations/typeMatching/intelligentTypeMatcher.d.ts +39 -59
  84. package/dist/augmentations/typeMatching/intelligentTypeMatcher.js +103 -389
  85. package/dist/augmentations/universalDisplayAugmentation.d.ts +191 -0
  86. package/dist/augmentations/universalDisplayAugmentation.js +371 -0
  87. package/dist/brainy-unified.d.ts +106 -0
  88. package/dist/brainy-unified.js +327 -0
  89. package/dist/brainy.d.ts +277 -0
  90. package/dist/brainy.js +1241 -0
  91. package/dist/brainyData.d.ts +56 -111
  92. package/dist/brainyData.js +912 -756
  93. package/dist/brainyDataV3.d.ts +186 -0
  94. package/dist/brainyDataV3.js +337 -0
  95. package/dist/config/distributedPresets-new.d.ts +118 -0
  96. package/dist/config/distributedPresets-new.js +318 -0
  97. package/dist/config/distributedPresets.d.ts +118 -0
  98. package/dist/config/distributedPresets.js +318 -0
  99. package/dist/config/extensibleConfig.d.ts +99 -0
  100. package/dist/config/extensibleConfig.js +268 -0
  101. package/dist/config/index.d.ts +17 -0
  102. package/dist/config/index.js +35 -0
  103. package/dist/config/modelAutoConfig.d.ts +32 -0
  104. package/dist/config/modelAutoConfig.js +139 -0
  105. package/dist/config/modelPrecisionManager.d.ts +42 -0
  106. package/dist/config/modelPrecisionManager.js +98 -0
  107. package/dist/config/sharedConfigManager.d.ts +67 -0
  108. package/dist/config/sharedConfigManager.js +215 -0
  109. package/dist/config/storageAutoConfig.d.ts +41 -0
  110. package/dist/config/storageAutoConfig.js +328 -0
  111. package/dist/config/zeroConfig.d.ts +68 -0
  112. package/dist/config/zeroConfig.js +301 -0
  113. package/dist/cortex/backupRestore.d.ts +2 -2
  114. package/dist/cortex/backupRestore.js +85 -27
  115. package/dist/cortex/healthCheck.d.ts +2 -2
  116. package/dist/cortex/neuralImport.d.ts +2 -2
  117. package/dist/cortex/neuralImport.js +18 -13
  118. package/dist/cortex/performanceMonitor.d.ts +2 -2
  119. package/dist/critical/model-guardian.d.ts +4 -0
  120. package/dist/critical/model-guardian.js +31 -11
  121. package/dist/demo.d.ts +4 -4
  122. package/dist/demo.js +7 -7
  123. package/dist/distributed/cacheSync.d.ts +112 -0
  124. package/dist/distributed/cacheSync.js +265 -0
  125. package/dist/distributed/coordinator.d.ts +193 -0
  126. package/dist/distributed/coordinator.js +548 -0
  127. package/dist/distributed/httpTransport.d.ts +120 -0
  128. package/dist/distributed/httpTransport.js +446 -0
  129. package/dist/distributed/index.d.ts +8 -0
  130. package/dist/distributed/index.js +5 -0
  131. package/dist/distributed/networkTransport.d.ts +132 -0
  132. package/dist/distributed/networkTransport.js +633 -0
  133. package/dist/distributed/queryPlanner.d.ts +104 -0
  134. package/dist/distributed/queryPlanner.js +327 -0
  135. package/dist/distributed/readWriteSeparation.d.ts +134 -0
  136. package/dist/distributed/readWriteSeparation.js +350 -0
  137. package/dist/distributed/shardManager.d.ts +114 -0
  138. package/dist/distributed/shardManager.js +357 -0
  139. package/dist/distributed/shardMigration.d.ts +110 -0
  140. package/dist/distributed/shardMigration.js +289 -0
  141. package/dist/distributed/storageDiscovery.d.ts +160 -0
  142. package/dist/distributed/storageDiscovery.js +551 -0
  143. package/dist/embeddings/CachedEmbeddings.d.ts +40 -0
  144. package/dist/embeddings/CachedEmbeddings.js +146 -0
  145. package/dist/embeddings/EmbeddingManager.d.ts +102 -0
  146. package/dist/embeddings/EmbeddingManager.js +291 -0
  147. package/dist/embeddings/SingletonModelManager.d.ts +95 -0
  148. package/dist/embeddings/SingletonModelManager.js +220 -0
  149. package/dist/embeddings/index.d.ts +12 -0
  150. package/dist/embeddings/index.js +16 -0
  151. package/dist/embeddings/lightweight-embedder.d.ts +0 -1
  152. package/dist/embeddings/lightweight-embedder.js +4 -12
  153. package/dist/embeddings/model-manager.d.ts +11 -0
  154. package/dist/embeddings/model-manager.js +43 -7
  155. package/dist/embeddings/universal-memory-manager.d.ts +1 -1
  156. package/dist/embeddings/universal-memory-manager.js +27 -67
  157. package/dist/embeddings/worker-embedding.js +4 -8
  158. package/dist/errors/brainyError.d.ts +5 -1
  159. package/dist/errors/brainyError.js +12 -0
  160. package/dist/examples/basicUsage.js +7 -4
  161. package/dist/graph/graphAdjacencyIndex.d.ts +96 -0
  162. package/dist/graph/graphAdjacencyIndex.js +288 -0
  163. package/dist/graph/pathfinding.js +4 -2
  164. package/dist/hnsw/scaledHNSWSystem.js +11 -2
  165. package/dist/importManager.js +8 -5
  166. package/dist/index.d.ts +17 -22
  167. package/dist/index.js +37 -23
  168. package/dist/mcp/brainyMCPAdapter.d.ts +4 -4
  169. package/dist/mcp/brainyMCPAdapter.js +5 -5
  170. package/dist/mcp/brainyMCPService.d.ts +3 -3
  171. package/dist/mcp/brainyMCPService.js +3 -11
  172. package/dist/mcp/mcpAugmentationToolset.js +20 -30
  173. package/dist/neural/embeddedPatterns.d.ts +1 -1
  174. package/dist/neural/embeddedPatterns.js +2 -2
  175. package/dist/neural/entityExtractor.d.ts +65 -0
  176. package/dist/neural/entityExtractor.js +316 -0
  177. package/dist/neural/improvedNeuralAPI.d.ts +357 -0
  178. package/dist/neural/improvedNeuralAPI.js +2628 -0
  179. package/dist/neural/naturalLanguageProcessor.d.ts +155 -10
  180. package/dist/neural/naturalLanguageProcessor.js +941 -66
  181. package/dist/neural/naturalLanguageProcessorStatic.d.ts +2 -2
  182. package/dist/neural/naturalLanguageProcessorStatic.js +3 -3
  183. package/dist/neural/neuralAPI.js +8 -2
  184. package/dist/neural/patternLibrary.d.ts +57 -3
  185. package/dist/neural/patternLibrary.js +348 -13
  186. package/dist/neural/staticPatternMatcher.d.ts +2 -2
  187. package/dist/neural/staticPatternMatcher.js +2 -2
  188. package/dist/neural/types.d.ts +287 -0
  189. package/dist/neural/types.js +24 -0
  190. package/dist/shared/default-augmentations.d.ts +3 -3
  191. package/dist/shared/default-augmentations.js +5 -5
  192. package/dist/storage/adapters/baseStorageAdapter.d.ts +42 -0
  193. package/dist/storage/adapters/fileSystemStorage.d.ts +26 -2
  194. package/dist/storage/adapters/fileSystemStorage.js +218 -15
  195. package/dist/storage/adapters/memoryStorage.d.ts +4 -4
  196. package/dist/storage/adapters/memoryStorage.js +17 -12
  197. package/dist/storage/adapters/opfsStorage.d.ts +2 -2
  198. package/dist/storage/adapters/opfsStorage.js +2 -2
  199. package/dist/storage/adapters/s3CompatibleStorage.d.ts +2 -2
  200. package/dist/storage/adapters/s3CompatibleStorage.js +2 -2
  201. package/dist/storage/backwardCompatibility.d.ts +10 -78
  202. package/dist/storage/backwardCompatibility.js +17 -132
  203. package/dist/storage/baseStorage.d.ts +18 -2
  204. package/dist/storage/baseStorage.js +74 -3
  205. package/dist/storage/cacheManager.js +2 -2
  206. package/dist/storage/readOnlyOptimizations.js +8 -3
  207. package/dist/streaming/pipeline.d.ts +154 -0
  208. package/dist/streaming/pipeline.js +551 -0
  209. package/dist/triple/TripleIntelligence.d.ts +25 -110
  210. package/dist/triple/TripleIntelligence.js +4 -574
  211. package/dist/triple/TripleIntelligenceSystem.d.ts +159 -0
  212. package/dist/triple/TripleIntelligenceSystem.js +519 -0
  213. package/dist/types/apiTypes.d.ts +278 -0
  214. package/dist/types/apiTypes.js +33 -0
  215. package/dist/types/brainy.types.d.ts +308 -0
  216. package/dist/types/brainy.types.js +8 -0
  217. package/dist/types/brainyDataInterface.d.ts +5 -8
  218. package/dist/types/brainyDataInterface.js +2 -2
  219. package/dist/types/graphTypes.js +2 -2
  220. package/dist/universal/crypto.d.ts +11 -1
  221. package/dist/universal/crypto.js +24 -93
  222. package/dist/universal/events.d.ts +3 -2
  223. package/dist/universal/events.js +6 -75
  224. package/dist/universal/fs.d.ts +2 -3
  225. package/dist/universal/fs.js +5 -211
  226. package/dist/universal/path.d.ts +3 -2
  227. package/dist/universal/path.js +22 -78
  228. package/dist/universal/uuid.d.ts +1 -1
  229. package/dist/universal/uuid.js +1 -1
  230. package/dist/utils/brainyTypes.d.ts +217 -0
  231. package/dist/utils/brainyTypes.js +261 -0
  232. package/dist/utils/cacheAutoConfig.d.ts +3 -3
  233. package/dist/utils/embedding.d.ts +9 -4
  234. package/dist/utils/embedding.js +89 -26
  235. package/dist/utils/enhancedLogger.d.ts +104 -0
  236. package/dist/utils/enhancedLogger.js +232 -0
  237. package/dist/utils/hybridModelManager.d.ts +19 -28
  238. package/dist/utils/hybridModelManager.js +36 -200
  239. package/dist/utils/index.d.ts +1 -1
  240. package/dist/utils/index.js +1 -1
  241. package/dist/utils/intelligentTypeMapper.d.ts +60 -0
  242. package/dist/utils/intelligentTypeMapper.js +349 -0
  243. package/dist/utils/metadataIndex.d.ts +118 -1
  244. package/dist/utils/metadataIndex.js +539 -16
  245. package/dist/utils/nodeVersionCheck.d.ts +24 -0
  246. package/dist/utils/nodeVersionCheck.js +65 -0
  247. package/dist/utils/paramValidation.d.ts +39 -0
  248. package/dist/utils/paramValidation.js +192 -0
  249. package/dist/utils/rateLimiter.d.ts +160 -0
  250. package/dist/utils/rateLimiter.js +271 -0
  251. package/dist/utils/statistics.d.ts +4 -4
  252. package/dist/utils/statistics.js +3 -3
  253. package/dist/utils/structuredLogger.d.ts +146 -0
  254. package/dist/utils/structuredLogger.js +394 -0
  255. package/dist/utils/textEncoding.js +2 -1
  256. package/dist/utils/typeValidation.d.ts +59 -0
  257. package/dist/utils/typeValidation.js +374 -0
  258. package/dist/utils/version.js +19 -3
  259. package/package.json +15 -17
  260. package/scripts/download-models.cjs +94 -20
  261. package/dist/augmentations/walAugmentation.d.ts +0 -109
  262. package/dist/augmentations/walAugmentation.js +0 -516
  263. package/dist/browserFramework.d.ts +0 -15
  264. package/dist/browserFramework.js +0 -31
  265. package/dist/browserFramework.minimal.d.ts +0 -14
  266. package/dist/browserFramework.minimal.js +0 -31
  267. package/dist/chat/BrainyChat.d.ts +0 -121
  268. package/dist/chat/BrainyChat.js +0 -396
  269. package/dist/chat/ChatCLI.d.ts +0 -61
  270. package/dist/chat/ChatCLI.js +0 -351
@@ -0,0 +1,350 @@
1
+ /**
2
+ * Read/Write Separation for Distributed Scaling
3
+ * Implements primary-replica architecture for scalable reads
4
+ */
5
+ import { EventEmitter } from 'events';
6
+ /**
7
+ * Read/Write Separation Manager
8
+ */
9
+ export class ReadWriteSeparation extends EventEmitter {
10
+ constructor(config, coordinator, _shardManager, cacheSync) {
11
+ super();
12
+ this.replicas = new Map();
13
+ this.isRunning = false;
14
+ this.config = config;
15
+ this.nodeId = config.nodeId;
16
+ this.role = config.role === 'auto' ? this.determineRole() : (config.role || 'replica');
17
+ this.coordinator = coordinator;
18
+ this.cacheSync = cacheSync;
19
+ this.replicationLog = {
20
+ operations: [],
21
+ lastSequence: 0,
22
+ primaryVersion: 0
23
+ };
24
+ // Setup connections based on role
25
+ this.setupConnections();
26
+ }
27
+ /**
28
+ * Start read/write separation
29
+ */
30
+ async start() {
31
+ if (this.isRunning)
32
+ return;
33
+ this.isRunning = true;
34
+ // Start components
35
+ await this.coordinator.start();
36
+ // Setup role-specific behavior
37
+ if (this.role === 'primary') {
38
+ this.startAsPrimary();
39
+ }
40
+ else {
41
+ this.startAsReplica();
42
+ }
43
+ this.emit('started', { nodeId: this.nodeId, role: this.role });
44
+ }
45
+ /**
46
+ * Stop read/write separation
47
+ */
48
+ async stop() {
49
+ if (!this.isRunning)
50
+ return;
51
+ this.isRunning = false;
52
+ if (this.syncTimer) {
53
+ clearInterval(this.syncTimer);
54
+ this.syncTimer = undefined;
55
+ }
56
+ await this.coordinator.stop();
57
+ this.emit('stopped', { nodeId: this.nodeId });
58
+ }
59
+ /**
60
+ * Execute a write operation (primary only)
61
+ */
62
+ async write(operation) {
63
+ if (this.role !== 'primary') {
64
+ // Forward to primary
65
+ if (this.primaryConnection) {
66
+ return this.primaryConnection.forwardWrite(operation);
67
+ }
68
+ throw new Error('Cannot write: not connected to primary');
69
+ }
70
+ // Generate operation metadata
71
+ const writeOp = {
72
+ id: this.generateOperationId(),
73
+ ...operation,
74
+ timestamp: Date.now(),
75
+ version: ++this.replicationLog.primaryVersion
76
+ };
77
+ // Add to replication log
78
+ this.replicationLog.operations.push(writeOp);
79
+ this.replicationLog.lastSequence++;
80
+ // Propagate to replicas
81
+ this.propagateToReplicas(writeOp);
82
+ // Update cache
83
+ if (operation.type !== 'delete') {
84
+ this.cacheSync.set(writeOp.id, operation.data);
85
+ }
86
+ else {
87
+ this.cacheSync.delete(writeOp.id);
88
+ }
89
+ this.emit('write', writeOp);
90
+ return writeOp.id;
91
+ }
92
+ /**
93
+ * Execute a read operation
94
+ */
95
+ async read(key, options) {
96
+ const consistency = options?.consistency || this.config.consistencyLevel || 'eventual';
97
+ if (consistency === 'strong' && this.role === 'replica') {
98
+ // For strong consistency, read from primary
99
+ if (this.primaryConnection) {
100
+ return this.primaryConnection.read(key);
101
+ }
102
+ throw new Error('Cannot guarantee strong consistency: not connected to primary');
103
+ }
104
+ // Check cache first
105
+ const cached = this.cacheSync.get(key);
106
+ if (cached !== undefined) {
107
+ return cached;
108
+ }
109
+ // Read from appropriate source based on preference
110
+ if (this.config.readPreference === 'primary' && this.primaryConnection) {
111
+ return this.primaryConnection.read(key);
112
+ }
113
+ // Read locally (replica or primary)
114
+ return this.readLocal(key);
115
+ }
116
+ /**
117
+ * Get replication lag (replica only)
118
+ */
119
+ getReplicationLag() {
120
+ if (this.role === 'primary')
121
+ return 0;
122
+ if (this.primaryConnection) {
123
+ return Date.now() - this.primaryConnection.lastSync;
124
+ }
125
+ return -1; // Unknown
126
+ }
127
+ /**
128
+ * Setup connections based on role
129
+ */
130
+ setupConnections() {
131
+ if (this.role === 'primary') {
132
+ // Setup replica connections
133
+ if (this.config.replicaUrls) {
134
+ for (const url of this.config.replicaUrls) {
135
+ const replica = new ReplicaConnection(url);
136
+ this.replicas.set(url, replica);
137
+ }
138
+ }
139
+ }
140
+ else {
141
+ // Setup primary connection
142
+ if (this.config.primaryUrl) {
143
+ this.primaryConnection = new PrimaryConnection(this.config.primaryUrl);
144
+ }
145
+ }
146
+ }
147
+ /**
148
+ * Start as primary node
149
+ */
150
+ startAsPrimary() {
151
+ // Start accepting writes
152
+ this.emit('roleEstablished', { role: 'primary' });
153
+ // Start replication timer
154
+ this.syncTimer = setInterval(() => {
155
+ this.syncReplicas();
156
+ }, this.config.syncInterval || 1000);
157
+ }
158
+ /**
159
+ * Start as replica node
160
+ */
161
+ startAsReplica() {
162
+ // Start syncing from primary
163
+ this.emit('roleEstablished', { role: 'replica' });
164
+ // Start sync timer
165
+ this.syncTimer = setInterval(() => {
166
+ this.syncFromPrimary();
167
+ }, this.config.syncInterval || 1000);
168
+ }
169
+ /**
170
+ * Sync replicas (primary only)
171
+ */
172
+ async syncReplicas() {
173
+ const batch = this.replicationLog.operations.slice(-100); // Last 100 ops
174
+ for (const [url, replica] of this.replicas) {
175
+ try {
176
+ await replica.sync(batch, this.replicationLog.primaryVersion);
177
+ }
178
+ catch (error) {
179
+ this.emit('replicaSyncError', { url, error });
180
+ }
181
+ }
182
+ }
183
+ /**
184
+ * Sync from primary (replica only)
185
+ */
186
+ async syncFromPrimary() {
187
+ if (!this.primaryConnection)
188
+ return;
189
+ try {
190
+ const updates = await this.primaryConnection.getUpdates(this.replicationLog.lastSequence);
191
+ // Apply updates
192
+ for (const op of updates) {
193
+ await this.applyOperation(op);
194
+ }
195
+ this.emit('synced', { operations: updates.length });
196
+ }
197
+ catch (error) {
198
+ this.emit('primarySyncError', { error });
199
+ }
200
+ }
201
+ /**
202
+ * Apply a replicated operation
203
+ */
204
+ async applyOperation(op) {
205
+ // Update local state
206
+ this.replicationLog.operations.push(op);
207
+ this.replicationLog.lastSequence = Math.max(this.replicationLog.lastSequence, op.version);
208
+ // Update cache
209
+ switch (op.type) {
210
+ case 'add':
211
+ case 'update':
212
+ this.cacheSync.set(op.id, op.data);
213
+ break;
214
+ case 'delete':
215
+ this.cacheSync.delete(op.id);
216
+ break;
217
+ }
218
+ this.emit('operationApplied', op);
219
+ }
220
+ /**
221
+ * Propagate operation to replicas
222
+ */
223
+ propagateToReplicas(op) {
224
+ for (const replica of this.replicas.values()) {
225
+ replica.sendOperation(op).catch(error => {
226
+ this.emit('replicationError', { replica, error });
227
+ });
228
+ }
229
+ }
230
+ /**
231
+ * Determine role automatically
232
+ */
233
+ determineRole() {
234
+ // Use coordinator's leader election
235
+ return this.coordinator.isLeader() ? 'primary' : 'replica';
236
+ }
237
+ /**
238
+ * Read from local storage
239
+ */
240
+ async readLocal(key) {
241
+ // This would connect to actual storage
242
+ // For now, return from cache or undefined
243
+ return this.cacheSync.get(key);
244
+ }
245
+ /**
246
+ * Generate unique operation ID
247
+ */
248
+ generateOperationId() {
249
+ return `${this.nodeId}-${Date.now()}-${Math.random().toString(36).substring(2, 11)}`;
250
+ }
251
+ /**
252
+ * Get replication statistics
253
+ */
254
+ getStats() {
255
+ return {
256
+ role: this.role,
257
+ replicas: this.replicas.size,
258
+ replicationLag: this.getReplicationLag(),
259
+ operationsInLog: this.replicationLog.operations.length,
260
+ primaryVersion: this.replicationLog.primaryVersion
261
+ };
262
+ }
263
+ /**
264
+ * Check if node can accept writes
265
+ */
266
+ canWrite() {
267
+ return this.role === 'primary';
268
+ }
269
+ /**
270
+ * Check if node can serve reads
271
+ */
272
+ canRead() {
273
+ if (this.config.consistencyLevel === 'strong') {
274
+ return this.role === 'primary' || this.primaryConnection !== undefined;
275
+ }
276
+ return true;
277
+ }
278
+ /**
279
+ * Set whether this node is primary (for leader election integration)
280
+ */
281
+ setPrimary(isPrimary) {
282
+ const newRole = isPrimary ? 'primary' : 'replica';
283
+ if (this.role !== newRole) {
284
+ this.role = newRole;
285
+ this.emit('roleChange', { oldRole: this.role, newRole });
286
+ if (isPrimary) {
287
+ // Became primary - stop syncing from old primary
288
+ this.primaryConnection = undefined;
289
+ }
290
+ else {
291
+ // Became replica - connect to new primary if URL is known
292
+ if (this.config.primaryUrl) {
293
+ this.primaryConnection = new PrimaryConnection(this.config.primaryUrl);
294
+ }
295
+ }
296
+ }
297
+ }
298
+ }
299
+ /**
300
+ * Connection to a replica (used by primary)
301
+ */
302
+ class ReplicaConnection {
303
+ constructor(url) {
304
+ this.url = url;
305
+ // Store URL for connection
306
+ void this.url;
307
+ }
308
+ async sync(_operations, _version) {
309
+ // In real implementation, this would use HTTP/gRPC to this.url
310
+ // For now, simulate network call
311
+ await new Promise(resolve => setTimeout(resolve, 10));
312
+ }
313
+ async sendOperation(_op) {
314
+ // Send single operation to replica at this.url
315
+ await new Promise(resolve => setTimeout(resolve, 5));
316
+ }
317
+ }
318
+ /**
319
+ * Connection to primary (used by replicas)
320
+ */
321
+ class PrimaryConnection {
322
+ constructor(url) {
323
+ this.url = url;
324
+ this.lastSync = Date.now();
325
+ // Store URL for connection
326
+ void this.url;
327
+ }
328
+ async getUpdates(_fromSequence) {
329
+ // In real implementation, fetch from primary at this.url
330
+ this.lastSync = Date.now();
331
+ return [];
332
+ }
333
+ async forwardWrite(_operation) {
334
+ // Forward write to primary at this.url
335
+ await new Promise(resolve => setTimeout(resolve, 20));
336
+ return `forwarded-${Date.now()}`;
337
+ }
338
+ async read(_key) {
339
+ // Read from primary at this.url for strong consistency
340
+ await new Promise(resolve => setTimeout(resolve, 10));
341
+ return undefined;
342
+ }
343
+ }
344
+ /**
345
+ * Create read/write separation manager
346
+ */
347
+ export function createReadWriteSeparation(config, coordinator, shardManager, cacheSync) {
348
+ return new ReadWriteSeparation(config, coordinator, shardManager, cacheSync);
349
+ }
350
+ //# sourceMappingURL=readWriteSeparation.js.map
@@ -0,0 +1,114 @@
1
+ /**
2
+ * Shard Manager for Horizontal Scaling
3
+ * Implements consistent hashing for data distribution across shards
4
+ */
5
+ import { EventEmitter } from 'events';
6
+ export interface ShardConfig {
7
+ shardCount?: number;
8
+ replicationFactor?: number;
9
+ virtualNodes?: number;
10
+ autoRebalance?: boolean;
11
+ }
12
+ export interface Shard {
13
+ id: string;
14
+ nodeId: string;
15
+ virtualNodes: string[];
16
+ itemCount: number;
17
+ sizeBytes: number;
18
+ status: 'active' | 'rebalancing' | 'offline';
19
+ }
20
+ export interface ShardAssignment {
21
+ shardId: string;
22
+ nodeId: string;
23
+ replicas: string[];
24
+ }
25
+ /**
26
+ * Shard Manager for distributing data across multiple nodes
27
+ */
28
+ export declare class ShardManager extends EventEmitter {
29
+ private hashRing;
30
+ private shards;
31
+ private nodeToShards;
32
+ private shardCount;
33
+ private replicationFactor;
34
+ private autoRebalance;
35
+ constructor(config?: ShardConfig);
36
+ /**
37
+ * Initialize shard configuration
38
+ */
39
+ private initializeShards;
40
+ /**
41
+ * Add a node to the cluster
42
+ */
43
+ addNode(nodeId: string): void;
44
+ /**
45
+ * Remove a node from the cluster
46
+ */
47
+ removeNode(nodeId: string): void;
48
+ /**
49
+ * Get shard assignment for a key
50
+ */
51
+ getShardForKey(key: string): ShardAssignment | null;
52
+ /**
53
+ * Get nodes responsible for a shard
54
+ */
55
+ getNodesForShard(shardId: string): string[];
56
+ /**
57
+ * Get total number of shards
58
+ */
59
+ getTotalShards(): number;
60
+ /**
61
+ * Update shard assignment to a new node
62
+ */
63
+ updateShardAssignment(shardId: string, newNodeId: string): void;
64
+ /**
65
+ * Get shard ID for a key
66
+ */
67
+ private getShardId;
68
+ /**
69
+ * Rebalance shards across nodes
70
+ */
71
+ private rebalanceShards;
72
+ /**
73
+ * Get shard assignment for all shards
74
+ */
75
+ getShardAssignments(): ShardAssignment[];
76
+ /**
77
+ * Get shard statistics
78
+ */
79
+ getShardStats(): {
80
+ totalShards: number;
81
+ activeShards: number;
82
+ rebalancingShards: number;
83
+ offlineShards: number;
84
+ averageItemsPerShard: number;
85
+ };
86
+ /**
87
+ * Update shard metrics
88
+ */
89
+ updateShardMetrics(shardId: string, itemCount: number, sizeBytes: number): void;
90
+ /**
91
+ * Get replication nodes for a shard
92
+ */
93
+ getReplicationNodes(shardId: string): string[];
94
+ /**
95
+ * Check if rebalancing is needed
96
+ */
97
+ needsRebalancing(): boolean;
98
+ /**
99
+ * Get cluster health
100
+ */
101
+ getHealth(): {
102
+ healthy: boolean;
103
+ nodes: number;
104
+ shards: {
105
+ total: number;
106
+ active: number;
107
+ inactive: number;
108
+ };
109
+ };
110
+ }
111
+ /**
112
+ * Create a shard manager instance
113
+ */
114
+ export declare function createShardManager(config?: ShardConfig): ShardManager;