Repository navigation
Conversation
| each do |message| | ||
| broadcast(message.channel, message.payload) | ||
| self.last_id = message.id | ||
| if channels[message.channel].present? && channels[message.channel] < message.id |
There was a problem hiding this comment.
@npezza93: I still think there are some race conditions present here. The other thread can call channels.delete(channel) in several places:
- Between
channels.keysandchannels.values.minat::SolidCable::Message.broadcastable(channels.keys, channels.values.min), resulting in.. not sure. :) - Between
channels[message.channel].present?andchannels[message.channel] < message.id, resulting in aNoMethodError - Before
channels[message.channel] = message.id, resulting in the channel staying in the Hash even if it should be gone, leaking.
Using Concurrent::Hash doesn't help here unfortunately as the if block is no single atomic operation. I think we should wrap a Mutex around the shared variable uses, but we can get rid of 2. and 3. by using a Concurrent::Map instead if that seems like a better solution to you. Like this:
def channels
@channels ||= Concurrent::Map.new
end
def broadcast_messages
::SolidCable::Message.broadcastable(channels.keys, channels.values.min).each do |message|
channels.compute_if_present(message.channel) do |last_id|
break if last_id >= message.id
broadcast(message.channel, message.payload)
message.id
end
end
endThere was a problem hiding this comment.
Good call on Concurrent::Map and compute_if_present(message.channel) is neat, thanks for the call out. I was trying to avoid using an explicit mutex and looking at concurrent it seems they favor Map over Hash. And I think for point 1, if we dup the hash to get the current state there shouldn't be a discrepancy between the two. But to be fair if channels.values.min changes and results in nothing the scope will coerce it to 0 which is fine.
Let me know what you think of #68
Fixes #65