-
Notifications
You must be signed in to change notification settings - Fork 137
Open
Labels
enhancementNew feature or requestNew feature or request
Description
Is your feature request related to a problem? Please describe.
We currently use the uuid4() function pretty heavily to generate unique ids within Workflow Tasks. For some use cases we want to generate UUIDv7 IDs for better indexing and sorting semantics. We cannot use the uuid npm package because it depends on the crypto module.
We've already added this function to our codebase, but it'd be helpful to merge upstream to expand the functionality provided by uuid4.
Describe the solution you'd like
The function can have an identical signature to the uuid4 function.
e.g. our implementation is:
export function uuid7() {
// Return the hexadecimal text representation of number `n`, padded with zeroes to be of length `p`
const ho = (n: number, p: number) => n.toString(16).padStart(p, '0')
// Get current timestamp in milliseconds since Unix epoch
const msecs = Date.now()
// Create a view backed by a 16-byte buffer
const view = new DataView(new ArrayBuffer(16))
// byte 0-5: timestamp (48 bits)
// DataView only allows setting bits in 8, 16, 32, 64 increments, so set using 32 + 16 chunks.
view.setUint32(0, Math.floor(msecs / 0x10000))
view.setUint16(4, msecs & 0xffff)
// byte 6-7: version (4 bits, 0x7) + random (12 bits)
view.setUint16(6, (0x7 << 12) | ((Math.random() * 0x1000) >>> 0))
// byte 8-9: variant (2 bits, we always use 0x2) + random (14 bits)
view.setUint16(8, (0x2 << 14) | (((Math.random() * 0x100000) >>> 0) & 0x3fff))
// bytes 10-15: random (48 bits)
view.setUint32(10, (Math.random() * 0x100000000) >>> 0)
view.setUint16(14, (Math.random() * 0x10000) >>> 0)
// Compile the canonical textual form from the array data
return `${ho(view.getUint32(0), 8)}-${ho(view.getUint16(4), 4)}-${ho(view.getUint16(6), 4)}-${ho(
view.getUint16(8),
4,
)}-${ho(view.getUint32(10), 8)}${ho(view.getUint16(14), 4)}`
}
Additional context
Metadata
Metadata
Assignees
Labels
enhancementNew feature or requestNew feature or request