ruby-cdk 0.1.0 → 0.2.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.
Files changed (37) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +136 -1
  3. data/README.md +39 -20
  4. data/THIRD_PARTY_NOTICES.md +56 -2
  5. data/data/spec/META.json +10 -10
  6. data/data/spec/model.json.gz +0 -0
  7. data/lib/ruby_cdk/cli/diff.rb +88 -7
  8. data/lib/ruby_cdk/cli/new.rb +13 -16
  9. data/lib/ruby_cdk/cli/operation.rb +28 -4
  10. data/lib/ruby_cdk/cli/session.rb +20 -3
  11. data/lib/ruby_cdk/cli.rb +14 -1
  12. data/lib/ruby_cdk/constructs/bucket.rb +84 -16
  13. data/lib/ruby_cdk/constructs/events_rule.rb +245 -0
  14. data/lib/ruby_cdk/constructs/function.rb +65 -6
  15. data/lib/ruby_cdk/constructs/kms_alias.rb +90 -0
  16. data/lib/ruby_cdk/constructs/kms_key.rb +436 -0
  17. data/lib/ruby_cdk/constructs/queue.rb +94 -15
  18. data/lib/ruby_cdk/constructs/restapi.rb +234 -0
  19. data/lib/ruby_cdk/constructs/schedule.rb +92 -0
  20. data/lib/ruby_cdk/constructs/secret.rb +104 -0
  21. data/lib/ruby_cdk/constructs/ssm_parameter.rb +238 -0
  22. data/lib/ruby_cdk/constructs/table.rb +87 -10
  23. data/lib/ruby_cdk/constructs/topic.rb +25 -14
  24. data/lib/ruby_cdk/constructs.rb +16 -4
  25. data/lib/ruby_cdk/deploy/deployer.rb +232 -16
  26. data/lib/ruby_cdk/deploy/fakes.rb +31 -3
  27. data/lib/ruby_cdk/deploy/hotswap.rb +175 -0
  28. data/lib/ruby_cdk/deploy/parameters.rb +16 -8
  29. data/lib/ruby_cdk/deploy/ports.rb +18 -0
  30. data/lib/ruby_cdk/deploy/sdk_adapters.rb +23 -0
  31. data/lib/ruby_cdk/deploy.rb +1 -0
  32. data/lib/ruby_cdk/diff/destructive.rb +68 -0
  33. data/lib/ruby_cdk/diff/template.rb +13 -2
  34. data/lib/ruby_cdk/diff.rb +1 -0
  35. data/lib/ruby_cdk/errors.rb +13 -0
  36. data/lib/ruby_cdk/version.rb +1 -1
  37. metadata +10 -1
@@ -7,18 +7,33 @@ require_relative "poller"
7
7
  require_relative "capabilities"
8
8
  require_relative "parameters"
9
9
  require_relative "states"
10
+ require_relative "hotswap"
10
11
 
11
12
  module RubyCdk
12
13
  module Deploy
13
14
  # What a deploy or a destroy may do.
14
15
  class DeployOptions
15
- attr_reader :parameters, :tags, :yes, :no_execute, :on_failure, :no_rollback, :outputs_file, :account, :force, :profile
16
+ attr_reader :parameters, :tags, :yes, :no_execute, :on_failure, :no_rollback, :outputs_file, :account, :force, :profile,
17
+ :hotswap, :hotswap_fallback, :use_previous_parameters
16
18
 
17
19
  # force deploys even when the template and the parameters are unchanged.
18
20
  # profile is the name of the credential profile; it is shown on the target
19
21
  # line and selects nothing here, because the client was built with it.
22
+ # hotswap and hotswap_fallback are the CDK's --hotswap (a fast path that
23
+ # ignores what it cannot apply) and --hotswap-fallback (the fast path
24
+ # that hands the deploy to the change set when it cannot apply it).
25
+ #
26
+ # use_previous_parameters is the CDK's --previous-parameters: a parameter
27
+ # that is not given again keeps the value the stack has, sent as
28
+ # use_previous_value. Without it every parameter is resolved from what
29
+ # is given and from the template's default, and one with neither is an
30
+ # error. It is on by default, as the CDK's flag is (cli.ts:497 and
31
+ # parse-command-line-arguments.ts:583-587 in aws-cdk-cli at
32
+ # f7c9dca95f440a076c2abd61b66b984624b8548e); only the CDK's deployStack
33
+ # call itself documents false (deploy-stack.ts:170-177), and every
34
+ # caller passes the flag through.
20
35
  def initialize(parameters: {}, tags: {}, yes: false, no_execute: false, on_failure: :delete, no_rollback: false, outputs_file: nil, account: nil,
21
- force: false, profile: nil)
36
+ force: false, profile: nil, hotswap: false, hotswap_fallback: false, use_previous_parameters: true)
22
37
  @parameters = parameters
23
38
  @tags = tags
24
39
  @yes = yes
@@ -29,17 +44,28 @@ module RubyCdk
29
44
  @account = account
30
45
  @force = force
31
46
  @profile = profile
47
+ @hotswap = hotswap
48
+ @hotswap_fallback = hotswap_fallback
49
+ @use_previous_parameters = use_previous_parameters
32
50
  end
33
51
  end
34
52
 
53
+ # What --hotswap did on one deploy, for the deploy result and --json. mode
54
+ # is the CDK's HotswapMode word; fell_back says the change set carried the
55
+ # deploy after the fast path could not; swapped and non_hotswappable are
56
+ # the classification's two lists.
57
+ HotswapFacts = Struct.new(:mode, :fell_back, :swapped, :non_hotswappable, keyword_init: true)
58
+
35
59
  # What came out of a deploy or a destroy. :destroyed is a destroy that
36
60
  # deleted the stack; the CDK tells the two apart as well.
37
61
  class DeployResult
38
62
  OUTCOMES = %i[deployed no_changes not_executed rejected failed destroyed].freeze
39
63
 
40
- attr_reader :stack_name, :stack_id, :outcome, :changes, :outputs, :exit_code
64
+ attr_reader :stack_name, :stack_id, :outcome, :changes, :outputs, :exit_code, :hotswap
41
65
 
42
- def initialize(stack_name:, outcome:, stack_id: nil, changes: [], outputs: {}, exit_code: 0)
66
+ # hotswap carries the HotswapFacts of a deploy that ran with --hotswap or
67
+ # --hotswap-fallback, and nil for every other one.
68
+ def initialize(stack_name:, outcome:, stack_id: nil, changes: [], outputs: {}, exit_code: 0, hotswap: nil)
43
69
  raise ArgumentError, "unknown outcome #{outcome.inspect}" unless OUTCOMES.include?(outcome)
44
70
 
45
71
  @stack_name = stack_name
@@ -48,6 +74,7 @@ module RubyCdk
48
74
  @changes = changes
49
75
  @outputs = outputs
50
76
  @exit_code = exit_code
77
+ @hotswap = hotswap
51
78
  end
52
79
  end
53
80
 
@@ -122,6 +149,13 @@ module RubyCdk
122
149
  # stack is the stack: anything that answers stack_name, env,
123
150
  # termination_protection and tags. template is the template as JSON text.
124
151
  # identity is who the credentials are for, from the client.
152
+ #
153
+ # The default is the change set (D-010, architecture section 9). With
154
+ # --hotswap or --hotswap-fallback the deploy first evaluates what the
155
+ # template would change, and applies it with update_stack directly when
156
+ # every change is one the fast path carries; anything else falls back to
157
+ # the change set (--hotswap-fallback) or is reported and ignored
158
+ # (--hotswap), as the CDK's two flags do.
125
159
  def deploy(stack:, template:, identity:, options:)
126
160
  name = stack.stack_name
127
161
  check_account(name, stack, identity, options)
@@ -136,20 +170,198 @@ module RubyCdk
136
170
 
137
171
  state, info = prepare_stack(name, client.stack_state(name))
138
172
  # The parameters are built once the stack has been looked up, as the
139
- # CDK builds them after its lookup: a parameter that is not given again
140
- # keeps the value the stack has (UsePreviousValue), so a NoEcho value
141
- # comes back masked and is sent back masked, and a deploy with nothing
142
- # new is recognised as such. With no stack, a parameter without a value
143
- # or a default is an error.
173
+ # CDK builds them after its lookup (deploy-stack.ts:296-301 at
174
+ # f7c9dca95f440a076c2abd61b66b984624b8548e, in aws/aws-cdk-cli): with
175
+ # --previous-parameters, a parameter that is not given again keeps the
176
+ # value the stack has (UsePreviousValue), so a NoEcho value comes back
177
+ # masked and is sent back masked, and a deploy with nothing new is
178
+ # recognised as such; without it, the stack's values are not offered
179
+ # and a parameter without a value or a default is an error, as for a
180
+ # stack that does not exist yet.
144
181
  deployed_parameters = info ? client.stack_parameters(info.id || name) : nil
145
- parameters = Parameters.new(body, options.parameters, deployed: deployed_parameters)
182
+ parameters = Parameters.new(body, options.parameters,
183
+ deployed: options.use_previous_parameters ? deployed_parameters : nil)
146
184
 
147
185
  if state == :stable && unchanged?(name, info, body, parameters, tags, options, deployed_parameters)
186
+ if options.hotswap || options.hotswap_fallback
187
+ # The CDK's skip line for a hotswap deploy (deploy-stack.ts:307-314
188
+ # at f7c9dca95f440a076c2abd61b66b984624b8548e). Nothing is
189
+ # evaluated: the template and the parameters and the tags are the
190
+ # ones the stack already has.
191
+ output.announce("✨ hotswap deployment skipped - no changes were detected (use --force to override)")
192
+ end
148
193
  reconcile_protection(info.id || name, info.termination_protection, stack.termination_protection)
149
194
  deliver_outputs(info, options, name)
150
- return DeployResult.new(stack_name: name, stack_id: info.id, outcome: :no_changes, outputs: outputs_of(info))
195
+ return hotswap_guarded(options,
196
+ DeployResult.new(stack_name: name, stack_id: info.id, outcome: :no_changes, outputs: outputs_of(info)),
197
+ HotswapFacts.new(mode: hotswap_mode(options), fell_back: false, swapped: [], non_hotswappable: []))
198
+ end
199
+
200
+ if options.hotswap || options.hotswap_fallback
201
+ result, facts = hotswap_deployment(stack, name, info, template, parameters, tags, capabilities, identity, options)
202
+ return result if result
203
+
204
+ return with_hotswap_facts(
205
+ change_set_deploy(stack, name, state, info, template, parameters, tags, capabilities, on_failure, identity, options),
206
+ facts
207
+ )
208
+ end
209
+
210
+ change_set_deploy(stack, name, state, info, template, parameters, tags, capabilities, on_failure, identity, options)
211
+ end
212
+
213
+ # --hotswap and --hotswap-fallback: the fast path. Everything here is
214
+ # the CDK's flow (hotswap-deployments.ts and deploy-stack.ts at
215
+ # f7c9dca95f440a076c2abd61b66b984624b8548e): read the deployed template,
216
+ # classify the diff, and apply it only when there is nothing in it the
217
+ # fast path cannot carry. Answers [result, facts]; a nil result hands the
218
+ # deploy to the change set below, with the facts its result is to carry.
219
+ def hotswap_deployment(stack, name, info, template, parameters, tags, capabilities, identity, options)
220
+ mode = hotswap_mode(options)
221
+ target = info&.id || name
222
+
223
+ plan = evaluated_plan(target, name, template)
224
+ unless plan
225
+ # The CDK catches its evaluation failure here and says this
226
+ # (deploy-stack.ts:379-383), then falls back -- or, without a
227
+ # fallback, deploys nothing.
228
+ output.announce("Could not perform a hotswap deployment, because the CloudFormation template could not be resolved.")
229
+ unless options.hotswap_fallback
230
+ return [ hotswap_result(name, info, :no_changes, mode),
231
+ HotswapFacts.new(mode: mode, fell_back: false, swapped: [], non_hotswappable: []) ]
232
+ end
233
+
234
+ return [ nil, HotswapFacts.new(mode: mode, fell_back: true, swapped: [], non_hotswappable: []) ]
235
+ end
236
+
237
+ if plan.rejected.any?
238
+ report_rejected(plan, mode)
239
+ if options.hotswap_fallback
240
+ output.announce("Could not perform a hotswap deployment, as the stack #{name} contains non-Asset changes")
241
+ output.announce("Falling back to doing a full deployment")
242
+ return [ nil, HotswapFacts.new(mode: mode, fell_back: true, swapped: [], non_hotswappable: plan.rejected) ]
243
+ end
244
+
245
+ # --hotswap ignores what it cannot apply, and applies nothing here:
246
+ # the one update_stack the fast path has carries the whole template,
247
+ # so a mixed diff is applied either whole or not at all (section 21).
248
+ return [ hotswap_result(name, info, :no_changes, mode, non_hotswappable: plan.rejected),
249
+ HotswapFacts.new(mode: mode, fell_back: false, swapped: [], non_hotswappable: plan.rejected) ]
250
+ end
251
+
252
+ if plan.swapped.empty?
253
+ # An empty diff never reaches here (the skip rule catches it), so
254
+ # this is a diff of nothing but ignored annotations -- the CDK's
255
+ # noOp deploy (hotswap-deployments.ts:146).
256
+ return [ hotswap_result(name, info, :no_changes, mode),
257
+ HotswapFacts.new(mode: mode, fell_back: false, swapped: [], non_hotswappable: []) ]
258
+ end
259
+
260
+ output.announce("\n✨ hotswapping resources:")
261
+ plan.swapped.each { |function| output.announce(" ✨ #{Hotswap.resource_text(function)}") }
262
+
263
+ unless approved?(options, "Hotswap these changes to stack #{name} in account #{identity.account} (#{identity.region})?")
264
+ raise ApprovalRequired, "Approval for the hotswap of stack #{name} was not given, so nothing was applied.\n" \
265
+ "Run the command again in a terminal to approve it, or with --yes to deploy without asking."
266
+ end
267
+
268
+ # A template too large for a request is placed in the bucket, and the
269
+ # update carries its URL instead of its body, as the change set does.
270
+ # The update names the stack the way the CDK's direct deployment does,
271
+ # by its name; the events are followed by its ID.
272
+ template_url = place_template(stack, template)
273
+ begin
274
+ client.update_stack(name, template: template_url ? nil : template, template_url: template_url,
275
+ parameters: parameters.api, tags: tags, capabilities: capabilities)
276
+ rescue RubyCdk::PreconditionError => e
277
+ raise unless /No updates are to be performed\./.match?(e.message)
278
+
279
+ # The race the CDK's direct deployment also catches: the stack took
280
+ # its new state from another deploy while this one was reading it.
281
+ output.announce("#{name}: CloudFormation reports that the update would change nothing. Nothing was applied.")
282
+ return [ hotswap_result(name, info, :no_changes, mode),
283
+ HotswapFacts.new(mode: mode, fell_back: false, swapped: [], non_hotswappable: []) ]
284
+ end
285
+ plan.swapped.each { |function| output.announce(" ✨ #{Hotswap.resource_text(function)} hotswapped!") }
286
+
287
+ final_state, final_info, events, problem = follow_operation(target, name)
288
+ if final_state == :stable && (final_info.nil? || DEPLOYED_STATUSES.include?(final_info.status))
289
+ deliver_outputs(final_info, options, name)
290
+ return [ hotswap_result(name, final_info, :deployed, mode, swapped: plan.swapped,
291
+ stack_id: final_info&.id || target, outputs: outputs_of(final_info)),
292
+ HotswapFacts.new(mode: mode, fell_back: false, swapped: plan.swapped, non_hotswappable: []) ]
293
+ end
294
+
295
+ output.failure(operation_failure(name, final_state, final_info, events, :deploy, problem))
296
+ [ hotswap_result(name, final_info, :failed, mode, swapped: plan.swapped,
297
+ stack_id: final_state == :absent ? nil : (final_info&.id || target), exit_code: 5),
298
+ HotswapFacts.new(mode: mode, fell_back: false, swapped: plan.swapped, non_hotswappable: []) ]
299
+ end
300
+
301
+ # The deployed template against the new one, classified. A template that
302
+ # cannot be read or compared stops the fast path here; the answer is nil
303
+ # then, and the deploy falls back or stops.
304
+ def evaluated_plan(target, name, template)
305
+ deployed = client.get_template(target)
306
+ Hotswap.plan(Diff.of(deployed, template, stack_name: name))
307
+ rescue StandardError
308
+ nil
309
+ end
310
+
311
+ # The rejected changes, as the CDK lists them (hotswap-deployments.ts,
312
+ # logRejectedChanges and nonHotswappableChangeMessage): a heading that
313
+ # names the way out, then one line per change. An output has its own
314
+ # shape; the rejected properties are named in the reason itself.
315
+ def report_rejected(plan, mode)
316
+ heading = if mode == Hotswap::FALL_BACK
317
+ "⚠️ The following non-hotswappable changes were found:"
318
+ else
319
+ "⚠️ The following non-hotswappable changes were found. To reconcile these using CloudFormation, " \
320
+ "specify --hotswap-fallback"
151
321
  end
322
+ output.announce(heading)
323
+ plan.rejected.each do |change|
324
+ output.announce(if change.resource_type == "Output"
325
+ " output: #{change.logical_id}, reason: #{change.reason}"
326
+ else
327
+ " resource: #{change.logical_id}, type: #{change.resource_type}, reason: #{change.reason}"
328
+ end)
329
+ end
330
+ end
152
331
 
332
+ # A hotswap deploy's result, with its facts. The lists are what the
333
+ # result stands for: what was applied and what was refused, not the
334
+ # whole plan. info is the stack's last read: its ID is the best name the
335
+ # stack has.
336
+ def hotswap_result(name, info, outcome, mode, swapped: [], non_hotswappable: [], stack_id: nil, outputs: {}, exit_code: 0)
337
+ DeployResult.new(stack_name: name, stack_id: stack_id || info&.id, outcome: outcome, outputs: outputs,
338
+ exit_code: exit_code, hotswap: HotswapFacts.new(mode: mode, fell_back: false, swapped: swapped,
339
+ non_hotswappable: non_hotswappable))
340
+ end
341
+
342
+ # Rebuilds a result of the change-set path with the facts of the hotswap
343
+ # that handed the deploy over to it.
344
+ def with_hotswap_facts(result, facts)
345
+ DeployResult.new(stack_name: result.stack_name, stack_id: result.stack_id, outcome: result.outcome,
346
+ changes: result.changes, outputs: result.outputs, exit_code: result.exit_code, hotswap: facts)
347
+ end
348
+
349
+ # A deploy without --hotswap carries no facts; the skip result of one
350
+ # that does carries the empty ones.
351
+ def hotswap_guarded(options, result, facts)
352
+ return result unless options.hotswap || options.hotswap_fallback
353
+
354
+ with_hotswap_facts(result, facts)
355
+ end
356
+
357
+ # The CDK's HotswapMode word for the flags given.
358
+ def hotswap_mode(options)
359
+ options.hotswap_fallback ? Hotswap::FALL_BACK : Hotswap::HOTSWAP_ONLY
360
+ end
361
+
362
+ # The change-set deploy: everything after the skip rule and the hotswap
363
+ # attempt, with what both computed.
364
+ def change_set_deploy(stack, name, state, info, template, parameters, tags, capabilities, on_failure, identity, options)
153
365
  # A template too large for a request is placed in the bucket, and the
154
366
  # change set carries its URL instead of its body. It is placed here, once
155
367
  # a change set is actually coming: a deploy that has nothing to do never
@@ -457,15 +669,19 @@ module RubyCdk
457
669
  end
458
670
  end
459
671
 
460
- # A change set that is gone answers as deleted or is not found at all;
461
- # anything else keeps being asked, until the change-set poller gives up.
672
+ # A change set that is not there raises ChangeSetNotFound -- CloudFormation's
673
+ # answer for one that was never created and for one already deleted, as it
674
+ # answered a real stack on 2026-11-29 -- and is gone; one that answers as
675
+ # deleted, or as failed to delete, is gone too; anything else keeps being
676
+ # asked, until the change-set poller gives up. The class is what is
677
+ # rescued: the first version matched the words "not found", which AWS
678
+ # does not say, and no update through a change set ever passed on a real
679
+ # stack.
462
680
  def wait_for_change_set_gone(name, change_set_id)
463
681
  polling(poller, "CloudFormation did not finish deleting the earlier change set of stack #{name}") do
464
682
  described = begin
465
683
  client.describe_change_set(name, change_set_id)
466
- rescue RubyCdk::PreconditionError => e
467
- raise unless /not found/i.match?(e.message)
468
-
684
+ rescue RubyCdk::ChangeSetNotFound
469
685
  :gone
470
686
  end
471
687
  :gone if described == :gone || %w[DELETE_COMPLETE DELETE_FAILED].include?(described.status)
@@ -188,13 +188,41 @@ module RubyCdk
188
188
  end
189
189
  end
190
190
 
191
+ # The direct update of --hotswap. CloudFormation refuses an update that
192
+ # would change nothing (the CDK's direct deployment matches the words
193
+ # of the refusal), so the fake refuses one whose template and
194
+ # parameters and tags are already the stack's. A test that wants
195
+ # another answer scripts it.
196
+ def update_stack(name, template:, parameters:, tags:, capabilities:, template_url: nil)
197
+ scripted(:update_stack, name, template: template, template_url: template_url, parameters: parameters,
198
+ tags: tags, capabilities: capabilities) do
199
+ record = lookup(name)
200
+ new_parameters = pairs_of(parameters, record)
201
+ if template_url.nil? && record && record.template == template &&
202
+ new_parameters == (record.parameters || {}) && tags == (record.tags || [])
203
+ raise RubyCdk::PreconditionError, "ValidationError: No updates are to be performed."
204
+ end
205
+
206
+ record.template = template if template
207
+ record.parameters = new_parameters
208
+ record.tags = tags
209
+ record.status = "UPDATE_COMPLETE"
210
+ nil
211
+ end
212
+ end
213
+
191
214
  def describe_change_set(name, change_set_id)
192
215
  scripted(:describe_change_set, name, change_set_id) do
193
216
  change_set = @change_sets[change_set_id]
194
217
  if change_set.nil?
195
- # A change set that is gone answers as a deleted one, as
196
- # CloudFormation answers for a deleted set.
197
- ChangeSet.new(id: change_set_id, status: "DELETE_COMPLETE")
218
+ # A change set that is not there is an error, as it is to
219
+ # CloudFormation: never created or already deleted, it answers
220
+ # ChangeSetNotFound (read on a real stack on 2026-11-29). The
221
+ # first version of this fake answered a DELETE_COMPLETE status
222
+ # instead, and the engine matched the words "not found": every
223
+ # test was green while every update through a change set failed
224
+ # on a real stack.
225
+ raise RubyCdk::ChangeSetNotFound, "ChangeSetNotFound: ChangeSet [#{change_set_id}] does not exist"
198
226
  elsif change_set.empty
199
227
  ChangeSet.new(id: change_set_id, status: "FAILED",
200
228
  status_reason: "The submitted information didn't contain changes.", changes: [])
@@ -0,0 +1,175 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../errors"
4
+ require_relative "../diff"
5
+
6
+ module RubyCdk
7
+ module Deploy
8
+ # What `deploy --hotswap` may apply directly, and what it may not
9
+ # (architecture section 9). The classification is the CDK's
10
+ # (packages/@aws-cdk/toolkit-lib/lib/api/hotswap/ at f7c9dca95f440a076c2abd61b66b984624b8548e,
11
+ # hotswap-deployments.ts and lambda-functions.ts): the changes of two
12
+ # templates are sorted into the ones a direct update can carry and the
13
+ # ones that need the change set.
14
+ #
15
+ # The CDK sorts changes per resource and applies each hotswappable one
16
+ # with the API of its service (a Lambda function's code and configuration
17
+ # go through the Lambda SDK). This engine applies through one
18
+ # CloudFormation UpdateStack, which carries the whole new template, so the
19
+ # whole diff has to be hotswappable: anything else, and the deploy falls
20
+ # back -- there is no partial hotswap here, because an UpdateStack whose
21
+ # template leaves resources out deletes them.
22
+ #
23
+ # Every line the engine prints around this is the CDK's own wording, read
24
+ # at the commit above (hotswap-deployments.ts, deploy-stack.ts,
25
+ # cdk-toolkit.ts).
26
+ module Hotswap
27
+ # The resource type the fast path updates. The CDK's detectors also
28
+ # carry AppSync, ECS, CodeBuild, Step Functions, ECR images and the
29
+ # CloudControl types; none of them is a construct of this tool, so a
30
+ # change to any other type is refused.
31
+ LAMBDA_FUNCTION = "AWS::Lambda::Function"
32
+
33
+ # The CDK's two HotswapMode words (hotswap/common.ts): --hotswap-fallback
34
+ # hands the deploy to the change set when anything is refused, --hotswap
35
+ # ignores what it cannot apply.
36
+ FALL_BACK = "fall-back"
37
+ HOTSWAP_ONLY = "hotswap-only"
38
+
39
+ # The function properties the fast path carries: the code (an asset's
40
+ # S3 location, or inline code) and the configuration CloudFormation
41
+ # updates in place. The CDK's detector classifies only Code,
42
+ # Environment and Description, because it applies them with the Lambda
43
+ # API; the difference is recorded in architecture section 21.
44
+ HOTSWAPPABLE_PROPERTIES = %w[Code Handler Runtime MemorySize Timeout Environment Description].freeze
45
+
46
+ # The code properties that name an image in a registry. The CDK's ECR
47
+ # image swap is a detector this tool does not carry: an image-based
48
+ # function falls back.
49
+ IMAGE_CODE = "ImageUri"
50
+
51
+ # The two lines above every hotswap deploy (cdk-toolkit.ts, printed once
52
+ # per command, as here).
53
+ WARNINGS = [
54
+ "⚠️ The --hotswap and --hotswap-fallback flags deliberately introduce CloudFormation drift to speed up deployments",
55
+ "⚠️ They should only be used for development - never use them for your production Stacks!"
56
+ ].freeze
57
+
58
+ # One function the fast path updates. name is the physical function
59
+ # name when the template writes it as a plain string, and nil when a
60
+ # CloudFormation expression stands in its place.
61
+ SwappedFunction = Struct.new(:logical_id, :resource_type, :name, keyword_init: true)
62
+
63
+ # One change the fast path cannot carry, with the CDK's reason.
64
+ RejectedChange = Struct.new(:logical_id, :resource_type, :reason, keyword_init: true)
65
+
66
+ # The classification of one template diff. What the diff found outside
67
+ # the resources -- a changed output, a changed parameter, a changed
68
+ # template attribute -- is here too, as rejected changes: an
69
+ # UpdateStack carries them, so they block the fast path rather than
70
+ # being applied unannounced.
71
+ Plan = Struct.new(:swapped, :rejected, keyword_init: true) do
72
+ def hotswappable?
73
+ rejected.empty?
74
+ end
75
+ end
76
+
77
+ module_function
78
+
79
+ # The classification of a TemplateDiff. The order is the diff's own:
80
+ # removals, additions, updates. A resource whose definition changed
81
+ # outside its Properties (DeletionPolicy, Metadata) does not block, as
82
+ # the CDK's detector ignores its otherDiffs. A change anywhere else in
83
+ # the template does block: the fast path's one UpdateStack would carry
84
+ # it, where the CDK's per-resource calls would leave it out -- every
85
+ # such entry is reported as a rejected change, the outputs with the
86
+ # CDK's own reason, the rest with one of this tool's.
87
+ def plan(diff)
88
+ swapped = []
89
+ rejected = []
90
+
91
+ if [ diff.format_version, diff.description, diff.transform ].compact.any?
92
+ rejected << RejectedChange.new(logical_id: diff.stack_name, resource_type: "Template",
93
+ reason: "the template's own attributes changed (AWSTemplateFormatVersion, Description or Transform)")
94
+ end
95
+ diff.sections.each do |section, entries|
96
+ entries.each_key do |name|
97
+ if section == "Outputs"
98
+ rejected << RejectedChange.new(logical_id: name, resource_type: "Output", reason: "output was changed")
99
+ else
100
+ rejected << RejectedChange.new(logical_id: name, resource_type: section,
101
+ reason: "template section '#{section}' changed outside the resources")
102
+ end
103
+ end
104
+ end
105
+ diff.unknown.each_key do |key|
106
+ rejected << RejectedChange.new(logical_id: key, resource_type: "Template",
107
+ reason: "template key '#{key}' changed outside the resources")
108
+ end
109
+
110
+ diff.changes.each do |change|
111
+ type = change.new_type || change.old_type
112
+ if change.removal?
113
+ rejected << RejectedChange.new(logical_id: change.logical_id, resource_type: change.old_type,
114
+ reason: "resource '#{change.logical_id}' was destroyed by this deployment")
115
+ elsif change.addition?
116
+ rejected << RejectedChange.new(logical_id: change.logical_id, resource_type: change.new_type,
117
+ reason: "resource '#{change.logical_id}' was created by this deployment")
118
+ elsif change.type_changed?
119
+ rejected << RejectedChange.new(logical_id: change.logical_id, resource_type: change.new_type,
120
+ reason: "resource '#{change.logical_id}' had its type changed from '#{change.old_type}' to '#{change.new_type}'")
121
+ elsif type != LAMBDA_FUNCTION
122
+ rejected << RejectedChange.new(logical_id: change.logical_id, resource_type: type,
123
+ reason: "This resource type is not supported for hotswap deployments")
124
+ else
125
+ classify_function(change, swapped, rejected)
126
+ end
127
+ end
128
+
129
+ Plan.new(swapped: swapped, rejected: rejected)
130
+ end
131
+
132
+ # One AWS::Lambda::Function that exists on both sides, of the same type:
133
+ # hotswappable when every changed property is one the fast path carries,
134
+ # and the code is not an image. The reason for a refused property list is
135
+ # the CDK's, its property names as Ruby writes them.
136
+ def classify_function(change, swapped, rejected)
137
+ names = change.properties.map(&:name)
138
+ refused = names - HOTSWAPPABLE_PROPERTIES
139
+ unless refused.empty?
140
+ rejected << RejectedChange.new(logical_id: change.logical_id, resource_type: LAMBDA_FUNCTION,
141
+ reason: "resource properties '#{refused.inspect}' are not hotswappable on this resource type")
142
+ return
143
+ end
144
+
145
+ code = new_properties(change)["Code"]
146
+ if code.is_a?(Hash) && code.key?(IMAGE_CODE)
147
+ rejected << RejectedChange.new(logical_id: change.logical_id, resource_type: LAMBDA_FUNCTION,
148
+ reason: "the function's code is an ECR image, which this tool does not hotswap")
149
+ return
150
+ end
151
+
152
+ swapped << SwappedFunction.new(logical_id: change.logical_id, resource_type: LAMBDA_FUNCTION,
153
+ name: function_name(change))
154
+ end
155
+
156
+ # What the fast path prints for one function: the CDK's resourceText --
157
+ # the physical name when there is one, the logical ID when there is not.
158
+ def resource_text(function)
159
+ "#{function.resource_type} '#{function.name || function.logical_id}'"
160
+ end
161
+
162
+ def new_properties(change)
163
+ value = change.new_value
164
+ value.is_a?(Hash) && value["Properties"].is_a?(Hash) ? value["Properties"] : {}
165
+ end
166
+
167
+ def function_name(change)
168
+ name = new_properties(change)["FunctionName"]
169
+ name.is_a?(String) ? name : nil
170
+ end
171
+
172
+ private_class_method :new_properties, :function_name
173
+ end
174
+ end
175
+ end
@@ -5,10 +5,16 @@ require_relative "errors"
5
5
  module RubyCdk
6
6
  module Deploy
7
7
  # The parameter values a deploy sends, and whether they differ from the
8
- # ones deployed. The rule is the CDK's (ParameterValues in its CLI): a value
9
- # that is given wins, then the template's default; a parameter that has
10
- # neither is an error; a value for a parameter the template does not declare
11
- # is passed on, and CloudFormation reports the typo.
8
+ # ones deployed. The rule is the CDK's (ParameterValues in
9
+ # lib/api/deployments/cfn-api.ts at f7c9dca95f440a076c2abd61b66b984624b8548e,
10
+ # in aws/aws-cdk-cli): a value that is given wins, then the value the stack
11
+ # was last deployed with, then the template's default; a parameter that has
12
+ # none of the three is an error; a value for a parameter the template does
13
+ # not declare is passed on, and CloudFormation reports the typo.
14
+ #
15
+ # Which values the stack has is the caller's decision, as it is the CDK's
16
+ # (deploy-stack.ts:299-301 at the commit above): deployed is what
17
+ # --previous-parameters hands over, and nil without it.
12
18
  class Parameters
13
19
  # CloudFormation resolves these at deploy time, so they can change with no local sign of it.
14
20
  SSM_TYPE_PREFIX = "AWS::SSM::Parameter::"
@@ -17,11 +23,13 @@ module RubyCdk
17
23
  attr_reader :values
18
24
  # What goes to create_change_set: an Array of
19
25
  # { parameter_key:, parameter_value: } and of
20
- # { parameter_key:, use_previous_value: true }.
26
+ # { parameter_key:, use_previous_value: true }. A parameter left to its
27
+ # default is in neither.
21
28
  attr_reader :api
22
29
 
23
30
  # template is parsed; overrides is { key => value }; deployed is
24
- # { key => value } as the stack last had it, when there is a stack.
31
+ # { key => value } as the stack last had it, when the stack exists and
32
+ # its values are to be used.
25
33
  def initialize(template, overrides = {}, deployed: nil)
26
34
  section = template["Parameters"]
27
35
  declared = section.is_a?(Hash) ? section : {}
@@ -33,14 +41,14 @@ module RubyCdk
33
41
  declared.each do |key, spec|
34
42
  if given.key?(key)
35
43
  add(key, given[key])
36
- elsif spec.is_a?(Hash) && !spec["Default"].nil?
37
- @values[key] = text(spec["Default"])
38
44
  elsif deployed && deployed.key?(key)
39
45
  # Not given again: keep what the stack has, as the CDK sends it
40
46
  # (UsePreviousValue). A NoEcho value comes back masked and is sent
41
47
  # back masked, so a deploy with nothing new is recognised as such.
42
48
  @values[key] = text(deployed[key])
43
49
  @api << { parameter_key: key, use_previous_value: true }
50
+ elsif spec.is_a?(Hash) && !spec["Default"].nil?
51
+ @values[key] = text(spec["Default"])
44
52
  else
45
53
  missing << key
46
54
  end
@@ -138,6 +138,22 @@ module RubyCdk
138
138
  Kernel.raise NotImplementedError
139
139
  end
140
140
 
141
+ # The direct update of a deployed stack, without a change set: the fast
142
+ # path `deploy --hotswap` takes (architecture section 9). template is the
143
+ # JSON text of the template, sent inline; template_url, when given, is
144
+ # the URL of the template placed in the bucket, and template is nil
145
+ # then: CloudFormation takes one or the other, never both (architecture
146
+ # §8) -- the same contract create_change_set carries. The template is
147
+ # the whole new one: CloudFormation updates what differs and needs the
148
+ # rest to know what to keep.
149
+ def update_stack(name, template:, parameters:, tags:, capabilities:, template_url: nil)
150
+ Kernel.raise NotImplementedError
151
+ end
152
+
153
+ # The change set change_set_id names, by its ARN or by its name. One that
154
+ # is not there -- never created, or already deleted -- raises
155
+ # ChangeSetNotFound (errors.rb), which is CloudFormation's own answer and
156
+ # is matched by its class, never by its words.
141
157
  def describe_change_set(name, change_set_id)
142
158
  Kernel.raise NotImplementedError
143
159
  end
@@ -146,6 +162,8 @@ module RubyCdk
146
162
  Kernel.raise NotImplementedError
147
163
  end
148
164
 
165
+ # Deleting a change set that is not there is not an error, as it is not
166
+ # one to CloudFormation: it answers success for a name it never saw.
149
167
  def delete_change_set(name, change_set_id)
150
168
  Kernel.raise NotImplementedError
151
169
  end