universal_renderer 0.2.4 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,132 +0,0 @@
1
- module UniversalRenderer
2
- module Rendering
3
- extend ActiveSupport::Concern
4
-
5
- included do
6
- include ActionController::Live
7
- helper UniversalRenderer::SsrHelpers
8
- before_action :initialize_props
9
- end
10
-
11
- private
12
-
13
- def default_render
14
- return super unless request.format.html?
15
- if use_ssr_streaming?
16
- render_ssr_stream
17
- else
18
- @ssr =
19
- UniversalRenderer::StaticClient.static(
20
- request.original_url,
21
- @universal_renderer_props
22
- )
23
- super
24
- end
25
- end
26
-
27
- def render_ssr_stream
28
- set_streaming_headers
29
-
30
- full_layout = render_to_string
31
-
32
- split_index = full_layout.index("<!-- SSR_META -->")
33
- before_meta = full_layout[0...split_index]
34
- after_meta = full_layout[split_index..]
35
-
36
- response.stream.write(before_meta)
37
-
38
- current_props = @universal_renderer_props.dup
39
-
40
- streaming_succeeded =
41
- UniversalRenderer::StreamClient.stream(
42
- request.original_url,
43
- current_props,
44
- after_meta,
45
- response
46
- )
47
-
48
- handle_ssr_stream_fallback(response) unless streaming_succeeded
49
- end
50
-
51
- def initialize_props
52
- @universal_renderer_props = {}
53
- end
54
-
55
- def add_props(key_or_hash, data_value = nil)
56
- if data_value.nil? && key_or_hash.is_a?(Hash)
57
- @universal_renderer_props.merge!(key_or_hash.deep_stringify_keys)
58
- else
59
- @universal_renderer_props[key_or_hash.to_s] = data_value
60
- end
61
- end
62
-
63
- # Allows a prop to be treated as an array, pushing new values to it.
64
- # If the prop does not exist or is nil, it's initialized as an array.
65
- # If the prop exists but is not an array (e.g., set as a scalar by `add_props`),
66
- # its current value will be converted into the first element of the new array.
67
- # If `value_to_add` is an array, its elements are concatenated. Otherwise, `value_to_add` is appended.
68
- def push_prop(key, value_to_add)
69
- prop_key = key.to_s
70
- current_value = @universal_renderer_props[prop_key]
71
-
72
- if current_value.nil?
73
- @universal_renderer_props[prop_key] = []
74
- elsif !current_value.is_a?(Array)
75
- @universal_renderer_props[prop_key] = [current_value]
76
- end
77
- # At this point, @universal_renderer_props[prop_key] is guaranteed to be an array.
78
-
79
- if value_to_add.is_a?(Array)
80
- @universal_renderer_props[prop_key].concat(value_to_add)
81
- else
82
- @universal_renderer_props[prop_key] << value_to_add
83
- end
84
- end
85
-
86
- def use_ssr_streaming?
87
- %w[1 true yes y].include?(ENV["ENABLE_SSR_STREAMING"]&.downcase)
88
- end
89
-
90
- def set_streaming_headers
91
- # Tell Cloudflare / proxies not to cache or buffer.
92
- response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
93
- response.headers["Pragma"] = "no-cache"
94
- response.headers["Expires"] = "0"
95
-
96
- # Disable Nginx buffering per-response.
97
- response.headers["X-Accel-Buffering"] = "no"
98
- response.headers["Content-Type"] = "text/html"
99
-
100
- # Remove Content-Length header to prevent buffering.
101
- response.headers.delete("Content-Length")
102
- end
103
-
104
- def handle_ssr_stream_fallback(response)
105
- # SSR streaming failed or was not possible (e.g. server down, config missing).
106
- # Ensure response hasn't been touched in a way that prevents a new render.
107
- return unless response.committed? || response.body.present?
108
-
109
- Rails.logger.error(
110
- "SSR stream fallback:" \
111
- "Cannot render default fallback template because response was already committed or body present."
112
- )
113
- # Close the stream if it's still open to prevent client connection from hanging
114
- # when we can't render a fallback page due to already committed response
115
- response.stream.close unless response.stream.closed?
116
- # If response not committed, no explicit render is called here,
117
- # allowing Rails' default rendering behavior to take over.
118
- end
119
-
120
- # Overrides the built-in render_to_string.
121
- # If you call render_to_string with no explicit template/partial/inline,
122
- # it will fall back to 'ssr/index'.
123
- def render_to_string(options = {}, *args, &block)
124
- if options.is_a?(Hash) && !options.key?(:template) &&
125
- !options.key?(:partial) && !options.key?(:inline) &&
126
- !options.key?(:json) && !options.key?(:xml)
127
- options = options.merge(template: "application/index")
128
- end
129
- super(options, *args, &block)
130
- end
131
- end
132
- end
@@ -1,19 +0,0 @@
1
- module UniversalRenderer
2
- module SsrHelpers
3
- def ssr_meta
4
- "<!-- SSR_META -->".html_safe
5
- end
6
-
7
- def ssr_body
8
- "<!-- SSR_BODY -->".html_safe
9
- end
10
-
11
- def sanitize_ssr(html)
12
- sanitize(html, scrubber: SsrScrubber.new)
13
- end
14
-
15
- def use_ssr_streaming?
16
- %w[1 true yes y].include?(ENV["ENABLE_SSR_STREAMING"]&.downcase)
17
- end
18
- end
19
- end
@@ -1,56 +0,0 @@
1
- # frozen_string_literal: true
2
-
3
- require "net/http"
4
- require "json" # Ensure JSON is required for parsing and generation
5
- require "uri" # Ensure URI is required for URI parsing
6
-
7
- module UniversalRenderer
8
- class StaticClient
9
- class << self
10
- # Performs a POST request to the SSR service to get statically rendered content.
11
- #
12
- # @param url [String] The URL of the page to render.
13
- # @param props [Hash] Additional data to be passed for rendering (renamed from query_data for clarity).
14
- # @return [Hash, nil] The parsed JSON response as symbolized keys if successful, otherwise nil.
15
- def static(url, props)
16
- ssr_url = UniversalRenderer.config.ssr_url
17
- return if ssr_url.blank?
18
-
19
- timeout = UniversalRenderer.config.timeout
20
-
21
- begin
22
- uri = URI.parse(ssr_url)
23
- http = Net::HTTP.new(uri.host, uri.port)
24
- http.use_ssl = (uri.scheme == "https")
25
- http.open_timeout = timeout
26
- http.read_timeout = timeout
27
-
28
- request = Net::HTTP::Post.new(uri.request_uri) # Use uri.request_uri to include path if present in ssr_url
29
- request.body = { url: url, props: props }.to_json
30
- request["Content-Type"] = "application/json"
31
-
32
- response = http.request(request)
33
-
34
- if response.is_a?(Net::HTTPSuccess)
35
- JSON.parse(response.body).deep_symbolize_keys
36
- else
37
- Rails.logger.error(
38
- "SSR static request to #{ssr_url} failed: #{response.code} - #{response.message} (URL: #{url})"
39
- )
40
- nil
41
- end
42
- rescue Net::OpenTimeout, Net::ReadTimeout => e
43
- Rails.logger.error(
44
- "SSR static request to #{ssr_url} timed out: #{e.class.name} - #{e.message} (URL: #{url})"
45
- )
46
- nil
47
- rescue StandardError => e
48
- Rails.logger.error(
49
- "SSR static request to #{ssr_url} failed: #{e.class.name} - #{e.message} (URL: #{url})"
50
- )
51
- nil
52
- end
53
- end
54
- end
55
- end
56
- end
@@ -1,29 +0,0 @@
1
- module UniversalRenderer
2
- class StreamClient
3
- module ErrorLogger
4
- class << self
5
- def _log_setup_error(error, target_uri_string)
6
- backtrace_info = error.backtrace&.first || "No backtrace available"
7
- Rails.logger.error(
8
- "Unexpected error during SSR stream setup for #{target_uri_string}: " \
9
- "#{error.class.name} - #{error.message} at #{backtrace_info}"
10
- )
11
- end
12
-
13
- def _log_connection_error(error, target_uri_string)
14
- Rails.logger.error(
15
- "SSR stream connection to #{target_uri_string} failed: #{error.class.name} - #{error.message}"
16
- )
17
- end
18
-
19
- def _log_unexpected_error(error, target_uri_string, context_message)
20
- backtrace_info = error.backtrace&.first || "No backtrace available"
21
- Rails.logger.error(
22
- "#{context_message} for #{target_uri_string}: " \
23
- "#{error.class.name} - #{error.message} at #{backtrace_info}"
24
- )
25
- end
26
- end
27
- end
28
- end
29
- end
@@ -1,88 +0,0 @@
1
- module UniversalRenderer
2
- class StreamClient
3
- module Execution
4
- class << self
5
- def _perform_streaming(
6
- http_client,
7
- http_post_request,
8
- response,
9
- stream_uri
10
- )
11
- http_client.request(http_post_request) do |node_res|
12
- Execution._handle_node_response_streaming(
13
- node_res,
14
- response,
15
- stream_uri
16
- )
17
-
18
- return true
19
- end
20
- false
21
- end
22
-
23
- def _handle_node_response_streaming(node_res, response, stream_uri)
24
- if node_res.is_a?(Net::HTTPSuccess)
25
- Execution._stream_response_body(node_res, response.stream)
26
- else
27
- Execution._handle_streaming_for_node_error(
28
- node_res,
29
- response,
30
- stream_uri
31
- )
32
- end
33
- rescue StandardError => e
34
- Rails.logger.error(
35
- "Error during SSR data transfer or stream writing from #{stream_uri}: #{e.class.name} - #{e.message}"
36
- )
37
-
38
- Execution._write_generic_html_error(
39
- response.stream,
40
- "Streaming Error",
41
- "<p>A problem occurred while loading content. Please refresh.</p>"
42
- )
43
- ensure
44
- response.stream.close unless response.stream.closed?
45
- end
46
-
47
- def _stream_response_body(source_http_response, target_io_stream)
48
- source_http_response.read_body do |chunk|
49
- target_io_stream.write(chunk)
50
- end
51
- end
52
-
53
- def _handle_streaming_for_node_error(node_res, response, stream_uri)
54
- Rails.logger.error(
55
- "SSR stream server at #{stream_uri} responded with #{node_res.code} #{node_res.message}."
56
- )
57
-
58
- is_potentially_viewable_error =
59
- node_res["Content-Type"]&.match?(%r{text/html}i)
60
-
61
- if is_potentially_viewable_error
62
- Rails.logger.info(
63
- "Attempting to stream HTML error page from Node SSR server."
64
- )
65
- Execution._stream_response_body(node_res, response.stream)
66
- else
67
- Rails.logger.warn(
68
- "Node SSR server error response Content-Type ('#{node_res["Content-Type"]}') is not text/html. " \
69
- "Injecting generic error message into the stream."
70
- )
71
-
72
- Execution._write_generic_html_error(
73
- response.stream,
74
- "Application Error",
75
- "<p>There was an issue rendering this page. Please try again later.</p>"
76
- )
77
- end
78
- end
79
-
80
- def _write_generic_html_error(stream, title_text, message_html_fragment)
81
- return if stream.closed?
82
-
83
- stream.write("<h1>#{title_text}</h1>#{message_html_fragment}")
84
- end
85
- end
86
- end
87
- end
88
- end
@@ -1,37 +0,0 @@
1
- module UniversalRenderer
2
- class StreamClient
3
- module Setup
4
- class << self
5
- def _ensure_ssr_server_url_configured?(config)
6
- config.ssr_url.present?
7
- end
8
-
9
- def _build_stream_request_components(body, config)
10
- # Ensure ssr_url is present, though _ensure_ssr_server_url_configured? should have caught this.
11
- # However, direct calls to this method might occur, so a check or reliance on config.ssr_url is important.
12
- if config.ssr_url.blank?
13
- raise ArgumentError, "SSR URL is not configured."
14
- end
15
-
16
- parsed_ssr_url = URI.parse(config.ssr_url)
17
- stream_uri = URI.join(parsed_ssr_url, config.ssr_stream_path)
18
-
19
- http = Net::HTTP.new(stream_uri.host, stream_uri.port)
20
- http.use_ssl = (stream_uri.scheme == "https")
21
- http.open_timeout = config.timeout
22
- http.read_timeout = config.timeout
23
-
24
- http_request =
25
- Net::HTTP::Post.new(
26
- stream_uri.request_uri,
27
- "Content-Type" => "application/json"
28
- )
29
-
30
- http_request.body = body.to_json
31
-
32
- [stream_uri, http, http_request]
33
- end
34
- end
35
- end
36
- end
37
- end
@@ -1,84 +0,0 @@
1
- # frozen_string_literal: true
2
-
3
- require_relative "stream_client/setup"
4
- require_relative "stream_client/execution"
5
- require_relative "stream_client/error_logger"
6
-
7
- module UniversalRenderer
8
- class StreamClient
9
- extend Setup
10
- extend Execution
11
- extend ErrorLogger
12
-
13
- # Orchestrates the streaming process for server-side rendering.
14
- #
15
- # @param url [String] The URL of the page to render.
16
- # @param props [Hash] Data to be passed for rendering, including layout HTML.
17
- # @param template [String] The HTML template to use for rendering.
18
- # @param response [ActionDispatch::Response] The Rails response object to stream to.
19
- # @return [Boolean] True if streaming was initiated, false otherwise.
20
- def self.stream(url, props, template, response)
21
- config = UniversalRenderer.config
22
-
23
- unless Setup._ensure_ssr_server_url_configured?(config)
24
- Rails.logger.warn(
25
- "StreamClient: SSR URL (config.ssr_url) is not configured. Falling back."
26
- )
27
- return false
28
- end
29
-
30
- stream_uri_obj = nil
31
- full_ssr_url_for_log = config.ssr_url.to_s # For logging in case of early error
32
-
33
- begin
34
- body = { url: url, props: props, template: template }
35
-
36
- actual_stream_uri, http_client, http_post_request =
37
- Setup._build_stream_request_components(body, config)
38
-
39
- stream_uri_obj = actual_stream_uri
40
-
41
- full_ssr_url_for_log = actual_stream_uri.to_s # Update for more specific logging
42
- rescue URI::InvalidURIError => e
43
- Rails.logger.error(
44
- "StreamClient: SSR stream failed due to invalid URI ('#{config.ssr_url}'): #{e.message}"
45
- )
46
-
47
- return false
48
- rescue StandardError => e
49
- _log_setup_error(e, full_ssr_url_for_log)
50
-
51
- return false
52
- end
53
-
54
- Execution._perform_streaming(
55
- http_client,
56
- http_post_request,
57
- response,
58
- stream_uri_obj
59
- )
60
- rescue Errno::ECONNREFUSED,
61
- Errno::EHOSTUNREACH,
62
- Net::OpenTimeout,
63
- Net::ReadTimeout,
64
- SocketError => e
65
- uri_str_for_conn_error =
66
- stream_uri_obj ? stream_uri_obj.to_s : full_ssr_url_for_log
67
-
68
- ErrorLogger._log_connection_error(e, uri_str_for_conn_error)
69
-
70
- false
71
- rescue StandardError => e
72
- uri_str_for_unexpected_error =
73
- stream_uri_obj ? stream_uri_obj.to_s : full_ssr_url_for_log
74
-
75
- ErrorLogger._log_unexpected_error(
76
- e,
77
- uri_str_for_unexpected_error,
78
- "StreamClient: Unexpected error during SSR stream process"
79
- )
80
-
81
- false
82
- end
83
- end
84
- end
@@ -1,61 +0,0 @@
1
- require "loofah"
2
-
3
- module UniversalRenderer
4
- class SsrScrubber < ::Loofah::Scrubber
5
- def initialize
6
- super
7
- @direction = :top_down
8
- end
9
-
10
- def scrub(node)
11
- # Primary actions: stop if script, continue if a passthrough tag, otherwise clean attributes.
12
- return Loofah::Scrubber::STOP if handle_script_node(node) # Checks for <script> and removes it
13
-
14
- # Allows <link rel="stylesheet">, <style>, <meta> to pass through this scrubber.
15
- return Loofah::Scrubber::CONTINUE if passthrough_node?(node)
16
-
17
- # For all other nodes, clean potentially harmful attributes.
18
- clean_attributes(node)
19
- # Default Loofah behavior (CONTINUE for children) applies if not returned earlier.
20
- end
21
-
22
- private
23
-
24
- # Handles <script> tags: removes them and returns true if a script node was processed.
25
- def handle_script_node(node)
26
- return false unless node.name == "script"
27
-
28
- node.remove
29
- true # Indicates the node was a script and has been handled.
30
- end
31
-
32
- # Checks if the node is a type that should bypass detailed attribute scrubbing.
33
- def passthrough_node?(node)
34
- (node.name == "link" && node["rel"]&.to_s&.downcase == "stylesheet") ||
35
- %w[style meta].include?(node.name)
36
- end
37
-
38
- # Orchestrates the cleaning of attributes for a given node.
39
- def clean_attributes(node)
40
- remove_javascript_href(node)
41
- remove_event_handlers(node)
42
- end
43
-
44
- # Removes "javascript:" hrefs from <a> tags.
45
- def remove_javascript_href(node)
46
- if node.name == "a" &&
47
- node["href"]&.to_s&.downcase&.start_with?("javascript:")
48
- node.remove_attribute("href")
49
- end
50
- end
51
-
52
- # Removes "on*" event handler attributes from any node.
53
- def remove_event_handlers(node)
54
- attrs_to_remove =
55
- node.attributes.keys.select do |name|
56
- name.to_s.downcase.start_with?("on")
57
- end
58
- attrs_to_remove.each { |attr_name| node.remove_attribute(attr_name) }
59
- end
60
- end
61
- end