Class: FiberJob::JID
- Inherits:
-
Object
- Object
- FiberJob::JID
- Defined in:
- lib/fiber_job/jid.rb
Overview
JID (Job ID) generation utilities for unique job identification. Provides methods to generate unique, sortable, and URL-safe job identifiers that can be used for tracking, logging, and job management operations.
Constant Summary collapse
- ENCODING =
Base32 alphabet for ULID encoding (Crockford’s Base32) Excludes ambiguous characters: 0, 1, I, L, O, U
'0123456789ABCDEFGHJKMNPQRSTVWXYZ'- TIMESTAMP_LENGTH =
Length of the timestamp component in the JID (10 characters)
10- RANDOM_LENGTH =
Length of the random component in the JID (16 characters)
16- TOTAL_LENGTH =
Total length of a JID
TIMESTAMP_LENGTH + RANDOM_LENGTH
Class Method Summary collapse
-
.generate(time = nil) ⇒ String
Generates a new unique Job ID (JID).
-
.generate_batch(count, time = nil) ⇒ Array<String>
Generates a batch of unique JIDs efficiently.
-
.timestamp(jid) ⇒ Time
Extracts the timestamp from a JID.
-
.valid?(jid) ⇒ Boolean
Validates JID format.
Class Method Details
.generate(time = nil) ⇒ String
Generates a new unique Job ID (JID).
JIDs are 26-character strings that combine:
-
10-character timestamp component (millisecond precision)
-
16-character random component
This format ensures:
-
Lexicographical sortability by creation time
-
URL-safe characters only
-
Extremely low collision probability
-
Easy visual identification
58 59 60 61 62 63 64 65 66 67 68 69 |
# File 'lib/fiber_job/jid.rb', line 58 def generate(time = nil) time ||= Time.now = (time.to_f * 1000).to_i # Encode timestamp as 10-character base32 string = () # Generate 16-character random component random_part = encode_random(16) "#{}#{random_part}" end |
.generate_batch(count, time = nil) ⇒ Array<String>
Generates a batch of unique JIDs efficiently. Ensures no duplicates within the batch by incrementing timestamp microseconds when necessary.
124 125 126 127 128 129 130 131 132 133 134 135 |
# File 'lib/fiber_job/jid.rb', line 124 def generate_batch(count, time = nil) base_time = time || Time.now jids = [] count.times do |i| # Ensure uniqueness by adding microseconds offset jid_time = Time.at(base_time.to_f + (i * 0.001)) jids << generate(jid_time) end jids end |
.timestamp(jid) ⇒ Time
Extracts the timestamp from a JID.
81 82 83 84 85 86 87 88 |
# File 'lib/fiber_job/jid.rb', line 81 def (jid) validate_format!(jid) = jid[0, TIMESTAMP_LENGTH] = () Time.at( / 1000.0) end |
.valid?(jid) ⇒ Boolean
Validates JID format.
98 99 100 101 102 103 104 105 106 107 108 109 110 111 |
# File 'lib/fiber_job/jid.rb', line 98 def valid?(jid) return false unless jid.is_a?(String) return false unless jid.length == TOTAL_LENGTH return false unless jid.match?(/\A[#{ENCODING}]+\z/) # Additional validation: timestamp should be reasonable begin ts = (jid) # JID timestamp should be within reasonable bounds ts > Time.new(2020, 1, 1) && ts < Time.now + 86400 # Not more than 1 day in future rescue ArgumentError false end end |