Class: Protobuf::Nats::UUIDv7Helper

Inherits:
Object
  • Object
show all
Defined in:
lib/protobuf/nats/uuidv7_helper.rb

Class Method Summary collapse

Class Method Details

.age_in_seconds(uuid, current_time: Time.now) ⇒ Float?

Calculate the age of a UUIDv7 in seconds Returns nil if the UUID cannot be parsed

Parameters:

  • uuid (String)

    A UUIDv7 string

  • current_time (Time) (defaults to: Time.now)

    The time to compare against (defaults to Time.now)

Returns:

  • (Float, nil)

    The age in seconds, or nil if parsing fails



29
30
31
32
33
34
# File 'lib/protobuf/nats/uuidv7_helper.rb', line 29

def self.age_in_seconds(uuid, current_time: Time.now)
  timestamp = extract_timestamp(uuid)
  return nil unless timestamp

  current_time - timestamp
end

.extract_timestamp(uuid) ⇒ Time?

Extract the Unix timestamp (in seconds) from a UUIDv7 string Returns nil if the UUID cannot be parsed

Parameters:

  • uuid (String)

    A UUIDv7 string (e.g., “01234567-89ab-7def-0123-456789abcdef”)

Returns:

  • (Time, nil)

    The timestamp embedded in the UUID, or nil if parsing fails



9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/protobuf/nats/uuidv7_helper.rb', line 9

def self.extract_timestamp(uuid)
  return nil unless uuid.is_a?(String)

  # UUIDv7 format: first 48 bits (12 hex chars) are Unix timestamp in milliseconds
  # Remove dashes and extract the timestamp portion
  uuid_bytes = uuid.gsub('-', '')
  return nil if uuid_bytes.length < 12

  timestamp_ms = uuid_bytes[0...12].to_i(16)
  Time.at(timestamp_ms / 1000.0)
rescue => e
  nil
end