Skip to content

About

Use this gem to run rack and roda on the ruby.wasm build for Internet Computer.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

10 Commits

Folders and files

Repository files navigation

juggalo_icp

This rack-based gem is being evolved into a production server designed and optimized for the Internet Computer on-chain runtime.

check it out in action via Philippine Ruby Users' Group's quickstarts: Roda - https://gitlab.com/phrug/phrug-icp-demo Rails - https://gitlab.com/phrug/phrug-icp-demo-rails

I've endeavoured to make it interchangeable with servers like Puma (which can't run, because the IC runtime is single-threaded only).

Serve a Rack app from a Ruby canister on the Internet Computer, through the IC HTTP gateway. For canisters packed by ruby_wasm_builder from 0.7.0.

Pure Ruby, no dependencies. It works the same on the minimal and full Builds: it names no standard library, no C extension and no Encoding constant.

Two pieces

  • The Adapter, require "juggalo_icp": turns one gateway request into a Rack env and a Rack response back into the gateway's record, and applies the query/update rule. About 150 lines, no dependency. Copy just this if you boot your app yourself.
  • The Server, require "juggalo_icp/server" (from 0.3.0): boots your app from its rackup file, answers the gateway for it, hands your canister's other Candid methods to it, and gives queries Block Randomness. It needs Rack, carried in your Application.

Setting up the Server

gem install juggalo_icp
juggalo_icp setup            # or: juggalo_icp setup --dry-run path/to/dir

setup works in the directory that holds app.rb (backend/, else backend/app/, else the one you name). It's safe to run again, after every upgrade of the gem:

  1. It copies the gem's lib/ to vendor/juggalo_icp/ beside app.rb.

  2. It writes the fence in app.rb, and touches nothing outside it:

    # >>> juggalo_icp (written by `juggalo_icp setup`; edit outside these lines)
    $LOAD_PATH.unshift(File.join(__dir__, "vendor/juggalo_icp"))
    require "juggalo_icp/server"
    SERVER = JuggaloIcp::Server.boot(
      root: RubyWasmIcInstaller::Canister.application_dir,
      settings: RubyWasmIcInstaller::Canister.server_settings,
    ) { |error| RubyWasmIcInstaller::Canister.boot_finished(error) }
    def http_request(req) = SERVER.query(req)
    def http_request_update(req) = SERVER.update(req)
    def visit(*args) = SERVER.call(:visit, *args)
    # <<< juggalo_icp

    That's the fence when app.rb uses ruby_wasm_ic_installer (it mentions RubyWasmIcInstaller::Canister). Otherwise the boot line is JuggaloIcp::Server.boot(root: File.join(__dir__, "application")): to change it, copy the fence's lines outside the markers and delete the markers. If app.rb calls boot_finished itself, setup says so: the fence's block calls it now.

  3. It writes one line per method of ic-interface.did's service, except the gateway's two and any method app.rb already defines outside the fence (and it prints each one it skips).

The gem defines no top-level methods; the fence does.

The boot

JuggaloIcp::Server.boot(root:, settings: {}) { |error| … } runs while app.rb is evaluated, after anything that sets ENV or the load path (the Server does neither):

Server Settings

settings: takes string or symbol keys (an installer's YAML map, or your own). An unknown key is logged and ignored; a wrong value is logged and the default used.

key default meaning
rackup config.ru the rackup file, relative to root
warm_up / the Warm-up Request's path; false for none
block_random_key BLOCK_RANDOM_KEY the ENV name of Block Randomness's key

Block Randomness

SecureRandom refuses in a query, and rand repeats until the next update. For a value a query may vary by block (a shuffle, a sample):

JuggaloIcp.block_random("story", visitor_id) # => 64 hex digits

It's HMAC-SHA256(key, [IC.time, *material].join("\0")), the key read from ENV["BLOCK_RANDOM_KEY"] (or the name in block_random_key); give it 64 random bytes as hex, drawn at install (ruby_wasm_ic_installer's Drawn Secrets). No key raises JuggaloIcp::NoBlockRandomKey. The same block and material give the same value, so it is not for secrets: node operators can read the key, and a caller who dislikes a value can ask again next block. It uses OpenSSL::HMAC where OpenSSL is loaded, and the gem's plain-Ruby SHA-256 on minimal (about 0.35 ms a call on MRI).

Logs

Every line the Server writes is one $stdout.write, starting juggalo, so it's one canister log record and grep juggalo finds them. The boot logs juggalo boot rack|app|warm_up|total <n>, where n is instructions on a canister (the IC's counter, behind Process::CLOCK_PROCESS_CPUTIME_ID) and CPU nanoseconds on MRI. The Server logs no requests.

Which method answered: env["ic.call"]

The Adapter sets env["ic.call"] to "query" (from http_request) or "update" (from http_request_update). The IC keeps no log line, and no write, from a gateway query, so skip that work there:

# A Rack middleware: no request logging in queries.
class QuietQueries
  def initialize(app) = @app = app

  def call(env)
    return @app.call(env) unless env["ic.call"] == "query"

    level = Rails.logger.level
    Rails.logger.level = :warn
    @app.call(env)
  ensure
    Rails.logger.level = level if level
  end
end

A query that the IC happens to run in replicated mode (whose logs it does keep) still says "query": the canister can't tell.

Carrying the Adapter alone

A canister has no bundle install. Carry the gem's files in your Application, as you carry Rack (juggalo_icp setup does this for you):

gem fetch juggalo_icp && gem unpack juggalo_icp-*.gem
cp -r juggalo_icp-*/lib my_app/vendor/juggalo_icp
# app.rb
$LOAD_PATH.unshift(File.join(__dir__, "vendor/juggalo_icp"))
require "juggalo_icp"

To move to a newer version, unpack it and copy its lib/ again.

Declaring and serving the gateway's methods

One word in ic-interface.rb declares the gateway's types and both methods:

# ic-interface.rb
http_gateway

They are declared as follows:

type :HeaderField, Tuple[Text, Text]
type :HttpRequest, record(method: Text, url: Text, headers: Vec[:HeaderField], body: Blob,
                          certificate_version: Opt[Nat16])
type :HttpUpdateRequest, record(method: Text, url: Text, headers: Vec[:HeaderField], body: Blob)
type :HttpResponse, record(status_code: Nat16, headers: Vec[:HeaderField], body: Blob, upgrade: Opt[Bool])

query  :http_request,        takes: [:HttpRequest],       returns: :HttpResponse
update :http_request_update, takes: [:HttpUpdateRequest], returns: :HttpResponse

Then hand both to your app (the Server's fence does this for you):

# app.rb
APP = ->(env) { [200, { "content-type" => "text/plain" }, ["hello from #{env['PATH_INFO']}"]] }

def http_request(req) = JuggaloIcp.query(APP, req)
def http_request_update(req) = JuggaloIcp.update(APP, req)
  • Client-written headers. The gateway passes the client's headers on unchanged, and adds no x-forwarded-for, x-real-ip or forwarded of its own. If one arrives, the client wrote it. They reach the app as HTTP_*, unchecked, so request.remote_ip in Rails (which prefers X-Forwarded-For) is whatever the client says, or 0.0.0.0. Don't key a rate limit or an audit trail on it.

  • The response: a header whose value is an Array, or lines joined by "\n" (Rack 3), goes out as one header each, so two set-cookie headers arrive as two. The body is joined and closed.

  • Upgrades. The gateway calls http_request as a query, and a query keeps nothing it writes. So JuggaloIcp.query answers only GET, HEAD and OPTIONS and upgrades everything else, via http_request_update through consensus. A GET that writes says so with the response header x-ic-upgrade (any value); the query upgrades it, and the header is never sent on.

  • env["ic.call"] is "query" or "update" (above).

  • rack.input is a small reader of its own (read, gets, each, rewind). For a StringIO, as Rack's own servers give, redefine JuggaloIcp.input:

    module JuggaloIcp
      def self.input(bytes) = StringIO.new(bytes.b)
    end

On the minimal Build

Rack and Roda need four libraries minimal lacks: Encoding::UTF_8 and its two siblings, date (only because time requires it), strscan and stringio. The ic_minimal gem carries pure-Ruby stand-ins for them, for a minimal canister only. juggalo_icp itself needs none of them.

Carry only the files of Rack your routes load, and check every carried file's magic comment: minimal knows only utf-8, us-ascii and ascii-8bit by those names, and Rack 3.1's rack/utils.rb says # encoding: binary, which traps the install. Change that word to ascii-8bit.

Not yet

  • Certified responses. Until the canister certifies its replies, the gateway refuses a plain query's reply on the certified domain (<id>.icp0.io) and serves it on <id>.raw.icp0.io. An upgraded request is served on either. So a public page is served raw, or by upgrading every GET (one update per page view).
  • File uploads (Tempfile) and streaming responses.

Development

bundle install
bundle exec rake        # the specs, on MRI, with no canister

The specs run on MRI: the Adapter's envs and responses from gateway records (spec/juggalo_icp_spec.rb), the Server booting rackup files in a temporary root (spec/server_spec.rb), and setup on a temporary app.rb (spec/setup_spec.rb). The development group carries Rack for them; the gem itself depends on nothing. What only a canister behind a real gateway can show is played by ruby_wasm_builder's suite, spec/gems/juggalo_icp_spec.rb. That spec installs the published gem and plays the 0.7.0 rack_adapter and roda_on_minimal Scripts with its lib/ in place of the Challenges' own copies.

MIT licensed.

About

Use this gem to run rack and roda on the ruby.wasm build for Internet Computer.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages