@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,357 @@
1
+ /**
2
+ * Shard Manager for Horizontal Scaling
3
+ * Implements consistent hashing for data distribution across shards
4
+ */
5
+ import { createHash } from 'crypto';
6
+ import { EventEmitter } from 'events';
7
+ /**
8
+ * Consistent Hash Ring for shard distribution
9
+ */
10
+ class ConsistentHashRing {
11
+ constructor(virtualNodes = 150) {
12
+ this.ring = new Map();
13
+ this.sortedKeys = [];
14
+ this.virtualNodes = virtualNodes;
15
+ }
16
+ /**
17
+ * Add a node to the hash ring
18
+ */
19
+ addNode(nodeId) {
20
+ for (let i = 0; i < this.virtualNodes; i++) {
21
+ const virtualNodeId = `${nodeId}:${i}`;
22
+ const hash = this.hash(virtualNodeId);
23
+ this.ring.set(hash, nodeId);
24
+ }
25
+ this.updateSortedKeys();
26
+ }
27
+ /**
28
+ * Remove a node from the hash ring
29
+ */
30
+ removeNode(nodeId) {
31
+ const keysToRemove = [];
32
+ for (const [hash, node] of this.ring) {
33
+ if (node === nodeId) {
34
+ keysToRemove.push(hash);
35
+ }
36
+ }
37
+ for (const key of keysToRemove) {
38
+ this.ring.delete(key);
39
+ }
40
+ this.updateSortedKeys();
41
+ }
42
+ /**
43
+ * Get the node responsible for a given key
44
+ */
45
+ getNode(key) {
46
+ if (this.ring.size === 0)
47
+ return null;
48
+ const hash = this.hash(key);
49
+ // Find the first node with hash >= key hash
50
+ for (const nodeHash of this.sortedKeys) {
51
+ if (nodeHash >= hash) {
52
+ return this.ring.get(nodeHash) || null;
53
+ }
54
+ }
55
+ // Wrap around to the first node
56
+ return this.ring.get(this.sortedKeys[0]) || null;
57
+ }
58
+ /**
59
+ * Get N nodes for replication
60
+ */
61
+ getNodes(key, count) {
62
+ if (this.ring.size === 0)
63
+ return [];
64
+ const nodes = new Set();
65
+ const hash = this.hash(key);
66
+ // Start from the primary node position
67
+ let startIdx = 0;
68
+ for (let i = 0; i < this.sortedKeys.length; i++) {
69
+ if (this.sortedKeys[i] >= hash) {
70
+ startIdx = i;
71
+ break;
72
+ }
73
+ }
74
+ // Collect unique nodes
75
+ let idx = startIdx;
76
+ while (nodes.size < count && nodes.size < this.getUniqueNodeCount()) {
77
+ const nodeHash = this.sortedKeys[idx % this.sortedKeys.length];
78
+ const node = this.ring.get(nodeHash);
79
+ if (node) {
80
+ nodes.add(node);
81
+ }
82
+ idx++;
83
+ }
84
+ return Array.from(nodes);
85
+ }
86
+ /**
87
+ * Get unique node count
88
+ */
89
+ getUniqueNodeCount() {
90
+ return new Set(this.ring.values()).size;
91
+ }
92
+ /**
93
+ * Update sorted keys for efficient lookup
94
+ */
95
+ updateSortedKeys() {
96
+ this.sortedKeys = Array.from(this.ring.keys()).sort((a, b) => a - b);
97
+ }
98
+ /**
99
+ * Hash function for consistent hashing
100
+ */
101
+ hash(key) {
102
+ const hash = createHash('md5').update(key).digest();
103
+ return hash.readUInt32BE(0);
104
+ }
105
+ /**
106
+ * Get all nodes in the ring
107
+ */
108
+ getAllNodes() {
109
+ return Array.from(new Set(this.ring.values()));
110
+ }
111
+ }
112
+ /**
113
+ * Shard Manager for distributing data across multiple nodes
114
+ */
115
+ export class ShardManager extends EventEmitter {
116
+ constructor(config = {}) {
117
+ super();
118
+ this.shards = new Map();
119
+ this.nodeToShards = new Map();
120
+ this.shardCount = config.shardCount || 64;
121
+ this.replicationFactor = config.replicationFactor || 3;
122
+ this.autoRebalance = config.autoRebalance ?? true;
123
+ this.hashRing = new ConsistentHashRing(config.virtualNodes || 150);
124
+ // Initialize shards
125
+ this.initializeShards();
126
+ }
127
+ /**
128
+ * Initialize shard configuration
129
+ */
130
+ initializeShards() {
131
+ for (let i = 0; i < this.shardCount; i++) {
132
+ const shardId = `shard-${i.toString().padStart(3, '0')}`;
133
+ this.shards.set(shardId, {
134
+ id: shardId,
135
+ nodeId: '',
136
+ virtualNodes: [],
137
+ itemCount: 0,
138
+ sizeBytes: 0,
139
+ status: 'offline'
140
+ });
141
+ }
142
+ }
143
+ /**
144
+ * Add a node to the cluster
145
+ */
146
+ addNode(nodeId) {
147
+ this.hashRing.addNode(nodeId);
148
+ this.nodeToShards.set(nodeId, new Set());
149
+ // Assign shards to the new node
150
+ this.rebalanceShards();
151
+ this.emit('nodeAdded', { nodeId });
152
+ }
153
+ /**
154
+ * Remove a node from the cluster
155
+ */
156
+ removeNode(nodeId) {
157
+ const affectedShards = this.nodeToShards.get(nodeId) || new Set();
158
+ this.hashRing.removeNode(nodeId);
159
+ this.nodeToShards.delete(nodeId);
160
+ // Reassign affected shards
161
+ for (const shardId of affectedShards) {
162
+ const shard = this.shards.get(shardId);
163
+ if (shard) {
164
+ shard.status = 'rebalancing';
165
+ }
166
+ }
167
+ this.rebalanceShards();
168
+ this.emit('nodeRemoved', { nodeId, affectedShards: Array.from(affectedShards) });
169
+ }
170
+ /**
171
+ * Get shard assignment for a key
172
+ */
173
+ getShardForKey(key) {
174
+ const shardId = this.getShardId(key);
175
+ const nodes = this.hashRing.getNodes(shardId, this.replicationFactor);
176
+ if (nodes.length === 0)
177
+ return null;
178
+ return {
179
+ shardId,
180
+ nodeId: nodes[0],
181
+ replicas: nodes.slice(1)
182
+ };
183
+ }
184
+ /**
185
+ * Get nodes responsible for a shard
186
+ */
187
+ getNodesForShard(shardId) {
188
+ const shard = this.shards.get(shardId);
189
+ if (!shard)
190
+ return [];
191
+ // Return primary node and replicas
192
+ const nodes = this.hashRing.getNodes(shardId, this.replicationFactor);
193
+ return nodes;
194
+ }
195
+ /**
196
+ * Get total number of shards
197
+ */
198
+ getTotalShards() {
199
+ return this.shardCount;
200
+ }
201
+ /**
202
+ * Update shard assignment to a new node
203
+ */
204
+ updateShardAssignment(shardId, newNodeId) {
205
+ const shard = this.shards.get(shardId);
206
+ if (!shard) {
207
+ throw new Error(`Shard ${shardId} not found`);
208
+ }
209
+ // Remove from old node
210
+ if (shard.nodeId) {
211
+ const oldNodeShards = this.nodeToShards.get(shard.nodeId);
212
+ if (oldNodeShards) {
213
+ oldNodeShards.delete(shardId);
214
+ }
215
+ }
216
+ // Add to new node
217
+ shard.nodeId = newNodeId;
218
+ const newNodeShards = this.nodeToShards.get(newNodeId);
219
+ if (newNodeShards) {
220
+ newNodeShards.add(shardId);
221
+ }
222
+ else {
223
+ this.nodeToShards.set(newNodeId, new Set([shardId]));
224
+ }
225
+ this.emit('shardReassigned', { shardId, newNodeId });
226
+ }
227
+ /**
228
+ * Get shard ID for a key
229
+ */
230
+ getShardId(key) {
231
+ const hash = createHash('md5').update(key).digest();
232
+ const shardIndex = hash.readUInt16BE(0) % this.shardCount;
233
+ return `shard-${shardIndex.toString().padStart(3, '0')}`;
234
+ }
235
+ /**
236
+ * Rebalance shards across nodes
237
+ */
238
+ rebalanceShards() {
239
+ if (!this.autoRebalance)
240
+ return;
241
+ const nodes = this.hashRing.getAllNodes();
242
+ if (nodes.length === 0)
243
+ return;
244
+ // Clear current assignments
245
+ for (const nodeSet of this.nodeToShards.values()) {
246
+ nodeSet.clear();
247
+ }
248
+ // Reassign each shard
249
+ for (const [shardId, shard] of this.shards) {
250
+ const assignedNodes = this.hashRing.getNodes(shardId, 1);
251
+ if (assignedNodes.length > 0) {
252
+ shard.nodeId = assignedNodes[0];
253
+ shard.status = 'active';
254
+ const nodeShards = this.nodeToShards.get(assignedNodes[0]);
255
+ if (nodeShards) {
256
+ nodeShards.add(shardId);
257
+ }
258
+ }
259
+ else {
260
+ shard.status = 'offline';
261
+ }
262
+ }
263
+ this.emit('rebalanced', { nodes, shardCount: this.shardCount });
264
+ }
265
+ /**
266
+ * Get shard assignment for all shards
267
+ */
268
+ getShardAssignments() {
269
+ const assignments = [];
270
+ for (const [shardId, shard] of this.shards) {
271
+ if (shard.nodeId) {
272
+ assignments.push({
273
+ shardId,
274
+ nodeId: shard.nodeId,
275
+ replicas: this.hashRing.getNodes(shardId, this.replicationFactor).slice(1)
276
+ });
277
+ }
278
+ }
279
+ return assignments;
280
+ }
281
+ /**
282
+ * Get shard statistics
283
+ */
284
+ getShardStats() {
285
+ let activeShards = 0;
286
+ let rebalancingShards = 0;
287
+ let offlineShards = 0;
288
+ let totalItems = 0;
289
+ for (const shard of this.shards.values()) {
290
+ switch (shard.status) {
291
+ case 'active':
292
+ activeShards++;
293
+ break;
294
+ case 'rebalancing':
295
+ rebalancingShards++;
296
+ break;
297
+ case 'offline':
298
+ offlineShards++;
299
+ break;
300
+ }
301
+ totalItems += shard.itemCount;
302
+ }
303
+ return {
304
+ totalShards: this.shardCount,
305
+ activeShards,
306
+ rebalancingShards,
307
+ offlineShards,
308
+ averageItemsPerShard: this.shardCount > 0 ? Math.floor(totalItems / this.shardCount) : 0
309
+ };
310
+ }
311
+ /**
312
+ * Update shard metrics
313
+ */
314
+ updateShardMetrics(shardId, itemCount, sizeBytes) {
315
+ const shard = this.shards.get(shardId);
316
+ if (shard) {
317
+ shard.itemCount = itemCount;
318
+ shard.sizeBytes = sizeBytes;
319
+ }
320
+ }
321
+ /**
322
+ * Get replication nodes for a shard
323
+ */
324
+ getReplicationNodes(shardId) {
325
+ return this.hashRing.getNodes(shardId, this.replicationFactor);
326
+ }
327
+ /**
328
+ * Check if rebalancing is needed
329
+ */
330
+ needsRebalancing() {
331
+ const stats = this.getShardStats();
332
+ return stats.offlineShards > 0 || stats.rebalancingShards > 0;
333
+ }
334
+ /**
335
+ * Get cluster health
336
+ */
337
+ getHealth() {
338
+ const nodes = this.hashRing.getAllNodes();
339
+ const stats = this.getShardStats();
340
+ return {
341
+ healthy: stats.activeShards >= this.shardCount * 0.9, // 90% shards active
342
+ nodes: nodes.length,
343
+ shards: {
344
+ total: this.shardCount,
345
+ active: stats.activeShards,
346
+ inactive: stats.offlineShards + stats.rebalancingShards
347
+ }
348
+ };
349
+ }
350
+ }
351
+ /**
352
+ * Create a shard manager instance
353
+ */
354
+ export function createShardManager(config) {
355
+ return new ShardManager(config);
356
+ }
357
+ //# sourceMappingURL=shardManager.js.map
@@ -0,0 +1,110 @@
1
+ /**
2
+ * Shard Migration System for Brainy 3.0
3
+ *
4
+ * Handles zero-downtime migration of data between nodes
5
+ * Uses streaming for efficient transfer of large datasets
6
+ */
7
+ import { EventEmitter } from 'events';
8
+ import type { StorageAdapter } from '../coreTypes.js';
9
+ import type { ShardManager } from './shardManager.js';
10
+ import type { HTTPTransport } from './httpTransport.js';
11
+ import type { DistributedCoordinator } from './coordinator.js';
12
+ export interface MigrationTask {
13
+ id: string;
14
+ shardId: string;
15
+ sourceNode: string;
16
+ targetNode: string;
17
+ status: 'pending' | 'transferring' | 'validating' | 'switching' | 'completed' | 'failed';
18
+ progress: number;
19
+ itemsTransferred: number;
20
+ totalItems: number;
21
+ startTime: number;
22
+ endTime?: number;
23
+ error?: string;
24
+ }
25
+ export interface MigrationOptions {
26
+ batchSize?: number;
27
+ validateData?: boolean;
28
+ maxRetries?: number;
29
+ timeout?: number;
30
+ }
31
+ export declare class ShardMigrationManager extends EventEmitter {
32
+ private storage;
33
+ private shardManager;
34
+ private transport;
35
+ private coordinator;
36
+ private nodeId;
37
+ private activeMigrations;
38
+ private migrationQueue;
39
+ private maxConcurrentMigrations;
40
+ constructor(nodeId: string, storage: StorageAdapter, shardManager: ShardManager, transport: HTTPTransport, coordinator: DistributedCoordinator);
41
+ /**
42
+ * Initiate migration of a shard to a new node
43
+ */
44
+ migrateShard(shardId: string, targetNode: string, options?: MigrationOptions): Promise<MigrationTask>;
45
+ /**
46
+ * Process migration queue
47
+ */
48
+ private processMigrationQueue;
49
+ /**
50
+ * Execute a single migration task
51
+ */
52
+ private executeMigration;
53
+ /**
54
+ * Transfer data from source to target node
55
+ */
56
+ private transferData;
57
+ /**
58
+ * Get items from a shard
59
+ */
60
+ private getShardItems;
61
+ /**
62
+ * Get count of items in a shard
63
+ */
64
+ private getShardItemCount;
65
+ /**
66
+ * Validate transferred data
67
+ */
68
+ private validateData;
69
+ /**
70
+ * Switch shard ownership atomically
71
+ */
72
+ private switchOwnership;
73
+ /**
74
+ * Wait for consensus on migration
75
+ */
76
+ private waitForConsensus;
77
+ /**
78
+ * Cleanup local shard data after migration
79
+ */
80
+ private cleanupShardData;
81
+ /**
82
+ * Handle incoming migration batch (when we're the target)
83
+ */
84
+ receiveMigrationBatch(data: {
85
+ migrationId: string;
86
+ shardId: string;
87
+ items: any[];
88
+ offset: number;
89
+ total: number;
90
+ }): Promise<void>;
91
+ /**
92
+ * Validate received migration data
93
+ */
94
+ validateMigration(data: {
95
+ migrationId: string;
96
+ shardId: string;
97
+ expectedCount: number;
98
+ }): Promise<{
99
+ valid: boolean;
100
+ error?: string;
101
+ }>;
102
+ /**
103
+ * Get status of all active migrations
104
+ */
105
+ getActiveMigrations(): MigrationTask[];
106
+ /**
107
+ * Cancel a migration
108
+ */
109
+ cancelMigration(migrationId: string): Promise<void>;
110
+ }