Ankusa.UUIDv7 (ankusa v0.7.0)

Copy Markdown View Source

UUIDv7 generation (RFC 9562 §5.7): 48-bit Unix millisecond timestamp followed by 74 random bits.

Ordering is at millisecond granularity only. Two ids generated inside the same millisecond are random relative to each other, and a backwards clock step (NTP correcting) can yield an id that sorts before an earlier one. That is sufficient for what ids are used for here — a lexicographically time-sortable key (claims/<tenant>/<id>, the sweeper's expiry parse) and a unique index key — and records are ordered by the store's seq, never by id.

If intra-millisecond ordering is ever genuinely needed (an audit listing sorted by id, say), the fix is RFC 9562's counter layout: a 12-bit counter in rand_a that borrows from the next millisecond on rollover. That needs shared mutable state (:atomics) plus a clock-regression guard, which is a deliberate design change rather than a tweak.

Summary

Functions

Generate a UUIDv7 as a lowercase, hyphenated string.

Generate a UUIDv7 for a specific Unix millisecond timestamp.

The highest possible UUIDv7 id whose timestamp is ms.

The lowest possible UUIDv7 id whose timestamp is ms.

Extract the 48-bit Unix millisecond timestamp embedded in a UUIDv7 string.

Functions

generate()

@spec generate() :: String.t()

Generate a UUIDv7 as a lowercase, hyphenated string.

generate(ms)

@spec generate(integer()) :: String.t()

Generate a UUIDv7 for a specific Unix millisecond timestamp.

max_for(ms)

@spec max_for(non_neg_integer()) :: String.t()

The highest possible UUIDv7 id whose timestamp is ms.

min_for(ms)

@spec min_for(non_neg_integer()) :: String.t()

The lowest possible UUIDv7 id whose timestamp is ms.

timestamp_ms(arg1)

@spec timestamp_ms(String.t()) :: {:ok, non_neg_integer()} | :error

Extract the 48-bit Unix millisecond timestamp embedded in a UUIDv7 string.

:error for anything that isn't a well-formed UUIDv7 (wrong length, wrong version/variant nibbles, non-hex characters) — never raises on untrusted input.