websocket_server.rb 1.9 KB

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