## Waku autosharding utils ## ## See 51/WAKU2-RELAY-SHARDING RFC: https://rfc.vac.dev/spec/51/#automatic-sharding when (NimMajor, NimMinor) < (1, 4): {.push raises: [Defect].} else: {.push raises: [].} import nimcrypto, std/options, std/math, std/sequtils, std/algorithm, stew/endians2, stew/results, stew/byteutils import ./content_topic, ./pubsub_topic ## For indices allocation and other magic numbers refer to RFC 51 const ClusterIndex* = 49152 const GenerationZeroShardsCount* = 5 type ShardsPriority = seq[tuple[topic: NsPubsubTopic, value: float64]] proc shardCount*(topic: NsContentTopic): Result[int, string] = ## Returns the total shard count, sharding selection bias ## and the shard name from the content topic. let shardCount = if topic.generation.isNone(): ## Implicit generation # is 0 for all content topic GenerationZeroShardsCount else: case topic.generation.get(): of 0: GenerationZeroShardsCount else: return err("Generation > 0 are not supported yet") ok((shardCount)) proc biasedWeights*(shardCount: int, bias: ShardingBias): seq[float64] = var weights = repeat(1.0, shardCount) case bias: of Unbiased: return weights of Lower20: # we choose the lower 20% of shards and double their weigths let index = shardCount div 5 for i in (0..