<commit_before>require 'singleton'

#
# Stores WebSocket connections and associates them
# with the device's hardware ID
#
class ConnectionHandler
  include Singleton

  def connection_opened( socket, device_id )
    Rails.logger.info "Connected: socket id: #{socket_id(socket)}, device id: #{device_id}"
    
    DeviceConnection.new( device_id, socket )
  end

  def on_message( socket, event )
    Rails.logger.info "Received: #{event.data.inspect}"
    # TODO add rescue and logging
    connection = DeviceConnection.find_by_socket socket
    ProtobufMessages::Handler.handle( event.data, connection )
  end

  def close_connection( socket, event )
    Rails.logger.info [:close, socket_id(socket), event.code, event.reason]

    connection = DeviceConnection.find_by_socket socket
    connection.delete
  end
  
  private

  def socket_id( socket )
    socket.object_id.to_s
  end
end

<commit_msg>Check if the connection is valid before deleting it.<commit_after>require 'singleton'

#
# Stores WebSocket connections and associates them
# with the device's hardware ID
#
class ConnectionHandler
  include Singleton

  def connection_opened( socket, device_id )
    Rails.logger.info "Connected: socket id: #{socket_id(socket)}, device id: #{device_id}"
    
    DeviceConnection.new( device_id, socket )
  end

  def on_message( socket, event )
    Rails.logger.info "Received: #{event.data.inspect}"
    # TODO add rescue and logging
    connection = DeviceConnection.find_by_socket socket
    ProtobufMessages::Handler.handle( event.data, connection )
  end

  def close_connection( socket, event )
    Rails.logger.info [:close, socket_id(socket), event.code, event.reason]

    connection = DeviceConnection.find_by_socket socket
    connection.delete if connection
  end
  
  private

  def socket_id( socket )
    socket.object_id.to_s
  end
end


{'fraction_non_alphanumeric': 0.0844540075309306, 'fraction_numerical': 0.0, 'mean_word_length': 4.027027027027027, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, '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': '1188035', 'n_tokens_mistral': 562, 'n_tokens_neox': 539, 'n_words': 156}