Class: SvelteOnRails::SsrServer
- Inherits:
-
Object
- Object
- SvelteOnRails::SsrServer
- Includes:
- Singleton
- Defined in:
- lib/svelte_on_rails/ssr_server.rb
Instance Attribute Summary collapse
-
#connection ⇒ Object
readonly
Returns the value of attribute connection.
Class Method Summary collapse
Instance Method Summary collapse
- #alive? ⇒ Boolean
- #configured? ⇒ Boolean
-
#initialize ⇒ SsrServer
constructor
A new instance of SsrServer.
- #kill_leftover_processes ⇒ Object
-
#logfile_max_lines ⇒ Object
parameter.
- #logfile_path ⇒ Object
- #node_server_pid ⇒ Object
- #parse_body_json(response_string) ⇒ Object
- #ping? ⇒ Boolean
- #render(component, props, debug, view_path_proc) ⇒ Object
- #socket_path ⇒ Object
- #start_node_server! ⇒ Object
Constructor Details
#initialize ⇒ SsrServer
Returns a new instance of SsrServer.
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 |
# File 'lib/svelte_on_rails/ssr_server.rb', line 65 def initialize @socket_namespace = [ "svelte-ssr", Rails.application.class.module_parent_name[0..30], Rails.env, ].join("-") @config = SvelteOnRails::Configuration.instance if @config.configs[:use_ssr_server] && defined?(Rails::Server) start_node_server! at_exit do Process.kill("SIGINT", (node_server_pid || 0)) if node_server_pid end end end |
Instance Attribute Details
#connection ⇒ Object (readonly)
Returns the value of attribute connection.
8 9 10 |
# File 'lib/svelte_on_rails/ssr_server.rb', line 8 def connection @connection end |
Class Method Details
.instance ⇒ Object
methods
61 62 63 |
# File 'lib/svelte_on_rails/ssr_server.rb', line 61 def self.instance @instance ||= new end |
.script_path ⇒ Object
55 56 57 |
# File 'lib/svelte_on_rails/ssr_server.rb', line 55 def self.script_path Pathname('node_modules/@csedl/svelte-on-rails/bin/svelte-ssr-server.js') end |
.script_path_full ⇒ Object
51 52 53 |
# File 'lib/svelte_on_rails/ssr_server.rb', line 51 def self.script_path_full Rails.root.join(script_path) end |
Instance Method Details
#alive? ⇒ Boolean
257 258 259 |
# File 'lib/svelte_on_rails/ssr_server.rb', line 257 def alive? @alive end |
#configured? ⇒ Boolean
170 171 172 |
# File 'lib/svelte_on_rails/ssr_server.rb', line 170 def configured? @configured ||= File.exist?(self.class.script_path_full) end |
#kill_leftover_processes ⇒ Object
237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 |
# File 'lib/svelte_on_rails/ssr_server.rb', line 237 def kill_leftover_processes stdout, stderr, status = Open3.capture3( "ps aux | grep svelte" ) leftover = stdout.split("\n").map do |line| if line.match?(/\/#{@socket_namespace}-[0-9]+.sock$/) unless line.include?("#{@socket_namespace}-#{Process.pid}.sock") line.match(/[0-9]+/).to_s.to_i end end end.compact stdout, stderr, status = Open3.capture3( "kill #{leftover.join(' ')}" ) start_server_log(nil, "Killed #{leftover.length} leftover processes") if leftover.length >= 1 end |
#logfile_max_lines ⇒ Object
parameter
12 13 14 15 16 17 18 19 20 21 22 |
# File 'lib/svelte_on_rails/ssr_server.rb', line 12 def logfile_max_lines if Rails.env.test? 20 elsif Rails.env.development? 50 elsif Rails.env.production? 1000 else 100 end end |
#logfile_path ⇒ Object
24 25 26 |
# File 'lib/svelte_on_rails/ssr_server.rb', line 24 def logfile_path Rails.root.join("log/svelte-ssr-server-#{Rails.env}.log") end |
#node_server_pid ⇒ Object
261 262 263 264 265 266 267 268 269 270 271 |
# File 'lib/svelte_on_rails/ssr_server.rb', line 261 def node_server_pid stdout, stderr, status = Open3.capture3( "ps aux | grep svelte" ) stdout.split("\n").each do |line| if line.include?("#{@socket_namespace}-#{Process.pid}.sock") return line.match(/[0-9]+/).to_s.to_i end end nil end |
#parse_body_json(response_string) ⇒ Object
160 161 162 163 164 165 166 167 168 |
# File 'lib/svelte_on_rails/ssr_server.rb', line 160 def parse_body_json(response_string) return {} unless response_string.to_s.present? body = response_string.split("\r\n\r\n", 2)[1] json_start = body.index('{') json_end = body.rindex('}') json_str = body[json_start..json_end] JSON.parse(json_str) end |
#ping? ⇒ Boolean
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 |
# File 'lib/svelte_on_rails/ssr_server.rb', line 174 def ping? @alive = false shorten_logfile unless File.exist?(socket_path) return false end response = '' begin sock = UNIXSocket.new(socket_path) request = "GET /ping HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n" sock.write(request) response = sock.read sock.close rescue => e puts "[SOR] Ping Failed: #{e.}" end if response.match?(/^HTTP\/\d\.\d 200/) @alive = true end end |
#render(component, props, debug, view_path_proc) ⇒ Object
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 |
# File 'lib/svelte_on_rails/ssr_server.rb', line 85 def render(component, props, debug, view_path_proc) # fetch asset manifest = @config.manifest(debug, component[:name]) _asset_path = manifest[component[:path]]['file'] full_asset_path = Rails.root.join('public', 'svelte-ssr', _asset_path) body_json = { component: full_asset_path, props: props }.to_json request = "POST /render HTTP/1.1\r\n" + "Host: localhost\r\n" + "Content-Type: application/json\r\n" + "Content-Length: #{body_json.bytesize}\r\n" + "Connection: close\r\n\r\n" begin socket = UNIXSocket.new(socket_path) socket.write(request + body_json) response = socket.read socket.close rescue => e if e.is_a?(Errno::ECONNREFUSED) SvelteOnRails::Lib::Utils.error_log( "Render #{component[:file_basename]}.svelte", [ "The SSR Server is not reachable.\nYou may need to restart your app.", "#{e}", SvelteOnRails::Lib::Utils.backtrace_until_sor(e).join("\n") ] ) return { success: false, ssr_server_unreachable: true } else raise e end end shorten_logfile raw_response = parse_body_json(response) if raw_response['status'] == 'SUCCESS' htm = raw_response['html'].to_s .gsub('<!--[-->', '') .gsub('<!--]-->', '') .gsub('<!---->', '') { success: true, html: htm, head: raw_response['head'].to_s, } else config = SvelteOnRails::Configuration.instance comp = Rails.root.join(component[:path]).to_s imps = if config.watch_changes? _src = config.fetch_source_files(component[:path], false, '') sources = _src.select { |f| f != comp } (sources.present? ? "\nImports:\n#{sources.join("\n")}" : '') else '' end utils = SvelteOnRails::Lib::Utils utils.error_log( "Render #{component[:file_basename]}.svelte", [ raw_response['errorLog'].to_a.join("\n"), "View:\n#{view_path_proc.call}\nComponent:\n#{Rails.root.join(component[:path]).to_s}#{imps}", ] ) { success: false, } end end |
#socket_path ⇒ Object
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
# File 'lib/svelte_on_rails/ssr_server.rb', line 28 def socket_path @socket_path ||= begin app_sock = Rails.root.join("tmp/sockets/#{@socket_namespace}-#{Process.pid}.sock").to_s preferred_dir = File.dirname(app_sock) FileUtils.mkdir_p(preferred_dir) if app_sock.to_s.length < 104 app_sock else FileUtils.rm_f(app_sock) if File.exist?(app_sock) # Fallback to shorter path in /tmp dir = File.("/tmp/svelte") FileUtils.mkdir_p(dir) FileUtils.chmod(0777, dir) s = dir + "/#{@socket_namespace}-#{Process.pid}.sock" start_server_log(nil, "sockets longer than 104 chars are risky, fallback to: #{s}") s end end end |
#start_node_server! ⇒ Object
195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 |
# File 'lib/svelte_on_rails/ssr_server.rb', line 195 def start_node_server! cnf = SvelteOnRails::Configuration.instance start = Time.now cmd = [ "SVELTE_SSR_SERVER_LOGFILE=#{logfile_path}", "#{cnf.node_bin_path} #{self.class.script_path}", "#{socket_path}" ].join(' ') Thread.new do stdout, stderr, status = Open3.capture3( cmd, chdir: Rails.root ) end start_server_log(start, "Start running Svelte-SSR-Server...") until node_server_pid do sleep 0.12 start_server_log(start, "Waiting for node server process-id") start_server_timeout!(start) end start_server_log(start, "Node-server process-id: #{node_server_pid}") until File.exist?(socket_path) do sleep 0.05 start_server_log(start, "Waiting for socket to be created #{socket_path}") start_server_timeout!(start) end start_server_log(start, "Socket created: #{socket_path}") until ping? do start_server_log(start, "Waiting for successful server-response") start_server_timeout!(start) sleep 0.1 end start_server_log(start, "Server responded successfully") kill_leftover_processes end |