nats-io / nats.net.v1

The official C# Client for NATS
Apache License 2.0
646 stars 154 forks source link

Not thread safe to start subscriptions concurrently in a connection #917

Open MENNAELMESALMY opened 1 month ago

MENNAELMESALMY commented 1 month ago

Observed behavior

we saw this error getting thrown when trying to start multiple subscriptions concurrently

"   at System.Collections.Generic.Dictionary`2.TryInsert(TKey key, TValue value, InsertionBehavior behavior)
   at NATS.Client.Connection.AddSubscription(Subscription s)
   at NATS.Client.Connection.subscribeAsync(String subject, String queue, EventHandler`1 handler, CreateAsyncSubscriptionDelegate createAsyncSubscriptionDelegate)
   at NATS.Client.JetStream.JetStream.CreateSubscription(String userSubscribeSubject, PushSubscribeOptions pushSubscribeOptions, PullSubscribeOptions pullSubscribeOptions, String queueName, EventHandler`1 userHandler, Boolean autoAck, PullMessageManager pmmInstance)
   at NATS.Client.JetStream.JetStream.PushSubscribeAsync(String subject, EventHandler`1 handler, Boolean autoAck, PushSubscribeOptions options)
   at NATS.Client.KeyValue.KeyValueWatchSubscription..ctor(KeyValue kv, IList`1 keyPatterns, IKeyValueWatcher watcher, UInt64 fromRevision, KeyValueWatchOption[] watchOptions)
   at NATS.Client.KeyValue.KeyValue.WatchAll(IKeyValueWatcher watcher, KeyValueWatchOption[] watchOptions)

...

I saw that the connection keeps track of all subscriptions in a dictionary but it's not thread safe

Expected behavior

Starting multiple subscriptions is thread-safe.

Server and client version

c# version: 1.1.5

Host environment

No response

Steps to reproduce

No response