Class: SvelteOnRails::SsrClientControlChannel

Inherits:
Object
  • Object
show all
Defined in:
lib/svelte_on_rails/ssr_client.rb

Class Method Summary collapse

Class Method Details

.install_control_listenerObject

enable communication by rake task for admin purposes



466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
# File 'lib/svelte_on_rails/ssr_client.rb', line 466

def self.install_control_listener

  path = socket_path.to_s
  FileUtils.mkdir_p(File.dirname(path))
  File.unlink(path) if File.exist?(path)

  server = UNIXServer.new(path)
  File.chmod(0600, path)

  Thread.new do
    loop do
      client = server.accept
      begin
        request = client.gets&.strip.to_sym
        client_instance = SsrClient.instance(caller: 'rake task (manual)')

        response = case request
                   when :status
                     {
                       env: Rails.env,
                       uptime: client_instance.uptime,
                       request: request,
                       socket_path: client_instance.socket_path,
                       initialized_by: client_instance.initialized_by,
                       ping: client_instance.ping?,
                       start_node_server_command: client_instance.start_node_server_command
                     }
                   when :stop
                     begin
                       client_instance.shutdown
                       {
                         success: true
                       }
                     rescue => e
                       {
                         error: "Failed to stop SSR server => #{e}"
                       }
                     end
                   end

        client.puts(response.to_json)
      rescue => e
        SvelteOnRails::Lib::Utils.ssr_server_log(
          "[control] handler error: #{e.class}: #{e.message}",
          ssr_logfile_only: true
        )
      ensure
        client.close rescue nil
      end
    end
  end

  at_exit do
    server.close rescue nil
    File.unlink(path) rescue nil
  end

  SvelteOnRails::Lib::Utils.ssr_server_log(
    "Control listener installed on #{path}",
    ssr_logfile_only: true
  )

end

.socket_pathObject

Full path of the control socket. Sits next to the SSR socket in tmp/sockets, or in the /tmp/svelte fallback directory when Rails.root pushes total length over 103 chars.



455
456
457
458
459
460
461
462
463
# File 'lib/svelte_on_rails/ssr_client.rb', line 455

def self.socket_path
  primary = Rails.root.join("tmp", "sockets", "svelte-ctl-#{Rails.env}.sock")
  if primary.to_s.length <= 103
    FileUtils.mkdir_p(File.dirname(primary))
    return primary
  end

  Pathname.new("/tmp/svelte-#{Rails.env}-ctl-#{Digest::XXH64.hexdigest(Rails.root.to_s)}.sock")
end