mareek / UUIDNext

A fast and modern .NET library to generate UUID/GUID that are either sequential and database friendly (versions 7), name based (versions 5) or random (version 4).
BSD Zero Clause License
240 stars 13 forks source link

Question: Is there a way to create UUIDv7 from specific DateTime(Offset)? #14

Closed jdvor closed 2 months ago

mareek commented 2 months ago

Currently there is no way to create a UUIDv7 from a specific dateTemie without using reflection in UUIDNext.

What would you use this for ?

jdvor commented 2 months ago

I have a bunch of events that all contain BusinessTimeUtc (DateTimeOffset), which do come at times slightly out of order. They do not have any other "better" identity than this one. I want to enrich them with a synthetic ID for further processing. It would be beneficial down the line for this identity to be unique and sorted by business time (which is different from receival time).

I think it would be beneficial for yours package to allow this option, because I don't think it is some kind of very rare use case.

mareek commented 2 months ago

I understand your use case and I think there may be many similar situations where a function to generate an UUIDv7 for a specific dateTime might be useful.

I have to think of a way to add this to UUIDNext's API in a way that's simple, hard to misuse and that doesn't break the sub-millisecond ordering mechanism.

jdvor commented 2 months ago

I think it's about surfacing this method, although for an API I would rather choose DateTimeOffset to avoid ambiguity of DateTimeKind.

I don't think there's any danger if it is used with a less precise DateTimeOffset than it would be otherwise obtained by DateTimeOffset.UtcNow. Yes, the resulting Guid may have more zeros around the 2nd byte, but clearly, the ones using the method with a time argument value time ordering slightly more than "uniqueness",  which is still high in most use cases.

It would suffice to warn the user not to generate millions of Guids at the same time, perhaps in an XML comment.

Should I close the ticket / question or do you want it to remain open?

mareek commented 2 months ago

It's more complex than just giving access to UuidV7Generator.New(DateTime). To guarantee that UUID are always increasing, the generator has some logic to handle overflow, computer clock update, leap second, etc. that won't work well if it is given random dateTimes as input.

BTW, I try to follow the "pit of success" philosophy for this library, so when I introduce a new feature, I want to make sure that the library user won't use it in an unintended way

mareek commented 1 month ago

Hi @jdvor, I've released a new beta version that allow you to create a UUID v7 based on a specific DateTimeOffset by using the UUIDNext.Tools.UuidToolkit.CreateUuidV7FromSpecificDate(DateTimeOffset) method.

Can you try it and tell me if it meet your needs ?

Thanks in advance