Class: Daytona::Sandbox

Inherits:
Object
  • Object
show all
Includes:
Instrumentation
Defined in:
lib/daytona/sandbox.rb

Overview

rubocop:disable Metrics/ClassLength

Constant Summary collapse

DEFAULT_TIMEOUT =
60

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Instrumentation

included

Constructor Details

#initialize(code_toolbox:, sandbox_dto:, config:, sandbox_api:, otel_state: nil) ⇒ Sandbox

Returns a new instance of Sandbox.



122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
# File 'lib/daytona/sandbox.rb', line 122

def initialize(code_toolbox:, sandbox_dto:, config:, sandbox_api:, otel_state: nil) # rubocop:disable Metrics/MethodLength
  process_response(sandbox_dto)
  @code_toolbox = code_toolbox
  @config = config
  @sandbox_api = sandbox_api
  @otel_state = otel_state

  # Create toolbox API clients with dynamic configuration
  toolbox_api_config = build_toolbox_api_config

  # Helper to create API client with authentication header
  create_authenticated_client = lambda do
    client = DaytonaToolboxApiClient::ApiClient.new(toolbox_api_config)
    client.default_headers['Authorization'] = "Bearer #{config.api_key || config.jwt_token}"
    client.default_headers['X-Daytona-Source'] = 'sdk-ruby'
    client.default_headers['X-Daytona-SDK-Version'] = Sdk::VERSION
    client.default_headers['X-Daytona-Organization-ID'] = config.organization_id if config.jwt_token
    client.user_agent = "sdk-ruby/#{Sdk::VERSION}"
    client
  end

  process_api = DaytonaToolboxApiClient::ProcessApi.new(create_authenticated_client.call)
  fs_api = DaytonaToolboxApiClient::FileSystemApi.new(create_authenticated_client.call)
  git_api = DaytonaToolboxApiClient::GitApi.new(create_authenticated_client.call)
  lsp_api = DaytonaToolboxApiClient::LspApi.new(create_authenticated_client.call)
  computer_use_api = DaytonaToolboxApiClient::ComputerUseApi.new(create_authenticated_client.call)
  interpreter_api = DaytonaToolboxApiClient::InterpreterApi.new(create_authenticated_client.call)
  info_api = DaytonaToolboxApiClient::InfoApi.new(create_authenticated_client.call)

  @process = Process.new(
    sandbox_id: id,
    code_toolbox:,
    toolbox_api: process_api,
    get_preview_link: proc { |port| preview_url(port) },
    otel_state:
  )
  @fs = FileSystem.new(sandbox_id: id, toolbox_api: fs_api, otel_state:)
  @git = Git.new(sandbox_id: id, toolbox_api: git_api, otel_state:)
  @computer_use = ComputerUse.new(sandbox_id: id, toolbox_api: computer_use_api, otel_state:)
  @code_interpreter = CodeInterpreter.new(
    sandbox_id: id,
    toolbox_api: interpreter_api,
    get_preview_link: proc { |port| preview_url(port) },
    otel_state:
  )
  @lsp_api = lsp_api
  @info_api = info_api
end

Instance Attribute Details

#auto_archive_intervalFloat

Returns Auto-archive interval in minutes.

Returns:

  • (Float)

    Auto-archive interval in minutes



72
73
74
# File 'lib/daytona/sandbox.rb', line 72

def auto_archive_interval
  @auto_archive_interval
end

#auto_delete_intervalFloat

(negative value means disabled, 0 means delete immediately upon stopping)

Returns:

  • (Float)

    Auto-delete interval in minutes



76
77
78
# File 'lib/daytona/sandbox.rb', line 76

def auto_delete_interval
  @auto_delete_interval
end

#auto_stop_intervalFloat

Returns Auto-stop interval in minutes (0 means disabled).

Returns:

  • (Float)

    Auto-stop interval in minutes (0 means disabled)



69
70
71
# File 'lib/daytona/sandbox.rb', line 69

def auto_stop_interval
  @auto_stop_interval
end

#backup_created_atString (readonly)

Returns The creation timestamp of the last backup.

Returns:

  • (String)

    The creation timestamp of the last backup



66
67
68
# File 'lib/daytona/sandbox.rb', line 66

def backup_created_at
  @backup_created_at
end

#backup_stateString (readonly)

Returns The state of the backup.

Returns:

  • (String)

    The state of the backup



63
64
65
# File 'lib/daytona/sandbox.rb', line 63

def backup_state
  @backup_state
end

#build_infoDaytonaApiClient::BuildInfo (readonly)

Returns Build information for the sandbox.

Returns:

  • (DaytonaApiClient::BuildInfo)

    Build information for the sandbox



82
83
84
# File 'lib/daytona/sandbox.rb', line 82

def build_info
  @build_info
end

#code_interpreterDaytona::CodeInterpreter (readonly)



115
116
117
# File 'lib/daytona/sandbox.rb', line 115

def code_interpreter
  @code_interpreter
end

#code_toolboxDaytona::SandboxPythonCodeToolbox, Daytona::SandboxTsCodeToolbox (readonly)



94
95
96
# File 'lib/daytona/sandbox.rb', line 94

def code_toolbox
  @code_toolbox
end

#computer_useDaytona::ComputerUse (readonly)



112
113
114
# File 'lib/daytona/sandbox.rb', line 112

def computer_use
  @computer_use
end

#configDaytona::Config (readonly)

Returns:



97
98
99
# File 'lib/daytona/sandbox.rb', line 97

def config
  @config
end

#cpuFloat (readonly)

Returns The CPU quota for the sandbox.

Returns:

  • (Float)

    The CPU quota for the sandbox



42
43
44
# File 'lib/daytona/sandbox.rb', line 42

def cpu
  @cpu
end

#created_atString (readonly)

Returns The creation timestamp of the sandbox.

Returns:

  • (String)

    The creation timestamp of the sandbox



85
86
87
# File 'lib/daytona/sandbox.rb', line 85

def created_at
  @created_at
end

#daemon_versionString (readonly)

Returns The version of the daemon running in the sandbox.

Returns:

  • (String)

    The version of the daemon running in the sandbox



91
92
93
# File 'lib/daytona/sandbox.rb', line 91

def daemon_version
  @daemon_version
end

#desired_stateDaytonaApiClient::SandboxDesiredState (readonly)

Returns The desired state of the sandbox.

Returns:

  • (DaytonaApiClient::SandboxDesiredState)

    The desired state of the sandbox



57
58
59
# File 'lib/daytona/sandbox.rb', line 57

def desired_state
  @desired_state
end

#diskFloat (readonly)

Returns The disk quota for the sandbox.

Returns:

  • (Float)

    The disk quota for the sandbox



51
52
53
# File 'lib/daytona/sandbox.rb', line 51

def disk
  @disk
end

#envHash<String, String> (readonly)

Returns Environment variables for the sandbox.

Returns:

  • (Hash<String, String>)

    Environment variables for the sandbox



24
25
26
# File 'lib/daytona/sandbox.rb', line 24

def env
  @env
end

#error_reasonString (readonly)

Returns The error reason of the sandbox.

Returns:

  • (String)

    The error reason of the sandbox



60
61
62
# File 'lib/daytona/sandbox.rb', line 60

def error_reason
  @error_reason
end

#fsDaytona::FileSystem (readonly)

Returns:



106
107
108
# File 'lib/daytona/sandbox.rb', line 106

def fs
  @fs
end

#gitDaytona::Git (readonly)

Returns:



109
110
111
# File 'lib/daytona/sandbox.rb', line 109

def git
  @git
end

#gpuFloat (readonly)

Returns The GPU quota for the sandbox.

Returns:

  • (Float)

    The GPU quota for the sandbox



45
46
47
# File 'lib/daytona/sandbox.rb', line 45

def gpu
  @gpu
end

#idString (readonly)

Returns The ID of the sandbox.

Returns:

  • (String)

    The ID of the sandbox



12
13
14
# File 'lib/daytona/sandbox.rb', line 12

def id
  @id
end

#labelsHash<String, String>

Returns Labels for the sandbox.

Returns:

  • (Hash<String, String>)

    Labels for the sandbox



27
28
29
# File 'lib/daytona/sandbox.rb', line 27

def labels
  @labels
end

#memoryFloat (readonly)

Returns The memory quota for the sandbox.

Returns:

  • (Float)

    The memory quota for the sandbox



48
49
50
# File 'lib/daytona/sandbox.rb', line 48

def memory
  @memory
end

#network_allow_listString (readonly)

Returns Comma-separated list of allowed CIDR network addresses for the sandbox.

Returns:

  • (String)

    Comma-separated list of allowed CIDR network addresses for the sandbox



36
37
38
# File 'lib/daytona/sandbox.rb', line 36

def network_allow_list
  @network_allow_list
end

#network_block_allBoolean (readonly)

Returns Whether to block all network access for the sandbox.

Returns:

  • (Boolean)

    Whether to block all network access for the sandbox



33
34
35
# File 'lib/daytona/sandbox.rb', line 33

def network_block_all
  @network_block_all
end

#organization_idString (readonly)

Returns The organization ID of the sandbox.

Returns:

  • (String)

    The organization ID of the sandbox



15
16
17
# File 'lib/daytona/sandbox.rb', line 15

def organization_id
  @organization_id
end

#processDaytona::Process (readonly)

Returns:



103
104
105
# File 'lib/daytona/sandbox.rb', line 103

def process
  @process
end

#publicBoolean (readonly)

Returns Whether the sandbox http preview is public.

Returns:

  • (Boolean)

    Whether the sandbox http preview is public



30
31
32
# File 'lib/daytona/sandbox.rb', line 30

def public
  @public
end

#sandbox_apiDaytonaApiClient::SandboxApi (readonly)

Returns:

  • (DaytonaApiClient::SandboxApi)


100
101
102
# File 'lib/daytona/sandbox.rb', line 100

def sandbox_api
  @sandbox_api
end

#snapshotString (readonly)

Returns The snapshot used for the sandbox.

Returns:

  • (String)

    The snapshot used for the sandbox



18
19
20
# File 'lib/daytona/sandbox.rb', line 18

def snapshot
  @snapshot
end

#stateDaytonaApiClient::SandboxState (readonly)

Returns The state of the sandbox.

Returns:

  • (DaytonaApiClient::SandboxState)

    The state of the sandbox



54
55
56
# File 'lib/daytona/sandbox.rb', line 54

def state
  @state
end

#targetString (readonly)

Returns The target environment for the sandbox.

Returns:

  • (String)

    The target environment for the sandbox



39
40
41
# File 'lib/daytona/sandbox.rb', line 39

def target
  @target
end

#updated_atString (readonly)

Returns The last update timestamp of the sandbox.

Returns:

  • (String)

    The last update timestamp of the sandbox



88
89
90
# File 'lib/daytona/sandbox.rb', line 88

def updated_at
  @updated_at
end

#userString (readonly)

Returns The user associated with the project.

Returns:

  • (String)

    The user associated with the project



21
22
23
# File 'lib/daytona/sandbox.rb', line 21

def user
  @user
end

#volumesArray<DaytonaApiClient::SandboxVolume> (readonly)

Returns Array of volumes attached to the sandbox.

Returns:

  • (Array<DaytonaApiClient::SandboxVolume>)

    Array of volumes attached to the sandbox



79
80
81
# File 'lib/daytona/sandbox.rb', line 79

def volumes
  @volumes
end

Instance Method Details

#archivevoid

This method returns an undefined value.

Archives the sandbox, making it inactive and preserving its state. When sandboxes are archived, the entire filesystem state is moved to cost-effective object storage, making it possible to keep sandboxes available for an extended period. The tradeoff between archived and stopped states is that starting an archived sandbox takes more time, depending on its size. Sandbox must be stopped before archiving.



178
179
180
181
# File 'lib/daytona/sandbox.rb', line 178

def archive
  sandbox_api.archive_sandbox(id)
  refresh
end

#create_lsp_server(language_id:, path_to_project:) ⇒ Daytona::LspServer

Creates a new Language Server Protocol (LSP) server instance. The LSP server provides language-specific features like code completion, diagnostics, and more.

Parameters:

  • language_id (Symbol)

    The language server type (e.g., Daytona::LspServer::Language::PYTHON)

  • path_to_project (String)

    Path to the project root directory. Relative paths are resolved based on the sandbox working directory.

Returns:



438
439
440
# File 'lib/daytona/sandbox.rb', line 438

def create_lsp_server(language_id:, path_to_project:)
  LspServer.new(language_id:, path_to_project:, toolbox_api: @lsp_api, sandbox_id: id, otel_state:)
end

#create_signed_preview_url(port, expires_in_seconds = nil) ⇒ DaytonaApiClient::SignedPortPreviewUrl

Creates a signed preview URL for the sandbox at the specified port.

Examples:

signed_url = sandbox.create_signed_preview_url(3000, 120)
puts "Signed URL: #{signed_url.url}"
puts "Token: #{signed_url.token}"

Parameters:

  • port (Integer)

    The port to open the preview link on

  • expires_in_seconds (Integer, nil) (defaults to: nil)

    The number of seconds the signed preview URL will be valid for. Defaults to 60 seconds.

Returns:

  • (DaytonaApiClient::SignedPortPreviewUrl)

    The signed preview URL response object



292
293
294
# File 'lib/daytona/sandbox.rb', line 292

def create_signed_preview_url(port, expires_in_seconds = nil)
  sandbox_api.get_signed_port_preview_url(id, port, { expires_in_seconds: })
end

#create_ssh_access(expires_in_minutes) ⇒ DaytonaApiClient::SshAccessDto

Creates an SSH access token for the sandbox.

Parameters:

  • expires_in_minutes (Integer)

    TThe number of minutes the SSH access token will be valid for

Returns:

  • (DaytonaApiClient::SshAccessDto)


226
# File 'lib/daytona/sandbox.rb', line 226

def create_ssh_access(expires_in_minutes) = sandbox_api.create_ssh_access(id, { expires_in_minutes: })

#deletevoid

This method returns an undefined value.



229
230
231
232
233
234
235
236
# File 'lib/daytona/sandbox.rb', line 229

def delete
  sandbox_api.delete_sandbox(id)
  refresh
rescue DaytonaApiClient::ApiError => e
  raise unless e.code == 404

  @state = 'destroyed'
end

#expire_signed_preview_url(port, token) ⇒ void

This method returns an undefined value.

Expires a signed preview URL for the sandbox at the specified port.

Examples:

sandbox.expire_signed_preview_url(3000, "token-value")

Parameters:

  • port (Integer)

    The port to expire the signed preview URL on

  • token (String)

    The token to expire



304
305
306
# File 'lib/daytona/sandbox.rb', line 304

def expire_signed_preview_url(port, token)
  sandbox_api.expire_signed_port_preview_url(id, port, token)
end

#get_user_home_dirString

Gets the user’s home directory path for the logged in user inside the Sandbox.

Examples:

user_home_dir = sandbox.get_user_home_dir
puts "Sandbox user home: #{user_home_dir}"

Returns:

  • (String)

    The absolute path to the Sandbox user’s home directory for the logged in user



245
246
247
248
249
# File 'lib/daytona/sandbox.rb', line 245

def get_user_home_dir
  @info_api.get_user_home_dir.dir
rescue StandardError => e
  raise Sdk::Error, "Failed to get user home directory: #{e.message}"
end

#get_work_dirString

Gets the working directory path inside the Sandbox.

Examples:

work_dir = sandbox.get_work_dir
puts "Sandbox working directory: #{work_dir}"

Returns:

  • (String)

    The absolute path to the Sandbox working directory. Uses the WORKDIR specified in the Dockerfile if present, or falling back to the user’s home directory if not.



259
260
261
262
263
# File 'lib/daytona/sandbox.rb', line 259

def get_work_dir
  @info_api.get_work_dir.dir
rescue StandardError => e
  raise Sdk::Error, "Failed to get working directory path: #{e.message}"
end

#preview_url(port) ⇒ DaytonaApiClient::PortPreviewUrl

Retrieves the preview link for the sandbox at the specified port. If the port is closed, it will be opened automatically. For private sandboxes, a token is included to grant access to the URL.

Parameters:

  • port (Integer)

Returns:

  • (DaytonaApiClient::PortPreviewUrl)


279
# File 'lib/daytona/sandbox.rb', line 279

def preview_url(port) = sandbox_api.get_port_preview_url(id, port)

#recover(timeout = DEFAULT_TIMEOUT) ⇒ void

This method returns an undefined value.

Recovers the Sandbox from a recoverable error and waits for it to be ready.

Examples:

sandbox = daytona.get('my-sandbox-id')
sandbox.recover(timeout: 40)  # Wait up to 40 seconds
puts 'Sandbox recovered successfully'

Parameters:

  • timeout (Numeric) (defaults to: DEFAULT_TIMEOUT)

    Maximum wait time in seconds (defaults to 60 s).



356
357
358
359
360
361
362
363
364
# File 'lib/daytona/sandbox.rb', line 356

def recover(timeout = DEFAULT_TIMEOUT)
  with_timeout(
    timeout:,
    message: "Sandbox #{id} failed to recover within the #{timeout} seconds timeout period",
    setup: proc { process_response(sandbox_api.recover_sandbox(id)) }
  ) { wait_for_states(operation: OPERATION_START, target_states: [DaytonaApiClient::SandboxState::STARTED]) }
rescue StandardError => e
  raise Sdk::Error, "Failed to recover sandbox: #{e.message}"
end

#refreshvoid

This method returns an undefined value.

Refresh the Sandbox data from the API.



311
# File 'lib/daytona/sandbox.rb', line 311

def refresh = process_response(sandbox_api.get_sandbox(id))

#refresh_activityvoid

This method returns an undefined value.

Refreshes the sandbox activity to reset the timer for automated lifecycle management actions.

This method updates the sandbox’s last activity timestamp without changing its state. It is useful for keeping long-running sessions alive while there is still user activity.

Examples:

sandbox.refresh_activity


322
323
324
325
326
327
# File 'lib/daytona/sandbox.rb', line 322

def refresh_activity
  sandbox_api.update_last_activity(id)
  nil
rescue StandardError => e
  raise Sdk::Error, "Failed to refresh sandbox activity: #{e.message}"
end

#resize(resources, timeout = DEFAULT_TIMEOUT) ⇒ void

This method returns an undefined value.

Resizes the Sandbox resources.

Changes the CPU, memory, or disk allocation for the Sandbox. Resizing a started sandbox allows increasing CPU and memory. To resize disk or decrease resources, the sandbox must be stopped first.

Examples:

Resize a started sandbox (CPU and memory can be increased)

sandbox.resize(Daytona::Resources.new(cpu: 4, memory: 8))

Resize a stopped sandbox (CPU, memory, and disk can be changed)

sandbox.stop
sandbox.resize(Daytona::Resources.new(cpu: 2, memory: 4, disk: 30))

Parameters:

  • resources (Daytona::Resources)

    New resource configuration

  • timeout (Numeric) (defaults to: DEFAULT_TIMEOUT)

    Maximum wait time in seconds (defaults to 60 s)

Raises:



403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
# File 'lib/daytona/sandbox.rb', line 403

def resize(resources, timeout = DEFAULT_TIMEOUT)
  raise Sdk::Error, 'Resources must not be nil' if resources.nil?

  with_timeout(
    timeout:,
    message: "Sandbox #{id} failed to resize within the #{timeout} seconds timeout period",
    setup: proc {
      resize_attrs = {}
      resize_attrs[:cpu] = resources.cpu if resources.cpu
      resize_attrs[:memory] = resources.memory if resources.memory
      resize_attrs[:disk] = resources.disk if resources.disk
      resize_request = DaytonaApiClient::ResizeSandbox.new(resize_attrs)
      process_response(sandbox_api.resize_sandbox(id, resize_request))
    }
  ) { wait_for_resize_complete }
end

#revoke_ssh_access(token) ⇒ void

This method returns an undefined value.

Revokes an SSH access token for the sandbox.

Parameters:

  • token (String)


333
# File 'lib/daytona/sandbox.rb', line 333

def revoke_ssh_access(token) = sandbox_api.revoke_ssh_access(id, token:)

#start(timeout = DEFAULT_TIMEOUT) ⇒ void

This method returns an undefined value.

Starts the Sandbox and waits for it to be ready.

Parameters:

  • timeout (Numeric) (defaults to: DEFAULT_TIMEOUT)

    Maximum wait time in seconds (defaults to 60 s).



339
340
341
342
343
344
345
# File 'lib/daytona/sandbox.rb', line 339

def start(timeout = DEFAULT_TIMEOUT)
  with_timeout(
    timeout:,
    message: "Sandbox #{id} failed to become ready within the #{timeout} seconds timeout period",
    setup: proc { process_response(sandbox_api.start_sandbox(id)) }
  ) { wait_for_states(operation: OPERATION_START, target_states: [DaytonaApiClient::SandboxState::STARTED]) }
end

#stop(timeout = DEFAULT_TIMEOUT, force: false) ⇒ void

This method returns an undefined value.

Stops the Sandbox and waits for it to be stopped.

Parameters:

  • timeout (Numeric) (defaults to: DEFAULT_TIMEOUT)

    Maximum wait time in seconds (defaults to 60 s).

  • force (Boolean) (defaults to: false)

    If true, uses SIGKILL instead of SIGTERM (defaults to false).



371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
# File 'lib/daytona/sandbox.rb', line 371

def stop(timeout = DEFAULT_TIMEOUT, force: false) # rubocop:disable Metrics/MethodLength
  with_timeout(
    timeout:,
    message: "Sandbox #{id} failed to become stopped within the #{timeout} seconds timeout period",
    setup: proc {
      sandbox_api.stop_sandbox(id, { force: force })
      refresh
    }
  ) do
    wait_for_states(
      operation: OPERATION_STOP,
      target_states: [DaytonaApiClient::SandboxState::STOPPED, DaytonaApiClient::SandboxState::DESTROYED]
    )
  end
end

#validate_ssh_access(token) ⇒ DaytonaApiClient::SshAccessValidationDto

Validates an SSH access token for the sandbox.

Parameters:

  • token (String)

Returns:

  • (DaytonaApiClient::SshAccessValidationDto)


446
# File 'lib/daytona/sandbox.rb', line 446

def validate_ssh_access(token) = sandbox_api.validate_ssh_access(token)

#wait_for_resize_complete(_timeout = DEFAULT_TIMEOUT) ⇒ void

This method returns an undefined value.

Waits for the Sandbox resize operation to complete. Polls the Sandbox status until the state is no longer ‘resizing’.

Parameters:

  • timeout (Numeric)

    Maximum wait time in seconds (defaults to 60 s)



425
426
427
428
# File 'lib/daytona/sandbox.rb', line 425

def wait_for_resize_complete(_timeout = DEFAULT_TIMEOUT)
  wait_for_states(operation: OPERATION_RESIZE, target_states: [DaytonaApiClient::SandboxState::STARTED,
                                                               DaytonaApiClient::SandboxState::STOPPED])
end

#wait_for_sandbox_start(_timeout = DEFAULT_TIMEOUT) ⇒ void

This method returns an undefined value.

Waits for the Sandbox to reach the ‘started’ state. Polls the Sandbox status until it reaches the ‘started’ state or encounters an error.

Parameters:

  • timeout (Numeric)

    Maximum wait time in seconds (defaults to 60 s).



453
454
455
# File 'lib/daytona/sandbox.rb', line 453

def wait_for_sandbox_start(_timeout = DEFAULT_TIMEOUT)
  wait_for_states(operation: OPERATION_START, target_states: [DaytonaApiClient::SandboxState::STARTED])
end

#wait_for_sandbox_stop(_timeout = DEFAULT_TIMEOUT) ⇒ void

This method returns an undefined value.

Waits for the Sandbox to reach the ‘stopped’ state. Polls the Sandbox status until it reaches the ‘stopped’ state or encounters an error. Treats destroyed as stopped to cover ephemeral sandboxes that are automatically deleted after stopping.

Parameters:

  • timeout (Numeric)

    Maximum wait time in seconds (defaults to 60 s).



463
464
465
466
# File 'lib/daytona/sandbox.rb', line 463

def wait_for_sandbox_stop(_timeout = DEFAULT_TIMEOUT)
  wait_for_states(operation: OPERATION_STOP, target_states: [DaytonaApiClient::SandboxState::STOPPED,
                                                             DaytonaApiClient::SandboxState::DESTROYED])
end