Skip to content

Prevent broadcasting old messages when new channels are subscribed - #67

Merged
npezza93 merged 1 commit into
mainfrom
wip
Jun 21, 2025
Merged

npezza93 merged 1 commit into
mainfrom
wip

Conversation

@npezza93

@npezza93 npezza93 commented Jun 21, 2025 •

Copy link
Copy Markdown
Collaborator

Fixes #65

@npezza93
npezza93 merged commit cb4f5eb into main Jun 21, 2025
@npezza93
npezza93 deleted the wip branch June 21, 2025 14:52
each do |message|
broadcast(message.channel, message.payload)
self.last_id = message.id
if channels[message.channel].present? && channels[message.channel] < message.id

@tbuehlmann tbuehlmann Jun 22, 2025 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@npezza93: I still think there are some race conditions present here. The other thread can call channels.delete(channel) in several places:

  1. Between channels.keys and channels.values.min at ::SolidCable::Message.broadcastable(channels.keys, channels.values.min), resulting in.. not sure. :)
  2. Between channels[message.channel].present? and channels[message.channel] < message.id, resulting in a NoMethodError
  3. 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
end

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

New subscribers receiving old messages

2 participants