workspaces 0.1.16 → 0.1.18

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.
@@ -19,6 +19,7 @@
19
19
  <a id="preview" class="button button--primary button--large" href="<%= escape(Config.preview_url(@id)) %>" <%= 'hidden' unless @presentation['ready'] %> target="_blank" rel="noopener noreferrer">Open workspace</a>
20
20
  <div id="lead-action" class="lead__action"><%= lead_action_form(@presentation['lead_action']) %></div>
21
21
  </div>
22
+ <p id="sleep-note" class="muted" <%= 'hidden' if sleep_note.empty? %>><%= escape(sleep_note) %></p>
22
23
  <p id="message" class="muted" hidden><%= field('message') %></p>
23
24
  <section class="error-panel setup-error" id="error-panel" role="alert" <%= 'hidden' unless @presentation['error'] %>>
24
25
  <h3>What went wrong</h3><pre id="error"><%= escape(@presentation['error']) %></pre>
@@ -43,9 +44,21 @@
43
44
  </div>
44
45
  <% end %>
45
46
  <div class="stack stack--tight">
46
- <label class="env-input-label" for="editable-env">Environment variables</label>
47
- <textarea id="editable-env" name="editable_env" rows="8" spellcheck="false" autocomplete="off" autocapitalize="off"><%= escape(editable_environment_text) %></textarea>
47
+ <p class="env-input-label" id="env-rows-label">Environment variables</p>
48
+ <div class="env-rows" id="env-rows" role="group" aria-labelledby="env-rows-label" data-env-rows>
49
+ <% environment_rows.each_with_index do |row, index| %>
50
+ <%= env_row_html(index, row) %>
51
+ <% end %>
52
+ </div>
53
+ <div class="env-row-actions">
54
+ <button type="button" class="button button--subtle button--small" data-env-add-row hidden>Add variable</button>
55
+ </div>
56
+ <% unless vault_status['available'] %>
57
+ <p class="muted env-vault-note" id="env-vault-note"><%= escape(vault_status['problem'] || 'Secrets are not available.') %></p>
58
+ <% end %>
59
+ <p class="muted env-secret-help">Secrets are write-only: once saved their values are never shown again. Leave a secret's value blank to keep what is stored.</p>
48
60
  </div>
61
+ <template id="env-row-template"><%= env_row_html('__INDEX__', { 'name' => '', 'value' => '', 'secret' => false }) %></template>
49
62
  </fieldset>
50
63
  <div class="env-actions">
51
64
  <button class="button button--primary" data-env-submit <%= 'disabled' if @presentation['busy'] %>><%= escape(@presentation['environment_submit']) %></button>
@@ -138,28 +138,86 @@ module Workspaces
138
138
  keys.map(&:to_s).sort
139
139
  end
140
140
 
141
- def editable_environment_text
141
+ # The rows the settings form starts with: visible variables with their values, then secrets by
142
+ # name only. A secret row never carries a value, so there is nothing to leak into the page.
143
+ def environment_rows
142
144
  values = @snapshot['editable_environment']
143
- return '' unless values.is_a?(Hash)
145
+ plain = values.is_a?(Hash) ? values.sort.map { |name, value| { 'name' => name.to_s, 'value' => value.to_s, 'secret' => false } } : []
146
+ names = @snapshot['secret_names']
147
+ secrets = names.is_a?(Array) ? names.map(&:to_s).sort.map { |name| { 'name' => name, 'value' => '', 'secret' => true } } : []
148
+ plain + secrets
149
+ end
144
150
 
145
- values.sort.map { |name, value| "#{name}=#{value}" }.join("\n")
151
+ # What a preset loads: its rows in the same shape. Secrets are untouched by presets.
152
+ def environment_preset_rows
153
+ environment_presets_raw.transform_values do |entries|
154
+ entries.sort.map { |name, value| { 'name' => name.to_s, 'value' => value.to_s } }
155
+ end
146
156
  end
147
157
 
148
- def environment_presets
158
+ # One row of the settings form. Plain rows show their value. Secret rows have a password field,
159
+ # never pre-filled, with a placeholder saying a value is stored. The secret checkbox is the only
160
+ # thing that decides which store a row goes to, and it is disabled for a stored secret so a
161
+ # saved secret cannot be quietly turned into a visible variable.
162
+ # Keeps password managers from offering to fill, save or generate anything for these inputs. No
163
+ # single attribute does it: `autocomplete="off"` is ignored on password fields, so each manager's
164
+ # own opt-out goes alongside it (1Password, LastPass, Bitwarden).
165
+ NO_AUTOFILL = 'autocomplete="off" data-1p-ignore data-lpignore="true" data-bwignore'
166
+
167
+ # One row of the settings form.
168
+ #
169
+ # A stored secret has no value input at all: just its name, a note, and a Replace button that
170
+ # adds the input when it is clicked. So the page holds no password field for a password manager
171
+ # to find until someone asks to replace one. (Without script, the input sits inside <noscript> so
172
+ # a secret can still be replaced.) A row posted with no value keeps what is stored.
173
+ #
174
+ # The secret checkbox is disabled for a stored secret, with a hidden field carrying it, so a
175
+ # saved secret cannot be quietly turned into a visible variable.
176
+ def env_row_html(index, row)
177
+ secret = row['secret']
178
+ stored = secret && !row['name'].to_s.empty?
179
+ <<~HTML.delete("\n")
180
+ <div class="env-row" data-env-row#{secret ? ' data-secret="true"' : ''}#{stored ? ' data-stored="true"' : ''}>
181
+ <input class="env-row__name" name="env[#{index}][name]" value="#{escape(row['name'])}" placeholder="NAME" aria-label="Variable name" spellcheck="false" #{NO_AUTOFILL} autocapitalize="off">
182
+ #{stored ? stored_value_html(index) : value_input_html(index, row)}
183
+ <label class="env-row__secret"><input type="checkbox" name="env[#{index}][secret]" value="1" data-env-secret#{secret ? ' checked' : ''}#{stored ? ' disabled' : ''}> Secret</label>
184
+ #{stored ? "<input type=\"hidden\" name=\"env[#{index}][secret]\" value=\"1\">" : ''}
185
+ <button type="button" class="button button--subtle button--small" data-env-remove-row aria-label="Remove variable" hidden>Remove</button>
186
+ </div>
187
+ HTML
188
+ end
189
+
190
+ def value_input_html(index, row, placeholder: nil)
191
+ secret = row['secret']
192
+ placeholder ||= secret ? 'Value' : 'value'
193
+ %(<input class="env-row__value" name="env[#{index}][value]" type="#{secret ? 'password' : 'text'}" value="#{secret ? '' : escape(row['value'])}" placeholder="#{escape(placeholder)}" aria-label="Value" spellcheck="false" #{NO_AUTOFILL} autocapitalize="off" data-env-value>)
194
+ end
195
+
196
+ def stored_value_html(index)
197
+ '<span class="env-row__stored" data-env-stored><span class="muted">Stored. Write-only.</span> ' \
198
+ '<button type="button" class="button button--subtle button--small" data-env-replace hidden>Replace</button></span>' \
199
+ "<noscript>#{value_input_html(index, { 'secret' => true }, placeholder: 'New value (leave blank to keep)')}</noscript>"
200
+ end
201
+
202
+ def environment_presets_raw
149
203
  presets = @snapshot['environment_presets']
150
204
  return {} unless presets.is_a?(Hash)
151
205
 
152
- presets.each_with_object({}) do |(name, entries), memo|
153
- next unless name.respond_to?(:to_s)
154
- next unless entries.is_a?(Hash)
206
+ presets.select { |name, entries| name.respond_to?(:to_s) && entries.is_a?(Hash) }.transform_keys(&:to_s)
207
+ end
155
208
 
156
- lines = entries.sort.map { |entry_name, value| "#{entry_name}=#{value}" }.join("\n")
157
- memo[name.to_s] = lines
158
- end
209
+ def vault_status
210
+ vault = @snapshot['vault']
211
+ vault.is_a?(Hash) ? vault : { 'available' => false, 'problem' => nil }
212
+ end
213
+
214
+ # The preset names and values the buttons are built from.
215
+ def environment_presets
216
+ environment_presets_raw
159
217
  end
160
218
 
161
219
  def environment_presets_json
162
- JSON.generate(environment_presets)
220
+ JSON.generate(environment_preset_rows)
163
221
  end
164
222
 
165
223
  # The lead's primary action. `open` is rendered separately as a link (it needs the
@@ -215,6 +273,16 @@ module Workspaces
215
273
  [progress_step_text, progress['eta_text']].compact.join('. ')
216
274
  end
217
275
 
276
+ def sleep_note
277
+ sleep = @presentation['sleep']
278
+ return '' unless sleep
279
+ return 'Kept awake: this workspace will not sleep when idle.' if sleep['keep_awake']
280
+ return '' unless @presentation['state'] == 'ready'
281
+
282
+ minutes = (sleep['after_seconds'] / 60.0).round
283
+ "Sleeps after #{minutes >= 1 ? "#{minutes} min" : "#{sleep['after_seconds'].round} s"} without preview traffic."
284
+ end
285
+
218
286
  def preset_badge_text
219
287
  name = @presentation['current_preset']
220
288
  name ? "Preset: #{name}" : ''
@@ -2,6 +2,7 @@
2
2
 
3
3
  require 'json'
4
4
  require 'securerandom'
5
+ require_relative 'vault'
5
6
 
6
7
  module Workspaces
7
8
  class EnvironmentOverrides
@@ -13,6 +14,7 @@ module Workspaces
13
14
  MAX_ENTRIES = 100
14
15
  MAX_VALUE_BYTES = 8192
15
16
  MAX_BODY_BYTES = 128 * 1024
17
+ MAX_ROWS = 200
16
18
 
17
19
  def self.validate_entries!(entries)
18
20
  raise Invalid, 'Environment overrides must be a mapping' unless entries.is_a?(Hash)
@@ -45,12 +47,26 @@ module Workspaces
45
47
  @home = home
46
48
  end
47
49
 
50
+ # Everything a step should see: saved variables and secrets. Raises Vault::Error when secrets
51
+ # exist but cannot be read, so a run fails with a reason instead of starting without them.
48
52
  def load
53
+ load_plain.merge(secret_values)
54
+ end
55
+
56
+ # The variables that are safe to show. No secrets, and no vault access.
57
+ def load_plain
49
58
  load_file(file_path).merge(load_file(editable_file_path))
50
59
  end
51
60
 
52
61
  def keys
53
- load.keys.sort
62
+ (load_plain.keys + secret_names).uniq.sort
63
+ end
64
+
65
+ # Names only, never values. Empty when the vault cannot be opened.
66
+ def secret_names
67
+ secret_values.keys.sort
68
+ rescue Vault::Error
69
+ []
54
70
  end
55
71
 
56
72
  def editable_values(defaults)
@@ -72,7 +88,28 @@ module Workspaces
72
88
  raise Invalid, 'Secret-like environment names cannot be stored in the visible editor'
73
89
  end
74
90
  persist_editable(entries, updated, defaults)
75
- load
91
+ load_plain
92
+ end
93
+
94
+ # Saves the settings form: a list of rows, each { 'name', 'value', 'secret' }. Plain rows are
95
+ # stored as editable settings. Secret rows go to the vault and are write-only: a secret row
96
+ # with no value keeps the value already stored, and a secret that is no longer listed is removed.
97
+ #
98
+ # Nothing is changed unless every row is valid and the vault can be used. Messages name
99
+ # variables, never values.
100
+ def replace_rows(rows, defaults:)
101
+ raise Invalid, 'Environment rows must be a list' unless rows.is_a?(Array)
102
+ raise Invalid, "Environment rows are limited to #{MAX_ROWS}" if rows.length > MAX_ROWS
103
+
104
+ self.class.validate_entries!(defaults)
105
+ plain, secrets = split_rows(rows)
106
+ self.class.validate_entries!(plain)
107
+ self.class.validate_entries!(secrets.compact)
108
+ raise Invalid, 'Environment overrides are limited to 100 entries' if plain.length + secrets.length > MAX_ENTRIES
109
+
110
+ write_secrets(secrets)
111
+ persist_editable(plain, plain.reject { |name, value| defaults[name] == value }, defaults)
112
+ load_plain
76
113
  end
77
114
 
78
115
  def apply_preset(name, recipe: Recipe.new)
@@ -111,9 +148,12 @@ module Workspaces
111
148
  updated
112
149
  end
113
150
 
151
+ # Removes saved variables and secrets. Returns the secrets that could not be removed (see
152
+ # Vault.purge_everywhere), empty when everything went.
114
153
  def clear!
115
154
  delete_file!
116
155
  delete_file!(editable_file_path)
156
+ Vault.purge_everywhere(workspace_id)
117
157
  end
118
158
 
119
159
  def scrub(value)
@@ -261,10 +301,69 @@ module Workspaces
261
301
  raise Invalid, 'Environment storage does not allow symlinks' if path.symlink?
262
302
  end
263
303
 
304
+ # Filtering still hides every secret that can be read, even when something else is wrong.
264
305
  def scrub_values
265
- load.values.reject(&:empty?).uniq.sort_by { |value| -value.bytesize }
266
- rescue Invalid
306
+ values = [safely { load_plain.values }, safely { secret_values.values }].flatten
307
+ values.reject(&:empty?).uniq.sort_by { |value| -value.bytesize }
308
+ end
309
+
310
+ def safely
311
+ yield
312
+ rescue Invalid, Vault::Error
267
313
  []
268
314
  end
315
+
316
+ def secret_values
317
+ Vault.provider.read(workspace_id)
318
+ end
319
+
320
+ def split_rows(rows)
321
+ plain = {}
322
+ secrets = {}
323
+ rows.each do |row|
324
+ raise Invalid, 'Each environment row needs a name and a value' unless row.is_a?(Hash)
325
+
326
+ name = row['name'].to_s.strip
327
+ value = row['value'].to_s
328
+ next if name.empty? && value.empty?
329
+
330
+ raise Invalid, 'Every variable needs a name' if name.empty?
331
+ raise Invalid, "#{name} is listed more than once" if plain.key?(name) || secrets.key?(name)
332
+
333
+ if [true, '1', 'true', 'on'].include?(row['secret'])
334
+ validate_name!(name)
335
+ secrets[name] = value.empty? ? nil : value
336
+ else
337
+ validate_plain_row!(name, value)
338
+ plain[name] = value
339
+ end
340
+ end
341
+ [plain, secrets]
342
+ end
343
+
344
+ def validate_plain_row!(name, value)
345
+ validate_name!(name)
346
+ validate_value!(value)
347
+ raise Invalid, "#{name} looks like a secret: tick Secret so it is stored write-only" if sensitive_name?(name)
348
+ raise Invalid, "#{name}: values must be a single line" if value.match?(/[\r\n]/)
349
+ end
350
+
351
+ # `submitted` maps each secret's name to its new value, or nil when the row was left blank. A blank
352
+ # row keeps the stored value. Existing secrets are never replaced blindly: if the vault cannot be
353
+ # read (wrong or missing key) an edit is refused rather than overwriting what is stored.
354
+ def write_secrets(submitted)
355
+ vault = Vault.provider
356
+ unless vault.available?
357
+ raise Vault::Unavailable, vault.problem unless submitted.empty?
358
+
359
+ return
360
+ end
361
+
362
+ stored = vault.read(workspace_id)
363
+ result = submitted.to_h do |name, value|
364
+ [name, value || stored.fetch(name) { raise Invalid, "#{name} is a new secret and needs a value" }]
365
+ end
366
+ vault.write(workspace_id, result) unless result == stored
367
+ end
269
368
  end
270
369
  end
@@ -6,20 +6,31 @@ require_relative 'coordinator'
6
6
  require_relative 'dashboard_view'
7
7
  require_relative 'environment_overrides'
8
8
  require_relative 'proxy_middleware'
9
+ require_relative 'activity_tracker'
10
+ require_relative 'sleep_policy'
9
11
 
10
12
  module Workspaces
11
13
  class FrontDoor
12
14
  WORKSPACE_ROUTE = %r{\A/workspaces/([a-z0-9]+(?:-[a-z0-9]+)*)
13
- (?:/(status|start|prepare|restart|resume|stop|remove|update-pr|environment))?\z}x
15
+ (?:/(status|start|prepare|restart|resume|stop|remove|update-pr|environment|keep-awake|allow-sleep))?\z}x
14
16
 
15
17
  # Rack env keys set on requests that reach a ready workspace backend, for use by
16
18
  # middleware registered with Workspaces.configure_proxy.
17
19
  WORKSPACE_ID_ENV = 'workspaces.workspace_id'.freeze
18
20
  WORKSPACE_ENV = 'workspaces.workspace'.freeze
19
21
 
20
- def initialize(coordinator: Coordinator.new, registry: Registry.new)
22
+ WAKE_POLL_SECONDS = 0.25
23
+ RETRY_AFTER_SECONDS = 5
24
+ private_constant :WAKE_POLL_SECONDS, :RETRY_AFTER_SECONDS
25
+
26
+ attr_reader :tracker
27
+
28
+ def initialize(coordinator: Coordinator.new, registry: Registry.new, tracker: ActivityTracker.new,
29
+ sleep_policy: SleepPolicy.new)
21
30
  @coordinator = coordinator
22
31
  @registry = registry
32
+ @tracker = tracker
33
+ @sleep_policy = sleep_policy
23
34
  @forwarder = ProxyMiddleware.build(method(:forward_to_backend))
24
35
  end
25
36
 
@@ -126,7 +137,9 @@ module Workspaces
126
137
  when 'prepare' then @coordinator.start(id, force: true)
127
138
  when 'restart' then @coordinator.restart(id)
128
139
  when 'resume' then resume(id, request)
129
- when 'stop' then stop(id)
140
+ when 'stop' then @coordinator.stop(id)
141
+ when 'keep-awake' then @coordinator.keep_awake(id, true)
142
+ when 'allow-sleep' then @coordinator.keep_awake(id, false)
130
143
  end
131
144
  end
132
145
 
@@ -135,7 +148,9 @@ module Workspaces
135
148
  return response(403, 'Actions require the configured dashboard origin') unless same_origin?(request)
136
149
 
137
150
  params = environment_params(request)
138
- updated = if params.key?('editable_env')
151
+ updated = if params.key?('env')
152
+ @coordinator.replace_environment_rows(id, rows: parse_environment_rows(params))
153
+ elsif params.key?('editable_env')
139
154
  @coordinator.replace_editable_environment(id, text: parse_editable_environment(params))
140
155
  else
141
156
  @coordinator.update_environment(id, **parse_environment_changes(params))
@@ -145,13 +160,8 @@ module Workspaces
145
160
  redirect(Config.dashboard_url(id))
146
161
  rescue EnvironmentOverrides::Invalid => e
147
162
  response(422, e.message)
148
- end
149
-
150
- def stop(id)
151
- @registry.with_lock(id) do
152
- Backend.new(id).stop!
153
- StateStore.new(Config.state_file).set(id, 'status' => 'stopped', 'message' => 'Server stopped')
154
- end
163
+ rescue Vault::Error => e
164
+ response(422, e.message)
155
165
  end
156
166
 
157
167
  def remove(request, id)
@@ -161,8 +171,13 @@ module Workspaces
161
171
  return response(413, 'Deletion confirmation is too large') if request.content_length.to_i > 512
162
172
  return response(422, 'Type the exact workspace ID to confirm deletion') unless request.POST['confirm_id'] == id
163
173
 
164
- @registry.remove(id, force: true)
165
- redirect("#{Config.public_origin}/workspaces")
174
+ leftover = @registry.remove(id, force: true)
175
+ @tracker.forget(id)
176
+ return redirect("#{Config.public_origin}/workspaces") if !leftover.is_a?(Array) || leftover.empty?
177
+
178
+ # The workspace is gone, but its secrets are not, and saying "removed" would be untrue.
179
+ response(500, "The workspace was removed, but its stored secrets could not be: #{leftover.join('; ')}. " \
180
+ 'Fix that, then run `workspaces purge-secrets`.')
166
181
  rescue ArgumentError, Worktree::CommandFailedError, SystemCallError
167
182
  response(409, 'Workspace was not removed. Check the server logs and retry when safe.')
168
183
  end
@@ -197,6 +212,24 @@ module Workspaces
197
212
  { set: normalize_set(params['set']), remove: normalize_remove(params['remove']) }
198
213
  end
199
214
 
215
+ # The form posts env[0][name], env[0][value] and env[0][secret] for each row. Rows are taken in
216
+ # the order of their numbers; anything that is not a mapping of strings is refused.
217
+ def parse_environment_rows(params)
218
+ rows = params['env']
219
+ raise EnvironmentOverrides::Invalid, 'Environment rows must be a numbered list' unless rows.is_a?(Hash)
220
+ unless rows.keys.all? { |key| key.to_s.match?(/\A\d{1,4}\z/) }
221
+ raise EnvironmentOverrides::Invalid, 'Environment rows must be a numbered list'
222
+ end
223
+
224
+ rows.sort_by { |key, _| key.to_i }.map do |_, row|
225
+ unless row.is_a?(Hash) && row.values.all?(String)
226
+ raise EnvironmentOverrides::Invalid, 'Each environment row needs a name and a value'
227
+ end
228
+
229
+ row.slice('name', 'value', 'secret')
230
+ end
231
+ end
232
+
200
233
  def parse_editable_environment(params)
201
234
  unless params['editable_env'].is_a?(String)
202
235
  raise EnvironmentOverrides::Invalid, 'Environment editor requires one editable_env field'
@@ -246,14 +279,106 @@ module Workspaces
246
279
  def proxy(id, request)
247
280
  return response(404, 'Unknown managed workspace') unless Worktree.new(id).exists?
248
281
 
282
+ counted = !@sleep_policy.ignored?(request.path_info)
283
+ lease = acquire_lease(id, counted)
284
+ return waking_unavailable(id) unless lease
285
+
286
+ begin
287
+ result = serve(id, request, counted)
288
+ rescue StandardError, Timeout::Error
289
+ lease.release
290
+ raise
291
+ end
292
+ hold_lease(result, lease)
293
+ rescue IOError, SystemCallError, Timeout::Error => e
294
+ response(502, "Workspace backend unavailable: #{e.class}")
295
+ end
296
+
297
+ def serve(id, request, counted)
298
+ phase = @coordinator.sleep_phase(id)
299
+ if phase
300
+ return sleeping_unavailable(id) unless counted
301
+
302
+ outcome = await_wake(id, phase)
303
+ return wake_failed(id) if outcome == :failed
304
+ return waking_unavailable(id) unless outcome == :ready
305
+ end
306
+
249
307
  snapshot = @coordinator.snapshot(id, include_log: false)
250
308
  return unavailable(id, request) unless snapshot['status'] == 'ready' && !snapshot['active']
251
309
 
252
310
  request.env[WORKSPACE_ID_ENV] = id
253
311
  request.env[WORKSPACE_ENV] = snapshot
254
312
  @forwarder.call(request.env)
255
- rescue IOError, SystemCallError, Timeout::Error => e
256
- response(502, "Workspace backend unavailable: #{e.class}")
313
+ end
314
+
315
+ # A lease keeps the workspace awake for as long as its request is being served. A response body
316
+ # that is still being produced (anything but a buffered Array) keeps it until the server closes it.
317
+ def hold_lease(result, lease)
318
+ status, headers, body = result
319
+ if body.is_a?(Array)
320
+ lease.release
321
+ return result
322
+ end
323
+
324
+ [status, headers, Rack::BodyProxy.new(body) { lease.release }]
325
+ end
326
+
327
+ # Requests are refused only while the workspace is being put to sleep, which takes a moment;
328
+ # they then wait their turn and wake it.
329
+ def acquire_lease(id, counted)
330
+ deadline = monotonic + Config.wake_timeout_seconds
331
+ loop do
332
+ lease = @tracker.acquire(id, counted: counted)
333
+ return lease if lease
334
+ return nil if monotonic >= deadline
335
+
336
+ sleep WAKE_POLL_SECONDS / 5
337
+ end
338
+ end
339
+
340
+ # Starts the wake (one request wins the workspace lock; the rest see it already running) and
341
+ # waits, within the wake timeout, for the server to be ready. :ready, :failed or :timeout.
342
+ def await_wake(id, phase)
343
+ @coordinator.wake(id) if phase == :sleeping
344
+ deadline = monotonic + Config.wake_timeout_seconds
345
+ loop do
346
+ outcome = wake_outcome(id)
347
+ return outcome if outcome
348
+ return :timeout if monotonic >= deadline
349
+
350
+ sleep WAKE_POLL_SECONDS
351
+ end
352
+ end
353
+
354
+ def wake_outcome(id)
355
+ return nil if @coordinator.sleep_phase(id)
356
+
357
+ case @coordinator.status_of(id)
358
+ when 'ready' then :ready
359
+ when 'preparing' then nil
360
+ else :failed
361
+ end
362
+ end
363
+
364
+ def monotonic
365
+ Process.clock_gettime(Process::CLOCK_MONOTONIC)
366
+ end
367
+
368
+ def waking_unavailable(id)
369
+ retryable(503, "Workspace is waking up and not ready yet. Try again in a few seconds. Status: #{Config.dashboard_url(id)}")
370
+ end
371
+
372
+ def sleeping_unavailable(id)
373
+ retryable(503, "Workspace is asleep. Open it to wake it. Status: #{Config.dashboard_url(id)}")
374
+ end
375
+
376
+ def wake_failed(id)
377
+ retryable(503, "Workspace could not wake up. Details: #{Config.dashboard_url(id)}")
378
+ end
379
+
380
+ def retryable(status, message)
381
+ [status, headers('text/plain').merge('retry-after' => RETRY_AFTER_SECONDS.to_s), [message]]
257
382
  end
258
383
 
259
384
  def unavailable(id, request)
@@ -3,11 +3,13 @@ require_relative 'progress'
3
3
  module Workspaces
4
4
  class Presentation
5
5
  TITLES = { 'idle' => 'Ready to start', 'stopped' => 'Server stopped', 'ready' => 'Workspace ready',
6
+ 'sleeping' => 'Workspace asleep',
6
7
  'preparing' => 'Running setup', 'error' => 'Setup failed',
7
8
  'interrupted' => 'Setup interrupted' }.freeze
8
9
  ACTIONS = { 'start' => 'Start workspace', 'prepare' => 'Rebuild & restart',
9
10
  'restart' => 'Restart server', 'stop' => 'Stop server',
10
- 'resume' => 'Retry failed step' }.freeze
11
+ 'resume' => 'Retry failed step', 'keep-awake' => 'Keep awake',
12
+ 'allow-sleep' => 'Allow sleep' }.freeze
11
13
 
12
14
  # Three layers, from friendly to technical. `lead` is the headline, one sentence and at
13
15
  # most one primary action. `environment` (presets and variables) is the area for
@@ -55,6 +57,14 @@ module Workspaces
55
57
  environment_submit: 'Save & restart', environment_title: 'Change settings',
56
58
  open_environment: false, open_technical: false
57
59
  },
60
+ 'sleeping' => {
61
+ sections: %w(lead environment) + TECHNICAL,
62
+ headline: 'Your workspace is asleep',
63
+ summary: 'It went quiet, so its server was stopped to free up resources. Your files and data are kept. ' \
64
+ 'Opening the preview wakes it in a few seconds.',
65
+ environment_submit: 'Save & start', environment_title: 'Change settings',
66
+ open_environment: false, open_technical: false
67
+ },
58
68
  'stopped' => {
59
69
  sections: %w(lead environment) + TECHNICAL,
60
70
  headline: 'Your workspace is paused',
@@ -95,7 +105,7 @@ module Workspaces
95
105
  'state' => state, 'sections' => sections,
96
106
  'headline' => definition[:headline], 'summary' => summary, 'resume' => resume,
97
107
  'lead_action' => lead_action, 'total' => total, 'progress' => progress,
98
- 'current_preset' => current_preset,
108
+ 'current_preset' => current_preset, 'sleep' => sleep_info,
99
109
  'environment_title' => definition[:environment_title],
100
110
  'environment_submit' => definition[:environment_submit],
101
111
  'open' => { 'environment' => definition[:open_environment], 'technical' => definition[:open_technical] } }
@@ -107,6 +117,14 @@ module Workspaces
107
117
  @snapshot.fetch('status', 'idle')
108
118
  end
109
119
 
120
+ # What the page needs to explain sleeping: whether this workspace is kept awake, and after how
121
+ # long an idle one sleeps. Nil for states where sleeping is not in play.
122
+ def sleep_info
123
+ return nil unless %w(ready sleeping).include?(status) && !@snapshot['sleep_after_seconds'].nil?
124
+
125
+ { 'keep_awake' => !!@snapshot['keep_awake'], 'after_seconds' => @snapshot['sleep_after_seconds'] }
126
+ end
127
+
110
128
  def busy?
111
129
  @snapshot['active'] || status == 'preparing'
112
130
  end
@@ -133,6 +151,7 @@ module Workspaces
133
151
  case state
134
152
  when 'ready' then { 'kind' => 'open', 'label' => 'Open workspace' }
135
153
  when 'stopped' then { 'kind' => 'post', 'key' => 'start', 'label' => 'Start workspace' }
154
+ when 'sleeping' then { 'kind' => 'post', 'key' => 'start', 'label' => 'Wake workspace' }
136
155
  when 'error', 'interrupted' then (retryable? ? resume_action : retry_action).merge('kind' => 'post')
137
156
  end
138
157
  end
@@ -228,7 +247,9 @@ module Workspaces
228
247
  def actions
229
248
  return [] if busy?
230
249
  available = if status == 'ready'
231
- %w(prepare restart stop).map { |key| action(key, false) }
250
+ %w(prepare restart stop).map { |key| action(key, false) } + keep_awake_actions
251
+ elsif status == 'sleeping'
252
+ [action('start', true).merge('label' => 'Wake workspace')] + keep_awake_actions
232
253
  elsif retryable?
233
254
  [resume_action, retry_action.merge('label' => 'Re-run all steps', 'primary' => false)]
234
255
  elsif %w(error interrupted).include?(status)
@@ -241,6 +262,12 @@ module Workspaces
241
262
 
242
263
  end
243
264
 
265
+ def keep_awake_actions
266
+ return [] if @snapshot['sleep_after_seconds'].nil?
267
+
268
+ [action(@snapshot['keep_awake'] ? 'allow-sleep' : 'keep-awake', false)]
269
+ end
270
+
244
271
  def retry_action
245
272
  restart = @snapshot['operation'] == 'restart'
246
273
  action(restart ? 'restart' : 'prepare', true).merge('label' => restart ? 'Retry restart' : 'Retry setup')