Class: ReactOnRails::ServerRenderingPool::RubyEmbeddedJavaScript
- Inherits:
-
Object
- Object
- ReactOnRails::ServerRenderingPool::RubyEmbeddedJavaScript
- Defined in:
- lib/react_on_rails/server_rendering_pool/ruby_embedded_java_script.rb
Overview
rubocop:disable Metrics/ClassLength
Constant Summary collapse
- RENDERER_CONNECTION_ERROR_CLASSES =
Error classes that signal Rails could not reach the renderer process (e.g. the Pro Node renderer configured via REACT_RENDERER_URL) rather than the renderer evaluating the bundle and the bundle itself failing. See issue #3604.
Errno::EPERM is intentionally NOT in this list: it is a general "Operation not permitted" error (file permissions, process signals, privileged-port binds), so a class match — especially across the #cause chain — would misclassify a non-network EPERM (e.g. a bundle file read wrapped in ReactOnRails::Error) as a renderer connection failure. The sandboxed connect(2) EPERM from issue #3604 is matched instead by the "connect(2) for" branch of RENDERER_CONNECTION_ERROR_REGEX below (its message is "Operation not permitted - connect(2) for host:port").
[ SocketError, Errno::ECONNREFUSED, Errno::ECONNRESET, Errno::EHOSTUNREACH, Errno::ENETUNREACH, Errno::ETIMEDOUT, Errno::EPIPE ].freeze
- RENDERER_CONNECTION_ERROR_REGEX =
Renderer-anchored connection signatures, used only as a fallback for failures that survive as text rather than as one of the Errno classes above. The Pro renderer client re-wraps transport failures as "<Connection|Time out> error on renderer request: ...", and raw Errno messages carry the "connect(2) for host:port" shape. These patterns are deliberately narrow (anchored to renderer/socket wording) so a genuine in-process bundle error whose text merely mentions a connection — e.g. a component's own failed
fetchduring SSR reporting "ECONNREFUSED" — is NOT misclassified as a renderer connectivity problem. Structured cases are handled by the Errno classes above, checked across the error's #cause chain. See issue #3604. / connect\(2\)\sfor | Failed\sto\sopen\sTCP\sconnection | error\son\srenderer\srequest /xi
Class Method Summary collapse
-
.console_polyfill ⇒ Object
Reimplement console methods for replaying on the client Save a handle to the original console if needed.
- .create_js_context ⇒ Object
- .eval_js(js_code, _render_options) ⇒ Object
-
.exec_server_render_js(js_code, render_options, js_evaluator = nil) ⇒ Object
js_code: JavaScript expression that returns a string.
- .execjs_timer_polyfills ⇒ Object
- .read_bundle_js_code ⇒ Object
- .reset_pool ⇒ Object
- .reset_pool_if_server_bundle_was_modified ⇒ Object
- .trace_js_code_used(msg, js_code, file_name = "tmp/server-generated.js", force: false) ⇒ Object
- .undefined_for_exec_js_logging(function_name) ⇒ Object
Class Method Details
.console_polyfill ⇒ Object
Reimplement console methods for replaying on the client Save a handle to the original console if needed.
251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 |
# File 'lib/react_on_rails/server_rendering_pool/ruby_embedded_java_script.rb', line 251 def console_polyfill <<~JS var debugConsole = console; var console = { history: [] }; ['error', 'log', 'info', 'warn'].forEach(function (level) { console[level] = function () { var argArray = Array.prototype.slice.call(arguments); if (argArray.length > 0) { argArray[0] = '[SERVER] ' + argArray[0]; } console.history.push({level: level, arguments: argArray}); }; }); JS end |
.create_js_context ⇒ Object
180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 |
# File 'lib/react_on_rails/server_rendering_pool/ruby_embedded_java_script.rb', line 180 def create_js_context return if ReactOnRails.configuration.server_bundle_js_file.blank? bundle_js_code = read_bundle_js_code base_js_code = <<~JS #{console_polyfill} #{execjs_timer_polyfills} #{bundle_js_code}; JS file_name = "tmp/base_js_code.js" begin if ReactOnRails.configuration.trace Rails.logger.info do "[react_on_rails] Created JavaScript context with file " \ "#{ReactOnRails::Utils.server_bundle_js_file_path}" end end ExecJS.compile(base_js_code) rescue StandardError => e msg = "ERROR when compiling base_js_code! " \ "See file #{file_name} to " \ "correlate line numbers of error. Error is\n\n#{e.}" \ "\n\n#{e.backtrace.join("\n")}" \ "\n\n#{Utils.default_troubleshooting_section}" Rails.logger.error(msg) trace_js_code_used("Error when compiling JavaScript code for the context.", base_js_code, file_name, force: true) raise e end end |
.eval_js(js_code, _render_options) ⇒ Object
144 145 146 147 148 |
# File 'lib/react_on_rails/server_rendering_pool/ruby_embedded_java_script.rb', line 144 def eval_js(js_code, ) @js_context_pool.with do |js_context| js_context.eval(js_code) end end |
.exec_server_render_js(js_code, render_options, js_evaluator = nil) ⇒ Object
js_code: JavaScript expression that returns a string. render_options: lib/react_on_rails/react_component/render_options.rb Using these options:
trace: saves the executed JS to a file, used in development
logging_on_server: put on server logs, not just in browser console
Returns a Hash:
html: string of HTML for direct insertion on the page by evaluating js_code
consoleReplayScript: script for replaying console
hasErrors: true if server rendering errors
Note, js_code does not have to be based on React. js_code MUST RETURN json stringify Object Calling code will probably call 'html_safe' on return value before rendering to the view.
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 |
# File 'lib/react_on_rails/server_rendering_pool/ruby_embedded_java_script.rb', line 90 def exec_server_render_js(js_code, , js_evaluator = nil) js_evaluator ||= self if .trace @file_index ||= 1 trace_js_code_used("Evaluating code to server render.", js_code, "tmp/server-generated-#{@file_index % 10}.js") @file_index += 1 end begin result = if .streaming? js_evaluator.eval_streaming_js(js_code, ) else js_evaluator.eval_js(js_code, ) end rescue ReactOnRails::ServerBundleLoadError raise rescue StandardError => err msg = if renderer_connection_error?(err) (err) else (err) end msg = "#{msg}\n#{Utils.default_troubleshooting_section}\n" raise ReactOnRails::Error, msg, err.backtrace end return parse_render_result(result, ) unless .streaming? # Streamed chunks are Hashes (from LengthPrefixedParser in stream_request.rb). # Just replay console messages and pass through. result.transform do |chunk| replay_console_to_rails_logger(chunk, ) chunk end end |
.execjs_timer_polyfills ⇒ Object
212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 |
# File 'lib/react_on_rails/server_rendering_pool/ruby_embedded_java_script.rb', line 212 def execjs_timer_polyfills <<~JS function getStackTrace () { var stack; try { throw new Error(''); } catch (error) { stack = error.stack || ''; } stack = stack.split('\\n').map(function (line) { return line.trim(); }); return stack.splice(stack[0] == 'Error' ? 2 : 1); } function setInterval() { #{undefined_for_exec_js_logging('setInterval')} } function setTimeout() { #{undefined_for_exec_js_logging('setTimeout')} } function clearTimeout() { #{undefined_for_exec_js_logging('clearTimeout')} } JS end |
.read_bundle_js_code ⇒ Object
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 |
# File 'lib/react_on_rails/server_rendering_pool/ruby_embedded_java_script.rb', line 150 def read_bundle_js_code server_js_file = ReactOnRails::Utils.server_bundle_js_file_path server_bundle_path_is_http = ReactOnRails::Utils.server_bundle_path_is_http? if server_bundle_path_is_http file_url_to_string(server_js_file) else File.read(server_js_file) end rescue StandardError => e # Sanitized: server_js_file may be an HTTP(S) URL with embedded basic-auth credentials # (a supported config convenience, e.g. https://:password@host:3800). This is the # public entry point that file_url_to_string is called from, so without this the # sanitization inside file_url_to_string's own raise/rescue is moot for any real # caller — the credential would still leak here regardless. Errors already wrapped by # file_url_to_string have passed through the same message sanitizer; scanning that # wrapper again would treat its diagnostic text as fresh untrusted input. Other errors # are scrubbed here because URI::InvalidURIError embeds the raw URL in its message. sanitized_url = sanitized_renderer_url(server_js_file) sanitized_error = if server_bundle_path_is_http && e.is_a?(ReactOnRails::ServerBundleLoadError) e. else (e., server_js_file, sanitized_url) end msg = "You specified server rendering JS file: #{sanitized_url}, but it cannot " \ "be read. You may set the server_bundle_js_file in your configuration to be \"\" to " \ "avoid this warning.\nError is: #{sanitized_error}\n\n" \ "#{Utils.default_troubleshooting_section}" raise ReactOnRails::ServerBundleLoadError, msg end |
.reset_pool ⇒ Object
49 50 51 52 53 54 |
# File 'lib/react_on_rails/server_rendering_pool/ruby_embedded_java_script.rb', line 49 def reset_pool @js_context_pool = ConnectionPool.new( size: ReactOnRails.configuration.server_renderer_pool_size, timeout: ReactOnRails.configuration.server_renderer_timeout ) { create_js_context } end |
.reset_pool_if_server_bundle_was_modified ⇒ Object
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 |
# File 'lib/react_on_rails/server_rendering_pool/ruby_embedded_java_script.rb', line 56 def reset_pool_if_server_bundle_was_modified return unless ReactOnRails.configuration.development_mode # RSC (React Server Components) bundle changes are not monitored here since: # 1. RSC is only supported in the Pro version of React on Rails # 2. This RubyEmbeddedJavaScript pool is used exclusively in the non-Pro version # 3. This pool uses ExecJS for JavaScript evaluation which does not support RSC if ReactOnRails::Utils.server_bundle_path_is_http? return if @server_bundle_url == ReactOnRails::Utils.server_bundle_js_file_path @server_bundle_url = ReactOnRails::Utils.server_bundle_js_file_path else file_mtime = File.mtime(ReactOnRails::Utils.server_bundle_js_file_path) @server_bundle_timestamp ||= file_mtime return if @server_bundle_timestamp == file_mtime @server_bundle_timestamp = file_mtime end ReactOnRails::ServerRenderingPool.reset_pool end |
.trace_js_code_used(msg, js_code, file_name = "tmp/server-generated.js", force: false) ⇒ Object
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 |
# File 'lib/react_on_rails/server_rendering_pool/ruby_embedded_java_script.rb', line 126 def trace_js_code_used(msg, js_code, file_name = "tmp/server-generated.js", force: false) return unless ReactOnRails.configuration.trace || force # Set to anything to print generated code. File.write(file_name, js_code) msg = <<~MSG #{'Z' * 80} [react_on_rails] #{msg} JavaScript code used: #{file_name} #{'Z' * 80} MSG if force Rails.logger.error(msg) else Rails.logger.info(msg) end end |
.undefined_for_exec_js_logging(function_name) ⇒ Object
240 241 242 243 244 245 246 247 |
# File 'lib/react_on_rails/server_rendering_pool/ruby_embedded_java_script.rb', line 240 def undefined_for_exec_js_logging(function_name) if ReactOnRails.configuration.trace "console.error('[React on Rails Rendering] #{function_name} is not defined for server rendering.');\n " \ "console.error(getStackTrace().join('\\n'));" else "" end end |