websocket_server.rb 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. # Copyright (C) 2012-2023 Zammad Foundation, https://zammad-foundation.org/
  2. RSpec.configure do |config|
  3. config.around(:each, type: :system) do |example|
  4. server_required = example.metadata.fetch(:websocket, true)
  5. if server_required
  6. port = ENV['WS_PORT'] || 6042
  7. ensure_port_available!(port)
  8. ws_thread = Thread.new do
  9. WebsocketServer.run(
  10. p: port,
  11. b: '0.0.0.0',
  12. s: true,
  13. v: false,
  14. d: false,
  15. tls_options: {
  16. private_key_file: "#{Dir.home}/.localhost/localhost.key",
  17. cert_chain_file: "#{Dir.home}/.localhost/localhost.crt",
  18. }
  19. )
  20. end
  21. end
  22. example.run
  23. rescue => e
  24. # Handle any errors occuring within this hook, for example Net::ReadTimeout errors of the WS server.
  25. # Otherwise, they would not cause the retry to kick in, but abort the process.
  26. example.example.set_exception(e)
  27. ensure
  28. stop_websocket_server(ws_thread) if server_required
  29. end
  30. def stop_websocket_server(ws_thread)
  31. # returns immediately and thread may be still shutting down
  32. EventMachine.stop_event_loop if ws_thread.status
  33. # give thread time to terminate
  34. sleep 0.01 while ws_thread.status
  35. rescue => e
  36. Rails.logger.error "Error occurred during web socket server shutdown: #{e}"
  37. $stderr.puts "Error occurred during web socket server shutdown: #{e}" # rubocop:disable Style/StderrPuts
  38. # Ignore this error and continue, to allow for the rspec-retry mechanism to work.
  39. end
  40. def ensure_port_available!(port)
  41. %w[0.0.0.0 127.0.0.1].each do |host|
  42. TCPServer.new(host, port).close # release port immediately
  43. end
  44. rescue Errno::EADDRINUSE
  45. raise "Couldn't start WebSocket server. Maybe another websocket server process is already running?"
  46. end
  47. end