daytona 0.233.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,
@@ -237,13 +213,14 @@ module Daytona
237
213
  def initialize(sandbox_dto:, config:, sandbox_api:, subscription_manager:, otel_state: nil, analytics_api_url_provider: nil) # rubocop:disable Metrics/MethodLength
238
214
  @state_waiters = []
239
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
240
218
  process_response(sandbox_dto)
241
219
  @config = config
242
220
  @sandbox_api = sandbox_api
243
221
  @otel_state = otel_state
244
222
  @analytics_api_url_provider = analytics_api_url_provider
245
223
  @subscription_manager = subscription_manager
246
- @sub_id = nil
247
224
  @signing_key = nil
248
225
  @signing_key_fetched_at = 0
249
226
 
@@ -294,8 +271,6 @@ module Daytona
294
271
  @system_api = system_api
295
272
  @nodes = SandboxNodes.new(self)
296
273
  @nodes.send(:update, sandbox_dto)
297
-
298
- ensure_subscribed
299
274
  end
300
275
 
301
276
  # Archives the sandbox, making it inactive and preserving its state. When sandboxes are
@@ -306,8 +281,7 @@ module Daytona
306
281
  #
307
282
  # @return [void]
308
283
  def archive
309
- sandbox_api.archive_sandbox(id)
310
- refresh
284
+ apply_operation_response(sandbox_api.archive_sandbox(id))
311
285
  end
312
286
 
313
287
  # Sets the auto-archive interval for the Sandbox.
@@ -455,43 +429,26 @@ module Daytona
455
429
  # Only meaningful when +wait+ is true.
456
430
  # @param wait [Boolean] When +true+, block until the Sandbox is destroyed.
457
431
  # @return [void]
458
- 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
+
459
435
  begin
460
- process_response(sandbox_api.delete_sandbox(id))
436
+ sandbox_dto = sandbox_api.delete_sandbox(id)
461
437
  rescue DaytonaApiClient::ApiError => e
462
438
  raise unless e.code == 404
463
439
 
464
- apply_state(DaytonaApiClient::SandboxState::DESTROYED)
440
+ return apply_state(DaytonaApiClient::SandboxState::DESTROYED)
465
441
  end
442
+ return process_response(sandbox_dto) if fresh_state?(sandbox_dto)
466
443
 
467
- if wait
468
- refresh_data_safe
469
- else
470
- begin
471
- refresh
472
- rescue DaytonaApiClient::ApiError => e
473
- raise unless e.code == 404
474
-
475
- apply_state(DaytonaApiClient::SandboxState::DESTROYED)
476
- end
477
- return
478
- end
479
- 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
480
449
 
481
- with_timeout(
482
- timeout:,
483
- message: "Sandbox #{id} failed to be destroyed within the #{timeout} seconds timeout period",
484
- setup: nil
485
- ) do |deadline|
486
- wait_for_state(
487
- target_states: [DaytonaApiClient::SandboxState::DESTROYED],
488
- error_states: [DaytonaApiClient::SandboxState::ERROR, DaytonaApiClient::SandboxState::BUILD_FAILED],
489
- safe_refresh: true,
490
- deadline:
491
- )
450
+ apply_state(DaytonaApiClient::SandboxState::DESTROYED)
492
451
  end
493
- ensure
494
- unsubscribe_from_events
495
452
  end
496
453
 
497
454
  # Gets the user's home directory path for the logged in user inside the Sandbox.
@@ -775,14 +732,13 @@ module Daytona
775
732
  # @param force [Boolean] If true, uses SIGKILL instead of SIGTERM (defaults to false).
776
733
  # @return [void]
777
734
  def stop(timeout = DEFAULT_TIMEOUT, force: false)
778
- with_timeout(
779
- timeout:,
780
- message: "Sandbox #{id} failed to become stopped within the #{timeout} seconds timeout period",
781
- setup: proc {
782
- sandbox_api.stop_sandbox(id, { force: force })
783
- refresh
784
- }
785
- ) { |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
786
742
  end
787
743
 
788
744
  # Resizes the Sandbox resources.
@@ -811,20 +767,17 @@ module Daytona
811
767
  'Resize does not support changes to gpu or gpu_type — to change GPU, create a new sandbox'
812
768
  end
813
769
 
814
- with_timeout(
815
- timeout:,
816
- message: "Sandbox #{id} failed to resize within the #{timeout} seconds timeout period",
817
- setup: proc {
818
- resize_attrs = {}
819
- resize_attrs[:cpu] = resources.cpu if resources.cpu
820
- resize_attrs[:memory] = resources.memory if resources.memory
821
- resize_attrs[:disk] = resources.disk if resources.disk
822
- resize_request = DaytonaApiClient::ResizeSandbox.new(resize_attrs)
823
- process_response(sandbox_api.resize_sandbox(id, resize_request))
824
- }
825
- ) do |deadline|
826
- # Under the resize deadline, but recorded as the wait_for_resize_complete call that it replaces.
827
- 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
828
781
  end
829
782
  end
830
783
 
@@ -913,7 +866,9 @@ module Daytona
913
866
  analytics_api_url_provider: @analytics_api_url_provider
914
867
  )
915
868
  # Under the fork deadline, but recorded as the wait_for_sandbox_start call that it replaces.
916
- 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
917
872
  return forked
918
873
  end
919
874
  end
@@ -958,30 +913,19 @@ module Daytona
958
913
  # @param timeout [Numeric] Maximum wait time in seconds (defaults to 60 s)
959
914
  # @return [void]
960
915
  def pause(timeout: DEFAULT_TIMEOUT)
961
- with_timeout(
962
- timeout:,
963
- message: "Sandbox #{id} failed to pause within the #{timeout} seconds timeout period",
964
- setup: proc {
965
- sandbox_api.pause_sandbox(id)
966
- refresh
967
- }
968
- ) do |deadline|
969
- error_states = [DaytonaApiClient::SandboxState::ERROR, DaytonaApiClient::SandboxState::BUILD_FAILED]
970
- exclude = [DaytonaApiClient::SandboxState::PAUSING] + error_states
971
- 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) }
972
919
 
973
- 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:) }
974
926
  end
975
927
  end
976
928
 
977
- with_events :archive, :auto_archive_interval=, :auto_delete_interval=, :auto_stop_interval=, :public=,
978
- :create_ssh_access, :delete, :get_user_home_dir, :get_work_dir, :labels=,
979
- :preview_url, :create_signed_preview_url, :expire_signed_preview_url,
980
- :refresh, :refresh_activity, :revoke_ssh_access, :start, :recover, :stop,
981
- :create_lsp_server, :validate_ssh_access, :wait_for_sandbox_start,
982
- :wait_for_sandbox_stop, :resize, :wait_for_resize_complete,
983
- :fork, :create_snapshot, :pause
984
-
985
929
  instrument :archive, :auto_archive_interval=, :auto_delete_interval=, :auto_pause_interval=, :auto_stop_interval=,
986
930
  :ttl_minutes=, :public=,
987
931
  :update_network_settings, :update_secrets, :update_env,
@@ -1001,15 +945,32 @@ module Daytona
1001
945
  # can wait for the forked Sandbox under its own deadline.
1002
946
  #
1003
947
  # @param deadline [WaitDeadline, nil]
948
+ # @param subscription [Hash, nil] See #wait_for_state
1004
949
  # @return [void]
1005
- def wait_for_start(deadline)
950
+ def wait_for_start(deadline, subscription: nil)
1006
951
  wait_for_state(
1007
952
  target_states: [DaytonaApiClient::SandboxState::STARTED],
1008
953
  error_states: [DaytonaApiClient::SandboxState::ERROR, DaytonaApiClient::SandboxState::BUILD_FAILED],
1009
- deadline:
954
+ deadline:,
955
+ subscription:
1010
956
  )
1011
957
  end
1012
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
+
1013
974
  private
1014
975
 
1015
976
  def pivot_sandbox_metrics(series)
@@ -1255,27 +1216,85 @@ module Daytona
1255
1216
  # Waits for the Sandbox to reach one of the target states via WebSocket events
1256
1217
  # with periodic polling safety net.
1257
1218
  #
1219
+ # The Sandbox is subscribed to its state events only for the duration of the wait, and unsubscribed on
1220
+ # every exit.
1221
+ #
1258
1222
  # @param target_states [Array<DaytonaApiClient::SandboxState>] States that indicate success.
1259
1223
  # @param error_states [Array<DaytonaApiClient::SandboxState>] States that indicate failure.
1260
1224
  # @param safe_refresh [Boolean] If true, use refresh_data_safe for polling (swallows transient errors).
1261
1225
  # @param deadline [WaitDeadline, nil] Raise Sdk::TimeoutError with its message once it passes; nil waits
1262
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.
1263
1229
  # @return [void]
1264
1230
  # @raise [Daytona::Sdk::Error]
1265
- def wait_for_state(target_states:, error_states:, safe_refresh: false, deadline: nil) # rubocop:disable Metrics/MethodLength,Metrics/CyclomaticComplexity,Metrics/PerceivedComplexity
1266
- ensure_subscribed
1267
- 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
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
1268
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
1269
1282
  target_strings = target_states.map(&:to_s)
1270
1283
  error_strings = error_states.map(&:to_s)
1271
1284
  started_at = ::Process.clock_gettime(::Process::CLOCK_MONOTONIC)
1272
- 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 }
1273
1288
 
1274
1289
  mutex = Mutex.new
1275
1290
  state_changed = ConditionVariable.new
1276
1291
  result_state = nil
1277
1292
  # The error reason that came with result_state; a refresh still in flight may replace error_reason after.
1278
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
1279
1298
 
1280
1299
  waiter = {
1281
1300
  matches: lambda do |new_state|
@@ -1287,26 +1306,49 @@ module Daytona
1287
1306
 
1288
1307
  result_state = new_state
1289
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
1290
1316
  state_changed.signal
1291
1317
  end
1292
1318
  end
1293
1319
  }
1294
1320
 
1295
- @waiter_mutex.synchronize do
1321
+ state_event_count = @waiter_mutex.synchronize do
1296
1322
  @state_waiters << waiter
1297
1323
 
1298
1324
  current_state = state.to_s
1299
1325
  result_state = current_state if target_strings.include?(current_state)
1326
+ @state_event_count
1300
1327
  end
1301
1328
 
1302
1329
  begin
1303
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
+
1304
1344
  until mutex.synchronize { result_state }
1305
1345
  unless first_poll
1306
1346
  should_refresh = mutex.synchronize do
1307
1347
  next false if result_state
1308
1348
 
1309
- 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
1310
1352
  result_state.nil?
1311
1353
  end
1312
1354
  next unless should_refresh
@@ -1315,11 +1357,17 @@ module Daytona
1315
1357
 
1316
1358
  raise Sdk::TimeoutError, deadline.message if deadline&.expired?
1317
1359
 
1318
- poll_refresh(safe: safe_refresh, http_timeout: deadline&.remaining, deadline:)
1319
- 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
1320
1368
 
1321
1369
  mutex.synchronize do
1322
- next if result_state
1370
+ next if result_state || retry_after
1323
1371
 
1324
1372
  current = state.to_s
1325
1373
  if target_strings.include?(current) || error_strings.include?(current)
@@ -1328,14 +1376,13 @@ module Daytona
1328
1376
  end
1329
1377
  end
1330
1378
 
1331
- poll_interval = next_wait_for_state_poll_interval(
1332
- current_interval: poll_interval,
1333
- started_at: started_at,
1334
- subscribed: subscribed
1335
- )
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:)
1336
1382
  end
1337
1383
 
1338
1384
  if result_state && error_strings.include?(result_state)
1385
+ result_reason = read_error_reason if result_from_event && result_reason.nil?
1339
1386
  raise Sdk::Error,
1340
1387
  "Sandbox #{id} entered error state: #{result_state}, error reason: #{result_reason}"
1341
1388
  end
@@ -1363,15 +1410,33 @@ module Daytona
1363
1410
  end
1364
1411
  end
1365
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
+
1366
1428
  # @param api [DaytonaApiClient::SandboxApi] sandbox_api, or a copy of it with an HTTP timeout
1367
- 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)
1368
1431
  refresh_through(api)
1369
1432
  rescue DaytonaApiClient::ApiError => e
1433
+ raise if raise_rate_limit && e.code == 429
1434
+
1370
1435
  apply_state(DaytonaApiClient::SandboxState::DESTROYED) if e.code == 404
1371
1436
  rescue StandardError # rubocop:disable Lint/SuppressedException
1372
1437
  end
1373
1438
 
1374
- # 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+.
1375
1440
  #
1376
1441
  # @param api [DaytonaApiClient::SandboxApi] sandbox_api, or a copy of it with an HTTP timeout
1377
1442
  # @return [void]
@@ -1379,7 +1444,6 @@ module Daytona
1379
1444
  return refresh if api.equal?(sandbox_api)
1380
1445
 
1381
1446
  instrument_as(:refresh, component: 'Sandbox') do
1382
- ensure_subscribed
1383
1447
  process_response(api.get_sandbox(id))
1384
1448
  end
1385
1449
  end
@@ -1389,11 +1453,12 @@ module Daytona
1389
1453
  # @param safe [Boolean] Swallow errors as #refresh_data_safe does, a timed out request included
1390
1454
  # @param http_timeout [Numeric, nil] Most seconds the request may take; nil leaves the API client's timeout
1391
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)
1392
1457
  # @return [void]
1393
1458
  # @raise [Daytona::Sdk::TimeoutError] If safe is false and the request times out at the deadline
1394
- def poll_refresh(safe:, http_timeout:, deadline: nil)
1459
+ def poll_refresh(safe:, http_timeout:, deadline: nil, raise_rate_limit: false)
1395
1460
  api = http_timeout ? sandbox_api_with_timeout(http_timeout) : sandbox_api
1396
- safe ? refresh_data_safe(api) : refresh_through(api)
1461
+ safe ? refresh_data_safe(api, raise_rate_limit:) : refresh_through(api)
1397
1462
  rescue DaytonaApiClient::ApiError => e
1398
1463
  raise unless deadline && deadline_timed_out?(e, http_timeout)
1399
1464
 
@@ -1445,71 +1510,254 @@ module Daytona
1445
1510
  "Sandbox #{id} was destroyed after waiting#{waited} for a runner (queue timed out at #{queue_timed_out_at})"
1446
1511
  end
1447
1512
 
1448
- def ensure_subscribed
1449
- @waiter_mutex.synchronize do
1450
- 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
1451
1518
 
1452
- if @sub_id
1453
- 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
1454
1522
 
1455
- @sub_id = nil
1456
- 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]
1457
1529
 
1458
- subscribe_to_events
1530
+ Thread.handle_interrupt(Object => :never) do
1531
+ subscription[:id] = subscribe_to_state_events unless @subscription_manager.refresh(subscription[:id])
1459
1532
  end
1460
1533
  end
1461
1534
 
1462
- def subscribe_to_events
1463
- 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
1464
1546
 
1465
- @sub_id = @subscription_manager.subscribe(
1466
- resource_id: id,
1467
- handler: method(:handle_event),
1468
- events: ['sandbox.state.updated', 'sandbox.created']
1469
- )
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
1470
1570
  end
1471
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 }.
1472
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)
1473
1698
  return unless data.is_a?(Hash)
1474
1699
 
1475
1700
  raw = data['sandbox'] || data
1476
1701
  return unless raw.is_a?(Hash)
1477
1702
 
1478
- if event_name == 'sandbox.created'
1479
- process_response(DaytonaApiClient::Sandbox.build_from_hash(raw))
1480
- else
1481
- # Set before the state: a wait that ends on an error state reports this reason. The event omits the field
1482
- # when the sandbox has none.
1483
- @error_reason = raw['errorReason'] if data.key?('sandbox')
1484
- new_state = raw['state'] || data['newState']
1485
- apply_state(new_state) if new_state
1486
- 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)
1487
1710
  rescue StandardError
1488
1711
  nil
1489
1712
  end
1490
1713
 
1491
- def unsubscribe_from_events
1492
- return unless @sub_id
1493
-
1494
- @subscription_manager&.unsubscribe(@sub_id)
1495
- @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)
1496
1720
  end
1497
1721
 
1498
- def next_wait_for_state_poll_interval(current_interval:, started_at:, subscribed:)
1499
- return [current_interval * BACKOFF_MULTIPLIER, MAX_POLL_INTERVAL].min if subscribed
1500
-
1722
+ def next_fast_poll_interval(current_interval:, started_at:)
1501
1723
  elapsed = ::Process.clock_gettime(::Process::CLOCK_MONOTONIC) - started_at
1502
1724
  return current_interval if elapsed <= POLL_BACKOFF_DELAY
1503
1725
 
1504
1726
  [current_interval * BACKOFF_MULTIPLIER, MAX_POLL_INTERVAL].min
1505
1727
  end
1506
1728
 
1729
+ STATE_EVENTS = ['sandbox.state.updated'].freeze
1730
+ private_constant :STATE_EVENTS
1731
+
1507
1732
  INITIAL_POLL_INTERVAL = 0.1
1508
1733
  private_constant :INITIAL_POLL_INTERVAL
1509
1734
 
1510
1735
  MAX_POLL_INTERVAL = 1.0
1511
1736
  private_constant :MAX_POLL_INTERVAL
1512
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
+
1513
1761
  BACKOFF_MULTIPLIER = 1.1
1514
1762
  private_constant :BACKOFF_MULTIPLIER
1515
1763
 
@@ -1534,20 +1782,57 @@ module Daytona
1534
1782
  end
1535
1783
  private_constant :WaitDeadline
1536
1784
 
1537
- def wait_for_stop(deadline)
1785
+ def wait_for_stop(deadline, subscription: nil)
1538
1786
  wait_for_state(
1539
1787
  target_states: [DaytonaApiClient::SandboxState::STOPPED, DaytonaApiClient::SandboxState::DESTROYED],
1540
1788
  error_states: [DaytonaApiClient::SandboxState::ERROR, DaytonaApiClient::SandboxState::BUILD_FAILED],
1541
- deadline:
1789
+ deadline:,
1790
+ subscription:
1542
1791
  )
1543
1792
  end
1544
1793
 
1545
- def wait_for_resize(deadline)
1794
+ def wait_for_resize(deadline, subscription: nil)
1546
1795
  error_states = [DaytonaApiClient::SandboxState::ERROR, DaytonaApiClient::SandboxState::BUILD_FAILED]
1547
1796
  exclude = [DaytonaApiClient::SandboxState::RESIZING] + error_states
1548
1797
  target_states = DaytonaApiClient::SandboxState.all_vars.reject { |s| exclude.include?(s) }
1549
1798
 
1550
- 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
1551
1836
  end
1552
1837
 
1553
1838
  def wait_for_snapshot_complete(deadline)