Noticed interesting sender behavior in JetStream #747
-
There is currently no subject verification in the JetStream api. If you use one connection to send several JetStream messages conditionally simultaneously and one of them has an invalid subject, then messages with a valid subject will also receive the error The following questions appear:
[Fact]
public async Task Publish_invalid_subject()
{
await using var server = await NatsServer.StartJSAsync();
await using var nats = await server.CreateClientConnectionAsync();
var js = new NatsJSContext(nats);
var stream = await js.CreateStreamAsync(
config: new StreamConfig( "events", new[] { "events.*" }));
var pub = async (string subject) =>
{
try
{
await js.PublishAsync(subject, new TestData { Test = 1 }, serializer: TestDataJsonSerializer<TestData>.Default);
return Task.CompletedTask;
}
catch (Exception e)
{
_output.WriteLine(subject + " " + e.Message);
return Task.CompletedTask;
}
};
await Task.WhenAll(pub("events.before"), pub("events.invalid subject 1"), pub("events.afterFirstInvalid1"), pub("events.afterFirstInvalid2"), pub("events.invalid subject 2"), pub("events.afterSecondInvalid1"));
} Ouput:
P.S. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
the subject with space is causing protocol error and disconnecting the client.
because they're all running concurrently by luck if one publishes right after disconnect, it is timing out and giving the same error some of the time. NATS .NET is designed to work with concurrent operations but the application code needs to handle the errors. in case of the subject with space as an invalid subject currently we don't have a protection against which might make it harder / impossible for applications handle the error. Let me check some of the other clients and with the team see how that's handled in general (remember this coming up before, i shall try to dig it out) |
Beta Was this translation helpful? Give feedback.
OK, so the short answer is you need to do your own validation if your subjects can be generated from other inputs which might be any string. some guidelines are here https://docs.nats.io/nats-concepts/subjects#characters-allowed-and-recommended-for-subject-names but
AFAIU, the main reason for the NATS client not to do the subject validation is not to create any performance loss and leave the validation to the server to avoid issues among different clients. So it is left to applications to build their subjects correctly and test before using their way of building subjects.