@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.
- package/CHANGELOG.md +53 -3
- package/README.md +427 -111
- package/bin/brainy.js +340 -62
- package/dist/api/ConfigAPI.d.ts +67 -0
- package/dist/api/ConfigAPI.js +166 -0
- package/dist/api/DataAPI.d.ts +123 -0
- package/dist/api/DataAPI.js +391 -0
- package/dist/api/SecurityAPI.d.ts +50 -0
- package/dist/api/SecurityAPI.js +139 -0
- package/dist/api/UniversalImportAPI.d.ts +134 -0
- package/dist/api/UniversalImportAPI.js +615 -0
- package/dist/augmentationManager.js +12 -7
- package/dist/augmentationPipeline.d.ts +0 -61
- package/dist/augmentationPipeline.js +0 -87
- package/dist/augmentationRegistry.d.ts +1 -1
- package/dist/augmentationRegistry.js +1 -1
- package/dist/augmentations/apiServerAugmentation.d.ts +27 -1
- package/dist/augmentations/apiServerAugmentation.js +290 -9
- package/dist/augmentations/auditLogAugmentation.d.ts +109 -0
- package/dist/augmentations/auditLogAugmentation.js +358 -0
- package/dist/augmentations/batchProcessingAugmentation.d.ts +3 -2
- package/dist/augmentations/batchProcessingAugmentation.js +123 -22
- package/dist/augmentations/brainyAugmentation.d.ts +142 -8
- package/dist/augmentations/brainyAugmentation.js +179 -2
- package/dist/augmentations/cacheAugmentation.d.ts +8 -5
- package/dist/augmentations/cacheAugmentation.js +116 -17
- package/dist/augmentations/conduitAugmentations.d.ts +2 -2
- package/dist/augmentations/conduitAugmentations.js +2 -2
- package/dist/augmentations/configResolver.d.ts +122 -0
- package/dist/augmentations/configResolver.js +440 -0
- package/dist/augmentations/connectionPoolAugmentation.d.ts +3 -1
- package/dist/augmentations/connectionPoolAugmentation.js +37 -12
- package/dist/augmentations/defaultAugmentations.d.ts +14 -10
- package/dist/augmentations/defaultAugmentations.js +16 -11
- package/dist/augmentations/discovery/catalogDiscovery.d.ts +142 -0
- package/dist/augmentations/discovery/catalogDiscovery.js +249 -0
- package/dist/augmentations/discovery/localDiscovery.d.ts +84 -0
- package/dist/augmentations/discovery/localDiscovery.js +246 -0
- package/dist/augmentations/discovery/runtimeLoader.d.ts +97 -0
- package/dist/augmentations/discovery/runtimeLoader.js +337 -0
- package/dist/augmentations/discovery.d.ts +152 -0
- package/dist/augmentations/discovery.js +441 -0
- package/dist/augmentations/display/cache.d.ts +130 -0
- package/dist/augmentations/display/cache.js +319 -0
- package/dist/augmentations/display/fieldPatterns.d.ts +52 -0
- package/dist/augmentations/display/fieldPatterns.js +393 -0
- package/dist/augmentations/display/iconMappings.d.ts +57 -0
- package/dist/augmentations/display/iconMappings.js +68 -0
- package/dist/augmentations/display/intelligentComputation.d.ts +109 -0
- package/dist/augmentations/display/intelligentComputation.js +462 -0
- package/dist/augmentations/display/types.d.ts +203 -0
- package/dist/augmentations/display/types.js +7 -0
- package/dist/augmentations/entityRegistryAugmentation.d.ts +3 -1
- package/dist/augmentations/entityRegistryAugmentation.js +5 -1
- package/dist/augmentations/indexAugmentation.d.ts +5 -3
- package/dist/augmentations/indexAugmentation.js +5 -2
- package/dist/augmentations/intelligentVerbScoringAugmentation.d.ts +24 -7
- package/dist/augmentations/intelligentVerbScoringAugmentation.js +111 -27
- package/dist/augmentations/manifest.d.ts +176 -0
- package/dist/augmentations/manifest.js +8 -0
- package/dist/augmentations/marketplace/AugmentationMarketplace.d.ts +168 -0
- package/dist/augmentations/marketplace/AugmentationMarketplace.js +329 -0
- package/dist/augmentations/marketplace/cli.d.ts +47 -0
- package/dist/augmentations/marketplace/cli.js +265 -0
- package/dist/augmentations/metricsAugmentation.d.ts +3 -3
- package/dist/augmentations/metricsAugmentation.js +2 -2
- package/dist/augmentations/monitoringAugmentation.d.ts +3 -3
- package/dist/augmentations/monitoringAugmentation.js +2 -2
- package/dist/augmentations/neuralImport.d.ts +1 -1
- package/dist/augmentations/neuralImport.js +4 -4
- package/dist/augmentations/rateLimitAugmentation.d.ts +82 -0
- package/dist/augmentations/rateLimitAugmentation.js +321 -0
- package/dist/augmentations/requestDeduplicatorAugmentation.d.ts +2 -2
- package/dist/augmentations/requestDeduplicatorAugmentation.js +1 -1
- package/dist/augmentations/storageAugmentation.d.ts +1 -1
- package/dist/augmentations/storageAugmentation.js +2 -2
- package/dist/augmentations/storageAugmentations.d.ts +37 -8
- package/dist/augmentations/storageAugmentations.js +204 -15
- package/dist/augmentations/synapseAugmentation.d.ts +1 -1
- package/dist/augmentations/synapseAugmentation.js +35 -16
- package/dist/augmentations/typeMatching/brainyTypes.d.ts +83 -0
- package/dist/augmentations/typeMatching/brainyTypes.js +425 -0
- package/dist/augmentations/typeMatching/intelligentTypeMatcher.d.ts +39 -59
- package/dist/augmentations/typeMatching/intelligentTypeMatcher.js +103 -389
- package/dist/augmentations/universalDisplayAugmentation.d.ts +191 -0
- package/dist/augmentations/universalDisplayAugmentation.js +371 -0
- package/dist/brainy-unified.d.ts +106 -0
- package/dist/brainy-unified.js +327 -0
- package/dist/brainy.d.ts +277 -0
- package/dist/brainy.js +1241 -0
- package/dist/brainyData.d.ts +56 -111
- package/dist/brainyData.js +912 -756
- package/dist/brainyDataV3.d.ts +186 -0
- package/dist/brainyDataV3.js +337 -0
- package/dist/config/distributedPresets-new.d.ts +118 -0
- package/dist/config/distributedPresets-new.js +318 -0
- package/dist/config/distributedPresets.d.ts +118 -0
- package/dist/config/distributedPresets.js +318 -0
- package/dist/config/extensibleConfig.d.ts +99 -0
- package/dist/config/extensibleConfig.js +268 -0
- package/dist/config/index.d.ts +17 -0
- package/dist/config/index.js +35 -0
- package/dist/config/modelAutoConfig.d.ts +32 -0
- package/dist/config/modelAutoConfig.js +139 -0
- package/dist/config/modelPrecisionManager.d.ts +42 -0
- package/dist/config/modelPrecisionManager.js +98 -0
- package/dist/config/sharedConfigManager.d.ts +67 -0
- package/dist/config/sharedConfigManager.js +215 -0
- package/dist/config/storageAutoConfig.d.ts +41 -0
- package/dist/config/storageAutoConfig.js +328 -0
- package/dist/config/zeroConfig.d.ts +68 -0
- package/dist/config/zeroConfig.js +301 -0
- package/dist/cortex/backupRestore.d.ts +2 -2
- package/dist/cortex/backupRestore.js +85 -27
- package/dist/cortex/healthCheck.d.ts +2 -2
- package/dist/cortex/neuralImport.d.ts +2 -2
- package/dist/cortex/neuralImport.js +18 -13
- package/dist/cortex/performanceMonitor.d.ts +2 -2
- package/dist/critical/model-guardian.d.ts +4 -0
- package/dist/critical/model-guardian.js +31 -11
- package/dist/demo.d.ts +4 -4
- package/dist/demo.js +7 -7
- package/dist/distributed/cacheSync.d.ts +112 -0
- package/dist/distributed/cacheSync.js +265 -0
- package/dist/distributed/coordinator.d.ts +193 -0
- package/dist/distributed/coordinator.js +548 -0
- package/dist/distributed/httpTransport.d.ts +120 -0
- package/dist/distributed/httpTransport.js +446 -0
- package/dist/distributed/index.d.ts +8 -0
- package/dist/distributed/index.js +5 -0
- package/dist/distributed/networkTransport.d.ts +132 -0
- package/dist/distributed/networkTransport.js +633 -0
- package/dist/distributed/queryPlanner.d.ts +104 -0
- package/dist/distributed/queryPlanner.js +327 -0
- package/dist/distributed/readWriteSeparation.d.ts +134 -0
- package/dist/distributed/readWriteSeparation.js +350 -0
- package/dist/distributed/shardManager.d.ts +114 -0
- package/dist/distributed/shardManager.js +357 -0
- package/dist/distributed/shardMigration.d.ts +110 -0
- package/dist/distributed/shardMigration.js +289 -0
- package/dist/distributed/storageDiscovery.d.ts +160 -0
- package/dist/distributed/storageDiscovery.js +551 -0
- package/dist/embeddings/CachedEmbeddings.d.ts +40 -0
- package/dist/embeddings/CachedEmbeddings.js +146 -0
- package/dist/embeddings/EmbeddingManager.d.ts +102 -0
- package/dist/embeddings/EmbeddingManager.js +291 -0
- package/dist/embeddings/SingletonModelManager.d.ts +95 -0
- package/dist/embeddings/SingletonModelManager.js +220 -0
- package/dist/embeddings/index.d.ts +12 -0
- package/dist/embeddings/index.js +16 -0
- package/dist/embeddings/lightweight-embedder.d.ts +0 -1
- package/dist/embeddings/lightweight-embedder.js +4 -12
- package/dist/embeddings/model-manager.d.ts +11 -0
- package/dist/embeddings/model-manager.js +43 -7
- package/dist/embeddings/universal-memory-manager.d.ts +1 -1
- package/dist/embeddings/universal-memory-manager.js +27 -67
- package/dist/embeddings/worker-embedding.js +4 -8
- package/dist/errors/brainyError.d.ts +5 -1
- package/dist/errors/brainyError.js +12 -0
- package/dist/examples/basicUsage.js +7 -4
- package/dist/graph/graphAdjacencyIndex.d.ts +96 -0
- package/dist/graph/graphAdjacencyIndex.js +288 -0
- package/dist/graph/pathfinding.js +4 -2
- package/dist/hnsw/scaledHNSWSystem.js +11 -2
- package/dist/importManager.js +8 -5
- package/dist/index.d.ts +17 -22
- package/dist/index.js +37 -23
- package/dist/mcp/brainyMCPAdapter.d.ts +4 -4
- package/dist/mcp/brainyMCPAdapter.js +5 -5
- package/dist/mcp/brainyMCPService.d.ts +3 -3
- package/dist/mcp/brainyMCPService.js +3 -11
- package/dist/mcp/mcpAugmentationToolset.js +20 -30
- package/dist/neural/embeddedPatterns.d.ts +1 -1
- package/dist/neural/embeddedPatterns.js +2 -2
- package/dist/neural/entityExtractor.d.ts +65 -0
- package/dist/neural/entityExtractor.js +316 -0
- package/dist/neural/improvedNeuralAPI.d.ts +357 -0
- package/dist/neural/improvedNeuralAPI.js +2628 -0
- package/dist/neural/naturalLanguageProcessor.d.ts +155 -10
- package/dist/neural/naturalLanguageProcessor.js +941 -66
- package/dist/neural/naturalLanguageProcessorStatic.d.ts +2 -2
- package/dist/neural/naturalLanguageProcessorStatic.js +3 -3
- package/dist/neural/neuralAPI.js +8 -2
- package/dist/neural/patternLibrary.d.ts +57 -3
- package/dist/neural/patternLibrary.js +348 -13
- package/dist/neural/staticPatternMatcher.d.ts +2 -2
- package/dist/neural/staticPatternMatcher.js +2 -2
- package/dist/neural/types.d.ts +287 -0
- package/dist/neural/types.js +24 -0
- package/dist/shared/default-augmentations.d.ts +3 -3
- package/dist/shared/default-augmentations.js +5 -5
- package/dist/storage/adapters/baseStorageAdapter.d.ts +42 -0
- package/dist/storage/adapters/fileSystemStorage.d.ts +26 -2
- package/dist/storage/adapters/fileSystemStorage.js +218 -15
- package/dist/storage/adapters/memoryStorage.d.ts +4 -4
- package/dist/storage/adapters/memoryStorage.js +17 -12
- package/dist/storage/adapters/opfsStorage.d.ts +2 -2
- package/dist/storage/adapters/opfsStorage.js +2 -2
- package/dist/storage/adapters/s3CompatibleStorage.d.ts +2 -2
- package/dist/storage/adapters/s3CompatibleStorage.js +2 -2
- package/dist/storage/backwardCompatibility.d.ts +10 -78
- package/dist/storage/backwardCompatibility.js +17 -132
- package/dist/storage/baseStorage.d.ts +18 -2
- package/dist/storage/baseStorage.js +74 -3
- package/dist/storage/cacheManager.js +2 -2
- package/dist/storage/readOnlyOptimizations.js +8 -3
- package/dist/streaming/pipeline.d.ts +154 -0
- package/dist/streaming/pipeline.js +551 -0
- package/dist/triple/TripleIntelligence.d.ts +25 -110
- package/dist/triple/TripleIntelligence.js +4 -574
- package/dist/triple/TripleIntelligenceSystem.d.ts +159 -0
- package/dist/triple/TripleIntelligenceSystem.js +519 -0
- package/dist/types/apiTypes.d.ts +278 -0
- package/dist/types/apiTypes.js +33 -0
- package/dist/types/brainy.types.d.ts +308 -0
- package/dist/types/brainy.types.js +8 -0
- package/dist/types/brainyDataInterface.d.ts +5 -8
- package/dist/types/brainyDataInterface.js +2 -2
- package/dist/types/graphTypes.js +2 -2
- package/dist/universal/crypto.d.ts +11 -1
- package/dist/universal/crypto.js +24 -93
- package/dist/universal/events.d.ts +3 -2
- package/dist/universal/events.js +6 -75
- package/dist/universal/fs.d.ts +2 -3
- package/dist/universal/fs.js +5 -211
- package/dist/universal/path.d.ts +3 -2
- package/dist/universal/path.js +22 -78
- package/dist/universal/uuid.d.ts +1 -1
- package/dist/universal/uuid.js +1 -1
- package/dist/utils/brainyTypes.d.ts +217 -0
- package/dist/utils/brainyTypes.js +261 -0
- package/dist/utils/cacheAutoConfig.d.ts +3 -3
- package/dist/utils/embedding.d.ts +9 -4
- package/dist/utils/embedding.js +89 -26
- package/dist/utils/enhancedLogger.d.ts +104 -0
- package/dist/utils/enhancedLogger.js +232 -0
- package/dist/utils/hybridModelManager.d.ts +19 -28
- package/dist/utils/hybridModelManager.js +36 -200
- package/dist/utils/index.d.ts +1 -1
- package/dist/utils/index.js +1 -1
- package/dist/utils/intelligentTypeMapper.d.ts +60 -0
- package/dist/utils/intelligentTypeMapper.js +349 -0
- package/dist/utils/metadataIndex.d.ts +118 -1
- package/dist/utils/metadataIndex.js +539 -16
- package/dist/utils/nodeVersionCheck.d.ts +24 -0
- package/dist/utils/nodeVersionCheck.js +65 -0
- package/dist/utils/paramValidation.d.ts +39 -0
- package/dist/utils/paramValidation.js +192 -0
- package/dist/utils/rateLimiter.d.ts +160 -0
- package/dist/utils/rateLimiter.js +271 -0
- package/dist/utils/statistics.d.ts +4 -4
- package/dist/utils/statistics.js +3 -3
- package/dist/utils/structuredLogger.d.ts +146 -0
- package/dist/utils/structuredLogger.js +394 -0
- package/dist/utils/textEncoding.js +2 -1
- package/dist/utils/typeValidation.d.ts +59 -0
- package/dist/utils/typeValidation.js +374 -0
- package/dist/utils/version.js +19 -3
- package/package.json +15 -17
- package/scripts/download-models.cjs +94 -20
- package/dist/augmentations/walAugmentation.d.ts +0 -109
- package/dist/augmentations/walAugmentation.js +0 -516
- package/dist/browserFramework.d.ts +0 -15
- package/dist/browserFramework.js +0 -31
- package/dist/browserFramework.minimal.d.ts +0 -14
- package/dist/browserFramework.minimal.js +0 -31
- package/dist/chat/BrainyChat.d.ts +0 -121
- package/dist/chat/BrainyChat.js +0 -396
- package/dist/chat/ChatCLI.d.ts +0 -61
- package/dist/chat/ChatCLI.js +0 -351
|
@@ -0,0 +1,289 @@
|
|
|
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
|
+
export class ShardMigrationManager extends EventEmitter {
|
|
9
|
+
constructor(nodeId, storage, shardManager, transport, coordinator) {
|
|
10
|
+
super();
|
|
11
|
+
this.activeMigrations = new Map();
|
|
12
|
+
this.migrationQueue = [];
|
|
13
|
+
this.maxConcurrentMigrations = 2;
|
|
14
|
+
this.nodeId = nodeId;
|
|
15
|
+
this.storage = storage;
|
|
16
|
+
this.shardManager = shardManager;
|
|
17
|
+
this.transport = transport;
|
|
18
|
+
this.coordinator = coordinator;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Initiate migration of a shard to a new node
|
|
22
|
+
*/
|
|
23
|
+
async migrateShard(shardId, targetNode, options = {}) {
|
|
24
|
+
const task = {
|
|
25
|
+
id: `migration-${Date.now()}-${Math.random().toString(36).substring(7)}`,
|
|
26
|
+
shardId,
|
|
27
|
+
sourceNode: this.nodeId,
|
|
28
|
+
targetNode,
|
|
29
|
+
status: 'pending',
|
|
30
|
+
progress: 0,
|
|
31
|
+
itemsTransferred: 0,
|
|
32
|
+
totalItems: 0,
|
|
33
|
+
startTime: Date.now()
|
|
34
|
+
};
|
|
35
|
+
// Add to queue
|
|
36
|
+
this.migrationQueue.push(task);
|
|
37
|
+
this.processMigrationQueue();
|
|
38
|
+
return task;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Process migration queue
|
|
42
|
+
*/
|
|
43
|
+
async processMigrationQueue() {
|
|
44
|
+
while (this.migrationQueue.length > 0 &&
|
|
45
|
+
this.activeMigrations.size < this.maxConcurrentMigrations) {
|
|
46
|
+
const task = this.migrationQueue.shift();
|
|
47
|
+
this.activeMigrations.set(task.id, task);
|
|
48
|
+
// Execute migration in background
|
|
49
|
+
this.executeMigration(task).catch(error => {
|
|
50
|
+
console.error(`Migration ${task.id} failed:`, error);
|
|
51
|
+
task.status = 'failed';
|
|
52
|
+
task.error = error.message;
|
|
53
|
+
this.emit('migrationFailed', task);
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Execute a single migration task
|
|
59
|
+
*/
|
|
60
|
+
async executeMigration(task) {
|
|
61
|
+
try {
|
|
62
|
+
this.emit('migrationStarted', task);
|
|
63
|
+
// Phase 1: Start transferring data
|
|
64
|
+
task.status = 'transferring';
|
|
65
|
+
await this.transferData(task);
|
|
66
|
+
// Phase 2: Validate transferred data
|
|
67
|
+
task.status = 'validating';
|
|
68
|
+
await this.validateData(task);
|
|
69
|
+
// Phase 3: Switch ownership atomically
|
|
70
|
+
task.status = 'switching';
|
|
71
|
+
await this.switchOwnership(task);
|
|
72
|
+
// Phase 4: Cleanup source
|
|
73
|
+
task.status = 'completed';
|
|
74
|
+
task.endTime = Date.now();
|
|
75
|
+
task.progress = 100;
|
|
76
|
+
this.activeMigrations.delete(task.id);
|
|
77
|
+
this.emit('migrationCompleted', task);
|
|
78
|
+
// Process next in queue
|
|
79
|
+
this.processMigrationQueue();
|
|
80
|
+
}
|
|
81
|
+
catch (error) {
|
|
82
|
+
task.status = 'failed';
|
|
83
|
+
task.error = error.message;
|
|
84
|
+
this.activeMigrations.delete(task.id);
|
|
85
|
+
throw error;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Transfer data from source to target node
|
|
90
|
+
*/
|
|
91
|
+
async transferData(task) {
|
|
92
|
+
const batchSize = 1000;
|
|
93
|
+
let offset = 0;
|
|
94
|
+
// Get total count
|
|
95
|
+
const totalItems = await this.getShardItemCount(task.shardId);
|
|
96
|
+
task.totalItems = totalItems;
|
|
97
|
+
while (offset < totalItems) {
|
|
98
|
+
// Get batch of items
|
|
99
|
+
const items = await this.getShardItems(task.shardId, offset, batchSize);
|
|
100
|
+
if (items.length === 0)
|
|
101
|
+
break;
|
|
102
|
+
// Send batch to target node
|
|
103
|
+
await this.transport.call(task.targetNode, 'receiveMigrationBatch', {
|
|
104
|
+
migrationId: task.id,
|
|
105
|
+
shardId: task.shardId,
|
|
106
|
+
items,
|
|
107
|
+
offset,
|
|
108
|
+
total: totalItems
|
|
109
|
+
});
|
|
110
|
+
offset += items.length;
|
|
111
|
+
task.itemsTransferred = offset;
|
|
112
|
+
task.progress = Math.floor((offset / totalItems) * 80); // 80% for transfer
|
|
113
|
+
this.emit('migrationProgress', task);
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* Get items from a shard
|
|
118
|
+
*/
|
|
119
|
+
async getShardItems(shardId, offset, limit) {
|
|
120
|
+
// Get all noun IDs for this shard
|
|
121
|
+
const nounKey = `shard:${shardId}:nouns`;
|
|
122
|
+
const verbKey = `shard:${shardId}:verbs`;
|
|
123
|
+
const items = [];
|
|
124
|
+
try {
|
|
125
|
+
// Get nouns
|
|
126
|
+
const nouns = await this.storage.getNounsByNounType('*');
|
|
127
|
+
const shardNouns = nouns.filter(n => {
|
|
128
|
+
const assignment = this.shardManager.getShardForKey(n.id);
|
|
129
|
+
return assignment?.shardId === shardId;
|
|
130
|
+
}).slice(offset, offset + limit);
|
|
131
|
+
items.push(...shardNouns.map(n => ({ type: 'noun', data: n })));
|
|
132
|
+
// Get verbs if we have room
|
|
133
|
+
if (items.length < limit) {
|
|
134
|
+
const verbs = await this.storage.getVerbsByType('*');
|
|
135
|
+
const shardVerbs = verbs.filter(v => {
|
|
136
|
+
const assignment = this.shardManager.getShardForKey(v.id);
|
|
137
|
+
return assignment?.shardId === shardId;
|
|
138
|
+
}).slice(0, limit - items.length);
|
|
139
|
+
items.push(...shardVerbs.map(v => ({ type: 'verb', data: v })));
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
catch (error) {
|
|
143
|
+
console.error(`Failed to get shard items for ${shardId}:`, error);
|
|
144
|
+
}
|
|
145
|
+
return items;
|
|
146
|
+
}
|
|
147
|
+
/**
|
|
148
|
+
* Get count of items in a shard
|
|
149
|
+
*/
|
|
150
|
+
async getShardItemCount(shardId) {
|
|
151
|
+
// For now, estimate based on total items / shard count
|
|
152
|
+
// In production, maintain accurate per-shard counts
|
|
153
|
+
const status = await this.storage.getStorageStatus();
|
|
154
|
+
const totalShards = this.shardManager.getTotalShards();
|
|
155
|
+
return Math.ceil(status.used / totalShards);
|
|
156
|
+
}
|
|
157
|
+
/**
|
|
158
|
+
* Validate transferred data
|
|
159
|
+
*/
|
|
160
|
+
async validateData(task) {
|
|
161
|
+
// Request validation from target node
|
|
162
|
+
const response = await this.transport.call(task.targetNode, 'validateMigration', {
|
|
163
|
+
migrationId: task.id,
|
|
164
|
+
shardId: task.shardId,
|
|
165
|
+
expectedCount: task.totalItems
|
|
166
|
+
});
|
|
167
|
+
if (!response.valid) {
|
|
168
|
+
throw new Error(`Validation failed: ${response.error}`);
|
|
169
|
+
}
|
|
170
|
+
task.progress = 90; // 90% after validation
|
|
171
|
+
this.emit('migrationProgress', task);
|
|
172
|
+
}
|
|
173
|
+
/**
|
|
174
|
+
* Switch shard ownership atomically
|
|
175
|
+
*/
|
|
176
|
+
async switchOwnership(task) {
|
|
177
|
+
// Coordinate with all nodes to update shard assignment
|
|
178
|
+
await this.coordinator.proposeMigration({
|
|
179
|
+
shardId: task.shardId,
|
|
180
|
+
fromNode: task.sourceNode,
|
|
181
|
+
toNode: task.targetNode,
|
|
182
|
+
migrationId: task.id
|
|
183
|
+
});
|
|
184
|
+
// Wait for consensus
|
|
185
|
+
await this.waitForConsensus(task.id);
|
|
186
|
+
// Update local shard manager
|
|
187
|
+
this.shardManager.updateShardAssignment(task.shardId, task.targetNode);
|
|
188
|
+
task.progress = 95; // 95% after ownership switch
|
|
189
|
+
this.emit('migrationProgress', task);
|
|
190
|
+
// Cleanup local data
|
|
191
|
+
await this.cleanupShardData(task.shardId);
|
|
192
|
+
}
|
|
193
|
+
/**
|
|
194
|
+
* Wait for consensus on migration
|
|
195
|
+
*/
|
|
196
|
+
async waitForConsensus(migrationId) {
|
|
197
|
+
const maxWait = 30000; // 30 seconds
|
|
198
|
+
const startTime = Date.now();
|
|
199
|
+
while (Date.now() - startTime < maxWait) {
|
|
200
|
+
const status = await this.coordinator.getMigrationStatus(migrationId);
|
|
201
|
+
if (status === 'committed') {
|
|
202
|
+
return;
|
|
203
|
+
}
|
|
204
|
+
else if (status === 'rejected') {
|
|
205
|
+
throw new Error('Migration rejected by cluster');
|
|
206
|
+
}
|
|
207
|
+
// Wait a bit before checking again
|
|
208
|
+
await new Promise(resolve => setTimeout(resolve, 1000));
|
|
209
|
+
}
|
|
210
|
+
throw new Error('Consensus timeout');
|
|
211
|
+
}
|
|
212
|
+
/**
|
|
213
|
+
* Cleanup local shard data after migration
|
|
214
|
+
*/
|
|
215
|
+
async cleanupShardData(shardId) {
|
|
216
|
+
// Mark shard data for deletion
|
|
217
|
+
// Don't delete immediately in case of rollback
|
|
218
|
+
const cleanupKey = `cleanup:${shardId}:${Date.now()}`;
|
|
219
|
+
await this.storage.saveMetadata(cleanupKey, {
|
|
220
|
+
shardId,
|
|
221
|
+
scheduledFor: Date.now() + 3600000 // Delete after 1 hour
|
|
222
|
+
});
|
|
223
|
+
}
|
|
224
|
+
/**
|
|
225
|
+
* Handle incoming migration batch (when we're the target)
|
|
226
|
+
*/
|
|
227
|
+
async receiveMigrationBatch(data) {
|
|
228
|
+
// Store items
|
|
229
|
+
for (const item of data.items) {
|
|
230
|
+
if (item.type === 'noun') {
|
|
231
|
+
await this.storage.saveNoun(item.data);
|
|
232
|
+
}
|
|
233
|
+
else if (item.type === 'verb') {
|
|
234
|
+
await this.storage.saveVerb(item.data);
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
// Track progress
|
|
238
|
+
const progress = {
|
|
239
|
+
migrationId: data.migrationId,
|
|
240
|
+
shardId: data.shardId,
|
|
241
|
+
received: data.offset + data.items.length,
|
|
242
|
+
total: data.total
|
|
243
|
+
};
|
|
244
|
+
await this.storage.saveMetadata(`migration:${data.migrationId}:progress`, progress);
|
|
245
|
+
}
|
|
246
|
+
/**
|
|
247
|
+
* Validate received migration data
|
|
248
|
+
*/
|
|
249
|
+
async validateMigration(data) {
|
|
250
|
+
// Check if we received all expected items
|
|
251
|
+
const progressKey = `migration:${data.migrationId}:progress`;
|
|
252
|
+
const progress = await this.storage.getMetadata(progressKey);
|
|
253
|
+
if (!progress) {
|
|
254
|
+
return { valid: false, error: 'No migration progress found' };
|
|
255
|
+
}
|
|
256
|
+
if (progress.received !== data.expectedCount) {
|
|
257
|
+
return {
|
|
258
|
+
valid: false,
|
|
259
|
+
error: `Expected ${data.expectedCount} items, received ${progress.received}`
|
|
260
|
+
};
|
|
261
|
+
}
|
|
262
|
+
// Verify data integrity (could add checksums)
|
|
263
|
+
return { valid: true };
|
|
264
|
+
}
|
|
265
|
+
/**
|
|
266
|
+
* Get status of all active migrations
|
|
267
|
+
*/
|
|
268
|
+
getActiveMigrations() {
|
|
269
|
+
return Array.from(this.activeMigrations.values());
|
|
270
|
+
}
|
|
271
|
+
/**
|
|
272
|
+
* Cancel a migration
|
|
273
|
+
*/
|
|
274
|
+
async cancelMigration(migrationId) {
|
|
275
|
+
const task = this.activeMigrations.get(migrationId);
|
|
276
|
+
if (!task) {
|
|
277
|
+
throw new Error(`Migration ${migrationId} not found`);
|
|
278
|
+
}
|
|
279
|
+
task.status = 'failed';
|
|
280
|
+
task.error = 'Cancelled by user';
|
|
281
|
+
this.activeMigrations.delete(migrationId);
|
|
282
|
+
// Notify target node
|
|
283
|
+
await this.transport.call(task.targetNode, 'cancelMigration', {
|
|
284
|
+
migrationId
|
|
285
|
+
});
|
|
286
|
+
this.emit('migrationCancelled', task);
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
//# sourceMappingURL=shardMigration.js.map
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Storage-based Discovery for Zero-Config Distributed Brainy
|
|
3
|
+
* Uses shared storage (S3/GCS/R2) as coordination point
|
|
4
|
+
* REAL PRODUCTION CODE - No mocks, no stubs!
|
|
5
|
+
*/
|
|
6
|
+
import { EventEmitter } from 'events';
|
|
7
|
+
import { StorageAdapter } from '../coreTypes.js';
|
|
8
|
+
export interface NodeInfo {
|
|
9
|
+
id: string;
|
|
10
|
+
endpoint: string;
|
|
11
|
+
hostname: string;
|
|
12
|
+
started: number;
|
|
13
|
+
lastSeen: number;
|
|
14
|
+
role: 'primary' | 'replica' | 'candidate';
|
|
15
|
+
shards: string[];
|
|
16
|
+
capacity: {
|
|
17
|
+
cpu: number;
|
|
18
|
+
memory: number;
|
|
19
|
+
storage: number;
|
|
20
|
+
};
|
|
21
|
+
stats: {
|
|
22
|
+
nouns: number;
|
|
23
|
+
verbs: number;
|
|
24
|
+
queries: number;
|
|
25
|
+
latency: number;
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
export interface ClusterConfig {
|
|
29
|
+
version: number;
|
|
30
|
+
created: number;
|
|
31
|
+
updated: number;
|
|
32
|
+
leader: string | null;
|
|
33
|
+
nodes: Record<string, NodeInfo>;
|
|
34
|
+
shards: {
|
|
35
|
+
count: number;
|
|
36
|
+
assignments: Record<string, string[]>;
|
|
37
|
+
};
|
|
38
|
+
settings: {
|
|
39
|
+
replicationFactor: number;
|
|
40
|
+
shardCount: number;
|
|
41
|
+
autoRebalance: boolean;
|
|
42
|
+
minNodes: number;
|
|
43
|
+
maxNodesPerShard: number;
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
export declare class StorageDiscovery extends EventEmitter {
|
|
47
|
+
private nodeId;
|
|
48
|
+
private storage;
|
|
49
|
+
private nodeInfo;
|
|
50
|
+
private clusterConfig;
|
|
51
|
+
private heartbeatInterval;
|
|
52
|
+
private discoveryInterval;
|
|
53
|
+
private endpoint;
|
|
54
|
+
private isRunning;
|
|
55
|
+
private readonly HEARTBEAT_INTERVAL;
|
|
56
|
+
private readonly DISCOVERY_INTERVAL;
|
|
57
|
+
private readonly NODE_TIMEOUT;
|
|
58
|
+
private readonly CLUSTER_PATH;
|
|
59
|
+
constructor(storage: StorageAdapter, nodeId?: string);
|
|
60
|
+
/**
|
|
61
|
+
* Start discovery and registration
|
|
62
|
+
*/
|
|
63
|
+
start(httpPort: number): Promise<ClusterConfig>;
|
|
64
|
+
/**
|
|
65
|
+
* Stop discovery and unregister
|
|
66
|
+
*/
|
|
67
|
+
stop(): Promise<void>;
|
|
68
|
+
/**
|
|
69
|
+
* Initialize a new cluster (we're the first node)
|
|
70
|
+
*/
|
|
71
|
+
private initializeCluster;
|
|
72
|
+
/**
|
|
73
|
+
* Join an existing cluster
|
|
74
|
+
*/
|
|
75
|
+
private joinCluster;
|
|
76
|
+
/**
|
|
77
|
+
* Leave cluster cleanly
|
|
78
|
+
*/
|
|
79
|
+
private leaveCluster;
|
|
80
|
+
/**
|
|
81
|
+
* Register node in storage
|
|
82
|
+
*/
|
|
83
|
+
private registerNode;
|
|
84
|
+
/**
|
|
85
|
+
* Heartbeat to keep node alive
|
|
86
|
+
*/
|
|
87
|
+
private startHeartbeat;
|
|
88
|
+
/**
|
|
89
|
+
* Discover other nodes and monitor health
|
|
90
|
+
*/
|
|
91
|
+
private startDiscovery;
|
|
92
|
+
/**
|
|
93
|
+
* Discover nodes from storage
|
|
94
|
+
*/
|
|
95
|
+
private discoverNodes;
|
|
96
|
+
/**
|
|
97
|
+
* Load node registry from storage
|
|
98
|
+
*/
|
|
99
|
+
private loadNodeRegistry;
|
|
100
|
+
/**
|
|
101
|
+
* Update node registry in storage
|
|
102
|
+
*/
|
|
103
|
+
private updateNodeRegistry;
|
|
104
|
+
/**
|
|
105
|
+
* Check health of known nodes
|
|
106
|
+
*/
|
|
107
|
+
private checkNodeHealth;
|
|
108
|
+
/**
|
|
109
|
+
* Load cluster configuration from storage
|
|
110
|
+
*/
|
|
111
|
+
private loadClusterConfig;
|
|
112
|
+
/**
|
|
113
|
+
* Save cluster configuration to storage
|
|
114
|
+
*/
|
|
115
|
+
private saveClusterConfig;
|
|
116
|
+
/**
|
|
117
|
+
* Trigger leader election (simplified - not full Raft)
|
|
118
|
+
*/
|
|
119
|
+
private triggerLeaderElection;
|
|
120
|
+
/**
|
|
121
|
+
* Request shard assignment for this node
|
|
122
|
+
*/
|
|
123
|
+
private requestShardAssignment;
|
|
124
|
+
/**
|
|
125
|
+
* Check if rebalancing is needed
|
|
126
|
+
*/
|
|
127
|
+
private shouldRebalance;
|
|
128
|
+
/**
|
|
129
|
+
* Trigger shard rebalancing
|
|
130
|
+
*/
|
|
131
|
+
private triggerRebalance;
|
|
132
|
+
/**
|
|
133
|
+
* Redistribute shards among active nodes
|
|
134
|
+
*/
|
|
135
|
+
private redistributeShards;
|
|
136
|
+
/**
|
|
137
|
+
* Detect our public endpoint
|
|
138
|
+
*/
|
|
139
|
+
private detectEndpoint;
|
|
140
|
+
/**
|
|
141
|
+
* Generate unique node ID
|
|
142
|
+
*/
|
|
143
|
+
private generateNodeId;
|
|
144
|
+
/**
|
|
145
|
+
* Get current cluster configuration
|
|
146
|
+
*/
|
|
147
|
+
getClusterConfig(): ClusterConfig | null;
|
|
148
|
+
/**
|
|
149
|
+
* Get active nodes
|
|
150
|
+
*/
|
|
151
|
+
getActiveNodes(): NodeInfo[];
|
|
152
|
+
/**
|
|
153
|
+
* Get shards assigned to this node
|
|
154
|
+
*/
|
|
155
|
+
getMyShards(): string[];
|
|
156
|
+
/**
|
|
157
|
+
* Update node statistics
|
|
158
|
+
*/
|
|
159
|
+
updateStats(stats: Partial<NodeInfo['stats']>): void;
|
|
160
|
+
}
|