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
9 changes: 4 additions & 5 deletions src/NATS.Client.JetStream/Models/ConsumerConfig.cs
Original file line number Diff line number Diff line change
Expand Up @@ -272,16 +272,15 @@ public ConsumerConfig(string name)
#endif

/// <summary>
/// Specifies the priority policy for consumer message selection, such as prioritizing <c>overflow</c> or <c>pinned_client</c>.
/// Specifies the priority policy for consumer message selection.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

no need for documenting values. it's an enum now. it's a breaking change but since this is a fairly new feature, i don't expect many applications would be affected by it. required recompilation but the fix should be straight forward.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, this is fine. I've done the same on brand new things.

/// </summary>
[System.Text.Json.Serialization.JsonPropertyName("priority_policy")]
[System.Text.Json.Serialization.JsonIgnore(Condition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingDefault)]
[System.ComponentModel.DataAnnotations.StringLength(int.MaxValue, MinimumLength = 1)]
[System.ComponentModel.DataAnnotations.RegularExpression(@"^[^.*>]+$")]
#if NET6_0
public string? PriorityPolicy { get; set; }
[System.Text.Json.Serialization.JsonConverter(typeof(NatsJSJsonStringEnumConverter<ConsumerConfigPriorityPolicy>))]
public ConsumerConfigPriorityPolicy? PriorityPolicy { get; set; }
#else
public string? PriorityPolicy { get; init; }
public ConsumerConfigPriorityPolicy? PriorityPolicy { get; init; }
#endif

/// <summary>
Expand Down
22 changes: 22 additions & 0 deletions src/NATS.Client.JetStream/Models/ConsumerConfigPriorityPolicy.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
namespace NATS.Client.JetStream.Models;

/// <summary>
/// The priority policy for consumer message selection.
/// </summary>
public enum ConsumerConfigPriorityPolicy
{
/// <summary>
/// No priority policy is set.
/// </summary>
None = 0,

/// <summary>
/// Messages are delivered based on priority level.
/// </summary>
Prioritized = 1,

/// <summary>
/// Messages overflow to the next available consumer.
/// </summary>
Overflow = 2,
}
13 changes: 13 additions & 0 deletions src/NATS.Client.JetStream/Models/ConsumerGetnextRequest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -82,4 +82,17 @@ public record ConsumerGetnextRequest
[System.Text.Json.Serialization.JsonPropertyName("id")]
[System.Text.Json.Serialization.JsonIgnore(Condition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingDefault)]
public string? Id { get; set; }

/// <summary>
/// Priority for message delivery when using prioritized priority policy.
/// </summary>
/// <remarks>
/// Lower values indicate higher priority (0 is the highest priority).
/// Maximum priority value is 9. This field is only used when the consumer
/// has PriorityPolicy set to "prioritized".
/// </remarks>
[System.Text.Json.Serialization.JsonPropertyName("priority")]
[System.Text.Json.Serialization.JsonIgnore(Condition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingDefault)]
[System.ComponentModel.DataAnnotations.Range(0, 9)]
public byte Priority { get; set; }

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

when these are serialized, are the names lowercased?
probably what this is for

 new JsonStringEnumConverter<ConsumerConfigPriorityPolicy (JsonNamingPolicy.SnakeCaseLower),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I assume None does not get written either.

}
3 changes: 3 additions & 0 deletions src/NATS.Client.JetStream/NatsJSConsumer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -336,6 +336,7 @@ await sub.CallMsgNextAsync(
Group = opts.PriorityGroup?.Group,
MinPending = opts.PriorityGroup?.MinPending ?? 0,
MinAckPending = opts.PriorityGroup?.MinAckPending ?? 0,
Priority = opts.PriorityGroup?.Priority ?? 0,
},
cancellationToken).ConfigureAwait(false);

Expand Down Expand Up @@ -438,6 +439,7 @@ await sub.CallMsgNextAsync(
Group = opts.PriorityGroup?.Group,
MinPending = opts.PriorityGroup?.MinPending ?? 0,
MinAckPending = opts.PriorityGroup?.MinAckPending ?? 0,
Priority = opts.PriorityGroup?.Priority ?? 0,
}
: new ConsumerGetnextRequest
{
Expand All @@ -449,6 +451,7 @@ await sub.CallMsgNextAsync(
Group = opts.PriorityGroup?.Group,
MinPending = opts.PriorityGroup?.MinPending ?? 0,
MinAckPending = opts.PriorityGroup?.MinAckPending ?? 0,
Priority = opts.PriorityGroup?.Priority ?? 0,
},
cancellationToken).ConfigureAwait(false);

Expand Down
11 changes: 0 additions & 11 deletions src/NATS.Client.JetStream/NatsJSContext.Consumers.cs
Original file line number Diff line number Diff line change
Expand Up @@ -263,17 +263,6 @@ private async ValueTask<NatsJSConsumer> CreateOrUpdateConsumerInternalAsync(
throw new NatsJSException("Cannot create consumers with multiple priority groups.");
}

if (config.PriorityPolicy is "pinned_client")
{
throw new NotImplementedException("Pinned clients are not supported yet.");

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

pinned_client wan't implemented anyway, so just removed it here.

}

// TODO: enum these values?
if (config.PriorityPolicy != null && config.PriorityPolicy != "none" && config.PriorityPolicy != "overflow" && config.PriorityPolicy != "pinned_client")

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

don't need this check any more. it's an enum now.

{
throw new NatsJSException("Cannot create consumers with priority policy other than 'overflow', 'pinned_client', or 'none'.");
}

var response = await JSRequestResponseAsync<ConsumerCreateRequest, ConsumerInfo>(
subject: subject,
new ConsumerCreateRequest
Expand Down
29 changes: 29 additions & 0 deletions src/NATS.Client.JetStream/NatsJSJsonSerializer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,7 @@ internal partial class NatsJSJsonSerializerContext : JsonSerializerContext
new JsonStringEnumConverter<StreamConfigStorage>(JsonNamingPolicy.SnakeCaseLower),
new JsonStringEnumConverter<StreamConfigPersistMode>(JsonNamingPolicy.SnakeCaseLower),
new JsonStringEnumConverter<ConsumerCreateAction>(JsonNamingPolicy.SnakeCaseLower),
new JsonStringEnumConverter<ConsumerConfigPriorityPolicy>(JsonNamingPolicy.SnakeCaseLower),
},
});
#endif
Expand Down Expand Up @@ -235,6 +236,19 @@ public override TEnum Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSe
}
}

if (typeToConvert == typeof(ConsumerConfigPriorityPolicy))
{
switch (stringValue)
{
case "none":
return (TEnum)(object)ConsumerConfigPriorityPolicy.None;
case "prioritized":
return (TEnum)(object)ConsumerConfigPriorityPolicy.Prioritized;
case "overflow":
return (TEnum)(object)ConsumerConfigPriorityPolicy.Overflow;
}
}

throw new InvalidOperationException($"Reading unknown enum type {typeToConvert.Name} or value {stringValue}");
}

Expand Down Expand Up @@ -369,6 +383,21 @@ public override void Write(Utf8JsonWriter writer, TEnum value, JsonSerializerOpt
return;
}
}
else if (value is ConsumerConfigPriorityPolicy consumerConfigPriorityPolicy)
{
switch (consumerConfigPriorityPolicy)
{
case ConsumerConfigPriorityPolicy.None:
writer.WriteStringValue("none");
return;
case ConsumerConfigPriorityPolicy.Prioritized:
writer.WriteStringValue("prioritized");
return;
case ConsumerConfigPriorityPolicy.Overflow:
writer.WriteStringValue("overflow");
return;
}
}

throw new InvalidOperationException($"Writing unknown enum value {value.GetType().Name}.{value}");
}
Expand Down
10 changes: 10 additions & 0 deletions src/NATS.Client.JetStream/NatsJSOpts.cs
Original file line number Diff line number Diff line change
Expand Up @@ -265,4 +265,14 @@ public record NatsJSPriorityGroupOpts
/// When specified, this Pull request will only receive messages when the consumer has at least this many ack pending messages.
/// </summary>
public long MinAckPending { get; set; }

/// <summary>
/// Priority for message delivery when using prioritized priority policy.
/// </summary>
/// <remarks>
/// Lower values indicate higher priority (0 is the highest priority).
/// Maximum priority value is 9. This field is only used when the consumer
/// has PriorityPolicy set to "prioritized".
/// </remarks>
public byte Priority { get; init; }
}
35 changes: 35 additions & 0 deletions tests/NATS.Client.JetStream.Tests/EnumJsonTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -252,4 +252,39 @@ public void StreamConfigPersistMode_roundtrip_preserves_server_values()
var jsonOut3 = Encoding.UTF8.GetString(bw3.WrittenSpan.ToArray());
Assert.DoesNotContain("persist_mode", jsonOut3);
}

[Theory]
[InlineData(ConsumerConfigPriorityPolicy.None, "\"priority_policy\":\"none\"")]
[InlineData(ConsumerConfigPriorityPolicy.Prioritized, "\"priority_policy\":\"prioritized\"")]
[InlineData(ConsumerConfigPriorityPolicy.Overflow, "\"priority_policy\":\"overflow\"")]
public void ConsumerConfigPriorityPolicy_test(ConsumerConfigPriorityPolicy value, string expected)
{
var serializer = NatsJSJsonSerializer<ConsumerConfig>.Default;

var bw = new NatsBufferWriter<byte>();
serializer.Serialize(bw, new ConsumerConfig { PriorityPolicy = value });

var json = Encoding.UTF8.GetString(bw.WrittenSpan.ToArray());
Assert.Contains(expected, json);

var result = serializer.Deserialize(new ReadOnlySequence<byte>(bw.WrittenMemory));
Assert.NotNull(result);
Assert.Equal(value, result.PriorityPolicy);
}

[Fact]
public void ConsumerConfigPriorityPolicy_null_test()

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we also have a test for null where it should not be serialized onto the wire at all when null.

{
var serializer = NatsJSJsonSerializer<ConsumerConfig>.Default;

var bw = new NatsBufferWriter<byte>();
serializer.Serialize(bw, new ConsumerConfig { PriorityPolicy = null });

var json = Encoding.UTF8.GetString(bw.WrittenSpan.ToArray());
Assert.DoesNotContain("priority_policy", json);

var result = serializer.Deserialize(new ReadOnlySequence<byte>(bw.WrittenMemory));
Assert.NotNull(result);
Assert.Null(result.PriorityPolicy);
}
}
91 changes: 88 additions & 3 deletions tests/NATS.Client.JetStream.Tests/PriorityGroupTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ public async Task Next_from_overflow_group()
ack.EnsureSuccess();
}

var consumerConfig = new ConsumerConfig($"{prefix}c1") { PriorityGroups = ["jobs"], PriorityPolicy = "overflow", };
var consumerConfig = new ConsumerConfig($"{prefix}c1") { PriorityGroups = ["jobs"], PriorityPolicy = ConsumerConfigPriorityPolicy.Overflow, };
var consumer = await js.CreateOrUpdateConsumerAsync($"{prefix}s1", consumerConfig, cancellationToken: cts.Token);

// Err on no group
Expand Down Expand Up @@ -77,7 +77,7 @@ public async Task Fetch_from_overflow_group()
ack.EnsureSuccess();
}

var consumerConfig = new ConsumerConfig($"{prefix}c1") { PriorityGroups = ["jobs"], PriorityPolicy = "overflow", };
var consumerConfig = new ConsumerConfig($"{prefix}c1") { PriorityGroups = ["jobs"], PriorityPolicy = ConsumerConfigPriorityPolicy.Overflow, };
var consumer = await js.CreateOrUpdateConsumerAsync($"{prefix}s1", consumerConfig, cancellationToken: cts.Token);

// Err on no group
Expand Down Expand Up @@ -123,7 +123,7 @@ public async Task Consume_from_overflow_group()
ack.EnsureSuccess();
}

var consumerConfig = new ConsumerConfig($"{prefix}c1") { PriorityGroups = ["jobs"], PriorityPolicy = "overflow", };
var consumerConfig = new ConsumerConfig($"{prefix}c1") { PriorityGroups = ["jobs"], PriorityPolicy = ConsumerConfigPriorityPolicy.Overflow, };
var consumer = await js.CreateOrUpdateConsumerAsync($"{prefix}s1", consumerConfig, cancellationToken: cts.Token);

// Err on no group
Expand Down Expand Up @@ -151,4 +151,89 @@ public async Task Consume_from_overflow_group()
}
}
}

[SkipIfNatsServer(versionEarlierThan: "2.12")]
public async Task Fetch_from_prioritized_group_with_priority()
{
await using var nats = new NatsConnection(new NatsOpts { Url = _server.Url });
var js = new NatsJSContext(nats);
var prefix = _server.GetNextId();

var cts = new CancellationTokenSource(TimeSpan.FromSeconds(30));

await js.CreateStreamAsync($"{prefix}s1", [$"{prefix}s1.>"], cts.Token);

for (var i = 0; i < 10; i++)
{
var ack = await js.PublishAsync($"{prefix}s1.{i}", i, cancellationToken: cts.Token);
ack.EnsureSuccess();
}

var consumerConfig = new ConsumerConfig($"{prefix}c1")
{
PriorityGroups = ["jobs"],
PriorityPolicy = ConsumerConfigPriorityPolicy.Prioritized,
};
var consumer = await js.CreateOrUpdateConsumerAsync($"{prefix}s1", consumerConfig, cancellationToken: cts.Token);

// Test with priority 5
{
var opts = new NatsJSFetchOpts
{
MaxMsgs = 3,
PriorityGroup = new NatsJSPriorityGroupOpts { Group = "jobs", Priority = 5 },
};
var count = 0;
await foreach (var msg in consumer.FetchAsync<int>(opts, cancellationToken: cts.Token))
{
Assert.Equal(count++, msg.Data);
if (count == 3)
break;
}

Assert.Equal(3, count);
}

// Test with priority 0 (highest priority)
{
var opts = new NatsJSFetchOpts
{
MaxMsgs = 2,
PriorityGroup = new NatsJSPriorityGroupOpts { Group = "jobs", Priority = 0 },
};
var count = 0;
await foreach (var msg in consumer.FetchAsync<int>(opts, cancellationToken: cts.Token))
{
Assert.Equal(count + 3, msg.Data); // Should continue from where we left off
count++;
if (count == 2)
break;
}

Assert.Equal(2, count);
}
}

[SkipIfNatsServer(versionEarlierThan: "2.12")]
public async Task Consumer_with_prioritized_policy_validation()
{
await using var nats = new NatsConnection(new NatsOpts { Url = _server.Url });
var js = new NatsJSContext(nats);
var prefix = _server.GetNextId();

var cts = new CancellationTokenSource(TimeSpan.FromSeconds(30));

await js.CreateStreamAsync($"{prefix}s1", [$"{prefix}s1.>"], cts.Token);

// Test that prioritized policy is accepted
var consumerConfig = new ConsumerConfig($"{prefix}c1")
{
PriorityGroups = ["jobs"],
PriorityPolicy = ConsumerConfigPriorityPolicy.Prioritized,
};

var consumer = await js.CreateOrUpdateConsumerAsync($"{prefix}s1", consumerConfig, cancellationToken: cts.Token);
Assert.NotNull(consumer);
Assert.Equal(ConsumerConfigPriorityPolicy.Prioritized, consumer.Info.Config.PriorityPolicy);
}
}
Loading