Float deadlines and lazy delete

Time.now.to_f returns wall-clock seconds as a Float. Easy to inspect. For production code, prefer Process.clock_gettime(Process::CLOCK_MONOTONIC) which is immune to NTP jumps.

04-expiry/server.rb
ruby
$expires = {}

# Caller must hold $mu.
def check_expired_locked!(key)
  ts = $expires[key]
  return false unless ts
  if Time.now.to_f >= ts
    $store.delete(key)
    $expires.delete(key)
    return true
  end
  false
end

sidecar $expires Hash. check_expired_locked! is a Bang-method - the ! flags that it mutates.

Ruby convention: ! flags methods that mutate. Array#sort returns a sorted copy; Array#sort! mutates in place. check_expired_locked! mutates both $store and $expires when the key has expired, so the bang signals to the reader that this read can also delete.

04-expiry/server.rb
ruby
def parse_set_options(rest)
  i = 2; ttl_sec = nil
  while i < rest.size
    case rest[i].upcase
    when 'EX' then ttl_sec = rest[i + 1].to_i.to_f; i += 2
    when 'PX' then ttl_sec = rest[i + 1].to_i / 1000.0; i += 2
    else return [nil, "ERR syntax"]
    end
  end
  [ttl_sec, nil]
end

SET ... EX N parses the option. Returns the TTL in seconds (Float).

Quiz: Quiz

Loading practice…