Skip to content

Sinatra

How a Sinatra app embeds droplets: a route fetches each fragment with Net::HTTP and an ERB view prints it into the page.

# shop.rb (trimmed)
def shop_fragment(id, params = [])
headers = { "accept" => "text/html", "x-droplet-location" => SHOP_ORIGIN, "referer" => SHOP_ORIGIN + shop_raw_target }
cookie = shop_cookie_header
headers["cookie"] = cookie if cookie
target = "/droplets/#{URI.encode_www_form_component(id)}?#{URI.encode_www_form(params)}"
result = { html: "", status: 502, location: nil, cookies: [], link: nil }
response = shop_request("GET", target, headers) # Net::HTTP to SHOP_INTERNAL_URL
code = response.code.to_i
result.merge!(status: code, cookies: response.get_fields("set-cookie") || [], link: response["link"])
if (300..399).cover?(code)
result[:location] = response["location"]
elsif (response.is_a?(Net::HTTPSuccess) || code == 500) && response["content-type"].to_s.start_with?("text/html")
result[:html] = response.body.to_s.force_encoding("UTF-8")
return result
end
# … anything else: result[:html] becomes a "droplet is unavailable" note
result
end
<%# views/shop/layout.erb, in <head>: once per page %>
<script type="module" src="/index.js"></script>
<%# views/shop/gallery.erb: the fragment's HTML, as it came %>
<aside><%= fragments[0] %></aside>
  • shop_fragment sends GET /droplets/<id>?<params> to SHOP_INTERNAL_URL with accept: text/html and x-droplet-location set to SHOP_ORIGIN, the origin of SHOP_PUBLIC_URL. It passes on the browser’s Cookie cut down to the shop’s own cart_id and shop_admin, and the page’s URL as referer: SHOP_ORIGIN plus the path and query as the browser sent them (shop_raw_target).
  • Net::HTTP never follows a redirect, so a droplet’s 3xx is kept: shop_render answers it with halt, and sends the fragments’ Set-Cookie with the page.
  • Only a text/html answer (a 2xx, or a 500 carrying the droplet’s error page) is pasted; <%= %> prints it unescaped.
  • views/shop/layout.erb loads /index.js once. SHOP_PROXIED, routed for every verb, passes /index.js, /env.js, /index.css, /droplets/*, /assets/* and /api/* on to the shop.

The shop demo on Sinatra 4, recorded by the end-to-end test. How the pieces fit has the diagram.

The shop flow on Sinatra 4, recorded by the end-to-end test.
  • The gallery, on Sinatra 4The gallery
  • A product in the cart, on Sinatra 4A product in the cart
  • The admin: stock set to 0, on Sinatra 4The admin: stock set to 0
  • The product page: out of stock, on Sinatra 4The product page: out of stock

The shop flow on Sinatra 4

The code is examples/hosts/sinatra/shop.rb (required by app.rb) and the ERB views in views/shop/.

docker-compose.yml starts three services:

Service Port What it is
web 8002, public Sinatra: the shop’s pages, the proxy, and the basic page at /
shop 8300, internal only the shop’s droplets server (examples/shop)
droplets 8000, public the Svelte example’s droplets server, for / only
On web Value Used for
SHOP_INTERNAL_URL http://shop:8300 internal: fragment fetches and the proxy
SHOP_PUBLIC_URL http://localhost:8002 public: this host’s own origin, sent as x-droplet-location
DROPLETS_INTERNAL_URL, DROPLETS_PUBLIC_URL http://droplets:8000, http://localhost:8000 the same pair, for the basic page

A server fetch with Net::HTTP, one thread per fragment, rendered into ERB. The fetch is shop_fragment and the view is views/shop/gallery.erb, both shown in the pattern above; the fragments’ Link preloads go into <head>. shop_render runs the fetches:

results = requests.map { |id, params| Thread.new { shop_fragment(id, params) } }.map(&:value)

referer is the page’s URL, query included. The shop’s handle reads it with hostFrom, so it is the droplet’s host, and after a form posted without JavaScript its query carries the form’s result. views/shop/layout.erb loads <script type="module" src="/index.js"> once, through the proxy, and each droplet hydrates itself. shop_render fetches the toasts and the header’s cart badge with every page’s fragments; the toast-center fragment comes first in the body, and /index.js installs window.shopMessageQueue before any droplet starts (the shop’s src/hooks.client.ts):

<%# views/shop/layout.erb %>
<body class="shop">
<%= @shop[:toasts] %>
<header class="shop-header">…<div class="shop-cart"><%= @shop[:cart] %></div>…</header>

The product page first reads the product from the shop’s public GET /droplets/product-page/_data?slug=<slug>; an unknown slug renders the not_found view with 404. The pages pass on only the query keys each droplet takes: the whole query to product-filter and product-library, order, page and showing (plus productId) to product-comments, slug and v to product-page, next to login, view and id to product-admin.

shop.rb
SHOP_PROXIED = %r{/(?:index\.js|env\.js|index\.css|(?:droplets|assets|api)/.*)}
%i[get post put patch delete options].each do |verb|
send(verb, SHOP_PROXIED) { shop_proxy }
end

/index.js, /env.js, /index.css, /droplets/* (fragments, _data, form actions), /assets/* and /api/* go to shop_proxy, for those verbs and HEAD, which Sinatra routes with every get. It sends the shop x-droplet-location written out. Of the browser’s headers it sends only accept, accept-language, content-type, if-none-match, origin, referer, user-agent, x-droplet-props and x-droplets-build, plus cookie cut down to the shop’s own cart_id and shop_admin (another app’s cookie on this origin stays here), with accept-encoding: identity so the body comes back as it is. The target is the raw path and query concatenated onto the shop’s base, never resolved, so //elsewhere stays a path on the shop. The answer comes back with its status, every Set-Cookie and any redirect, without connection, keep-alive, transfer-encoding, content-encoding and content-length. Net::HTTP waits 5 seconds to connect and 10 to read; a shop that cannot be reached answers 502 The shop is unreachable.

The shop’s cookies are first-party, and nothing is cross-origin; the shop sets them only from form actions and /api, which come through here.

  • Sinatra reads a form body before the route runs, and the server’s input cannot be rewound. A small middleware (ShopBufferedInput) buffers it so the proxy can pass the same body on, up to 4 MB (the admin’s image uploads; a bigger body is a 413), and method_override is off, since Rack::MethodOverride would read it even earlier.
  • Sinatra’s ERB does not escape <%= %> by default, which is how the fragments are pasted; the views escape everything else with h(). See For hosts.
  • The page is private, no-store. shop_render sets it before it answers the page or a fragment’s redirect: the fragments were rendered with the visitor’s cookies.
Terminal window
cd examples/hosts/sinatra
docker compose up --build
open http://localhost:8002/gallery # log in as admin / droplets

Set SHOP_SECRET and DROPLETS_SECRET first; compose refuses to start without them. The shop trusts one origin besides its own, DROPLETS_TRUSTED_ORIGINS: http://localhost:8002, this host’s; the rest of its environment is the same on every host: see Running a host.

The same app serves the Svelte example at /: its three droplets, one per mode, from examples/frameworks/svelte (the droplets service), fetched one after the other.

# app.rb (trimmed)
DROPLETS_INTERNAL_URL = ENV.fetch("DROPLETS_INTERNAL_URL", "http://localhost:8000")
DROPLETS_PUBLIC_URL = ENV.fetch("DROPLETS_PUBLIC_URL", "http://localhost:8000")
IDS = %w[client ssr-hydrate ssr-nohydrate].freeze
def fetch_droplet(droplet, props = {})
uri = URI("#{DROPLETS_INTERNAL_URL}/droplets/#{droplet}")
uri.query = URI.encode_www_form(props) unless props.empty?
# Net::HTTP never follows a redirect.
response = Net::HTTP.start(uri.host, uri.port, open_timeout: 5, read_timeout: 5) do |http|
http.get(uri.request_uri, { "accept" => "text/html", "x-droplet-location" => DROPLETS_PUBLIC_URL })
end
# Only an HTML answer is a fragment (a 500 carries the droplet's error
# page); anything else may echo the props, so it is never pasted.
is_html = response["content-type"].to_s.start_with?("text/html")
return response.body if (response.is_a?(Net::HTTPSuccess) || response.code == "500") && is_html
%(<p class="error">droplet "#{Rack::Utils.escape_html(droplet)}" unavailable: HTTP #{response.code}</p>)
rescue StandardError => e
%(<p class="error">droplet "#{Rack::Utils.escape_html(droplet)}" unavailable: #{Rack::Utils.escape_html(e.message)}</p>)
end
get "/" do
@droplets_public_url = DROPLETS_PUBLIC_URL
who = params.fetch("who", "Sinatra")
@fragments = IDS.map { |id| fetch_droplet(id, who: who) }
erb :index
end
<%# views/index.erb %>
<script type="module" src="<%= @droplets_public_url %>/index.js"></script>
…
<% @fragments.each do |fragment| %>
<%= fragment %>
<% end %>

Here the page loads /index.js from the droplets server’s public URL, another origin than the page, so the Svelte example runs with cors: true and DROPLETS_TRUSTED_ORIGINS lists both DROPLETS_URL and this host’s WEB_URL. Rails works the same way: fetch in the controller, raw or html_safe in the view.