Cloudflare WorkersでRuby via WebAssemblyを動かそうと調べた
WASMとかWASIとか
WebAssembly | MDN
Standardizing WASI: A system interface to run WebAssembly outside the web - Mozilla Hacks - the Web developer blog
RubyをWASIファイルに変換する
Ruby 3.2.0 リリース
3.2.0からWASIベースのWebAssemblyへのコンパイルがサポートされた。
kateinoigakukun/wasi-vfs: A virtual filesystem layer for WASI.
wasi-vfsというのが必要らしい。これは何...ファイルシステム?
wasi-vfsでパックしたバイナリ(CRuby)を眺めてみた
つまり実行したいスクリプトも埋め込んじゃって、ワンバイナリでWasmのCRubyでアプリケーションを配布 できてしまうということ。
https://www.youtube.com/watch?v=-x8pU6mGtPIにRubyKaigiで作者からの解説があるので後で見てみる。
Macで実行するためのHomebrewが用意されてた。
code:sh
brew tap kateinoigakukun/wasi-vfs https://github.com/kateinoigakukun/wasi-vfs.git
brew install kateinoigakukun/wasi-vfs/wasi-vfs
WasmerというWASMを実行できるランタイムをダウンロード。今回はRubyで作成したWASMアプリを実行するのに使う。
code:sh
curl https://get.wasmer.io -sSfL | sh
ruby.wasmをダウンロードして展開し作成
code:sh
curl -LO https://github.com/ruby/ruby.wasm/releases/latest/download/ruby-3_2-wasm32-unknown-wasi-full.tar.gz
tar xfz ruby-3_2-wasm32-unknown-wasi-full.tar.gz
mv 3_2-wasm32-unknown-wasi-full/usr/local/bin/ruby ruby.wasm
Rubyのコードを書く。
code:sh
mkdir src
vim hello.rb
code:hello.rb
time = Time.now.strftime('%Y-%m-%d %H:%M:%S')
puts "#{time}Hello, WASM Ruby!"
Rubyと上で書いたコードをそれぞれvfsの/usrと/srcに配置してパッケージング
code:sh
wasi-vfs pack ruby.wasm --mapdir /src::./src --mapdir /usr::./3_2-wasm32-unknown-wasi-full/usr -o hello.wasm
実行
code:sh
wasmer hello.wasm -- /src/hello.rb
2023-09-03 13:30:00Hello, WASM Ruby!
生成されたWASMファイルは16MBもある!!!Workerのアップロード制限は1MBなので無理!!!
リンク
WebAssembly | MDN
Standardizing WASI: A system interface to run WebAssembly outside the web - Mozilla Hacks - the Web developer blog
Ruby 3.2.0 リリース
https://github.com/ruby/ruby/tree/master/wasm
kateinoigakukun/wasi-vfs: A virtual filesystem layer for WASI.
Introduction to Wasmer Documentation
wasm cloudflare ruby