@@ -8,6 +8,7 @@ def initialize(client, resource_name, reconcile_timeout: 15 * 60, logger: nil)
88 @logger = logger
99 @cache = nil
1010 @started = nil
11+ @stopped = false
1112 @watching = [ ]
1213 end
1314
@@ -21,22 +22,34 @@ def watch(&block)
2122
2223 # not implicit so users know they have to `stop`
2324 def start_worker
25+ @stopped = false
2426 @worker = Thread . new do
2527 loop do
26- fill_cache
27- watch_to_update_cache
28- rescue StandardError => e
29- # need to keep retrying since we work in the background
30- @logger &.error ( "ignoring error during background work #{ e } " )
31- ensure
32- sleep ( 1 ) # do not overwhelm the api-server if we are somehow broken
28+ begin
29+ fill_cache
30+ watch_to_update_cache
31+ rescue StandardError => e
32+ # need to keep retrying since we work in the background
33+ @logger &.error ( "ignoring error during background work #{ e } " )
34+ ensure
35+ sleep ( 1 ) # do not overwhelm the api-server if we are somehow broken
36+ end
37+ break if @stopped
3338 end
3439 end
35- sleep ( 0.01 ) until @cache
40+ sleep ( 0.01 ) until @cache || @stopped
3641 end
3742
3843 def stop_worker
39- @worker &.kill # TODO: be nicer ?
44+ @stopped = true
45+ [ @waiter , @worker ] . compact . each do |thread |
46+ begin
47+ thread . run # cancel sleep so either the loop sleep or the timeout sleep are interrupted
48+ rescue ThreadError
49+ # thread was already dead
50+ end
51+ thread . join
52+ end
4053 end
4154
4255 private
@@ -69,7 +82,7 @@ def watch_to_update_cache
6982 stop_reason = 'disconnect'
7083
7184 # stop watcher without using timeout
72- Thread . new do
85+ @waiter = Thread . new do
7386 sleep ( @reconcile_timeout )
7487 stop_reason = 'reconcile'
7588 @watcher . finish
@@ -88,6 +101,13 @@ def watch_to_update_cache
88101 @watching . each { |q | q << notice }
89102 end
90103 @logger &.info ( "watch restarted: #{ stop_reason } " )
104+
105+ # wake the waiter unless it's dead so it does not hang around
106+ begin
107+ @waiter . run
108+ rescue ThreadError # rubocop:disable Lint/SuppressedException
109+ end
110+ @waiter . join
91111 end
92112 end
93113end
0 commit comments