Rails 5 Actioncable - сбой: ошибка во время рукопожатия WebSocket: неожиданный код ответа: 502

Я пытаюсь использовать ActionCable в рельсах 5, но не знаю, почему он не работает.

В консоли браузера я получаю:

Ошибка подключения WebSocket к ws: //my.website/cable: WebSocket закрывается до установления соединения.

Ошибка подключения WebSocket к ws: //my.website/cable: ошибка во время рукопожатия WebSocket: неожиданный код ответа: 502

Uncaught TypeError: невозможно прочитать подписки на свойство undefined

Я установил Passenger + Nginx

руководство: https://www.phusionpassenger.com/library/install/nginx/install/oss/xenial/

sudo / usr / bin / Passenger-config validate-install:

* Checking whether this Passenger install is in PATH... ✓  
* Checking whether there are no other Passenger installations... ✓

sudo / usr / sbin / Passenger-memory-stats:

Version: 5.1.4
Date   : 2017-06-14 10:05:30 +0000

------- Apache processes --------

### Processes: 0
### Total private dirty RSS: 0.00 MB


--------- Nginx processes ----------
PID   PPID  VMSize    Private  Name
------------------------------------
8176  1     142.8 MB  0.5 MB   nginx: master process /usr/sbin/nginx -g daemon on; master_process on;
8179  8176  142.8 MB  0.7 MB   nginx: worker process
### Processes: 2
### Total private dirty RSS: 1.22 MB


---- Passenger processes -----
PID   VMSize    Private  Name
------------------------------
8156  421.3 MB  1.1 MB   Passenger watchdog
8159  636.5 MB  1.7 MB   Passenger core
8165  429.6 MB  1.2 MB   Passenger ust-router
### Processes: 3
### Total private dirty RSS: 4.07 MB

У меня есть Integrated Action Cable с Passenger + Nginx благодаря этому руководству: Интеграция Action Cable с Passenger + Nginx

Итак, nginx + пассажир работает нормально, так как приложение подключено к сети.

Имя моего приложения rails "final"

/opt/nginx/config/nginx.config: (внутри http {...})

        user www-data;
worker_processes auto;
pid /run/nginx.pid;

events {
    worker_connections 768;
    # multi_accept on;
}

http {
    ##
    # Basic Settings
    ##

    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;
    # server_tokens off;
server {
    listen       80;
    server_name  my.website www.my.website;
    rails_env production;


root /var/www/final/public;
passenger_enabled on;
passenger_app_root   /var/www/final;        







location /cable {
    passenger_app_group_name final_websocket;
    passenger_force_max_concurrent_requests_per_process 0;

}

      }

final / config / routes.rb: mount ActionCable.server => '/cable'

Также я добавил <%= action_cable_meta_tag %> в application.html.erb

final / config / cable.yml:

production: &production
  url: redis://localhost:6379

меньше log / production.log:

I, [2017-06-14T11:55:49.841674 #7666]  INFO -- : [7b1f4cd9-5fbf-44f5-ba77-e4d7dc40c8f1]   Rendering account/seting.html.erb within layouts/application
I, [2017-06-14T11:55:49.842952 #7666]  INFO -- : [7b1f4cd9-5fbf-44f5-ba77-e4d7dc40c8f1]   Rendered account/_header.html.erb (1.0ms) [cache miss]
I, [2017-06-14T11:55:50.469493 #7666]  INFO -- : [7b1f4cd9-5fbf-44f5-ba77-e4d7dc40c8f1]   Rendered account/_footer.html.erb (0.5ms) [cache miss]
I, [2017-06-14T11:55:50.469629 #7666]  INFO -- : [7b1f4cd9-5fbf-44f5-ba77-e4d7dc40c8f1]   Rendered account/seting.html.erb within layouts/application (627.9ms)
I, [2017-06-14T11:55:50.470586 #7666]  INFO -- : [7b1f4cd9-5fbf-44f5-ba77-e4d7dc40c8f1] Completed 200 OK in 633ms (Views: 629.2ms | ActiveRecord: 0.4ms)
I, [2017-06-14T11:55:51.024845 #7709]  INFO -- : [2c674f25-f747-4cbc-9ad8-b6f517bd5b72] Started GET "/cable" for 213.7.71.70 at 2017-06-14 11:55:51 +0000
I, [2017-06-14T11:55:51.062689 #7709]  INFO -- : [2c674f25-f747-4cbc-9ad8-b6f517bd5b72] Started GET "/cable/" [WebSocket] for 213.7.71.70 at 2017-06-14 11:55:51 +0000
I, [2017-06-14T11:55:51.062890 #7709]  INFO -- : [2c674f25-f747-4cbc-9ad8-b6f517bd5b72] Successfully upgraded to WebSocket (REQUEST_METHOD: GET, HTTP_CONNECTION: upgrade, HTTP_UPGRADE: websocket)
D, [2017-06-14T11:55:51.081839 #7709] DEBUG -- :   ESC[1mESC[35m (0.5ms)ESC[0m  ESC[1mESC[35mSET NAMES utf8,  @@SESSION.sql_mode = CONCAT(CONCAT(@@sql_mode, ',STRICT_ALL_TABLES'), log/production.log

enviroment / production.rb:

   config.action_cable.url = "/cable"  
   config.action_cable.allowed_request_origins = [ 'http://my-server-ip-address', /http:\/\/example.*/ ]

В консоли rails - ActionCable.server.config:

=> #<ActionCable::Server::Configuration:0x007f9ec2027598 @log_tags=[], @connection_class=#<Proc:0x007f9ec20224a8@/usr/local/lib/ruby/gems/2.4.0/gems/actioncable-5.1.1/lib/action_ca
ble/engine.rb:35 (lambda)>, @worker_pool_size=4, @disable_request_forgery_protection=false, @allow_same_origin_as_host=true, @logger=#<ActiveSupport::Logger:0x007f9ec3242c28 @level
=0, @progname=nil, @default_formatter=#<Logger::Formatter:0x007f9ec3242b60 @datetime_format=nil>, @formatter=#<ActiveSupport::Logger::SimpleFormatter:0x007f9ec3242a48 @datetime_for
mat=nil, @thread_key="activesupport_tagged_logging_tags:70159927743780">, @logdev=#<Logger::LogDevice:0x007f9ec3242b10 @shift_period_suffix=nil, @shift_size=nil, @shift_age=nil, @f
ilename=nil, @dev=#<IO:/dev/pts/2>, @mon_owner=nil, @mon_count=0, @mon_mutex=#<Thread::Mutex:0x007f9ec3242a98>>, @local_levels=#<Concurrent::Map:0x007f9ec32429d0 entries=0 default_
proc=nil>>, @cable={"adapter"=>"redis", "url"=>"redis://localhost:6379"}, @mount_path="/cable", @url="/cable", @allowed_request_origins=["http://my.website"]>

assets / javascripts / cable.js:

// Action Cable provides the framework to deal with WebSockets in Rails.
// You can generate new channels where WebSocket features live using the `rails generate channel` command.
//
//= require action_cable
//= require_self
//= require_tree ./channels

(function() {
  this.App || (this.App = {});

  App.cable = ActionCable.createConsumer('/cable');

}).call(this);

каналы / application_cable / connection.rb:

module ApplicationCable
  class Connection < ActionCable::Connection::Base


    identified_by :current_user

    def connect
      self.current_user = find_verified_user
    end

    private
      def find_verified_user
        if verified_user = User.find_by(id: cookies.signed[:user_id])
          verified_user
        else
          reject_unauthorized_connection
        end
      end
  end
end

var / log / nginx / error.log:

[ 2017-06-14 12:46:00.0110 14157/7f41c30e9700 age/Cor/App/Poo/AnalyticsCollection.cpp:102 ]: Process (pid=15020, group=final_websocket) no longer exists! Detaching it from the pool.
[ 2017-06-14 12:46:00.0132 14157/7f41c30e9700 age/Cor/CoreMain.cpp:907 ]: Checking whether to disconnect long-running connections for process 15020, application final_websocket
App 15037 stdout: 
App 14181 stderr: /usr/local/lib/ruby/gems/2.4.0/gems/redis-3.3.3/lib/redis/connection/ruby.rb:229:in `getaddrinfo': getaddrinfo: Name or service not known (SocketError)
App 14181 stderr:   from /usr/local/lib/ruby/gems/2.4.0/gems/redis-3.3.3/lib/redis/connection/ruby.rb:229:in `connect'
App 14181 stderr:   from /usr/local/lib/ruby/gems/2.4.0/gems/redis-3.3.3/lib/redis/connection/ruby.rb:313:in `connect'
App 14181 stderr:   from /usr/local/lib/ruby/gems/2.4.0/gems/redis-3.3.3/lib/redis/client.rb:336:in `establish_connection'
App 14181 stderr:   from /usr/local/lib/ruby/gems/2.4.0/gems/redis-3.3.3/lib/redis/client.rb:101:in `block in connect'
App 14181 stderr:   from /usr/local/lib/ruby/gems/2.4.0/gems/redis-3.3.3/lib/redis/client.rb:293:in `with_reconnect'
App 14181 stderr:   from /usr/local/lib/ruby/gems/2.4.0/gems/redis-3.3.3/lib/redis/client.rb:100:in `connect'
App 14181 stderr:   from /usr/local/lib/ruby/gems/2.4.0/gems/redis-3.3.3/lib/redis/client.rb:276:in `with_socket_timeout'
App 14181 stderr:   from /usr/local/lib/ruby/gems/2.4.0/gems/redis-3.3.3/lib/redis/client.rb:133:in `call_loop'
App 14181 stderr:   from /usr/local/lib/ruby/gems/2.4.0/gems/redis-3.3.3/lib/redis/subscribe.rb:43:in `subscription'
App 14181 stderr:   from /usr/local/lib/ruby/gems/2.4.0/gems/redis-3.3.3/lib/redis/subscribe.rb:12:in `subscribe'
App 14181 stderr:   from /usr/local/lib/ruby/gems/2.4.0/gems/redis-3.3.3/lib/redis.rb:2765:in `_subscription'
App 14181 stderr:   from /usr/local/lib/ruby/gems/2.4.0/gems/redis-3.3.3/lib/redis.rb:2143:in `block in subscribe'
App 14181 stderr:   from /usr/local/lib/ruby/gems/2.4.0/gems/redis-3.3.3/lib/redis.rb:58:in `block in synchronize'
App 14181 stderr:   from /usr/local/lib/ruby/2.4.0/monitor.rb:214:in `mon_synchronize'
App 14181 stderr:   from /usr/local/lib/ruby/gems/2.4.0/gems/redis-3.3.3/lib/redis.rb:58:in `synchronize'
App 14181 stderr:   from /usr/local/lib/ruby/gems/2.4.0/gems/redis-3.3.3/lib/redis.rb:2142:in `subscribe'
App 14181 stderr:   from /usr/local/lib/ruby/gems/2.4.0/gems/actioncable-5.1.1/lib/action_cable/subscription_adapter/redis.rb:77:in `block in listen'
App 14181 stderr:   from /usr/local/lib/ruby/gems/2.4.0/gems/redis-3.3.3/lib/redis/client.rb:293:in `with_reconnect'
App 14181 stderr:   from /usr/local/lib/ruby/gems/2.4.0/gems/redis-3.3.3/lib/redis.rb:64:in `block in with_reconnect'
App 14181 stderr:   from /usr/local/lib/ruby/gems/2.4.0/gems/redis-3.3.3/lib/redis.rb:58:in `block in synchronize'
App 14181 stderr:   from /usr/local/lib/ruby/2.4.0/monitor.rb:214:in `mon_synchronize'
App 14181 stderr:   from /usr/local/lib/ruby/gems/2.4.0/gems/redis-3.3.3/lib/redis.rb:58:in `synchronize'
App 14181 stderr:   from /usr/local/lib/ruby/gems/2.4.0/gems/redis-3.3.3/lib/redis.rb:63:in `with_reconnect'
App 14181 stderr:   from /usr/local/lib/ruby/gems/2.4.0/gems/redis-3.3.3/lib/redis.rb:70:in `without_reconnect'
App 14181 stderr:   from /usr/local/lib/ruby/gems/2.4.0/gems/actioncable-5.1.1/lib/action_cable/subscription_adapter/redis.rb:74:in `listen'
App 14181 stderr:   from /usr/local/lib/ruby/gems/2.4.0/gems/actioncable-5.1.1/lib/action_cable/subscription_adapter/redis.rb:148:in `block in ensure_listener_running'

person Navid Farjad    schedule 14.06.2017    source источник


Ответы (1)


здесь были две проблемы: 1. cable.js должен быть таким

:`// app/assets/javascripts/cable.js
//= require action_cable
//= require_self
//= require_tree ./channels
(function() {
  this.App || (this.App = {});

  App.cable = ActionCable.createConsumer();
}).call(this);`
  1. Я прокомментирую эту строку в nginx.conf: #include /etc/nginx/sites-enabled/*; Конфигурация Becaouse в файле sites-enabled / default перекрывает вашу конфигурацию в nginx.conf

Я надеюсь, что этот вопрос и ответ помогут кому-то сэкономить время.

person Navid Farjad    schedule 18.06.2017