Class: Streamdal::HostFunc
- Inherits:
-
Object
- Object
- Streamdal::HostFunc
- Defined in:
- lib/hostfunc.rb
Instance Method Summary collapse
- #encode(str) ⇒ Object
-
#http_request(caller, ptr, len) ⇒ Object
http_request performs a http request on behalf of a wasm module since WASI cannot talk sockets.
-
#initialize(kv) ⇒ HostFunc
constructor
This class holds methods that are called by wasm modules.
-
#kv_exists(caller, ptr, len) ⇒ Object
kv_exists is a host function that is used to check if a key exists in the KV store.
Constructor Details
#initialize(kv) ⇒ HostFunc
This class holds methods that are called by wasm modules
11 12 13 |
# File 'lib/hostfunc.rb', line 11 def initialize(kv) @kv = kv end |
Instance Method Details
#encode(str) ⇒ Object
65 66 67 |
# File 'lib/hostfunc.rb', line 65 def encode(str) str.force_encoding('ascii-8bit').encode('utf-8', invalid: :replace, undef: :replace, replace: '?') end |
#http_request(caller, ptr, len) ⇒ Object
http_request performs a http request on behalf of a wasm module since WASI cannot talk sockets
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 |
# File 'lib/hostfunc.rb', line 39 def http_request(caller, ptr, len) data = caller.export('memory').to_memory.read(ptr, len) # Read request from memory and decode into HttpRequest req = Streamdal::Protos::WASMRequest.decode(data) begin req_body = _get_request_body_for_mode(req) rescue => e return _http_request_response(caller, 400, e.to_s, {}) end # Attempt to make HTTP request # On error, return a mock 400 response with the error as the body begin response = _make_http_request(req.step.http_request.request, req_body) rescue => e return _http_request_response(caller, 400, "Unable to execute HTTP request: #{e}", {}) end # Convert body to utf8 out = encode(response.body) _http_request_response(caller, response.code, out, response.headers) end |
#kv_exists(caller, ptr, len) ⇒ Object
kv_exists is a host function that is used to check if a key exists in the KV store
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
# File 'lib/hostfunc.rb', line 17 def kv_exists(caller, ptr, len) data = caller.export('memory').to_memory.read(ptr, len) # Read request from memory and decode into HttpRequest req = Streamdal::Protos::KVStep.decode(data) exists = @kv.exists(req.key) msg = exists ? "Key '#{req.key}' exists" : "Key #{req.key} does not exist" status = exists ? :KV_STATUS_SUCCESS : :KV_STATUS_FAILURE wasm_resp = Streamdal::Protos::KVStepResponse.new wasm_resp.status = status wasm_resp. = msg write_to_memory(caller, wasm_resp) end |