TL;DR: Rails-server restarts aren't handled gracefully in Action Cable, resulting in corrupted state. How to fix that?
I run a Rails server which uses Action Cable, among other things.
When I change a file, the server restarts as expected. But it doesn't exactly restart gracefully.
The Action Cable connection logs {"type":"disconnect","reason":"server_restart","reconnect":true}
in the established socket. Then the socket appears to be cut and my channel's unsubscribed
method does not run. Upon reconnect, however, the subscribed
method does run—as it should, but now we have an asymmetry. Something as simple as keeping track of the number of connected clients has become unreliable because upon a server restart that number will now double although the true number remained the same. That's because it gets to increment the count when subscribed
is called, but decrementing the counter happens in unsubscribed
, which is not called when the server restarts.
If this only happened in development, it wouldn't be a huge issue, but it happens in production as well during server restarts caused by deployments.
How do I tell Rails to restart the server gracefully, by which I mean it should also run the unsubscribed
method in my channel instead of just cutting the connection?
EDIT: I've also filed an issue with Rails: https://github.com/rails/rails/issues/41005
question from:
https://stackoverflow.com/questions/65557765/how-to-restart-a-rails-server-gracefully 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…