Skip to content

Instantly share code, notes, and snippets.

@stephenprater
Last active March 14, 2018 23:36
Show Gist options
  • Save stephenprater/8b0be50412085757a2bad1bc62d1ee73 to your computer and use it in GitHub Desktop.
Save stephenprater/8b0be50412085757a2bad1bc62d1ee73 to your computer and use it in GitHub Desktop.
require 'stan/client'
require 'monitor'
require 'thread'
class MinimalTest
def initialize
@queue = Queue.new
@subscriptions = []
end
def subscribe_to_stan(durable)
@subscriptions << stan.subscribe('test.nats', queue: 'goldstar', durable_name: durable) do |payload|
STDOUT.puts("got test.nats #{payload} #{durable}")
end
end
def publish_to_stan
@count ||= 0
@count += 1
STDOUT.puts("publishing")
stan.publish('test.nats', @count.to_s)
end
def unsubscriber
STDOUT.puts("setting up unsubscriber")
stan.nats.subscribe("unsubscribe_all.goldstar") do
STDOUT.puts("unsubscribing")
@queue.push(@subscription)
end
end
def execute
loop do
publish_to_stan
sleep 2
end
end
def unsubscribe_thread
STDOUT.puts('running thread')
Thread.new do
subscription = @queue.pop
subscription.close
end
end
def stan
return @stan if @stan
@stan = STAN::Client.new.tap do |client|
client.connect('gse_cluster', 'stan_test', nats: {
servers: ['nats://0.0.0.0:4222']
})
client.nats.on_error do |e|
STDOUT.puts("NATS ERROR #{e}")
STDOUT.puts(e.backtrace)
end
at_exit do
client.close
end
end
end
end
MinimalTest.new.tap do |m|
m.unsubscriber
m.unsubscribe_thread
m.subscribe_to_stan('durable1')
m.execute
end
@stephenprater
Copy link
Author

doesn't actually event require two subscriptions - a single subscription is enough to demonstrate the issue.

@stephenprater
Copy link
Author

Turns out the trick is to unsubscribe from a different thread. You can communicate which subscriptions objects should be unsubscribed over a Queue.

@wallyqs
Copy link

wallyqs commented Mar 14, 2018

@stephenprater Thanks for sharing, fixing the issue in the client now here: nats-io/nats-pure.rb#27

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