<commit_before>require "redic/connection"
require "uri"

class Redic
  class Client
    def initialize(url)
      @uri = URI.parse(url)
      @ttl = Integer(ENV.fetch("REDIC_TTL", 60))
      @connection = nil
      @semaphore = Mutex.new
    end

    def read
      @connection.read
    end

    def write(command)
      @connection.write(command)
    end

    def connect
      establish_connection unless connected?

      @semaphore.synchronize do
        yield
      end
    end

  private
    def establish_connection
      begin
        @connection = Redic::Connection.new(@uri)
        @timestamp = Time.now.to_i
      rescue StandardError => err
        raise err, "Can't connect to: %s" % @uri
      end

      authenticate
    end

    def authenticate
      if @uri.password
        @semaphore.synchronize do
          write [:auth, @uri.password]
          read
        end
      end
    end

    def connected?
      @connection && @connection.connected? && alive?
    end

    def alive?
      Time.now.to_i - @timestamp < @ttl
    end
  end
end<commit_msg>Timestamp the connection after each successful attempt.<commit_after>require "redic/connection"
require "uri"

class Redic
  class Client
    def initialize(url)
      @uri = URI.parse(url)
      @ttl = Integer(ENV.fetch("REDIC_TTL", 60))
      @connection = nil
      @semaphore = Mutex.new
    end

    def read
      @connection.read
    end

    def write(command)
      @connection.write(command)
    end

    def connect
      establish_connection unless connected?
      timestamp_connection

      @semaphore.synchronize do
        yield
      end
    end

  private
    def establish_connection
      begin
        @connection = Redic::Connection.new(@uri)
      rescue StandardError => err
        raise err, "Can't connect to: %s" % @uri
      end

      authenticate
    end

    def timestamp_connection
      @timestamp = Time.now.to_i
    end

    def authenticate
      if @uri.password
        @semaphore.synchronize do
          write [:auth, @uri.password]
          read
        end
      end
    end

    def connected?
      @connection && @connection.connected? && alive?
    end

    def alive?
      Time.now.to_i - @timestamp < @ttl
    end
  end
end
{'fraction_non_alphanumeric': 0.08055184690698709, 'fraction_numerical': 0.0017801513128615932, 'mean_word_length': 1.9853917662682603, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4968451', 'n_tokens_mistral': 696, 'n_tokens_neox': 668, 'n_words': 181}