Skip to content

Commit

Permalink
Moving the redis pinger logic so when the cable server shuts down, th…
Browse files Browse the repository at this point in the history
…e redis pinger doesn't leak memory and can be closed properly
  • Loading branch information
jwoertink committed Oct 5, 2022
1 parent 43dd234 commit 6b11799
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 20 deletions.
1 change: 0 additions & 1 deletion src/cable/handler.cr
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@ module Cable
# Send welcome message to the client
socket.send({type: Cable.message(:welcome)}.to_json)

Cable::RedisPinger.start(Cable.server)
ws_pinger = Cable::WebsocketPinger.build(socket)

socket.on_ping do
Expand Down
25 changes: 6 additions & 19 deletions src/cable/redis_pinger.cr
Original file line number Diff line number Diff line change
@@ -1,26 +1,9 @@
module Cable
class RedisPinger
@@started : Bool = false
class_getter interval : Time::Span = Cable.settings.redis_ping_interval

def self.run_every(value : Time::Span)
@@interval = value

yield

@@interval = Cable.settings.redis_ping_interval
end

def self.start(server : Cable::Server)
new(server).start unless @@started
@@started = true
end
private getter task : Tasker::Task

def initialize(@server : Cable::Server)
end

def start
Tasker.every(Cable::RedisPinger.interval) do
@task = Tasker.every(Cable.settings.redis_ping_interval) do
check_redis_subscribe
check_redis_publish
rescue e
Expand All @@ -29,6 +12,10 @@ module Cable
end
end

def stop
@task.cancel
end

# since @server.redis_subscribe connection is called on a block loop
# we basically cannot call ping outside of the block
# instead, we just spin up another new redis connection
Expand Down
4 changes: 4 additions & 0 deletions src/cable/server.cr
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,9 @@ module Cable
# Use a single connection
getter redis_subscribe = Redis::Connection.new(URI.parse(Cable.settings.url))
getter fiber_channel = ::Channel({String, String}).new
getter pinger : Cable::RedisPinger do
Cable::RedisPinger.new(self)
end

@channels = {} of String => Channels
@channel_mutex = Mutex.new
Expand Down Expand Up @@ -114,6 +117,7 @@ module Cable
# the @writer IO is closed already
Cable::Logger.debug { "Cable::Server#shutdown Connection to redis was severed: #{e.message}" }
end
pinger.stop
redis_subscribe.close
redis_publish.close
connections.each do |_, v|
Expand Down

0 comments on commit 6b11799

Please sign in to comment.