Skip to content

Commit

Permalink
Better error handling when page disconnects/unbinds.
Browse files Browse the repository at this point in the history
  • Loading branch information
ioquatix committed May 12, 2024
1 parent 801866d commit a9e7688
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 2 deletions.
12 changes: 10 additions & 2 deletions lib/live/element.rb
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@
require 'securerandom'

module Live
class PageError < RuntimeError
end

# Represents a single dynamic content area on the page.
class Element
def self.unique_id
Expand Down Expand Up @@ -66,8 +69,13 @@ def handle(event)
# @parameter method [Symbol] The name of the remote functio to invoke.
# @parameter arguments [Array]
def rpc(*arguments)
# This update might not be sent right away. Therefore, mutable arguments may be serialized to JSON at a later time (or never). This could be a race condition:
@page.updates.enqueue(arguments)
if @page
# This update might not be sent right away. Therefore, mutable arguments may be serialized to JSON at a later time (or never). This could be a race condition:
@page.updates.enqueue(arguments)
else
# This is a programming error, as it probably means the element is still part of the logic of the server side (e.g. async loop), but it is not bound to a page, so there is nothing to update/access/rpc.
raise PageError, "Element is not bound to a page, make sure to implement #close!"
end
end
end
end
16 changes: 16 additions & 0 deletions test/live/website.rb
Original file line number Diff line number Diff line change
Expand Up @@ -140,4 +140,20 @@ def app

expect(session.document_title).to be == "Executed"
end

it "can handle disconnects" do
navigate_to("/index.html")

# Wait for the page to load.
find_element(css: "#test p")

tag = resolver.bound.values.first

# Disconnect the session:
navigate_to("about:blank")

expect do
tag.update!
end.to raise_exception(Live::PageError, message: be =~ /not bound/)
end
end

0 comments on commit a9e7688

Please sign in to comment.