nats-io / nats-pure.rb

Ruby client for NATS, the cloud native messaging system.
https://nats.io
Apache License 2.0
131 stars 30 forks source link

Fix annoying after_fork error messages in specs (in Ruby 3.3+) #128

Closed Envek closed 1 year ago

Envek commented 1 year ago

Amends https://github.com/nats-io/nats-pure.rb/pull/114

The problem:

When running full test suite, there is a lot of messages like this:

nats: Error during handling after_fork callback: Connection refused - connect(2) for 127.0.0.1:4243
nats: Error during handling after_fork callback: Connection refused - connect(2) for 127.0.0.1:4242

This is because fork detection feature tracks instances of NATS::Client in a weak reference map.

However, as one-off client instances are made for every test case, they are generally not garbage collected in time (GC doesn't make any guarantees on when stale objects will be removed)

Because of this, there are a lot of stale instances are accumulated in this map at the moment when specs/client_fork_spec.rb starts to execute, and all of them are trying to re-connect after fork.

The solution

On upcoming Ruby 3.3 (where ObjectSpace::WeakMap#delete method was added recently) clean this weak map before running fork-specific tests. It removes these annoying messages competely.

On previous Rubies (3.2 and older) just ask garbage collector to run and clean unused client instances, which somewhat reduces number of messages (around 2x from ≈20 to ≈10) but doesn't get rid from them completely.

wallyqs commented 1 year ago

Confirmed locally so merging, (need to fix the ruby 3.3 preview build... 🤔 )