nats.net icon indicating copy to clipboard operation
nats.net copied to clipboard

Key Value TryCreate/TryUpdate

Open thinkbeforecoding opened this issue 2 years ago • 5 comments

Feature Request

Key Value TryCreate/TryUpdate

Use Case:

The Key Value features are excellent, enabling simple synchronization mechanisms as Leader election etc. using the Create/Update methods that check expected revision before storing proposed value.

Proposed Change:

The Create and Update methods currently throw exceptions, but it would be useful to add new TryCreate/TryUpdate methods that indicates success/failure without throwing an exception.

Who Benefits From The Change(s)?

Throwing/Catching exceptions is costly, and does not make code simpler when it is expected that the call could fail.

Alternative Approaches

Catching the exception to return a boolean, but it makes code less efficient and hard to read.

thinkbeforecoding avatar Jan 06 '22 13:01 thinkbeforecoding

For now, the exception is thrown in PublishAck.Init(): https://github.com/nats-io/nats.net/blob/1e5f0fb6b63a9b9c578613b95ff32e9899fb19e8/src/NATS.Client/JetStream/PublishAck.cs#L35

Avoiding the exception thus require to throw this exception only in some cases.

thinkbeforecoding avatar Jan 21 '22 15:01 thinkbeforecoding

To implement a TryCreate/TryUpdate correctly, we need to implement a TryPublish that is returning the PublishAck without raising an exception in case of an error code. This could be kept private if we don't want to change the Api, but it could be a good idea to provide it for other scenarios.

thinkbeforecoding avatar Jan 26 '22 16:01 thinkbeforecoding

Eventually we'll want to implement also UpdateAsync and TryUpdateAsync.

thinkbeforecoding avatar Jan 26 '22 16:01 thinkbeforecoding

For the Method/TryMethod pattern I usually proceed like this: Implement the TryMethod first that doesn't raise an exception but indicates a success or error. Implement then Method by calling TryMethod and raising an exception in case of error. This avoids reimplementing everything twice.

thinkbeforecoding avatar Jan 26 '22 16:01 thinkbeforecoding

Would it be ok to add a flag in PublishOptions to indicate that Publish should not raise exception on error ? This could avoid passing an extra parameter along the chain. The response parsing would use it to know if it raises the exception directly when parsing the Publish response.

thinkbeforecoding avatar Feb 14 '22 12:02 thinkbeforecoding