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.
@@ -0,0 +1,94 @@
1
+ module UniversalRenderer
2
+ module Client
3
+ class Stream
4
+ module Execution
5
+ class << self
6
+ def _perform_streaming(
7
+ http_client,
8
+ http_post_request,
9
+ response,
10
+ stream_uri
11
+ )
12
+ http_client.request(http_post_request) do |node_res|
13
+ Execution._handle_node_response_streaming(
14
+ node_res,
15
+ response,
16
+ stream_uri
17
+ )
18
+
19
+ return true
20
+ end
21
+ false
22
+ end
23
+
24
+ def _handle_node_response_streaming(node_res, response, stream_uri)
25
+ if node_res.is_a?(Net::HTTPSuccess)
26
+ Execution._stream_response_body(node_res, response.stream)
27
+ else
28
+ Execution._handle_streaming_for_node_error(
29
+ node_res,
30
+ response,
31
+ stream_uri
32
+ )
33
+ end
34
+ rescue StandardError => e
35
+ Rails.logger.error(
36
+ "Error during SSR data transfer or stream writing from #{stream_uri}: #{e.class.name} - #{e.message}"
37
+ )
38
+
39
+ Execution._write_generic_html_error(
40
+ response.stream,
41
+ "Streaming Error",
42
+ "<p>A problem occurred while loading content. Please refresh.</p>"
43
+ )
44
+ ensure
45
+ response.stream.close unless response.stream.closed?
46
+ end
47
+
48
+ def _stream_response_body(source_http_response, target_io_stream)
49
+ source_http_response.read_body do |chunk|
50
+ target_io_stream.write(chunk)
51
+ end
52
+ end
53
+
54
+ def _handle_streaming_for_node_error(node_res, response, stream_uri)
55
+ Rails.logger.error(
56
+ "SSR stream server at #{stream_uri} responded with #{node_res.code} #{node_res.message}."
57
+ )
58
+
59
+ is_potentially_viewable_error =
60
+ node_res["Content-Type"]&.match?(%r{text/html}i)
61
+
62
+ if is_potentially_viewable_error
63
+ Rails.logger.info(
64
+ "Attempting to stream HTML error page from Node SSR server."
65
+ )
66
+ Execution._stream_response_body(node_res, response.stream)
67
+ else
68
+ Rails.logger.warn(
69
+ "Node SSR server error response Content-Type ('#{node_res["Content-Type"]}') is not text/html. " \
70
+ "Injecting generic error message into the stream."
71
+ )
72
+
73
+ Execution._write_generic_html_error(
74
+ response.stream,
75
+ "Application Error",
76
+ "<p>There was an issue rendering this page. Please try again later.</p>"
77
+ )
78
+ end
79
+ end
80
+
81
+ def _write_generic_html_error(
82
+ stream,
83
+ title_text,
84
+ message_html_fragment
85
+ )
86
+ return if stream.closed?
87
+
88
+ stream.write("<h1>#{title_text}</h1>#{message_html_fragment}")
89
+ end
90
+ end
91
+ end
92
+ end
93
+ end
94
+ end
@@ -0,0 +1,39 @@
1
+ module UniversalRenderer
2
+ module Client
3
+ class Stream
4
+ module Setup
5
+ class << self
6
+ def _ensure_ssr_server_url_configured?(config)
7
+ config.ssr_url.present?
8
+ end
9
+
10
+ def _build_stream_request_components(body, config)
11
+ # Ensure ssr_url is present, though _ensure_ssr_server_url_configured? should have caught this.
12
+ # However, direct calls to this method might occur, so a check or reliance on config.ssr_url is important.
13
+ if config.ssr_url.blank?
14
+ raise ArgumentError, "SSR URL is not configured."
15
+ end
16
+
17
+ parsed_ssr_url = URI.parse(config.ssr_url)
18
+ stream_uri = URI.join(parsed_ssr_url, config.ssr_stream_path)
19
+
20
+ http = Net::HTTP.new(stream_uri.host, stream_uri.port)
21
+ http.use_ssl = (stream_uri.scheme == "https")
22
+ http.open_timeout = config.timeout
23
+ http.read_timeout = config.timeout
24
+
25
+ http_request =
26
+ Net::HTTP::Post.new(
27
+ stream_uri.request_uri,
28
+ "Content-Type" => "application/json"
29
+ )
30
+
31
+ http_request.body = body.to_json
32
+
33
+ [stream_uri, http, http_request]
34
+ end
35
+ end
36
+ end
37
+ end
38
+ end
39
+ end
@@ -0,0 +1,87 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "stream/error_logger"
4
+ require_relative "stream/execution"
5
+ require_relative "stream/setup"
6
+
7
+ module UniversalRenderer
8
+ module Client
9
+ class Stream
10
+ extend ErrorLogger
11
+ extend Execution
12
+ extend Setup
13
+
14
+ # Orchestrates the streaming process for server-side rendering.
15
+ #
16
+ # @param url [String] The URL of the page to render.
17
+ # @param props [Hash] Data to be passed for rendering, including layout HTML.
18
+ # @param template [String] The HTML template to use for rendering.
19
+ # @param response [ActionDispatch::Response] The Rails response object to stream to.
20
+ # @return [Boolean] True if streaming was initiated, false otherwise.
21
+ def self.stream(url, props, template, response)
22
+ config = UniversalRenderer.config
23
+
24
+ unless Setup._ensure_ssr_server_url_configured?(config)
25
+ Rails.logger.warn(
26
+ "Stream: SSR URL (config.ssr_url) is not configured. Falling back."
27
+ )
28
+ return false
29
+ end
30
+
31
+ stream_uri_obj = nil
32
+ full_ssr_url_for_log = config.ssr_url.to_s # For logging in case of early error
33
+
34
+ begin
35
+ body = { url: url, props: props, template: template }
36
+
37
+ actual_stream_uri, http_client, http_post_request =
38
+ Setup._build_stream_request_components(body, config)
39
+
40
+ stream_uri_obj = actual_stream_uri
41
+
42
+ full_ssr_url_for_log = actual_stream_uri.to_s # Update for more specific logging
43
+ rescue URI::InvalidURIError => e
44
+ Rails.logger.error(
45
+ "Stream: SSR stream failed due to invalid URI ('#{config.ssr_url}'): #{e.message}"
46
+ )
47
+
48
+ return false
49
+ rescue StandardError => e
50
+ _log_setup_error(e, full_ssr_url_for_log)
51
+
52
+ return false
53
+ end
54
+
55
+ Execution._perform_streaming(
56
+ http_client,
57
+ http_post_request,
58
+ response,
59
+ stream_uri_obj
60
+ )
61
+ rescue Errno::ECONNREFUSED,
62
+ Errno::EHOSTUNREACH,
63
+ Net::OpenTimeout,
64
+ Net::ReadTimeout,
65
+ SocketError,
66
+ IOError => e
67
+ uri_str_for_conn_error =
68
+ stream_uri_obj ? stream_uri_obj.to_s : full_ssr_url_for_log
69
+
70
+ ErrorLogger._log_connection_error(e, uri_str_for_conn_error)
71
+
72
+ false
73
+ rescue StandardError => e
74
+ uri_str_for_unexpected_error =
75
+ stream_uri_obj ? stream_uri_obj.to_s : full_ssr_url_for_log
76
+
77
+ ErrorLogger._log_unexpected_error(
78
+ e,
79
+ uri_str_for_unexpected_error,
80
+ "Stream: Unexpected error during SSR stream process"
81
+ )
82
+
83
+ false
84
+ end
85
+ end
86
+ end
87
+ end
@@ -1,4 +1,7 @@
1
1
  module UniversalRenderer
2
2
  class Engine < ::Rails::Engine
3
+ ActiveSupport.on_load(:action_controller) do
4
+ include UniversalRenderer::Renderable
5
+ end
3
6
  end
4
7
  end
@@ -0,0 +1,162 @@
1
+ module UniversalRenderer
2
+ module Renderable
3
+ extend ActiveSupport::Concern
4
+
5
+ included do
6
+ include ActionController::Live
7
+ helper UniversalRenderer::SSR::Helpers
8
+ before_action :initialize_props
9
+ end
10
+
11
+ class_methods do
12
+ def enable_ssr(options = {})
13
+ class_attribute :enable_ssr, instance_writer: false
14
+ self.enable_ssr = true
15
+
16
+ class_attribute :ssr_streaming_preference, instance_writer: false
17
+ self.ssr_streaming_preference = options[:streaming]
18
+ end
19
+ end
20
+
21
+ # Fetches Server-Side Rendered (SSR) content for the current request.
22
+ # This method makes a blocking call to the SSR service using {UniversalRenderer::Client::Base.fetch}
23
+ # and stores the result in the `@ssr` instance variable.
24
+ #
25
+ # The SSR content is fetched based on the `request.original_url` and the
26
+ # `@universal_renderer_props` accumulated for the request.
27
+ #
28
+ # @return [Hash, nil] The fetched SSR data (typically a hash with keys like `:head`, `:body_html`, `:body_attrs`),
29
+ # or `nil` if the fetch fails or SSR is not configured.
30
+ def fetch_ssr
31
+ @ssr =
32
+ UniversalRenderer::Client::Base.fetch(
33
+ request.original_url,
34
+ @universal_renderer_props
35
+ )
36
+ end
37
+
38
+ def use_ssr_streaming?
39
+ self.class.try(:ssr_streaming_preference)
40
+ end
41
+
42
+ private
43
+
44
+ def render(*args, **kwargs)
45
+ return super unless self.class.enable_ssr
46
+
47
+ return super unless request.format.html?
48
+
49
+ if use_ssr_streaming?
50
+ render_ssr_stream(*args, **kwargs)
51
+ else
52
+ fetch_ssr
53
+ super
54
+ end
55
+ end
56
+
57
+ def render_ssr_stream(*args, **kwargs)
58
+ set_streaming_headers
59
+
60
+ full_layout = render_to_string(*args, **kwargs)
61
+
62
+ split_index = full_layout.index(SSR::Placeholders::META)
63
+ before_meta = full_layout[0...split_index]
64
+ after_meta = full_layout[split_index..]
65
+
66
+ response.stream.write(before_meta)
67
+
68
+ current_props = @universal_renderer_props.dup
69
+
70
+ streaming_succeeded =
71
+ UniversalRenderer::Client::Stream.stream(
72
+ request.original_url,
73
+ current_props,
74
+ after_meta,
75
+ response
76
+ )
77
+
78
+ # SSR streaming failed or was not possible (e.g. server down, config missing).
79
+ unless streaming_succeeded
80
+ Rails.logger.error(
81
+ "SSR stream fallback: " \
82
+ "Streaming failed, proceeding with standard rendering."
83
+ )
84
+ response.stream.write(after_meta)
85
+ end
86
+
87
+ response.stream.close unless response.stream.closed?
88
+ end
89
+
90
+ def initialize_props
91
+ @universal_renderer_props = {}
92
+ end
93
+
94
+ # Adds a prop or a hash of props to be sent to the SSR service.
95
+ # Props are deep-stringified if a hash is provided.
96
+ #
97
+ # @param key_or_hash [String, Symbol, Hash] The key for the prop or a hash of props.
98
+ # @param data_value [Object, nil] The value for the prop if `key_or_hash` is a key.
99
+ # If `key_or_hash` is a Hash, this parameter is ignored.
100
+ # @example Adding a single prop
101
+ # add_prop(:user_id, 123)
102
+ # @example Adding multiple props from a hash
103
+ # add_prop({theme: "dark", locale: "en"})
104
+ # @return [void]
105
+ def add_prop(key_or_hash, data_value = nil)
106
+ if data_value.nil? && key_or_hash.is_a?(Hash)
107
+ @universal_renderer_props.merge!(key_or_hash.deep_stringify_keys)
108
+ else
109
+ @universal_renderer_props[key_or_hash.to_s] = data_value
110
+ end
111
+ end
112
+
113
+ # Allows a prop to be treated as an array, pushing new values to it.
114
+ # If the prop does not exist or is `nil`, it\'s initialized as an empty array.
115
+ # If the prop exists but is not an array (e.g., set as a scalar by `add_prop`),
116
+ # its current value will be converted into the first element of the new array.
117
+ # If `value_to_add` is an array, its elements are concatenated to the existing array.
118
+ # Otherwise, `value_to_add` is appended as a single element.
119
+ #
120
+ # @param key [String, Symbol] The key of the prop to modify.
121
+ # @param value_to_add [Object, Array] The value or array of values to add to the prop.
122
+ # @example Pushing a single value
123
+ # push_prop(:notifications, "New message")
124
+ # @example Pushing multiple values from an array
125
+ # push_prop(:tags, ["rails", "ruby"])
126
+ # @example Appending to an existing scalar value (converts to array)
127
+ # add_prop(:item, "first")
128
+ # push_prop(:item, "second") # @universal_renderer_props becomes { "item" => ["first", "second"] }
129
+ # @return [void]
130
+ def push_prop(key, value_to_add)
131
+ prop_key = key.to_s
132
+ current_value = @universal_renderer_props[prop_key]
133
+
134
+ if current_value.nil?
135
+ @universal_renderer_props[prop_key] = []
136
+ elsif !current_value.is_a?(Array)
137
+ @universal_renderer_props[prop_key] = [current_value]
138
+ end
139
+ # At this point, @universal_renderer_props[prop_key] is guaranteed to be an array.
140
+
141
+ if value_to_add.is_a?(Array)
142
+ @universal_renderer_props[prop_key].concat(value_to_add)
143
+ else
144
+ @universal_renderer_props[prop_key] << value_to_add
145
+ end
146
+ end
147
+
148
+ def set_streaming_headers
149
+ # Tell Cloudflare / proxies not to cache or buffer.
150
+ response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
151
+ response.headers["Pragma"] = "no-cache"
152
+ response.headers["Expires"] = "0"
153
+
154
+ # Disable Nginx buffering per-response.
155
+ response.headers["X-Accel-Buffering"] = "no"
156
+ response.headers["Content-Type"] = "text/html"
157
+
158
+ # Remove Content-Length header to prevent buffering.
159
+ response.headers.delete("Content-Length")
160
+ end
161
+ end
162
+ end
@@ -0,0 +1,45 @@
1
+ module UniversalRenderer
2
+ module SSR
3
+ module Helpers
4
+ # @!method ssr_meta
5
+ # Outputs a meta tag placeholder for SSR content.
6
+ # This placeholder is used by the rendering process to inject SSR metadata.
7
+ # @return [String] The HTML-safe string "<!-- SSR_META -->".
8
+ def ssr_meta
9
+ Placeholders::META.html_safe
10
+ end
11
+
12
+ # @!method ssr_body
13
+ # Outputs a body placeholder for SSR content.
14
+ # This placeholder is used by the rendering process to inject the main SSR body.
15
+ # @return [String] The HTML-safe string "<!-- SSR_BODY -->".
16
+ def ssr_body
17
+ Placeholders::BODY.html_safe
18
+ end
19
+
20
+ # @!method sanitize_ssr(html)
21
+ # Sanitizes HTML content rendered by the SSR service.
22
+ # Uses a custom scrubber ({UniversalRenderer::SSR::Scrubber}) to remove potentially
23
+ # harmful elements like scripts and event handlers, while allowing safe tags
24
+ # like stylesheets and meta tags.
25
+ # @param html [String] The HTML string to sanitize.
26
+ # @return [String] The sanitized HTML string.
27
+ def sanitize_ssr(html)
28
+ sanitize(html, scrubber: Scrubber.new)
29
+ end
30
+
31
+ # @!method use_ssr_streaming?
32
+ # Determines if SSR streaming should be used for the current request.
33
+ # The decision is based solely on the `ssr_streaming_preference` class attribute
34
+ # set on the controller.
35
+ # - If `ssr_streaming_preference` is `true`, streaming is enabled.
36
+ # - If `ssr_streaming_preference` is `false`, streaming is disabled.
37
+ # - If `ssr_streaming_preference` is `nil` (not set), streaming is disabled.
38
+ # @return [Boolean, nil] The value of `ssr_streaming_preference` (true, false, or nil).
39
+ # In conditional contexts, `nil` will behave as `false`.
40
+ def use_ssr_streaming?
41
+ controller.use_ssr_streaming?
42
+ end
43
+ end
44
+ end
45
+ end
@@ -0,0 +1,8 @@
1
+ module UniversalRenderer
2
+ module SSR
3
+ module Placeholders
4
+ META = "<!-- SSR_META -->".freeze
5
+ BODY = "<!-- SSR_BODY -->".freeze
6
+ end
7
+ end
8
+ end
@@ -0,0 +1,62 @@
1
+ require "loofah"
2
+
3
+ module UniversalRenderer
4
+ module SSR
5
+ class Scrubber < ::Loofah::Scrubber
6
+ def initialize
7
+ super
8
+ @direction = :top_down
9
+ end
10
+
11
+ def scrub(node)
12
+ # Primary actions: stop if script, continue if a passthrough tag, otherwise clean attributes.
13
+ return Loofah::Scrubber::STOP if handle_script_node(node) # Checks for <script> and removes it
14
+
15
+ # Allows <link rel="stylesheet">, <style>, <meta> to pass through this scrubber.
16
+ return Loofah::Scrubber::CONTINUE if passthrough_node?(node)
17
+
18
+ # For all other nodes, clean potentially harmful attributes.
19
+ clean_attributes(node)
20
+ # Default Loofah behavior (CONTINUE for children) applies if not returned earlier.
21
+ end
22
+
23
+ private
24
+
25
+ # Handles <script> tags: removes them and returns true if a script node was processed.
26
+ def handle_script_node(node)
27
+ return false unless node.name == "script"
28
+
29
+ node.remove
30
+ true # Indicates the node was a script and has been handled.
31
+ end
32
+
33
+ # Checks if the node is a type that should bypass detailed attribute scrubbing.
34
+ def passthrough_node?(node)
35
+ (node.name == "link" && node["rel"]&.to_s&.downcase == "stylesheet") ||
36
+ %w[style meta].include?(node.name)
37
+ end
38
+
39
+ # Orchestrates the cleaning of attributes for a given node.
40
+ def clean_attributes(node)
41
+ remove_javascript_href(node)
42
+ remove_event_handlers(node)
43
+ end
44
+
45
+ # Removes "javascript:" hrefs from <a> tags.
46
+ def remove_javascript_href(node)
47
+ return unless node.name == "a" && node["href"]
48
+ href = node["href"].to_s.downcase
49
+ node.remove_attribute("href") if href.start_with?("javascript:")
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
62
+ end
@@ -1,3 +1,3 @@
1
1
  module UniversalRenderer
2
- VERSION = "0.2.4".freeze
2
+ VERSION = "0.3.1".freeze
3
3
  end
@@ -1,7 +1,15 @@
1
1
  require "universal_renderer/version"
2
2
  require "universal_renderer/engine"
3
3
  require "universal_renderer/configuration"
4
- require "universal_renderer/ssr_scrubber"
4
+
5
+ require "universal_renderer/renderable"
6
+
7
+ require "universal_renderer/client/base"
8
+ require "universal_renderer/client/stream"
9
+
10
+ require "universal_renderer/ssr/helpers"
11
+ require "universal_renderer/ssr/placeholders"
12
+ require "universal_renderer/ssr/scrubber"
5
13
 
6
14
  module UniversalRenderer
7
15
  class << self
metadata CHANGED
@@ -1,13 +1,13 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: universal_renderer
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.2.4
4
+ version: 0.3.1
5
5
  platform: ruby
6
6
  authors:
7
7
  - thaske
8
8
  bindir: bin
9
9
  cert_chain: []
10
- date: 2025-05-20 00:00:00.000000000 Z
10
+ date: 2025-05-21 00:00:00.000000000 Z
11
11
  dependencies:
12
12
  - !ruby/object:Gem::Dependency
13
13
  name: loofah
@@ -30,9 +30,6 @@ dependencies:
30
30
  - - "~>"
31
31
  - !ruby/object:Gem::Version
32
32
  version: '7.1'
33
- - - ">="
34
- - !ruby/object:Gem::Version
35
- version: 7.1.5.1
36
33
  type: :runtime
37
34
  prerelease: false
38
35
  version_requirements: !ruby/object:Gem::Requirement
@@ -40,9 +37,6 @@ dependencies:
40
37
  - - "~>"
41
38
  - !ruby/object:Gem::Version
42
39
  version: '7.1'
43
- - - ">="
44
- - !ruby/object:Gem::Version
45
- version: 7.1.5.1
46
40
  description: Provides helper methods and configuration to forward rendering requests
47
41
  from a Rails app to an external SSR server and return the response.
48
42
  email:
@@ -54,21 +48,22 @@ files:
54
48
  - MIT-LICENSE
55
49
  - README.md
56
50
  - Rakefile
57
- - app/controllers/concerns/universal_renderer/rendering.rb
58
- - app/helpers/universal_renderer/ssr_helpers.rb
59
- - app/services/universal_renderer/static_client.rb
60
- - app/services/universal_renderer/stream_client.rb
61
- - app/services/universal_renderer/stream_client/error_logger.rb
62
- - app/services/universal_renderer/stream_client/execution.rb
63
- - app/services/universal_renderer/stream_client/setup.rb
64
51
  - config/routes.rb
65
52
  - lib/generators/universal_renderer/install_generator.rb
66
53
  - lib/generators/universal_renderer/templates/initializer.rb
67
54
  - lib/tasks/universal_renderer_tasks.rake
68
55
  - lib/universal_renderer.rb
56
+ - lib/universal_renderer/client/base.rb
57
+ - lib/universal_renderer/client/stream.rb
58
+ - lib/universal_renderer/client/stream/error_logger.rb
59
+ - lib/universal_renderer/client/stream/execution.rb
60
+ - lib/universal_renderer/client/stream/setup.rb
69
61
  - lib/universal_renderer/configuration.rb
70
62
  - lib/universal_renderer/engine.rb
71
- - lib/universal_renderer/ssr_scrubber.rb
63
+ - lib/universal_renderer/renderable.rb
64
+ - lib/universal_renderer/ssr/helpers.rb
65
+ - lib/universal_renderer/ssr/placeholders.rb
66
+ - lib/universal_renderer/ssr/scrubber.rb
72
67
  - lib/universal_renderer/version.rb
73
68
  homepage: https://github.com/thaske/universal_renderer
74
69
  licenses: