beaneater 1.3.1 → 1.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,749 +0,0 @@
1
- # frozen_string_literal: true
2
-
3
- # test/connection_test.rb
4
-
5
- require File.expand_path('../test_helper', __FILE__)
6
-
7
- describe Beaneater::Connection do
8
-
9
- describe 'for #new' do
10
- before do
11
- @host = 'localhost'
12
- @bc = Beaneater::Connection.new(@host)
13
- end
14
-
15
- it "should store address, host and port" do
16
- assert_equal 'localhost', @bc.address
17
- assert_equal 'localhost', @bc.host
18
- assert_equal 11300, @bc.port
19
- end
20
-
21
- it "should init connection" do
22
- assert_kind_of TCPSocket, @bc.connection
23
- if @bc.connection.peeraddr[0] == 'AF_INET'
24
- assert_equal '127.0.0.1', @bc.connection.peeraddr[3]
25
- else
26
- assert_equal 'AF_INET6', @bc.connection.peeraddr[0]
27
- assert_equal '::1', @bc.connection.peeraddr[3]
28
- end
29
- assert_equal 11300, @bc.connection.peeraddr[1]
30
- end
31
-
32
- it "should raise on invalid connection" do
33
- error = assert_raises(Beaneater::NotConnected) { Beaneater::Connection.new("localhost:8544") }
34
- assert_equal "Connection to beanstalk 'localhost:8544' is closed!", error.message
35
- end
36
-
37
- it "should leave the user and password out of the address it names" do
38
- { 'user:secret@127.0.0.1:1' => '127.0.0.1:1',
39
- 'beanstalk://user:secret@127.0.0.1:11300' => 'beanstalk://127.0.0.1:11300',
40
- 'user@localhost:8544' => 'localhost:8544' }.each do |address, shown|
41
- error = assert_raises(Beaneater::NotConnected) { Beaneater::Connection.new(address) }
42
- assert_equal "Connection to beanstalk '#{shown}' is closed!", error.message
43
- end
44
- end
45
-
46
- it "should name an address it can't parse as given" do
47
- ['[::1]:11300', '::1', 'beanstalk://127.0.0.1:11300'].each do |address|
48
- error = assert_raises(Beaneater::NotConnected) { Beaneater::Connection.new(address) }
49
- assert_equal "Connection to beanstalk '#{address}' is closed!", error.message
50
- end
51
- end
52
-
53
- it "should support array connection to single connection" do
54
- @bc2 = Beaneater::Connection.new([@host])
55
- assert_equal 'localhost', @bc.address
56
- assert_equal 'localhost', @bc.host
57
- assert_equal 11300, @bc.port
58
- end
59
- end # new
60
-
61
- describe 'for timeout configuration' do
62
- after do
63
- Beaneater.configure do |config|
64
- config.connect_timeout = nil
65
- config.resolv_timeout = nil
66
- config.read_timeout = nil
67
- config.write_timeout = nil
68
- end
69
- end
70
-
71
- it "should pass connect_timeout and resolv_timeout to TCPSocket.new on Ruby >= 3.0" do
72
- skip("connect_timeout/resolv_timeout kwargs require Ruby >= 3.0") if RUBY_VERSION < "3.0"
73
-
74
- Beaneater.configure do |config|
75
- config.connect_timeout = 2
76
- config.resolv_timeout = 2
77
- end
78
-
79
- real_socket = TCPSocket.new('localhost', 11300)
80
- TCPSocket.expects(:new).with('localhost', 11300, connect_timeout: 2, resolv_timeout: 2).returns(real_socket)
81
-
82
- bc = Beaneater::Connection.new('localhost')
83
- assert_kind_of TCPSocket, bc.connection
84
- end
85
-
86
- it "should ignore connect_timeout and resolv_timeout on Ruby < 3.0" do
87
- skip("connect_timeout/resolv_timeout kwargs are supported on Ruby >= 3.0") if RUBY_VERSION >= "3.0"
88
-
89
- Beaneater.configure do |config|
90
- config.connect_timeout = 2
91
- config.resolv_timeout = 4
92
- end
93
-
94
- real_socket = TCPSocket.new('localhost', 11300)
95
- TCPSocket.expects(:new).with('localhost', 11300).returns(real_socket)
96
-
97
- bc = Beaneater::Connection.new('localhost')
98
- assert_same real_socket, bc.connection
99
- end
100
-
101
- # A server that accepts connections and then neither reads nor replies.
102
- def with_silent_server
103
- server = TCPServer.new('127.0.0.1', 0)
104
- clients = []
105
- acceptor = Thread.new { loop { clients << server.accept } }
106
- yield "127.0.0.1:#{server.addr[1]}", clients
107
- ensure
108
- acceptor.kill if acceptor
109
- clients.each(&:close)
110
- server.close if server
111
- end
112
-
113
- def elapsed
114
- started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
115
- yield
116
- Process.clock_gettime(Process::CLOCK_MONOTONIC) - started
117
- end
118
-
119
- it "should raise SocketTimeout and drop the connection when no reply arrives within read_timeout" do
120
- Beaneater.configure { |config| config.read_timeout = 0.5 }
121
- with_silent_server do |address, clients|
122
- bc = Beaneater::Connection.new(address)
123
- time = elapsed do
124
- assert_raises(Beaneater::SocketTimeout) { Timeout.timeout(5) { bc.transmit('stats') } }
125
- end
126
- assert_in_delta 0.5, time, 0.4
127
- assert_nil bc.connection
128
- # the next command opens a new connection rather than reading the late reply
129
- assert_raises(Beaneater::SocketTimeout) { Timeout.timeout(5) { bc.transmit('stats') } }
130
- assert_equal 2, clients.size
131
- end
132
- end
133
-
134
- it "should raise SocketTimeout when a command cannot be written within write_timeout" do
135
- Beaneater.configure { |config| config.write_timeout = 0.5 }
136
- with_silent_server do |address|
137
- bc = Beaneater::Connection.new(address)
138
- body = 'x' * (64 * 1024 * 1024) # more than the socket buffers hold
139
- time = elapsed do
140
- assert_raises(Beaneater::SocketTimeout) do
141
- Timeout.timeout(5) { bc.transmit("put 0 0 100 #{body.bytesize}\r\n#{body}") }
142
- end
143
- end
144
- assert_operator time, :<, 2
145
- assert_nil bc.connection
146
- end
147
- end
148
-
149
- it "should accept timeouts given as numeric strings" do
150
- Beaneater.configure do |config|
151
- config.read_timeout = '0.5'
152
- config.write_timeout = '0.5'
153
- end
154
- with_silent_server do |address|
155
- bc = Beaneater::Connection.new(address)
156
- assert_raises(Beaneater::SocketTimeout) { Timeout.timeout(5) { bc.transmit('stats') } }
157
- end
158
- end
159
-
160
- it "should read a reply that is already there when the deadline has passed" do
161
- Beaneater.configure { |config| config.read_timeout = 0 }
162
- server = TCPServer.new('127.0.0.1', 0)
163
- # answers before the command arrives, so the reply is waiting when the client polls
164
- responder = Thread.new { peer = server.accept; peer.write("USING eager\r\n"); peer }
165
- bc = Beaneater::Connection.new("127.0.0.1:#{server.addr[1]}")
166
- peer = responder.value
167
- sleep 0.2
168
- res = bc.transmit('use eager')
169
- assert_equal 'USING', res[:status]
170
- assert_equal 'eager', res[:id]
171
- ensure
172
- peer.close if peer
173
- server.close if server
174
- end
175
-
176
- it "should wait reserve-with-timeout's own timeout on top of read_timeout" do
177
- Beaneater.configure { |config| config.read_timeout = 0.5 }
178
- client = Beaneater.new('localhost')
179
- client.tubes.watch!('read_timeout_empty')
180
- time = elapsed do
181
- assert_raises(Beaneater::TimedOutError) { client.tubes.reserve(1) }
182
- end
183
- assert_operator time, :>=, 0.9
184
- assert client.connection.connection, "connection should stay open"
185
- client.close
186
- end
187
-
188
- it "should not cut off a plain reserve with read_timeout" do
189
- Beaneater.configure { |config| config.read_timeout = 0.5 }
190
- client = Beaneater.new('localhost')
191
- client.tubes.watch!('read_timeout_reserve')
192
- producer = Thread.new do
193
- sleep 1
194
- Beaneater.new('localhost').tubes['read_timeout_reserve'].put('late')
195
- end
196
- job = nil
197
- time = elapsed { job = Timeout.timeout(5) { client.tubes.reserve } }
198
- assert_equal 'late', job.body
199
- assert_operator time, :>=, 0.9
200
- job.delete
201
- producer.join
202
- client.close
203
- end
204
-
205
- end # timeout configuration
206
-
207
- describe 'for #transmit' do
208
- before do
209
- @host = 'localhost'
210
- @bc = Beaneater::Connection.new(@host)
211
- end
212
-
213
- it "should return yaml loaded response" do
214
- res = @bc.transmit 'stats'
215
- refute_nil res[:body]['current-connections']
216
- assert_equal 'OK', res[:status]
217
- end
218
-
219
- it "should keep the types of stats values without mangling them" do
220
- @bc.transmit "use stats-tube.1"
221
- id = @bc.transmit("put 0 0 100 1\r\nX")[:id]
222
- tube = @bc.transmit('stats-tube stats-tube.1')[:body]
223
- assert_equal 'stats-tube.1', tube['name']
224
- assert_equal 1, tube['current-jobs-ready']
225
-
226
- stats = @bc.transmit('stats')[:body]
227
- assert_kind_of Integer, stats['current-connections']
228
- assert_kind_of Float, stats['rusage-utime']
229
- assert_kind_of String, stats['version']
230
- assert_kind_of String, stats['hostname']
231
- assert_equal false, stats['draining']
232
- ensure
233
- @bc.transmit "delete #{id}" if id
234
- @bc.transmit "use default"
235
- end
236
-
237
- it "should return id" do
238
- res = @bc.transmit "put 0 0 100 1\r\nX"
239
- assert res[:id]
240
- assert_equal 'INSERTED', res[:status]
241
- end
242
-
243
- it "should support dashes in response" do
244
- res = @bc.transmit "use foo-bar\r\n"
245
- assert_equal 'USING', res[:status]
246
- assert_equal 'foo-bar', res[:id]
247
- end
248
-
249
- it "should pass crlf through without changing its length" do
250
- res = @bc.transmit "put 0 0 100 2\r\n\r\n"
251
- assert_equal 'INSERTED', res[:status]
252
- end
253
-
254
- it "should handle *any* byte value without changing length" do
255
- res = @bc.transmit "put 0 0 100 256\r\n"+(0..255).to_a.pack("c*")
256
- assert_equal 'INSERTED', res[:status]
257
- end
258
-
259
- it "should retry command with success after one connection failure" do
260
- TCPSocket.any_instance.expects(:readpartial).times(2).
261
- raises(EOFError.new).then.
262
- returns("DELETED 56\r\n")
263
-
264
- res = @bc.transmit "delete 56\r\n"
265
- assert_equal 'DELETED', res[:status]
266
- end
267
-
268
- it "should fail after exceeding retries with DrainingError" do
269
- TCPSocket.any_instance.expects(:readpartial).times(3).
270
- raises(Beaneater::UnexpectedResponse.from_status("DRAINING", "delete 56"))
271
-
272
- assert_raises(Beaneater::DrainingError) { @bc.transmit "delete 56\r\n" }
273
- end
274
-
275
- it "should fail after exceeding reconnect max retries" do
276
- # next connection attempts should fail
277
- TCPSocket.stubs(:new).times(3).raises(Errno::ECONNREFUSED.new)
278
- TCPSocket.any_instance.stubs(:readpartial).times(1).raises(EOFError.new)
279
-
280
- assert_raises(Beaneater::NotConnected) { @bc.transmit "delete 56\r\n" }
281
- end
282
-
283
- it "tubes_watched are restored after reconnect" do
284
- client = Beaneater.new('127.0.0.1:11300')
285
- client.tubes.watch! "another"
286
- socket = client.connection.connection
287
- socket.expects(:readpartial).once.raises(EOFError.new) # this socket only
288
-
289
- assert_equal %w[another], client.tubes.watched.map(&:name)
290
- refute_same socket, client.connection.connection
291
- ensure
292
- client.close if client
293
- end
294
-
295
- it "should raise NotConnected when reconnecting fails with any connect error" do
296
- TCPSocket.stubs(:new).raises(Errno::EHOSTUNREACH.new)
297
- TCPSocket.any_instance.stubs(:readpartial).raises(EOFError.new)
298
-
299
- assert_raises(Beaneater::NotConnected) { @bc.transmit "stats", retry_interval: 0 }
300
- end
301
-
302
- it "should reconnect on the next command after draining retries ran out" do
303
- TCPSocket.any_instance.stubs(:readpartial).raises(Beaneater::UnexpectedResponse.from_status("DRAINING", "stats"))
304
- assert_raises(Beaneater::DrainingError) { @bc.transmit "stats", retry_interval: 0 }
305
-
306
- TCPSocket.any_instance.unstub(:readpartial)
307
- assert_equal 'OK', @bc.transmit('stats')[:status]
308
- end
309
-
310
- it "should drop the connection when a command is interrupted, so the next command reads its own reply" do
311
- client = Beaneater.new('localhost')
312
- client.tubes.watch!('interrupted')
313
- assert_raises(Timeout::Error) { Timeout.timeout(0.3) { client.tubes.reserve } }
314
-
315
- producer = Beaneater.new('localhost')
316
- producer.tubes.find('interrupted').put('late job')
317
- producer.close
318
- sleep 0.1 # let a reserve still pending on the old socket take the job
319
-
320
- assert_equal %w[interrupted], client.tubes.watched.map(&:name)
321
- job = client.tubes.reserve(1)
322
- assert_equal 'late job', job.body
323
- job.delete
324
- ensure
325
- client.close if client
326
- end
327
-
328
- it "should keep the connection after an error reply" do
329
- socket = @bc.connection
330
- assert_raises(Beaneater::NotFoundError) { @bc.transmit 'peek 4294967295' }
331
- assert_same socket, @bc.connection
332
- end
333
-
334
- it "restores the watched tubes again when the connection drops while restoring them" do
335
- # A minimal beanstalkd that drops the 1st connection on 'stats' and the 2nd on 'ignore'
336
- server = TCPServer.new('127.0.0.1', 0)
337
- accepted = 0
338
- fake = Thread.new do
339
- loop do
340
- sock = server.accept
341
- accepted += 1
342
- Thread.new(sock, accepted) do |peer, n|
343
- watched = ['default']
344
- while (line = peer.gets("\r\n"))
345
- cmd, arg = line.chomp("\r\n").split(' ', 2)
346
- if (n == 1 && cmd == 'stats') || (n == 2 && cmd == 'ignore')
347
- peer.close
348
- break
349
- end
350
- reply = case cmd
351
- when 'watch' then watched |= [arg]; "WATCHING #{watched.size}\r\n"
352
- when 'ignore'
353
- if watched == [arg] then "NOT_IGNORED\r\n"
354
- else watched -= [arg]; "WATCHING #{watched.size}\r\n"
355
- end
356
- when 'list-tubes-watched', 'stats'
357
- body = cmd == 'stats' ? "---\nuptime: 1\n" : "---\n" + watched.map { |t| "- #{t}\n" }.join
358
- "OK #{body.bytesize}\r\n#{body}\r\n"
359
- else "UNKNOWN_COMMAND\r\n"
360
- end
361
- peer.write(reply)
362
- end
363
- end
364
- end
365
- end
366
- client = Beaneater.new("127.0.0.1:#{server.addr[1]}")
367
- client.tubes.watch!('restore-a', 'restore-b')
368
-
369
- assert_equal({ 'uptime' => 1 }, Timeout.timeout(5) { client.connection.transmit('stats', retry_interval: 0)[:body] })
370
- assert_equal %w[restore-a restore-b], client.tubes.watched.map(&:name)
371
- assert_equal 3, accepted
372
- ensure
373
- client.close if client
374
- fake.kill if fake
375
- server.close if server
376
- end
377
-
378
- it "gives up when every new connection is dropped as soon as a command is sent" do
379
- # like a proxy that accepts connections while its backend is down
380
- server = TCPServer.new('127.0.0.1', 0)
381
- accepted = 0
382
- acceptor = Thread.new do
383
- loop do
384
- peer = server.accept
385
- accepted += 1
386
- if accepted == 1
387
- Thread.new(peer) { |p| p.gets("\r\n"); p.write("USING x\r\n"); p.gets("\r\n"); p.close }
388
- else
389
- Thread.new(peer) { |p| p.gets("\r\n"); p.close }
390
- end
391
- end
392
- end
393
- bc = Beaneater::Connection.new("127.0.0.1:#{server.addr[1]}")
394
- assert_equal 'USING', bc.transmit('use x')[:status]
395
- assert_raises(Beaneater::NotConnected) { Timeout.timeout(5) { bc.transmit('stats', retry_interval: 0) } }
396
- assert_operator accepted, :<=, Beaneater::Connection::MAX_RETRIES + 1
397
- ensure
398
- acceptor.kill if acceptor
399
- server.close if server
400
- end
401
-
402
- describe "after the server was down for longer than the reconnect retries" do
403
- before do
404
- @port = free_port
405
- @pid = start_beanstalkd(@port)
406
- @client = Beaneater.new("127.0.0.1:#{@port}")
407
- end
408
-
409
- after do
410
- @client.close if @client
411
- stop_beanstalkd(@pid) if @pid
412
- end
413
-
414
- it "reconnects on the next command and restores the used and watched tubes" do
415
- @client.tubes.watch('reconnect-watched')
416
- @client.tubes.use('reconnect-used')
417
-
418
- stop_beanstalkd(@pid)
419
- assert_raises(Beaneater::NotConnected) do
420
- @client.connection.transmit('list-tubes', retry_interval: 0.01)
421
- end
422
-
423
- @pid = start_beanstalkd(@port)
424
- assert_equal 'reconnect-used', @client.tubes.used.name
425
- assert_equal %w[default reconnect-watched], @client.tubes.watched.map(&:name).sort
426
- end
427
-
428
- it "lets threads sharing the client wait out their reconnect retries side by side" do
429
- stop_beanstalkd(@pid)
430
- now = -> { Process.clock_gettime(Process::CLOCK_MONOTONIC) }
431
- started = now.call
432
- waits = 4.times.map do
433
- Thread.new do
434
- t = now.call
435
- begin
436
- @client.connection.transmit('stats', retry_interval: 0.5)
437
- rescue Beaneater::NotConnected
438
- end
439
- now.call - t
440
- end
441
- end.map(&:value)
442
- # each thread waits out about 1 s of retries; one after another that would be 4 s
443
- assert_operator now.call - started, :<, 2, "waits: #{waits.inspect}"
444
-
445
- @pid = start_beanstalkd(@port)
446
- assert_equal 'OK', @client.connection.transmit('stats')[:status]
447
- end
448
-
449
- it "lets threads sharing the client recover when the server restarts under them" do
450
- @client.tubes.use('restart-used')
451
- stop = false
452
- workers = 2.times.map do |i|
453
- Thread.new do
454
- until stop
455
- begin
456
- i.zero? ? @client.tubes['restart-used'].put('x') : @client.tubes.used
457
- rescue Beaneater::NotConnected, IOError
458
- sleep 0.01
459
- end
460
- end
461
- end
462
- end
463
- 5.times do
464
- sleep 0.3
465
- stop_beanstalkd(@pid)
466
- @pid = start_beanstalkd(@port)
467
- end
468
- sleep 0.3
469
- stop = true
470
- stuck = workers.reject { |t| t.join(5) }
471
- stuck.each(&:kill)
472
- assert_empty stuck, "threads still blocked 5s after the last restart"
473
- assert_equal 'restart-used', Timeout.timeout(5) { @client.tubes.used.name }
474
- end
475
-
476
- it "does not reopen a connection closed while it was reconnecting" do
477
- stop_beanstalkd(@pid)
478
- result = nil
479
- worker = Thread.new do
480
- begin
481
- @client.connection.transmit('stats', retry_interval: 0.5)
482
- result = :answered
483
- rescue Exception => ex
484
- result = ex.class
485
- end
486
- end
487
- sleep 0.2 # the worker is between reconnect attempts
488
- @client.close
489
- @pid = start_beanstalkd(@port)
490
- assert worker.join(5), "worker still running"
491
- assert_equal Beaneater::NotConnected, result
492
- assert_nil @client.connection.connection
493
- end
494
- end
495
-
496
- describe "while the server is draining" do
497
- before do
498
- @port = free_port
499
- @pid = start_beanstalkd(@port)
500
- @client = Beaneater.new("127.0.0.1:#{@port}")
501
- end
502
-
503
- after do
504
- @client.close if @client
505
- stop_beanstalkd(@pid) if @pid
506
- end
507
-
508
- it "lets threads sharing the client wait out their draining retries side by side" do
509
- Process.kill('USR1', @pid) # beanstalkd answers DRAINING to put from now on
510
- sleep 0.2
511
- started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
512
- errors = 4.times.map do
513
- Thread.new do
514
- begin
515
- @client.connection.transmit("put 0 0 100 1\r\nx", retry_interval: 0.3)
516
- rescue Beaneater::DrainingError => ex
517
- ex.class
518
- end
519
- end
520
- end.map(&:value)
521
- assert_equal [Beaneater::DrainingError] * 4, errors
522
- # each put waits 2 x 0.3 s between its tries; one after another that would be 2.4 s
523
- assert_operator Process.clock_gettime(Process::CLOCK_MONOTONIC) - started, :<, 1.5
524
- end
525
-
526
- it "lets Timeout stop a command pausing between retries while another thread holds the client" do
527
- @client.tubes.find('slow-parse').put('slow')
528
- @client.tubes.watch!('slow-parse')
529
- Process.kill('USR1', @pid) # draining: put is refused, reserve still works
530
- sleep 0.2
531
- Beaneater.configure.job_parser = lambda { |body| sleep 2 if body == 'slow'; body }
532
- started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
533
- put = Thread.new do
534
- begin
535
- Timeout.timeout(0.5) { @client.connection.transmit("put 0 0 100 1\r\nx", retry_interval: 0.3) }
536
- rescue Exception => ex
537
- [ex.class, Process.clock_gettime(Process::CLOCK_MONOTONIC) - started]
538
- end
539
- end
540
- sleep 0.1 # the put got DRAINING and is pausing before its next try
541
- holder = Thread.new { @client.connection.transmit('reserve-with-timeout 0') } # holds the client ~2 s
542
- error, at = put.value
543
- holder.join
544
- assert_equal Timeout::Error, error
545
- assert_operator at, :<, 1, "Timeout fired after #{at.round(2)}s"
546
- ensure
547
- Beaneater.configure.job_parser = lambda { |body| body }
548
- end
549
-
550
- it "uses the default retry interval between DRAINING retries when given nil" do
551
- Process.kill('USR1', @pid)
552
- sleep 0.2
553
- started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
554
- assert_raises(Beaneater::DrainingError) do
555
- Timeout.timeout(5) { @client.connection.transmit("put 0 0 100 1\r\nx", retry_interval: nil) }
556
- end
557
- elapsed = Process.clock_gettime(Process::CLOCK_MONOTONIC) - started
558
- assert_in_delta 2 * Beaneater::Connection::DEFAULT_RETRY_INTERVAL, elapsed, 0.5
559
- end
560
- end
561
- end # transmit
562
-
563
- describe 'for #close' do
564
- before do
565
- @host = 'localhost'
566
- @bc = Beaneater::Connection.new(@host)
567
- end
568
-
569
- it "should clear connection" do
570
- assert_kind_of TCPSocket, @bc.connection
571
- @bc.close
572
- assert_nil @bc.connection
573
- assert_raises(Beaneater::NotConnected) { @bc.transmit 'stats' }
574
- end
575
-
576
- # Removes the job a test left in tube name. Its client was closed with the job reserved, so
577
- # wait (briefly) for the server to release it before clearing the tube.
578
- def clear_after_close(name)
579
- cleaner = Beaneater.new('localhost')
580
- 20.times do
581
- cleanup_tubes!([name], cleaner)
582
- stats = begin
583
- cleaner.tubes.find(name).stats
584
- rescue Beaneater::NotFoundError
585
- break # the tube is gone: no jobs left
586
- end
587
- break if stats.current_jobs_reserved.zero? && stats.current_jobs_ready.zero?
588
- sleep 0.05
589
- end
590
- ensure
591
- cleaner.close if cleaner
592
- end
593
-
594
- it "should close the socket once a command whose job_parser closed the client is over" do
595
- client = Beaneater.new('localhost')
596
- client.tubes.find('close-from-parser').put('x')
597
- client.tubes.watch!('close-from-parser')
598
- socket = client.connection.connection
599
- Beaneater.configure.job_parser = lambda { |body| client.close; body }
600
- assert_equal 'x', client.tubes.reserve(0).body
601
- assert_nil client.connection.connection
602
- assert socket.closed?, "the shut-down socket is still open"
603
- ensure
604
- Beaneater.configure.job_parser = lambda { |body| body }
605
- clear_after_close('close-from-parser')
606
- end
607
-
608
- it "should not raise when the socket is closed by another thread while #close shuts it down" do
609
- client = Beaneater.new('localhost')
610
- client.tubes.find('close-race').put('x')
611
- client.tubes.watch!('close-race')
612
- client.connection.connection.stubs(:shutdown).raises(IOError, 'closed stream')
613
- Beaneater.configure.job_parser = lambda { |body| client.close; body }
614
- assert_equal 'x', client.tubes.reserve(0).body
615
- ensure
616
- Beaneater.configure.job_parser = lambda { |body| body }
617
- clear_after_close('close-race')
618
- end
619
-
620
- describe "in a forked child" do
621
- before do
622
- skip("needs fork") unless Process.respond_to?(:fork)
623
- @client = Beaneater.new('localhost')
624
- cleanup_tubes!(['fork-close'], @client)
625
- @client.tubes.find('fork-close').put('work')
626
- @client.tubes.watch!('fork-close')
627
- end
628
-
629
- after do
630
- Beaneater.configure.job_parser = lambda { |body| body }
631
- @client.close if @client
632
- cleaner = Beaneater.new('localhost')
633
- cleanup_tubes!(['fork-close'], cleaner) # a failed run leaves the job behind
634
- cleaner.close
635
- end
636
-
637
- # The parent still holds the job it reserved: another client cannot get it, and the
638
- # parent can delete it on its own connection.
639
- def assert_parent_keeps(job)
640
- other = Beaneater.new('localhost')
641
- other.tubes.watch!('fork-close')
642
- assert_raises(Beaneater::TimedOutError) { other.tubes.reserve(0) }
643
- assert_equal 'DELETED', @client.connection.transmit("delete #{job.id}")[:status]
644
- ensure
645
- other.close if other
646
- end
647
-
648
- it "should leave the parent's connection alone" do
649
- job = @client.tubes.reserve(0)
650
- child = fork { @client.close; exit!(0) }
651
- Process.wait(child)
652
- assert_parent_keeps(job)
653
- end
654
-
655
- it "should leave the parent's connection alone when forked during a command" do
656
- child = nil
657
- Beaneater.configure.job_parser = lambda { |body| child = fork { @client.close; exit!(0) }; body }
658
- job = @client.tubes.reserve(0)
659
- Beaneater.configure.job_parser = lambda { |body| body } # no second fork if anything below fails
660
- Process.wait(child)
661
- assert_parent_keeps(job)
662
- end
663
- end
664
-
665
- it "should end a reserve when a signal handler on the same thread closes the client" do
666
- # Guards the contract: the reserve ends with NotConnected. It also runs the case that
667
- # crashed Ruby 3.3 (closing the socket under the wait), but that crash came in about one
668
- # run in four, so 20 runs catch it with high probability, not certainty. A child process
669
- # keeps a crash from taking the suite down.
670
- script = <<-RUBY
671
- require 'beaneater'
672
- 20.times do
673
- client = Beaneater.new('localhost')
674
- client.tubes.watch!('close-from-trap')
675
- Signal.trap('USR2') { client.close }
676
- Thread.new { sleep 0.05; Process.kill('USR2', Process.pid) }
677
- puts(begin; client.tubes.reserve; 'reserved'; rescue Exception => ex; ex.class.name; end)
678
- end
679
- RUBY
680
- lib = File.expand_path('../../lib', __FILE__)
681
- out = IO.popen([RbConfig.ruby, '-I', lib, '-e', script]) do |child|
682
- begin
683
- Timeout.timeout(60) { child.read }
684
- rescue Timeout::Error
685
- Process.kill('KILL', child.pid)
686
- flunk "the child was still running after 60s"
687
- end
688
- end
689
- assert $?.success?, "child failed (#{$?.inspect}) after: #{out.lines.size} reserves"
690
- assert_equal ['Beaneater::NotConnected'] * 20, out.lines.map(&:chomp)
691
- end
692
-
693
- it "should end a reserve in another thread when a signal handler closes the client" do
694
- # Same contract and same caveat as the test above (the 3.3 crash is caught only with high
695
- # probability), with the reserve in a second thread and the main thread idle.
696
- script = <<-RUBY
697
- require 'beaneater'
698
- 20.times do
699
- client = Beaneater.new('localhost')
700
- client.tubes.watch!('close-from-trap-other-thread')
701
- trap_error = '-'
702
- Signal.trap('USR2') do
703
- begin
704
- client.close
705
- rescue Exception => ex
706
- trap_error = ex.class.name
707
- end
708
- end
709
- waiter = Thread.new { begin; client.tubes.reserve; 'reserved'; rescue Exception => ex; ex.class.name; end }
710
- sleep 0.05 # the waiter is blocked in reserve
711
- Process.kill('USR2', Process.pid)
712
- puts "\#{waiter.join(5) ? waiter.value : 'still blocked'} \#{trap_error}"
713
- end
714
- RUBY
715
- lib = File.expand_path('../../lib', __FILE__)
716
- out = IO.popen([RbConfig.ruby, '-I', lib, '-e', script]) do |child|
717
- begin
718
- Timeout.timeout(60) { child.read }
719
- rescue Timeout::Error
720
- Process.kill('KILL', child.pid)
721
- flunk "the child was still running after 60s"
722
- end
723
- end
724
- assert $?.success?, "child failed (#{$?.inspect}) after: #{out.lines.size} reserves"
725
- assert_equal ['Beaneater::NotConnected -'] * 20, out.lines.map(&:chomp)
726
- end
727
-
728
- it "should unblock a reserve waiting in another thread" do
729
- client = Beaneater.new('localhost')
730
- client.tubes.watch!('close-unblocks-reserve')
731
- result = nil
732
- waiter = Thread.new do
733
- begin
734
- client.tubes.reserve
735
- result = :reserved
736
- rescue Exception => ex
737
- result = ex
738
- end
739
- end
740
- sleep 0.3 # the waiter is blocked in reserve
741
- client.close
742
- assert waiter.join(1), "reserve still blocked 1s after close"
743
- assert_kind_of Beaneater::NotConnected, result
744
- assert_nil client.connection.connection
745
- ensure
746
- waiter.kill if waiter
747
- end
748
- end # close
749
- end # Beaneater::Connection