crystal-lang / crystal

The Crystal Programming Language
https://crystal-lang.org
Apache License 2.0
19.2k stars 1.61k forks source link

Add UUID v7 #14732

Closed jgaskins closed 5 days ago

jgaskins commented 1 week ago

Part of #14288. This PR doesn't implement all of the requested UUID versions, but v7 is gaining in popularity for its ability to sort UUID values chronologically and RFC 9562 was published last month.

It's notable that RFC 4122 has been obsoleted via RFC 9562, so I included an alias for the new RFC in the Variant enum.

Spec: https://www.rfc-editor.org/rfc/rfc9562#name-uuid-version-7

jgaskins commented 1 week ago

the spec is weird as the format has optional non-random parts to increase precision + counter 😕

I understand the more precise, the better for database indexes, but less randomness means more chances for collisions, so we should give some control over it.

Do you think we could specify the precision (second vs millisecond), and later a counter to control this aspect?

I hear you, reducing entropy honestly sounds scary. I've given it the maximum randomness and minimum monotonicity the spec allows for. Millisecond precision is prescribed by the spec.

In thinking about the failure modes of a UUID collision (admittedly from my own perspective, which mostly revolves around using them as DB primary keys), the most likely scenario would be an exception due to INSERTing 2 rows into a table with the same primary key. With a keyspace of 2**74 (roughly 1.9e22) values per millisecond, this would happen infrequently enough that a simple retry should work.

Since there are other UUID solutions that provide more randomness and less precision, if that's what you need, I'd argue that a v7 UUID is not.

ysbaddaden commented 1 week ago

Sorry, I misread the spec, the timestamp is in milliseconds :+1:

ysbaddaden commented 1 week ago

Feel free to ignore the above suggestions, they're just nitpicks. But WASM32 doesn't like the call to sleep in the spec. I think the eventloop isn't implemented.

jgaskins commented 6 days ago

Looks like pending! also doesn't work on WASM? 🤔

jkthorne commented 6 days ago

nice, I didn't know this existed. I will be switching a few projects to V7.

straight-shoota commented 6 days ago

Dang, didn't realize that. We can use pending_wasm32 instead of a custom method.