Class: Wasval::Executor

Inherits:
Object
  • Object
show all
Defined in:
lib/wasval/executor.rb

Constant Summary collapse

STDOUT_BUFFER_SIZE =

10 MB

10 * 1024 * 1024
STDERR_BUFFER_SIZE =

1 MB

1 * 1024 * 1024
WASM_PATH =
ENV["WASVAL_RUBY_WASM_PATH"]
CWASM_PATH =
ENV["WASVAL_RUBY_CWASM_PATH"]

Instance Method Summary collapse

Constructor Details

#initializeExecutor

Returns a new instance of Executor.



12
13
14
15
16
17
18
19
20
21
22
# File 'lib/wasval/executor.rb', line 12

def initialize
  @engine = Wasmtime::Engine.new(epoch_interruption: true)

  if WASM_PATH
    @mod = Wasmtime::Module.from_file(@engine, WASM_PATH)
  elsif CWASM_PATH
    @mod = Wasmtime::Module.deserialize_file(@engine, CWASM_PATH)
  else
    raise ArgumentError.new "Please specify 'WASVAL_RUBY_WASM_PATH' or 'WASVAL_RUBY_CWASM_PATH' env"
  end
end

Instance Method Details

#execute(code:, timeout:, memory_limit:) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
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
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/wasval/executor.rb', line 24

def execute(code:, timeout:, memory_limit:)
  if code.nil? || code.strip.empty?
    return Result.new(
      status: :sandbox_error,
      output: "",
      stderr: "",
      error_message: "code must not be nil or empty"
    )
  end

  stdout_buf = +""
  stderr_buf = +""

  wasi_config = Wasmtime::WasiConfig.new
    .set_argv(["ruby", "-"])
    .set_stdin_string(wrapped_code(code))
    .set_stdout_buffer(stdout_buf, STDOUT_BUFFER_SIZE)
    .set_stderr_buffer(stderr_buf, STDERR_BUFFER_SIZE)

  store = Wasmtime::Store.new(@engine,
    wasi_p1_config: wasi_config,
    limits: { memory_size: memory_limit * 1024 * 1024 }
  )
  store.set_epoch_deadline(timeout)

  linker = Wasmtime::Linker.new(@engine)
  Wasmtime::WASI::P1.add_to_linker_sync(linker)

  @engine.start_epoch_interval(1000)

  begin
    linker.instantiate(store, @mod).invoke("_start")
    classify_output(stdout_buf, stderr_buf, store)
  rescue Wasmtime::WasiExit
    classify_output(stdout_buf, stderr_buf, store)
  rescue Wasmtime::Trap => e
    if e.code == :interrupt
      Result.new(status: :timeout, output: stdout_buf, stderr: "", error_message: "execution timed out")
    elsif store.linear_memory_limit_hit?
      Result.new(status: :memory_limit, output: stdout_buf, stderr: "", error_message: "memory limit exceeded")
    else
      Result.new(status: :sandbox_error, output: stdout_buf, stderr: stderr_buf, error_message: e.message)
    end
  rescue Wasmtime::Error => e
    if store.linear_memory_limit_hit?
      Result.new(status: :memory_limit, output: stdout_buf, stderr: "", error_message: "memory limit exceeded")
    else
      Result.new(status: :sandbox_error, output: stdout_buf, stderr: stderr_buf, error_message: e.message)
    end
  rescue => e
    Result.new(status: :sandbox_error, output: stdout_buf, stderr: stderr_buf, error_message: e.message)
  end
end