Class: Ask::Sandbox::Cloudflare

Inherits:
Base
  • Object
show all
Defined in:
lib/ask/sandbox/cloudflare.rb

Overview

Executes commands in a Cloudflare Workers sandbox via a user-deployed proxy Worker.

The proxy Worker wraps the @cloudflare/sandbox SDK and exposes an HTTP API. The user is responsible for deploying the proxy Worker to Cloudflare.

Examples:

sandbox = Ask::Sandbox::Cloudflare.new(
  worker_url: "https://sandbox-proxy.my-worker.workers.dev",
  auth_token: ENV["CLOUDFLARE_SANDBOX_TOKEN"]
)
sandbox.call(["ruby", "-e", "puts 1+1"])

Instance Method Summary collapse

Constructor Details

#initialize(worker_url: nil, auth_token: nil, timeout: 60) ⇒ Cloudflare

Returns a new instance of Cloudflare.

Parameters:

  • worker_url (String) (defaults to: nil)

    URL of the deployed proxy Worker

  • auth_token (String, nil) (defaults to: nil)

    auth token for the proxy Worker (optional)

  • timeout (Integer) (defaults to: 60)

    default timeout in seconds (default: 60)



25
26
27
28
29
# File 'lib/ask/sandbox/cloudflare.rb', line 25

def initialize(worker_url: nil, auth_token: nil, timeout: 60)
  @worker_url = worker_url || ENV["CLOUDFLARE_SANDBOX_WORKER_URL"]
  @auth_token = auth_token || ENV["CLOUDFLARE_SANDBOX_AUTH_TOKEN"]
  @default_timeout = timeout
end

Instance Method Details

#call(command, timeout: @default_timeout, workdir: nil, env: {}, stdin: nil) ⇒ Ask::Sandbox::Result

Execute a command in the sandbox.

Parameters:

  • command (String, Array<String>)

    When a String, executed via a shell (bash -c). When an Array, executed directly with no shell interpretation.

  • timeout (Integer) (defaults to: @default_timeout)

    max execution time in seconds (default: 30)

  • workdir (String, nil) (defaults to: nil)

    working directory inside the sandbox

  • env (Hash{String => String}) (defaults to: {})

    extra environment variables

  • stdin (String, nil) (defaults to: nil)

    data to pipe to the command’s stdin

Returns:

Raises:

  • (ArgumentError)


32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/ask/sandbox/cloudflare.rb', line 32

def call(command, timeout: @default_timeout, workdir: nil, env: {}, stdin: nil)
  raise ArgumentError, "command must not be nil" if command.nil?
  raise ArgumentError, "command must not be empty" if command.respond_to?(:empty?) && command.empty?
  raise ConfigurationError, "Cloudflare sandbox requires a worker_url. " \
                             "Set CLOUDFLARE_SANDBOX_WORKER_URL in your " \
                             "environment or pass `worker_url:` to #{self.class.name}.new" \
                             unless @worker_url

  command_str = case command
                when Array then command.map(&:to_s).join(" ")
                when String then command
                end

  make_request(command_str, timeout)
end