Skip to content

Commit a379c0a

Browse files
make retries HTTPX plugin not to retry if a streaming chunk is already received
1 parent 2eb6dd5 commit a379c0a

File tree

1 file changed

+25
-1
lines changed
  • react_on_rails_pro/lib/react_on_rails_pro

1 file changed

+25
-1
lines changed

react_on_rails_pro/lib/react_on_rails_pro/request.rb

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -227,7 +227,31 @@ def create_connection
227227
# For persistent connections we want retries,
228228
# so the requests don't just fail if the other side closes the connection
229229
# https://honeyryderchuck.gitlab.io/httpx/wiki/Persistent
230-
.plugin(:retries, max_retries: 1, retry_change_requests: true)
230+
.plugin(
231+
:retries, max_retries: 1,
232+
retry_change_requests: true,
233+
# Official HTTPx docs says that we should use the retry_on option to decide if teh request should be retried or not
234+
# However, HTTPx assumes that connection errors such as timeout error should be retried by default and it doesn't consider retry_on block at all at that case
235+
# So, we have to do the following trick to avoid retries when a Timeout error happens while streaming a component
236+
# If the streamed component returned any chunks, it shouldn't retry on errors, as it would cause page duplication
237+
# The SSR-generated html will be written to the page two times in this case
238+
retry_after: ->(request, response) do
239+
if (request.stream.instance_variable_get(:@react_on_rails_received_first_chunk))
240+
e = response.error
241+
raise ReactOnRailsPro::Error, "An error happened during server side render streaming of a component.\n" \
242+
"Original error:\n#{e}\n#{e.backtrace}"
243+
end
244+
245+
Rails.logger.info do
246+
"[ReactOnRailsPro] An error happneding while making a request to the Node Renderer.\n" \
247+
"Error: #{response.error}.\n" \
248+
"Retrying by HTTPX \"retries\" plugin..."
249+
end
250+
# The retry_after block expects to return a delay to wait before retrying the request
251+
# nil means no waiting delay
252+
nil
253+
end
254+
)
231255
.plugin(:stream)
232256
# See https://www.rubydoc.info/gems/httpx/1.3.3/HTTPX%2FOptions:initialize for the available options
233257
.with(

0 commit comments

Comments
 (0)