daytona 0.232.0 → 0.234.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -22,30 +22,6 @@ module Daytona
22
22
  # Pass as a timeout to wait without a limit.
23
23
  NO_TIMEOUT = 0
24
24
 
25
- def self.with_events(*method_names)
26
- method_names.each do |method_name|
27
- original = instance_method(method_name)
28
-
29
- visibility = if private_method_defined?(method_name, false)
30
- :private
31
- elsif protected_method_defined?(method_name, false)
32
- :protected
33
- else
34
- :public
35
- end
36
-
37
- define_method(method_name) do |*args, **kwargs, &blk|
38
- ensure_subscribed
39
- original.bind_call(self, *args, **kwargs, &blk)
40
- end
41
-
42
- case visibility
43
- when :private then private method_name
44
- when :protected then protected method_name
45
- end
46
- end
47
- end
48
-
49
25
  SANDBOX_METRIC_FIELD_BY_NAME = {
50
26
  'daytona.sandbox.cpu.utilization' => :cpu_used_pct,
51
27
  'daytona.sandbox.cpu.limit' => :cpu_count,
@@ -206,6 +182,15 @@ module Daytona
206
182
  # @return [Daytona::Process]
207
183
  attr_reader :process
208
184
 
185
+ # @return [Daytona::SandboxNodes] Rank-ordered node handles. A gang head includes all ranks. A direct worker lookup includes only that worker.
186
+ attr_reader :nodes
187
+ # @return [Integer] Number of nodes reported by the last refresh
188
+ attr_reader :node_count
189
+ # @return [Integer, nil] Current topology generation
190
+ attr_reader :topology_generation
191
+ # @return [Boolean, nil] Whether the API reports a degraded gang
192
+ attr_reader :degraded
193
+
209
194
  # @return [Daytona::FileSystem]
210
195
  attr_reader :fs
211
196
 
@@ -228,13 +213,14 @@ module Daytona
228
213
  def initialize(sandbox_dto:, config:, sandbox_api:, subscription_manager:, otel_state: nil, analytics_api_url_provider: nil) # rubocop:disable Metrics/MethodLength
229
214
  @state_waiters = []
230
215
  @waiter_mutex = Mutex.new
216
+ # State events received; handlers run on the event connection's thread. Guarded by @waiter_mutex.
217
+ @state_event_count = 0
231
218
  process_response(sandbox_dto)
232
219
  @config = config
233
220
  @sandbox_api = sandbox_api
234
221
  @otel_state = otel_state
235
222
  @analytics_api_url_provider = analytics_api_url_provider
236
223
  @subscription_manager = subscription_manager
237
- @sub_id = nil
238
224
  @signing_key = nil
239
225
  @signing_key_fetched_at = 0
240
226
 
@@ -283,8 +269,8 @@ module Daytona
283
269
  @info_api = info_api
284
270
  @server_api = server_api
285
271
  @system_api = system_api
286
-
287
- ensure_subscribed
272
+ @nodes = SandboxNodes.new(self)
273
+ @nodes.send(:update, sandbox_dto)
288
274
  end
289
275
 
290
276
  # Archives the sandbox, making it inactive and preserving its state. When sandboxes are
@@ -295,8 +281,7 @@ module Daytona
295
281
  #
296
282
  # @return [void]
297
283
  def archive
298
- sandbox_api.archive_sandbox(id)
299
- refresh
284
+ apply_operation_response(sandbox_api.archive_sandbox(id))
300
285
  end
301
286
 
302
287
  # Sets the auto-archive interval for the Sandbox.
@@ -444,43 +429,26 @@ module Daytona
444
429
  # Only meaningful when +wait+ is true.
445
430
  # @param wait [Boolean] When +true+, block until the Sandbox is destroyed.
446
431
  # @return [void]
447
- def delete(timeout = DEFAULT_TIMEOUT, wait: false) # rubocop:disable Metrics/AbcSize,Metrics/MethodLength
432
+ def delete(timeout = DEFAULT_TIMEOUT, wait: false) # rubocop:disable Metrics/MethodLength
433
+ return delete_and_wait(timeout) if wait
434
+
448
435
  begin
449
- process_response(sandbox_api.delete_sandbox(id))
436
+ sandbox_dto = sandbox_api.delete_sandbox(id)
450
437
  rescue DaytonaApiClient::ApiError => e
451
438
  raise unless e.code == 404
452
439
 
453
- apply_state(DaytonaApiClient::SandboxState::DESTROYED)
440
+ return apply_state(DaytonaApiClient::SandboxState::DESTROYED)
454
441
  end
442
+ return process_response(sandbox_dto) if fresh_state?(sandbox_dto)
455
443
 
456
- if wait
457
- refresh_data_safe
458
- else
459
- begin
460
- refresh
461
- rescue DaytonaApiClient::ApiError => e
462
- raise unless e.code == 404
463
-
464
- apply_state(DaytonaApiClient::SandboxState::DESTROYED)
465
- end
466
- return
467
- end
468
- return if state.to_s == DaytonaApiClient::SandboxState::DESTROYED.to_s
444
+ # Older servers return no sandbox.
445
+ begin
446
+ refresh
447
+ rescue DaytonaApiClient::ApiError => e
448
+ raise unless e.code == 404
469
449
 
470
- with_timeout(
471
- timeout:,
472
- message: "Sandbox #{id} failed to be destroyed within the #{timeout} seconds timeout period",
473
- setup: nil
474
- ) do |deadline|
475
- wait_for_state(
476
- target_states: [DaytonaApiClient::SandboxState::DESTROYED],
477
- error_states: [DaytonaApiClient::SandboxState::ERROR, DaytonaApiClient::SandboxState::BUILD_FAILED],
478
- safe_refresh: true,
479
- deadline:
480
- )
450
+ apply_state(DaytonaApiClient::SandboxState::DESTROYED)
481
451
  end
482
- ensure
483
- unsubscribe_from_events
484
452
  end
485
453
 
486
454
  # Gets the user's home directory path for the logged in user inside the Sandbox.
@@ -764,14 +732,13 @@ module Daytona
764
732
  # @param force [Boolean] If true, uses SIGKILL instead of SIGTERM (defaults to false).
765
733
  # @return [void]
766
734
  def stop(timeout = DEFAULT_TIMEOUT, force: false)
767
- with_timeout(
768
- timeout:,
769
- message: "Sandbox #{id} failed to become stopped within the #{timeout} seconds timeout period",
770
- setup: proc {
771
- sandbox_api.stop_sandbox(id, { force: force })
772
- refresh
773
- }
774
- ) { |deadline| wait_for_stop(deadline) }
735
+ with_operation_subscription do |subscription|
736
+ with_timeout(
737
+ timeout:,
738
+ message: "Sandbox #{id} failed to become stopped within the #{timeout} seconds timeout period",
739
+ setup: proc { apply_operation_response(sandbox_api.stop_sandbox(id, { force: force })) }
740
+ ) { |deadline| wait_for_stop(deadline, subscription:) }
741
+ end
775
742
  end
776
743
 
777
744
  # Resizes the Sandbox resources.
@@ -794,25 +761,23 @@ module Daytona
794
761
  def resize(resources, timeout = DEFAULT_TIMEOUT)
795
762
  raise Sdk::Error, 'Resources must not be nil' if resources.nil?
796
763
 
764
+ resources.validate_scalar! if resources.is_a?(Resources)
797
765
  if resources.gpu || resources.gpu_type
798
766
  raise Sdk::Error,
799
767
  'Resize does not support changes to gpu or gpu_type — to change GPU, create a new sandbox'
800
768
  end
801
769
 
802
- with_timeout(
803
- timeout:,
804
- message: "Sandbox #{id} failed to resize within the #{timeout} seconds timeout period",
805
- setup: proc {
806
- resize_attrs = {}
807
- resize_attrs[:cpu] = resources.cpu if resources.cpu
808
- resize_attrs[:memory] = resources.memory if resources.memory
809
- resize_attrs[:disk] = resources.disk if resources.disk
810
- resize_request = DaytonaApiClient::ResizeSandbox.new(resize_attrs)
811
- process_response(sandbox_api.resize_sandbox(id, resize_request))
812
- }
813
- ) do |deadline|
814
- # Under the resize deadline, but recorded as the wait_for_resize_complete call that it replaces.
815
- instrument_as(:wait_for_resize_complete, component: 'Sandbox') { wait_for_resize(deadline) }
770
+ resize_request = DaytonaApiClient::ResizeSandbox.new(resources.to_h.slice(:cpu, :memory, :disk).compact)
771
+
772
+ with_operation_subscription do |subscription|
773
+ with_timeout(
774
+ timeout:,
775
+ message: "Sandbox #{id} failed to resize within the #{timeout} seconds timeout period",
776
+ setup: proc { apply_operation_response(sandbox_api.resize_sandbox(id, resize_request)) }
777
+ ) do |deadline|
778
+ # Under the resize deadline, but recorded as the wait_for_resize_complete call that it replaces.
779
+ instrument_as(:wait_for_resize_complete, component: 'Sandbox') { wait_for_resize(deadline, subscription:) }
780
+ end
816
781
  end
817
782
  end
818
783
 
@@ -901,7 +866,9 @@ module Daytona
901
866
  analytics_api_url_provider: @analytics_api_url_provider
902
867
  )
903
868
  # Under the fork deadline, but recorded as the wait_for_sandbox_start call that it replaces.
904
- instrument_as(:wait_for_sandbox_start, component: 'Sandbox') { forked.wait_for_start(deadline) }
869
+ instrument_as(:wait_for_sandbox_start, component: 'Sandbox') do
870
+ forked.wait_for_start_after_fork(deadline, fresh: fresh_fork_response?(forked_dto))
871
+ end
905
872
  return forked
906
873
  end
907
874
  end
@@ -946,30 +913,19 @@ module Daytona
946
913
  # @param timeout [Numeric] Maximum wait time in seconds (defaults to 60 s)
947
914
  # @return [void]
948
915
  def pause(timeout: DEFAULT_TIMEOUT)
949
- with_timeout(
950
- timeout:,
951
- message: "Sandbox #{id} failed to pause within the #{timeout} seconds timeout period",
952
- setup: proc {
953
- sandbox_api.pause_sandbox(id)
954
- refresh
955
- }
956
- ) do |deadline|
957
- error_states = [DaytonaApiClient::SandboxState::ERROR, DaytonaApiClient::SandboxState::BUILD_FAILED]
958
- exclude = [DaytonaApiClient::SandboxState::PAUSING] + error_states
959
- target_states = DaytonaApiClient::SandboxState.all_vars.reject { |s| exclude.include?(s) }
916
+ error_states = [DaytonaApiClient::SandboxState::ERROR, DaytonaApiClient::SandboxState::BUILD_FAILED]
917
+ exclude = [DaytonaApiClient::SandboxState::PAUSING] + error_states
918
+ target_states = DaytonaApiClient::SandboxState.all_vars.reject { |s| exclude.include?(s) }
960
919
 
961
- wait_for_state(target_states:, error_states:, deadline:)
920
+ with_operation_subscription do |subscription|
921
+ with_timeout(
922
+ timeout:,
923
+ message: "Sandbox #{id} failed to pause within the #{timeout} seconds timeout period",
924
+ setup: proc { apply_operation_response(sandbox_api.pause_sandbox(id)) }
925
+ ) { |deadline| wait_for_state(target_states:, error_states:, deadline:, subscription:) }
962
926
  end
963
927
  end
964
928
 
965
- with_events :archive, :auto_archive_interval=, :auto_delete_interval=, :auto_stop_interval=, :public=,
966
- :create_ssh_access, :delete, :get_user_home_dir, :get_work_dir, :labels=,
967
- :preview_url, :create_signed_preview_url, :expire_signed_preview_url,
968
- :refresh, :refresh_activity, :revoke_ssh_access, :start, :recover, :stop,
969
- :create_lsp_server, :validate_ssh_access, :wait_for_sandbox_start,
970
- :wait_for_sandbox_stop, :resize, :wait_for_resize_complete,
971
- :fork, :create_snapshot, :pause
972
-
973
929
  instrument :archive, :auto_archive_interval=, :auto_delete_interval=, :auto_pause_interval=, :auto_stop_interval=,
974
930
  :ttl_minutes=, :public=,
975
931
  :update_network_settings, :update_secrets, :update_env,
@@ -989,15 +945,32 @@ module Daytona
989
945
  # can wait for the forked Sandbox under its own deadline.
990
946
  #
991
947
  # @param deadline [WaitDeadline, nil]
948
+ # @param subscription [Hash, nil] See #wait_for_state
992
949
  # @return [void]
993
- def wait_for_start(deadline)
950
+ def wait_for_start(deadline, subscription: nil)
994
951
  wait_for_state(
995
952
  target_states: [DaytonaApiClient::SandboxState::STARTED],
996
953
  error_states: [DaytonaApiClient::SandboxState::ERROR, DaytonaApiClient::SandboxState::BUILD_FAILED],
997
- deadline:
954
+ deadline:,
955
+ subscription:
998
956
  )
999
957
  end
1000
958
 
959
+ # #wait_for_start for a Sandbox just returned by #fork. The fork endpoint returns before the fork starts,
960
+ # so a subscription taken now sees the transition and the wait can skip its first read.
961
+ #
962
+ # @param deadline [WaitDeadline, nil]
963
+ # @param fresh [Boolean] Whether the fork response carried a state; without one the wait reads first
964
+ # @return [void]
965
+ def wait_for_start_after_fork(deadline, fresh:)
966
+ return if state.to_s == DaytonaApiClient::SandboxState::STARTED.to_s
967
+
968
+ with_operation_subscription do |subscription|
969
+ subscription[:live] = false unless fresh
970
+ wait_for_start(deadline, subscription:)
971
+ end
972
+ end
973
+
1001
974
  private
1002
975
 
1003
976
  def pivot_sandbox_metrics(series)
@@ -1130,6 +1103,7 @@ module Daytona
1130
1103
  return if sandbox_dto.nil?
1131
1104
 
1132
1105
  new_state = sandbox_dto.state
1106
+ @node_count ||= 1
1133
1107
 
1134
1108
  # Fields shared by both DaytonaApiClient::Sandbox and DaytonaApiClient::SandboxListItem.
1135
1109
  @id = sandbox_dto.id
@@ -1182,6 +1156,10 @@ module Daytona
1182
1156
  @volumes = sandbox_dto.volumes
1183
1157
  @build_info = sandbox_dto.build_info
1184
1158
  @backup_created_at = sandbox_dto.backup_created_at
1159
+ @node_count = sandbox_dto.node_count unless sandbox_dto.node_count.nil?
1160
+ @topology_generation = sandbox_dto.topology_generation unless sandbox_dto.topology_generation.nil?
1161
+ @degraded = sandbox_dto.degraded unless sandbox_dto.degraded.nil?
1162
+ @nodes&.send(:update, sandbox_dto)
1185
1163
  end
1186
1164
 
1187
1165
  apply_state(new_state)
@@ -1238,25 +1216,85 @@ module Daytona
1238
1216
  # Waits for the Sandbox to reach one of the target states via WebSocket events
1239
1217
  # with periodic polling safety net.
1240
1218
  #
1219
+ # The Sandbox is subscribed to its state events only for the duration of the wait, and unsubscribed on
1220
+ # every exit.
1221
+ #
1241
1222
  # @param target_states [Array<DaytonaApiClient::SandboxState>] States that indicate success.
1242
1223
  # @param error_states [Array<DaytonaApiClient::SandboxState>] States that indicate failure.
1243
1224
  # @param safe_refresh [Boolean] If true, use refresh_data_safe for polling (swallows transient errors).
1244
1225
  # @param deadline [WaitDeadline, nil] Raise Sdk::TimeoutError with its message once it passes; nil waits
1245
1226
  # without a limit.
1227
+ # @param subscription [Hash, nil] Taken by #with_operation_subscription; the wait releases it on
1228
+ # every exit. nil subscribes here.
1246
1229
  # @return [void]
1247
1230
  # @raise [Daytona::Sdk::Error]
1248
- def wait_for_state(target_states:, error_states:, safe_refresh: false, deadline: nil) # rubocop:disable Metrics/MethodLength,Metrics/CyclomaticComplexity,Metrics/PerceivedComplexity
1249
- ensure_subscribed
1250
- subscribed = !@sub_id.nil?
1231
+ def wait_for_state(target_states:, error_states:, safe_refresh: false, deadline: nil, subscription: nil)
1232
+ owned = subscription || { id: nil }
1233
+ # The wait runs inside Timeout.timeout, whose exception can arrive at any point. Taking and releasing the
1234
+ # subscription defers it, so it can never land halfway and leak the subscription; only the polling can
1235
+ # be interrupted.
1236
+ Thread.handle_interrupt(Object => :never) do
1237
+ # Already there: nothing to wait for, so no subscription (and no event connection) is needed.
1238
+ return if target_states.map(&:to_s).include?(state.to_s)
1239
+
1240
+ owned[:id] = subscribe_to_state_events unless subscription
1241
+ Thread.handle_interrupt(Object => :immediate) do
1242
+ poll_for_state(target_states:, error_states:, safe_refresh:, deadline:, subscription: owned)
1243
+ end
1244
+ ensure
1245
+ release_state_subscription(owned)
1246
+ end
1247
+ end
1251
1248
 
1249
+ # Takes the state subscription of the wait that follows an operation on this Sandbox: before the
1250
+ # operation's request, or right after it for a new Sandbox (fork). Every later state change arrives as an
1251
+ # event, so the wait can skip its first read. Released when the block exits, if the wait has not released
1252
+ # it already.
1253
+ #
1254
+ # @yieldparam subscription [Hash] { id:, live:, connection_epoch:, state_events: } for #wait_for_state
1255
+ def with_operation_subscription
1256
+ subscription = { id: nil, live: false, connection_epoch: nil, state_events: nil }
1257
+ Thread.handle_interrupt(Object => :never) do
1258
+ # Snapshot before subscribing: an event delivered once the subscription exists may apply its state
1259
+ # after the operation's response, so it must change the count. Likewise a reconnect from then on
1260
+ # must change the epoch.
1261
+ subscription[:state_events] = @waiter_mutex.synchronize { @state_event_count }
1262
+ subscription[:connection_epoch] = @subscription_manager&.connection_epoch
1263
+ subscription[:id] = subscribe_to_state_events
1264
+ subscription[:live] = !subscription[:id].nil? && @subscription_manager.event_backed?(id)
1265
+ Thread.handle_interrupt(Object => :immediate) { yield subscription }
1266
+ ensure
1267
+ release_state_subscription(subscription)
1268
+ end
1269
+ end
1270
+
1271
+ # @param subscription [Hash] { id: String, nil }
1272
+ def release_state_subscription(subscription)
1273
+ unsubscribe_from_state_events(subscription[:id])
1274
+ subscription[:id] = nil
1275
+ end
1276
+
1277
+ # The body of #wait_for_state. Polls immediately (unless #skip_first_read? says the operation's response
1278
+ # stands in for that read), then at the interval #next_poll_interval picks, re-evaluated after every poll.
1279
+ #
1280
+ # @param subscription [Hash] { id: String, nil } The wait's event subscription, renewed after every poll
1281
+ def poll_for_state(target_states:, error_states:, safe_refresh:, deadline:, subscription:) # rubocop:disable Metrics/MethodLength,Metrics/CyclomaticComplexity,Metrics/PerceivedComplexity,Metrics/AbcSize
1252
1282
  target_strings = target_states.map(&:to_s)
1253
1283
  error_strings = error_states.map(&:to_s)
1254
1284
  started_at = ::Process.clock_gettime(::Process::CLOCK_MONOTONIC)
1255
- poll_interval = subscribed ? MAX_POLL_INTERVAL : INITIAL_POLL_INTERVAL
1285
+ fast_poll_interval = INITIAL_POLL_INTERVAL
1286
+ poll_interval = INITIAL_POLL_INTERVAL
1287
+ backoff = { interval: FALLBACK_POLL_INTERVAL }
1256
1288
 
1257
1289
  mutex = Mutex.new
1258
1290
  state_changed = ConditionVariable.new
1259
1291
  result_state = nil
1292
+ # The error reason that came with result_state; a refresh still in flight may replace error_reason after.
1293
+ result_reason = nil
1294
+ # Whether result_state came from an event, which may carry no reason.
1295
+ result_from_event = false
1296
+ # Set when the server rejects this Sandbox's subscription: no events will come, so read now.
1297
+ read_now = false
1260
1298
 
1261
1299
  waiter = {
1262
1300
  matches: lambda do |new_state|
@@ -1267,26 +1305,50 @@ module Daytona
1267
1305
  next if result_state
1268
1306
 
1269
1307
  result_state = new_state
1308
+ result_reason = error_reason
1309
+ result_from_event = true
1310
+ state_changed.signal
1311
+ end
1312
+ end,
1313
+ read_now: lambda do
1314
+ mutex.synchronize do
1315
+ read_now = true
1270
1316
  state_changed.signal
1271
1317
  end
1272
1318
  end
1273
1319
  }
1274
1320
 
1275
- @waiter_mutex.synchronize do
1321
+ state_event_count = @waiter_mutex.synchronize do
1276
1322
  @state_waiters << waiter
1277
1323
 
1278
1324
  current_state = state.to_s
1279
1325
  result_state = current_state if target_strings.include?(current_state)
1326
+ @state_event_count
1280
1327
  end
1281
1328
 
1282
1329
  begin
1283
1330
  first_poll = true
1331
+ if !result_state && skip_first_read?(subscription, state_event_count, target_strings:, error_strings:)
1332
+ first_poll = false
1333
+ raise_destroyed_lifecycle_error_if_needed(target_strings)
1334
+ mutex.synchronize do
1335
+ current = state.to_s
1336
+ if !result_state && error_strings.include?(current)
1337
+ result_state = current
1338
+ result_reason = error_reason
1339
+ end
1340
+ end
1341
+ poll_interval = next_poll_interval(subscription:, fast_poll_interval:, backoff:)
1342
+ end
1343
+
1284
1344
  until mutex.synchronize { result_state }
1285
1345
  unless first_poll
1286
1346
  should_refresh = mutex.synchronize do
1287
1347
  next false if result_state
1288
1348
 
1289
- state_changed.wait(mutex, deadline ? deadline.remaining.clamp(0, poll_interval) : poll_interval)
1349
+ wait_seconds = deadline ? deadline.remaining.clamp(0, poll_interval) : poll_interval
1350
+ state_changed.wait(mutex, wait_seconds) unless read_now
1351
+ read_now = false
1290
1352
  result_state.nil?
1291
1353
  end
1292
1354
  next unless should_refresh
@@ -1295,26 +1357,34 @@ module Daytona
1295
1357
 
1296
1358
  raise Sdk::TimeoutError, deadline.message if deadline&.expired?
1297
1359
 
1298
- poll_refresh(safe: safe_refresh, http_timeout: deadline&.remaining, deadline:)
1299
- raise_destroyed_lifecycle_error_if_needed(target_strings)
1360
+ retry_after = poll_rate_limited do
1361
+ poll_refresh(safe: safe_refresh, http_timeout: deadline&.remaining, deadline:, raise_rate_limit: true)
1362
+ end
1363
+ # A rejection that arrived during this read needs no read of its own: this one covers it, and the next
1364
+ # interval, chosen below, is the fallback.
1365
+ mutex.synchronize { read_now = false }
1366
+ # A rate-limited read saw nothing: the cached state (an operation's error response, say) decides nothing.
1367
+ raise_destroyed_lifecycle_error_if_needed(target_strings) unless retry_after
1300
1368
 
1301
1369
  mutex.synchronize do
1302
- next if result_state
1370
+ next if result_state || retry_after
1303
1371
 
1304
1372
  current = state.to_s
1305
- result_state = current if target_strings.include?(current) || error_strings.include?(current)
1373
+ if target_strings.include?(current) || error_strings.include?(current)
1374
+ result_state = current
1375
+ result_reason = error_reason
1376
+ end
1306
1377
  end
1307
1378
 
1308
- poll_interval = next_wait_for_state_poll_interval(
1309
- current_interval: poll_interval,
1310
- started_at: started_at,
1311
- subscribed: subscribed
1312
- )
1379
+ fast_poll_interval = next_fast_poll_interval(current_interval: fast_poll_interval, started_at:)
1380
+ renew_state_subscription(subscription)
1381
+ poll_interval = next_poll_interval(subscription:, fast_poll_interval:, backoff:, retry_after:)
1313
1382
  end
1314
1383
 
1315
1384
  if result_state && error_strings.include?(result_state)
1385
+ result_reason = read_error_reason if result_from_event && result_reason.nil?
1316
1386
  raise Sdk::Error,
1317
- "Sandbox #{id} entered error state: #{result_state}, error reason: #{error_reason}"
1387
+ "Sandbox #{id} entered error state: #{result_state}, error reason: #{result_reason}"
1318
1388
  end
1319
1389
  rescue Sdk::TimeoutError => e
1320
1390
  begin
@@ -1340,15 +1410,33 @@ module Daytona
1340
1410
  end
1341
1411
  end
1342
1412
 
1413
+ # #refresh_data_safe, telling whether the cached state is now current.
1414
+ #
1415
+ # @return [Boolean] true when the refresh succeeded or found the Sandbox gone (destroyed)
1416
+ def refresh_after_subscribing
1417
+ refresh
1418
+ true
1419
+ rescue DaytonaApiClient::ApiError => e
1420
+ return false unless e.code == 404
1421
+
1422
+ apply_state(DaytonaApiClient::SandboxState::DESTROYED)
1423
+ true
1424
+ rescue StandardError
1425
+ false
1426
+ end
1427
+
1343
1428
  # @param api [DaytonaApiClient::SandboxApi] sandbox_api, or a copy of it with an HTTP timeout
1344
- def refresh_data_safe(api = sandbox_api)
1429
+ # @param raise_rate_limit [Boolean] Raise a 429 instead of swallowing it
1430
+ def refresh_data_safe(api = sandbox_api, raise_rate_limit: false)
1345
1431
  refresh_through(api)
1346
1432
  rescue DaytonaApiClient::ApiError => e
1433
+ raise if raise_rate_limit && e.code == 429
1434
+
1347
1435
  apply_state(DaytonaApiClient::SandboxState::DESTROYED) if e.code == 404
1348
1436
  rescue StandardError # rubocop:disable Lint/SuppressedException
1349
1437
  end
1350
1438
 
1351
- # Does what #refresh does, recorded as #refresh and renewing the event subscription, but through +api+.
1439
+ # Does what #refresh does, recorded as #refresh, but through +api+.
1352
1440
  #
1353
1441
  # @param api [DaytonaApiClient::SandboxApi] sandbox_api, or a copy of it with an HTTP timeout
1354
1442
  # @return [void]
@@ -1356,7 +1444,6 @@ module Daytona
1356
1444
  return refresh if api.equal?(sandbox_api)
1357
1445
 
1358
1446
  instrument_as(:refresh, component: 'Sandbox') do
1359
- ensure_subscribed
1360
1447
  process_response(api.get_sandbox(id))
1361
1448
  end
1362
1449
  end
@@ -1366,11 +1453,12 @@ module Daytona
1366
1453
  # @param safe [Boolean] Swallow errors as #refresh_data_safe does, a timed out request included
1367
1454
  # @param http_timeout [Numeric, nil] Most seconds the request may take; nil leaves the API client's timeout
1368
1455
  # @param deadline [WaitDeadline, nil] Deadline that http_timeout is the time left on, if any
1456
+ # @param raise_rate_limit [Boolean] Raise a 429 even when +safe+ (the wait backs off on it)
1369
1457
  # @return [void]
1370
1458
  # @raise [Daytona::Sdk::TimeoutError] If safe is false and the request times out at the deadline
1371
- def poll_refresh(safe:, http_timeout:, deadline: nil)
1459
+ def poll_refresh(safe:, http_timeout:, deadline: nil, raise_rate_limit: false)
1372
1460
  api = http_timeout ? sandbox_api_with_timeout(http_timeout) : sandbox_api
1373
- safe ? refresh_data_safe(api) : refresh_through(api)
1461
+ safe ? refresh_data_safe(api, raise_rate_limit:) : refresh_through(api)
1374
1462
  rescue DaytonaApiClient::ApiError => e
1375
1463
  raise unless deadline && deadline_timed_out?(e, http_timeout)
1376
1464
 
@@ -1422,68 +1510,254 @@ module Daytona
1422
1510
  "Sandbox #{id} was destroyed after waiting#{waited} for a runner (queue timed out at #{queue_timed_out_at})"
1423
1511
  end
1424
1512
 
1425
- def ensure_subscribed
1426
- @waiter_mutex.synchronize do
1427
- return unless @subscription_manager
1513
+ # @return [String, nil] The subscription id; nil when events are unavailable (polling-only mode, closed
1514
+ # client)
1515
+ def subscribe_to_state_events
1516
+ @subscription_manager&.subscribe(resource_id: id, handler: method(:handle_event), events: STATE_EVENTS)
1517
+ end
1428
1518
 
1429
- if @sub_id
1430
- return if @subscription_manager.refresh(@sub_id)
1519
+ def unsubscribe_from_state_events(sub_id)
1520
+ @subscription_manager.unsubscribe(sub_id) if sub_id
1521
+ end
1431
1522
 
1432
- @sub_id = nil
1433
- end
1523
+ # Keeps a wait's subscription alive, subscribing again (new id) if it expired meanwhile. Not interruptible
1524
+ # (see #wait_for_state), so the new id always reaches +subscription+ and is released.
1525
+ #
1526
+ # @param subscription [Hash] { id: String, nil }
1527
+ def renew_state_subscription(subscription)
1528
+ return unless subscription[:id]
1434
1529
 
1435
- subscribe_to_events
1530
+ Thread.handle_interrupt(Object => :never) do
1531
+ subscription[:id] = subscribe_to_state_events unless @subscription_manager.refresh(subscription[:id])
1436
1532
  end
1437
1533
  end
1438
1534
 
1439
- def subscribe_to_events
1440
- return if @sub_id || !@subscription_manager
1535
+ # @param subscription [Hash] { id: String, nil }
1536
+ # @param fast_poll_interval [Float] The polling-only cadence, used as is when the wait holds no subscription
1537
+ # @return [Float] Seconds until the next poll
1538
+ # @param retry_after [Float, nil] nil unless the poll was rate limited; then the seconds Retry-After asks
1539
+ # for (0 without one)
1540
+ def next_poll_interval(subscription:, fast_poll_interval:, backoff: { interval: FALLBACK_POLL_INTERVAL },
1541
+ retry_after: nil)
1542
+ fallback = backoff[:interval]
1543
+ mode = poll_mode(subscription)
1544
+ delay = mode_poll_interval(mode, fast_poll_interval, backoff)
1545
+ return delay unless retry_after
1441
1546
 
1442
- @sub_id = @subscription_manager.subscribe(
1443
- resource_id: id,
1444
- handler: method(:handle_event),
1445
- events: ['sandbox.state.updated', 'sandbox.created']
1446
- )
1547
+ rate_limited_poll_interval(mode, delay, fallback, backoff, retry_after)
1548
+ end
1549
+
1550
+ # @return [Symbol] :unsubscribed, :event_backed or :fallback (subscribed, but no events come)
1551
+ def poll_mode(subscription)
1552
+ return :unsubscribed unless subscription[:id]
1553
+
1554
+ @subscription_manager.event_backed?(id) ? :event_backed : :fallback
1555
+ end
1556
+
1557
+ # The interval of +mode+: the fast cadence without a subscription; 5 s while event-backed, which restarts
1558
+ # the backoff; otherwise the fallback backoff, which then grows.
1559
+ def mode_poll_interval(mode, fast_poll_interval, backoff)
1560
+ case mode
1561
+ when :unsubscribed then fast_poll_interval
1562
+ when :event_backed
1563
+ backoff[:interval] = FALLBACK_POLL_INTERVAL
1564
+ jittered(EVENT_BACKED_POLL_INTERVAL)
1565
+ else
1566
+ interval = backoff[:interval]
1567
+ backoff[:interval] = grown_fallback(interval)
1568
+ jittered(interval)
1569
+ end
1447
1570
  end
1448
1571
 
1572
+ # After a 429, in any mode: no sooner than the mode's interval, the fallback interval or Retry-After, and the
1573
+ # fallback backoff advances one step, so repeated 429s back off even without a subscription. When
1574
+ # Retry-After decides, it gets up to 20 % more, so waits that got the same header do not retry together.
1575
+ def rate_limited_poll_interval(mode, delay, fallback, backoff, retry_after)
1576
+ delay = [delay, jittered(fallback)].max unless mode == :fallback
1577
+ backoff[:interval] = grown_fallback(fallback)
1578
+ return delay unless retry_after > delay
1579
+
1580
+ retry_after * (1 + (POLL_JITTER * poll_jitter_random))
1581
+ end
1582
+
1583
+ def grown_fallback(interval) = [interval * FALLBACK_POLL_GROWTH, FALLBACK_POLL_MAX_INTERVAL].min
1584
+
1585
+ # @param interval [Float]
1586
+ # @return [Float] +interval+ with up to POLL_JITTER either way
1587
+ def jittered(interval) = interval * (1 + (POLL_JITTER * ((2 * poll_jitter_random) - 1)))
1588
+
1589
+ # Runs a wait's poll. A 429 does not end the wait: the next poll comes no sooner than the server's
1590
+ # Retry-After, nor than the regular interval.
1591
+ #
1592
+ # @return [Float, nil] nil unless rate limited; otherwise the seconds Retry-After asks for (0 without one)
1593
+ def poll_rate_limited
1594
+ yield
1595
+ nil
1596
+ rescue DaytonaApiClient::ApiError => e
1597
+ raise unless e.code == 429
1598
+
1599
+ retry_after_seconds(e.response_headers)
1600
+ end
1601
+
1602
+ # @param headers [Hash, nil]
1603
+ # @return [Float] The delay a Retry-After header asks for (whole seconds or an HTTP date), at most
1604
+ # MAX_RETRY_AFTER; 0 when absent, negative or unparseable
1605
+ def retry_after_seconds(headers)
1606
+ text = Array(headers&.find { |name, _| name.to_s.casecmp?('retry-after') }&.last).first.to_s.strip
1607
+ seconds = if text.match?(/\A\d+\z/) then text.to_f
1608
+ elsif text.empty? then 0.0
1609
+ else Time.httpdate(text) - Time.now
1610
+ end
1611
+ seconds.clamp(0.0, MAX_RETRY_AFTER)
1612
+ rescue ArgumentError
1613
+ 0.0
1614
+ end
1615
+
1616
+ # @return [Float] Uniform in [0, 1); stubbed in specs
1617
+ def poll_jitter_random = rand
1618
+
1619
+ # Whether the operation's response (or the refresh standing in for it) can replace a wait's first read:
1620
+ # the subscription was live when taken, events can still arrive and the connection was not re-established
1621
+ # since (a reconnect loses the events emitted while the socket was down), no state event arrived since (it
1622
+ # may be newer than the response that overwrote it), and the response does not fail the wait (read again
1623
+ # at once, so it fails as fast as before).
1624
+ #
1625
+ # @param subscription [Hash] { id:, live:, connection_epoch:, state_events: }; a wait's own subscription
1626
+ # has no :live
1627
+ # @param state_event_count [Integer] The Sandbox's state-event count when the wait started
1628
+ # @param target_strings [Array<String>]
1629
+ # @param error_strings [Array<String>]
1630
+ # @return [Boolean]
1631
+ def skip_first_read?(subscription, state_event_count, target_strings:, error_strings:)
1632
+ current = state.to_s
1633
+ return false if error_strings.include?(current)
1634
+ return false if current == DaytonaApiClient::SandboxState::DESTROYED.to_s && !target_strings.include?(current)
1635
+
1636
+ subscription[:live] == true && events_reached_wait?(subscription) &&
1637
+ subscription[:state_events] == state_event_count
1638
+ end
1639
+
1640
+ # @param subscription [Hash] { id:, connection_epoch: }
1641
+ # @return [Boolean] Whether every state event since +subscription+ was taken has reached this Sandbox:
1642
+ # it is held, the server serves this Sandbox, the connection is up and has not been re-established
1643
+ # meanwhile
1644
+ def events_reached_wait?(subscription)
1645
+ !subscription[:id].nil? && @subscription_manager.event_backed?(id) &&
1646
+ @subscription_manager.connection_epoch == subscription[:connection_epoch] &&
1647
+ # An expired subscription went nowhere in the gap; the wait renews it after its first read.
1648
+ @subscription_manager.refresh(subscription[:id])
1649
+ end
1650
+
1651
+ # Older servers return no sandbox from an operation, or one without a state; only then is a refresh
1652
+ # needed.
1653
+ #
1654
+ # @param sandbox_dto [DaytonaApiClient::Sandbox, nil]
1655
+ # @return [void]
1656
+ def apply_operation_response(sandbox_dto)
1657
+ fresh_state?(sandbox_dto) ? process_response(sandbox_dto) : refresh
1658
+ end
1659
+
1660
+ # A fork response whose toolbox proxy URL is missing (older servers) is not fresh: building the forked
1661
+ # Sandbox fetched it, which widened the gap before the forked Sandbox's subscription.
1662
+ #
1663
+ # @param forked_dto [DaytonaApiClient::Sandbox, nil]
1664
+ # @return [Boolean]
1665
+ def fresh_fork_response?(forked_dto)
1666
+ fresh_state?(forked_dto) && !forked_dto.toolbox_proxy_url.to_s.empty?
1667
+ end
1668
+
1669
+ # @param sandbox_dto [DaytonaApiClient::Sandbox, nil]
1670
+ # @return [Boolean] Whether an operation's response carries the Sandbox's state after the operation
1671
+ def fresh_state?(sandbox_dto)
1672
+ !sandbox_dto.nil? && !sandbox_dto.state.to_s.empty?
1673
+ end
1674
+
1675
+ # A wait ended on an error state from an event that carried no reason: read it once before failing.
1676
+ #
1677
+ # @return [String, nil]
1678
+ def read_error_reason
1679
+ refresh_data_safe
1680
+ error_reason
1681
+ end
1682
+
1683
+ # The server rejected this Sandbox's subscription: the running waits read now and poll from then on.
1684
+ def wake_waits_to_read
1685
+ @waiter_mutex.synchronize { @state_waiters.each { |waiter| waiter[:read_now].call } }
1686
+ nil
1687
+ end
1688
+
1689
+ # Accepts both the full and the slim state payload: { sandbox: { id, state, ... }, oldState, newState }.
1449
1690
  def handle_event(event_name, data)
1691
+ return wake_waits_to_read if event_name == EventDispatcher::SUBSCRIPTION_REJECTED_EVENT
1692
+
1693
+ apply_state_event(data)
1694
+ end
1695
+
1696
+ # @param data [Object] A state event payload
1697
+ def apply_state_event(data)
1450
1698
  return unless data.is_a?(Hash)
1451
1699
 
1452
1700
  raw = data['sandbox'] || data
1453
1701
  return unless raw.is_a?(Hash)
1454
1702
 
1455
- if event_name == 'sandbox.created'
1456
- process_response(DaytonaApiClient::Sandbox.build_from_hash(raw))
1457
- else
1458
- new_state = raw['state'] || data['newState']
1459
- apply_state(new_state) if new_state
1460
- end
1703
+ new_state = raw['state'] || data['newState']
1704
+ return unless new_state
1705
+
1706
+ @waiter_mutex.synchronize { @state_event_count += 1 }
1707
+ # Set before the state: a wait that ends on an error state reports this reason.
1708
+ apply_event_error_reason(data)
1709
+ apply_state(new_state)
1461
1710
  rescue StandardError
1462
1711
  nil
1463
1712
  end
1464
1713
 
1465
- def unsubscribe_from_events
1466
- return unless @sub_id
1467
-
1468
- @subscription_manager&.unsubscribe(@sub_id)
1469
- @sub_id = nil
1714
+ # The event omits errorReason when the sandbox has none, so an event with a sandbox object clears it then.
1715
+ #
1716
+ # @param data [Hash] A state event payload
1717
+ def apply_event_error_reason(data)
1718
+ sandbox = data['sandbox']
1719
+ @error_reason = sandbox['errorReason'] if sandbox.is_a?(Hash)
1470
1720
  end
1471
1721
 
1472
- def next_wait_for_state_poll_interval(current_interval:, started_at:, subscribed:)
1473
- return [current_interval * BACKOFF_MULTIPLIER, MAX_POLL_INTERVAL].min if subscribed
1474
-
1722
+ def next_fast_poll_interval(current_interval:, started_at:)
1475
1723
  elapsed = ::Process.clock_gettime(::Process::CLOCK_MONOTONIC) - started_at
1476
1724
  return current_interval if elapsed <= POLL_BACKOFF_DELAY
1477
1725
 
1478
1726
  [current_interval * BACKOFF_MULTIPLIER, MAX_POLL_INTERVAL].min
1479
1727
  end
1480
1728
 
1729
+ STATE_EVENTS = ['sandbox.state.updated'].freeze
1730
+ private_constant :STATE_EVENTS
1731
+
1481
1732
  INITIAL_POLL_INTERVAL = 0.1
1482
1733
  private_constant :INITIAL_POLL_INTERVAL
1483
1734
 
1484
1735
  MAX_POLL_INTERVAL = 1.0
1485
1736
  private_constant :MAX_POLL_INTERVAL
1486
1737
 
1738
+ # State events drive event-backed waits; polling is only a safety net.
1739
+ EVENT_BACKED_POLL_INTERVAL = 5.0
1740
+ private_constant :EVENT_BACKED_POLL_INTERVAL
1741
+
1742
+ # A subscribed wait without events (connection down, or the subscription rejected by the server, including
1743
+ # past its per-socket limit) starts at 1 s and backs off, so many such waits do not spend the request budget.
1744
+ FALLBACK_POLL_INTERVAL = 1.0
1745
+ private_constant :FALLBACK_POLL_INTERVAL
1746
+
1747
+ FALLBACK_POLL_GROWTH = 1.5
1748
+ private_constant :FALLBACK_POLL_GROWTH
1749
+
1750
+ FALLBACK_POLL_MAX_INTERVAL = 10.0
1751
+ private_constant :FALLBACK_POLL_MAX_INTERVAL
1752
+
1753
+ # A longer Retry-After is capped: the wait's own timeout still decides.
1754
+ MAX_RETRY_AFTER = 60.0
1755
+ private_constant :MAX_RETRY_AFTER
1756
+
1757
+ # Spreads safety-net polls of concurrent waits apart.
1758
+ POLL_JITTER = 0.2
1759
+ private_constant :POLL_JITTER
1760
+
1487
1761
  BACKOFF_MULTIPLIER = 1.1
1488
1762
  private_constant :BACKOFF_MULTIPLIER
1489
1763
 
@@ -1508,20 +1782,57 @@ module Daytona
1508
1782
  end
1509
1783
  private_constant :WaitDeadline
1510
1784
 
1511
- def wait_for_stop(deadline)
1785
+ def wait_for_stop(deadline, subscription: nil)
1512
1786
  wait_for_state(
1513
1787
  target_states: [DaytonaApiClient::SandboxState::STOPPED, DaytonaApiClient::SandboxState::DESTROYED],
1514
1788
  error_states: [DaytonaApiClient::SandboxState::ERROR, DaytonaApiClient::SandboxState::BUILD_FAILED],
1515
- deadline:
1789
+ deadline:,
1790
+ subscription:
1516
1791
  )
1517
1792
  end
1518
1793
 
1519
- def wait_for_resize(deadline)
1794
+ def wait_for_resize(deadline, subscription: nil)
1520
1795
  error_states = [DaytonaApiClient::SandboxState::ERROR, DaytonaApiClient::SandboxState::BUILD_FAILED]
1521
1796
  exclude = [DaytonaApiClient::SandboxState::RESIZING] + error_states
1522
1797
  target_states = DaytonaApiClient::SandboxState.all_vars.reject { |s| exclude.include?(s) }
1523
1798
 
1524
- wait_for_state(target_states:, error_states:, deadline:)
1799
+ wait_for_state(target_states:, error_states:, deadline:, subscription:)
1800
+ end
1801
+
1802
+ # #delete with +wait: true+.
1803
+ #
1804
+ # @param timeout [Numeric]
1805
+ # @return [void]
1806
+ def delete_and_wait(timeout) # rubocop:disable Metrics/MethodLength
1807
+ with_operation_subscription do |subscription|
1808
+ begin
1809
+ sandbox_dto = sandbox_api.delete_sandbox(id)
1810
+ if fresh_state?(sandbox_dto)
1811
+ process_response(sandbox_dto)
1812
+ elsif !refresh_after_subscribing
1813
+ # Older servers return no sandbox; without a successful refresh the cached state is stale.
1814
+ subscription[:live] = false
1815
+ end
1816
+ rescue DaytonaApiClient::ApiError => e
1817
+ raise unless e.code == 404
1818
+
1819
+ apply_state(DaytonaApiClient::SandboxState::DESTROYED)
1820
+ end
1821
+
1822
+ with_timeout(
1823
+ timeout:,
1824
+ message: "Sandbox #{id} failed to be destroyed within the #{timeout} seconds timeout period",
1825
+ setup: nil
1826
+ ) do |deadline|
1827
+ wait_for_state(
1828
+ target_states: [DaytonaApiClient::SandboxState::DESTROYED],
1829
+ error_states: [DaytonaApiClient::SandboxState::ERROR, DaytonaApiClient::SandboxState::BUILD_FAILED],
1830
+ safe_refresh: true,
1831
+ deadline:,
1832
+ subscription:
1833
+ )
1834
+ end
1835
+ end
1525
1836
  end
1526
1837
 
1527
1838
  def wait_for_snapshot_complete(deadline)