# All files / framework/sharding ShardManager.ts

0% Statements 0/120
0% Branches 0/36
0% Functions 0/21
0% Lines 0/117

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

     import { ShardingConfig, StoreType } from '../types/framework';
    import { FrameworkOrbitDBService } from '../services/OrbitDBService';

    export interface ShardInfo {
      name: string;
      index: number;
      database: any;
      address: string;
    }

    export class ShardManager {
      private orbitDBService?: FrameworkOrbitDBService;
      private shards: Map<string, ShardInfo[]> = new Map();
      private shardConfigs: Map<string, ShardingConfig> = new Map();

      setOrbitDBService(service: FrameworkOrbitDBService): void {
        this.orbitDBService = service;
      }

      async createShards(
        modelName: string,
        config: ShardingConfig,
        dbType: StoreType = 'docstore',
      ): Promise<void> {
        if (!this.orbitDBService) {
          throw new Error('OrbitDB service not initialized');
        }

        console.log(`🔀 Creating ${config.count} shards for model: ${modelName}`);

        const shards: ShardInfo[] = [];
        this.shardConfigs.set(modelName, config);

        for (let i = 0; i < config.count; i++) {
          const shardName = `${modelName.toLowerCase()}-shard-${i}`;

          try {
            const shard = await this.createShard(shardName, i, dbType);
            shards.push(shard);

            console.log(`✓ Created shard: ${shardName} (${shard.address})`);
          } catch (error) {
            console.error(`❌ Failed to create shard ${shardName}:`, error);
            throw error;
          }
        }

        this.shards.set(modelName, shards);
        console.log(`✅ Created ${shards.length} shards for ${modelName}`);
      }

      getShardForKey(modelName: string, key: string): ShardInfo {
        const shards = this.shards.get(modelName);
        if (!shards || shards.length === 0) {
          throw new Error(`No shards found for model ${modelName}`);
        }

        const config = this.shardConfigs.get(modelName);
        if (!config) {
          throw new Error(`No shard configuration found for model ${modelName}`);
        }

        const shardIndex = this.calculateShardIndex(key, shards.length, config.strategy);
        return shards[shardIndex];
      }

      getAllShards(modelName: string): ShardInfo[] {
        return this.shards.get(modelName) || [];
      }

      getShardByIndex(modelName: string, index: number): ShardInfo | undefined {
        const shards = this.shards.get(modelName);
        if (!shards || index < 0 || index >= shards.length) {
          return undefined;
        }
        return shards[index];
      }

      getShardCount(modelName: string): number {
        const shards = this.shards.get(modelName);
        return shards ? shards.length : 0;
      }

      private calculateShardIndex(
        key: string,
        shardCount: number,
        strategy: ShardingConfig['strategy'],
      ): number {
        switch (strategy) {
          case 'hash':
            return this.hashSharding(key, shardCount);

          case 'range':
            return this.rangeSharding(key, shardCount);

          case 'user':
            return this.userSharding(key, shardCount);

          default:
            throw new Error(`Unsupported sharding strategy: ${strategy}`);
        }
      }

      private hashSharding(key: string, shardCount: number): number {
        // Consistent hash-based sharding
        let hash = 0;
        for (let i = 0; i < key.length; i++) {
          hash = ((hash << 5) - hash + key.charCodeAt(i)) & 0xffffffff;
        }
        return Math.abs(hash) % shardCount;
      }

      private rangeSharding(key: string, shardCount: number): number {
        // Range-based sharding (alphabetical)
        const firstChar = key.charAt(0).toLowerCase();
        const charCode = firstChar.charCodeAt(0);

        // Map a-z (97-122) to shard indices
        const normalizedCode = Math.max(97, Math.min(122, charCode));
        const range = (normalizedCode - 97) / 25; // 0-1 range

        return Math.floor(range * shardCount);
      }

      private userSharding(key: string, shardCount: number): number {
        // User-based sharding - similar to hash but optimized for user IDs
        return this.hashSharding(key, shardCount);
      }

      private async createShard(
        shardName: string,
        index: number,
        dbType: StoreType,
      ): Promise<ShardInfo> {
        if (!this.orbitDBService) {
          throw new Error('OrbitDB service not initialized');
        }

        const database = await this.orbitDBService.openDatabase(shardName, dbType);

        return {
          name: shardName,
          index,
          database,
          address: database.address.toString(),
        };
      }

      // Global indexing support
      async createGlobalIndex(modelName: string, indexName: string): Promise<void> {
        if (!this.orbitDBService) {
          throw new Error('OrbitDB service not initialized');
        }

        console.log(`📇 Creating global index: ${indexName} for model: ${modelName}`);

        // Create sharded global index
        const INDEX_SHARD_COUNT = 4; // Configurable
        const indexShards: ShardInfo[] = [];

        for (let i = 0; i < INDEX_SHARD_COUNT; i++) {
          const indexShardName = `${indexName}-shard-${i}`;

          try {
            const shard = await this.createShard(indexShardName, i, 'keyvalue');
            indexShards.push(shard);

            console.log(`✓ Created index shard: ${indexShardName}`);
          } catch (error) {
            console.error(`❌ Failed to create index shard ${indexShardName}:`, error);
            throw error;
          }
        }

        // Store index shards
        this.shards.set(indexName, indexShards);

        console.log(`✅ Created global index ${indexName} with ${indexShards.length} shards`);
      }

      async addToGlobalIndex(indexName: string, key: string, value: any): Promise<void> {
        const indexShards = this.shards.get(indexName);
        if (!indexShards) {
          throw new Error(`Global index ${indexName} not found`);
        }

        // Determine which shard to use for this key
        const shardIndex = this.hashSharding(key, indexShards.length);
        const shard = indexShards[shardIndex];

        try {
          // For keyvalue stores, we use set
          await shard.database.set(key, value);
        } catch (error) {
          console.error(`Failed to add to global index ${indexName}:`, error);
          throw error;
        }
      }

      async getFromGlobalIndex(indexName: string, key: string): Promise<any> {
        const indexShards = this.shards.get(indexName);
        if (!indexShards) {
          throw new Error(`Global index ${indexName} not found`);
        }

        // Determine which shard contains this key
        const shardIndex = this.hashSharding(key, indexShards.length);
        const shard = indexShards[shardIndex];

        try {
          return await shard.database.get(key);
        } catch (error) {
          console.error(`Failed to get from global index ${indexName}:`, error);
          return null;
        }
      }

      async removeFromGlobalIndex(indexName: string, key: string): Promise<void> {
        const indexShards = this.shards.get(indexName);
        if (!indexShards) {
          throw new Error(`Global index ${indexName} not found`);
        }

        // Determine which shard contains this key
        const shardIndex = this.hashSharding(key, indexShards.length);
        const shard = indexShards[shardIndex];

        try {
          await shard.database.del(key);
        } catch (error) {
          console.error(`Failed to remove from global index ${indexName}:`, error);
          throw error;
        }
      }

      // Query all shards for a model
      async queryAllShards(
        modelName: string,
        queryFn: (database: any) => Promise<any[]>,
      ): Promise<any[]> {
        const shards = this.shards.get(modelName);
        if (!shards) {
          throw new Error(`No shards found for model ${modelName}`);
        }

        const results: any[] = [];

        // Query all shards in parallel
        const promises = shards.map(async (shard) => {
          try {
            return await queryFn(shard.database);
          } catch (error) {
            console.warn(`Query failed on shard ${shard.name}:`, error);
            return [];
          }
        });

        const shardResults = await Promise.all(promises);

        // Flatten results
        for (const shardResult of shardResults) {
          results.push(...shardResult);
        }

        return results;
      }

      // Statistics and monitoring
      getShardStatistics(modelName: string): any {
        const shards = this.shards.get(modelName);
        if (!shards) {
          return null;
        }

        return {
          modelName,
          shardCount: shards.length,
          shards: shards.map((shard) => ({
            name: shard.name,
            index: shard.index,
            address: shard.address,
          })),
        };
      }

      getAllModelsWithShards(): string[] {
        return Array.from(this.shards.keys());
      }

      // Cleanup
      async stop(): Promise<void> {
        console.log('🛑 Stopping ShardManager...');

        this.shards.clear();
        this.shardConfigs.clear();

        console.log('✅ ShardManager stopped');
      }
    }