Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,7 @@ public async Task EnqueueMessage(NatsStreamMessage message, CancellationToken ca

var subject = $"{this._providerName}.{ns}.{id}";

var context = this._producerNatsContexts[Math.Abs(id.GetHashCode()) % this._producerNatsContexts.Length];
var context = this._producerNatsContexts[GetProducerIndex(id.GetHashCode(), this._producerNatsContexts.Length)];

var ack = await context.TryPublishAsync(
subject,
Expand Down Expand Up @@ -192,6 +192,9 @@ public NatsStreamConsumer CreateConsumer(uint partition) =>
this._options.BatchSize,
this._natsClientOptions.SerializerRegistry.GetDeserializer<NatsStreamMessage>());

internal static int GetProducerIndex(int hashCode, int producerCount)
=> (int)((uint)hashCode % (uint)producerCount);

/// <summary>
/// Acknowledge messages on a subject in a NATS JetStream stream
/// </summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,31 @@ public void DefaultStorageType_ShouldBeFile()
Assert.Equal(StreamConfigStorage.File, options.StorageType);
}

[Theory]
[InlineData(int.MinValue, 1, 0)]
[InlineData(int.MinValue, 3, 2)]
[InlineData(int.MinValue, 8, 0)]
[InlineData(int.MinValue, int.MaxValue, 1)]
[InlineData(-1, 1, 0)]
[InlineData(-1, 3, 0)]
[InlineData(-1, 8, 7)]
[InlineData(-1, int.MaxValue, 1)]
[InlineData(0, 1, 0)]
[InlineData(0, 3, 0)]
[InlineData(0, 8, 0)]
[InlineData(0, int.MaxValue, 0)]
[InlineData(int.MaxValue, 1, 0)]
[InlineData(int.MaxValue, 3, 1)]
[InlineData(int.MaxValue, 8, 7)]
[InlineData(int.MaxValue, int.MaxValue, 0)]
public void ProducerIndex_IsAlwaysWithinBounds(int hashCode, int producerCount, int expectedIndex)
{
var index = NatsConnectionManager.GetProducerIndex(hashCode, producerCount);

Assert.Equal(expectedIndex, index);
Assert.InRange(index, 0, producerCount - 1);
}

[Theory]
[InlineData(0)]
[InlineData(-1)]
Expand Down
Loading