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
@@ -58,8 +58,8 @@ module RubyCdk
58
58
  # (initializeProject, init.ts:729-733), and what it cannot run itself
59
59
  # as a "Please run" line (postInstallTypescript's no-network path).
60
60
  session.io.say(File.read(File.join(target, "README.md")))
61
- session.io.say("Please run `bundle install --local` in #{parts.name}: ruby-cdk is not on rubygems.org yet, " \
62
- "so the Gemfile resolves from the gem installed on this machine.")
61
+ session.io.say("Please run `bundle install` in #{parts.name}: ruby-cdk is on rubygems.org, " \
62
+ "so the Gemfile resolves like any other gem.")
63
63
  session.io.say("All done! #{parts.name}/README.md has the three commands: synth, deploy, destroy.")
64
64
  Cli::SUCCESS
65
65
  end
@@ -224,21 +224,18 @@ module RubyCdk
224
224
  RUBY
225
225
  end
226
226
 
227
- # The version, not a path: the README's install story is "build and
228
- # install the gem from source", so the gem is on this machine like any
229
- # installed gem, and a path would hard-wire a checkout that does not
230
- # exist anywhere else. `bundle install --local` resolves it today;
231
- # `bundle install` resolves the same line once a release is published.
227
+ # The version, not a path: the gem is published, so `bundle install`
228
+ # resolves the line from rubygems.org like any other gem, and a path
229
+ # would hard-wire a checkout that does not exist anywhere else.
232
230
  def self.gemfile
233
231
  <<~RUBY
234
232
  # frozen_string_literal: true
235
233
 
236
234
  source "https://rubygems.org"
237
235
 
238
- # ruby-cdk is not on rubygems.org yet: install it from source (the
239
- # ruby-cdk README's Install) and run `bundle install --local` in this
240
- # directory to resolve the line below from the installed gem. Once a
241
- # release is published, plain `bundle install` resolves it too.
236
+ # ruby-cdk is on rubygems.org: plain `bundle install` resolves this
237
+ # line. `bundle install --local` resolves it from the gem installed
238
+ # on this machine instead, without the network.
242
239
  gem "ruby-cdk", "~> #{RubyCdk::VERSION}"
243
240
  RUBY
244
241
  end
@@ -255,7 +252,7 @@ module RubyCdk
255
252
  ## The three commands
256
253
 
257
254
  ```sh
258
- bundle install --local # once, in this directory: see "The Gemfile"
255
+ bundle install # once, in this directory: see "The Gemfile"
259
256
  bundle exec ruby-cdk synth # writes cdk.out/#{parts.stack_id}.template.json and prints the template
260
257
  bundle exec ruby-cdk deploy # shows the change set, asks, then deploys it
261
258
  bundle exec ruby-cdk destroy # prints what is kept, asks for the stack name, then deletes
@@ -295,10 +292,10 @@ module RubyCdk
295
292
 
296
293
  ## The Gemfile
297
294
 
298
- ruby-cdk is not on rubygems.org yet: install it from source (the
299
- ruby-cdk README's Install), then run `bundle install --local` here, which
300
- resolves `gem "ruby-cdk"` from the gem installed on this machine. Once a
301
- release is published, plain `bundle install` resolves the same line.
295
+ ruby-cdk is on rubygems.org: plain `bundle install` here resolves
296
+ `gem "ruby-cdk"` like any other gem. `bundle install --local`
297
+ resolves the same line from the gem installed on this machine,
298
+ without the network.
302
299
 
303
300
  ## Files
304
301
 
@@ -35,7 +35,8 @@ module RubyCdk
35
35
 
36
36
  # The options are read, and so checked, before any client is built: a
37
37
  # typo in one is a usage error and never a request.
38
- kind == :deploy ? session.deploy_options : session.destroy_options
38
+ options = kind == :deploy ? session.deploy_options : session.destroy_options
39
+ warn_hotswap if kind == :deploy && (options.hotswap || options.hotswap_fallback)
39
40
 
40
41
  entries.each_with_index do |entry, index|
41
42
  result = nil
@@ -96,9 +97,10 @@ module RubyCdk
96
97
  end
97
98
 
98
99
  # For --json, one object on standard out per stack (architecture section
99
- # 11): name, stack id, outcome, exit code, changes, outputs, and the error
100
- # when it failed. Nothing else is written there. An error carries the exit
101
- # code its class decides; code: overrides that, nil included.
100
+ # 11): name, stack id, outcome, exit code, changes, outputs, the error
101
+ # when it failed, and what --hotswap did when it was in play. Nothing
102
+ # else is written there. An error carries the exit code its class
103
+ # decides; code: overrides that, nil included.
102
104
  def record(name, result: nil, error: nil, code: :unset)
103
105
  return unless session.options.json
104
106
 
@@ -116,9 +118,31 @@ module RubyCdk
116
118
  "changes" => (result&.changes || []).map(&:to_h),
117
119
  "outputs" => result&.outputs || {}
118
120
  }
121
+ object["hotswap"] = hotswap_facts(result&.hotswap) if result&.hotswap
119
122
  object["error"] = error.is_a?(Exception) ? error.message : error.to_s if error
120
123
  session.io.result("#{JSON.generate(object)}\n")
121
124
  end
125
+
126
+ # The hotswap facts of one deploy, as the machine contract carries them:
127
+ # the CDK's mode word, whether the change set took the deploy after all,
128
+ # and the classification's two lists.
129
+ def hotswap_facts(facts)
130
+ {
131
+ "mode" => facts.mode,
132
+ "fell_back" => facts.fell_back,
133
+ "swapped" => facts.swapped.map { |function| { "logical_id" => function.logical_id, "resource_type" => function.resource_type,
134
+ "name" => function.name } },
135
+ "non_hotswappable" => facts.non_hotswappable.map { |change| { "logical_id" => change.logical_id,
136
+ "resource_type" => change.resource_type, "reason" => change.reason } }
137
+ }
138
+ end
139
+
140
+ # The two lines above every hotswap deploy, printed once per command
141
+ # where the CDK prints them (cdk-toolkit.ts:566-569 at
142
+ # f7c9dca95f440a076c2abd61b66b984624b8548e): before the first stack.
143
+ def warn_hotswap
144
+ Deploy::Hotswap::WARNINGS.each { |line| session.io.say(line) }
145
+ end
122
146
  end
123
147
  end
124
148
  end
@@ -19,8 +19,8 @@ module RubyCdk
19
19
  # command does not take, or that was not given, is nil; a boolean that
20
20
  # was given is true.
21
21
  Options = Data.define(:app, :out, :profile, :region, :account, :yes, :force, :quiet, :verbose, :json, :color,
22
- :long, :all, :exclusively, :execute, :on_failure, :parameters, :tags, :outputs_file,
23
- :no_validate, :strict_types, :deployer, :fail, :security_only)
22
+ :long, :all, :exclusively, :execute, :on_failure, :parameters, :tags, :outputs_file, :previous_parameters,
23
+ :no_validate, :strict_types, :deployer, :fail, :fail_on, :security_only, :hotswap, :hotswap_fallback)
24
24
 
25
25
  # Thor's options as Options.
26
26
  def self.options_from(given)
@@ -186,6 +186,7 @@ module RubyCdk
186
186
 
187
187
  # What the engine is given for a deploy.
188
188
  def deploy_options
189
+ check_hotswap_flags
189
190
  @deploy_options ||= Deploy::DeployOptions.new(
190
191
  parameters: Pairs.parse(options.parameters, option: "--parameters", command:),
191
192
  tags: Pairs.parse(options.tags, option: "--tags", command:),
@@ -195,7 +196,12 @@ module RubyCdk
195
196
  outputs_file: outputs_file,
196
197
  account: options.account,
197
198
  force: !!options.force,
198
- profile: options.profile
199
+ profile: options.profile,
200
+ hotswap: !!options.hotswap,
201
+ hotswap_fallback: !!options.hotswap_fallback,
202
+ # --previous-parameters is on unless it is turned off (cli.ts:497 in
203
+ # aws-cdk-cli hands the flag over as it was parsed).
204
+ use_previous_parameters: options.previous_parameters != false
199
205
  )
200
206
  end
201
207
 
@@ -224,6 +230,17 @@ module RubyCdk
224
230
 
225
231
  private
226
232
 
233
+ # The two flags are two forms of the same question, and the CDK refuses
234
+ # the pair by name (cli.ts, determineHotswapMode at
235
+ # f7c9dca95f440a076c2abd61b66b984624b8548e: ConflictingHotswapArgs).
236
+ # Checked before any client is built, like every other option.
237
+ def check_hotswap_flags
238
+ return unless options.hotswap && options.hotswap_fallback
239
+
240
+ raise Usage.new("Can not supply both --hotswap and --hotswap-fallback at the same time",
241
+ next_step: "Run `ruby-cdk #{command}` again with only one of the two flags.")
242
+ end
243
+
227
244
  def clock
228
245
  Process.clock_gettime(Process::CLOCK_MONOTONIC)
229
246
  end
data/lib/ruby_cdk/cli.rb CHANGED
@@ -128,6 +128,15 @@ module RubyCdk
128
128
  method_option :tags, type: :string, desc: "Tags for the stacks, as KEY=VALUE pairs separated by commas"
129
129
  method_option :outputs_file, type: :string, aliases: "-O",
130
130
  desc: "File the outputs of each stack are written to, as JSON"
131
+ method_option :previous_parameters, type: :boolean, default: true,
132
+ desc: "A parameter that is not named again keeps the value the stack was last deployed with. " \
133
+ "--no-previous-parameters: every parameter without a template default must be named on every deploy"
134
+ method_option :hotswap, type: :boolean,
135
+ desc: "Attempts to perform a 'hotswap' deployment, but does not fall back to a full deployment if that is not " \
136
+ "possible. Instead, changes to any non-hotswappable properties are ignored. Do not use this in production environments"
137
+ method_option :hotswap_fallback, type: :boolean,
138
+ desc: "Attempts to perform a 'hotswap' deployment, which skips the change set and updates the stack directly, " \
139
+ "and falls back to a full deployment if that is not possible. Do not use this in production environments"
131
140
  def deploy(*names)
132
141
  Cli::Operation.new(session, kind: :deploy).call(names)
133
142
  end
@@ -145,7 +154,11 @@ module RubyCdk
145
154
  method_option :exclusively, type: :boolean, aliases: "-e",
146
155
  desc: "Diff only the stacks named, not the ones they depend on"
147
156
  method_option :fail, type: :boolean,
148
- desc: "Exit with 1 when a stack has differences. Without it the command exits 0 either way, as the CDK's diff does"
157
+ desc: "Exit with 1 when a stack has differences: the same as --fail-on=any-change, and never given together with it. " \
158
+ "Without it the command exits 0 either way, as the CDK's diff does"
159
+ method_option :fail_on, type: :string, enum: Cli::Diff::FAIL_ON,
160
+ desc: "Exit with 1 when the diff holds the kind of change named. any-change: any difference; broadening: a change that " \
161
+ "broadens permissions; destructive: a resource replaced, destroyed or orphaned; never: nothing. Cannot be used with --fail"
149
162
  method_option :security_only, type: :boolean,
150
163
  desc: "Show only the security view: the IAM statements and the capability-affecting resources a deployment adds or " \
151
164
  "takes away. It is exact by resource type: every property name AWS publishes a policy document in is read, " \
@@ -3,6 +3,7 @@
3
3
  require_relative "../errors"
4
4
  require_relative "../fn"
5
5
  require_relative "grant"
6
+ require_relative "kms_key"
6
7
 
7
8
  module RubyCdk
8
9
  module S3
@@ -11,6 +12,7 @@ module RubyCdk
11
12
  #
12
13
  # RubyCdk::S3::Bucket.new(stack, "Images",
13
14
  # versioned: true, bucket_name: "my-images-1a2b3c4d")
15
+ # RubyCdk::S3::Bucket.new(stack, "Images", encryption: :kms, encryption_key: key)
14
16
  #
15
17
  # Defaults, and where they differ from the CDK (architecture section 7
16
18
  # wins; both rows are listed in section 21):
@@ -34,13 +36,28 @@ module RubyCdk
34
36
  # synthesis gives every AWS::S3::Bucket, as the CDK's
35
37
  # applyRemovalPolicy does.
36
38
  #
39
+ # Customer-managed encryption is the CDK's KMS mode (bucket.ts:2873-2892,
40
+ # parseEncryption): encryption: :kms writes aws:kms with the key's ARN in
41
+ # KMSMasterKeyID. encryption_key is a RubyCdk::KMS::Key, the ARN of a key
42
+ # that exists, or an intrinsic; with none given a key is created under the
43
+ # bucket, id Key, described "Created by <the bucket's path>" and with
44
+ # rotation on, as the CDK's. A key given with no encryption: implies :kms,
45
+ # as in the CDK - and a key given with any other mode is refused, as the
46
+ # CDK refuses it (EncryptionkeySpecified). bucketKeyEnabled and the DSSE
47
+ # modes are not carried.
48
+ #
37
49
  # The grants are the CDK's read and readWrite (aws-s3/lib/bucket-grants.ts
38
50
  # and perms.ts, at the same commit): read is s3:GetObject*, s3:GetBucket*
39
51
  # and s3:List* on the bucket ARN and on the objects' ARN; read_write adds
40
- # the delete and put actions. A bucket encrypted with a KMS key here has no
41
- # key object to grant on, so the kms:* actions the CDK adds on the key are
42
- # not granted; use encryption: :kms_managed only with principals that
43
- # already may use aws/s3.
52
+ # the delete and put actions. On a bucket encrypted with a customer-managed
53
+ # key, each also grants the key's actions on the key's ARN, a second
54
+ # statement on the same principal's policy: read adds kms:Decrypt and
55
+ # kms:DescribeKey (KEY_READ_ACTIONS), read_write those and the write set,
56
+ # kms:Encrypt, kms:ReEncrypt* and kms:GenerateDataKey* (KEY_WRITE_ACTIONS,
57
+ # its kms:Decrypt already in the read set), as the CDK's grantOnKey does
58
+ # (BucketBase#grantOnKey, bucket.ts:675-679; bucket-grants.ts:52-54 and
59
+ # 177-183). A bucket under :kms_managed has no key to grant on: its
60
+ # principals need aws/s3's key already.
44
61
  class Bucket < Construct
45
62
  # The four settings, all true, as the CDK's BlockPublicAccess.BLOCK_ALL.
46
63
  PUBLIC_ACCESS_BLOCK = {
@@ -64,11 +81,37 @@ module RubyCdk
64
81
  "s3:PutObjectTagging", "s3:PutObjectVersionTagging", "s3:Abort*"
65
82
  ].freeze
66
83
 
67
- attr_reader :encryption, :public_access_block
84
+ # The CDK's key actions of a KMS-encrypted bucket (perms.ts,
85
+ # KEY_READ_ACTIONS): what read grants on the key.
86
+ KEY_READ_ACTIONS = [ "kms:Decrypt", "kms:DescribeKey" ].freeze
87
+
88
+ # perms.ts, KEY_WRITE_ACTIONS: the write set, with the Decrypt that
89
+ # multipart uploads need.
90
+ KEY_WRITE_ACTIONS = [ "kms:Encrypt", "kms:ReEncrypt*", "kms:GenerateDataKey*", "kms:Decrypt" ].freeze
91
+
92
+ # readWrite's key actions: the two lists without a repeat, first
93
+ # occurrences kept (bucket-grants.ts:177-183).
94
+ KEY_READ_WRITE_ACTIONS = (KEY_READ_ACTIONS + KEY_WRITE_ACTIONS).uniq.freeze
95
+
96
+ # What encryption: is when it is not given (bucket.ts:2827-2831 picks
97
+ # KMS for a key and UNENCRYPTED otherwise; section 7 makes SSE-S3 the
98
+ # written default here).
99
+ DEFAULT_ENCRYPTION = :s3_managed
100
+
101
+ # Stands for an encryption: that was not given, which nil is not: nil is
102
+ # UNENCRYPTED, the rule left out.
103
+ UNSET = Object.new.freeze
104
+ private_constant :UNSET
105
+
106
+ ENCRYPTION_NAMES = { nil => "UNENCRYPTED", s3_managed: "S3_MANAGED", kms_managed: "KMS_MANAGED", kms: "KMS" }.freeze
107
+ private_constant :ENCRYPTION_NAMES
68
108
 
69
- def initialize(scope, id, bucket_name: nil, versioned: false, encryption: :s3_managed, public_access_block: nil)
109
+ attr_reader :encryption, :public_access_block, :encryption_key
110
+
111
+ def initialize(scope, id, bucket_name: nil, versioned: false, encryption: UNSET, encryption_key: nil, public_access_block: nil)
70
112
  super(scope, id)
71
- @encryption = valid_encryption(encryption)
113
+ @encryption_key = encryption_key && KMS.key_reference(encryption_key, "#{path}: encryption_key")
114
+ @encryption, @encryption_key = parse_encryption(encryption, @encryption_key)
72
115
  @bucket_name = valid_bucket_name(bucket_name)
73
116
  @public_access_block = public_access_settings(public_access_block)
74
117
 
@@ -108,24 +151,46 @@ module RubyCdk
108
151
  # Grants read on the bucket and its contents to the principal: the CDK's
109
152
  # grantRead (bucket-grants.ts, read). An IAM::Role carries the statement
110
153
  # on its own policy; a principal named by ARN gets the Grant back
111
- # unapplied.
154
+ # unapplied. Under a customer-managed key, the key's read actions are
155
+ # granted the same way, after it.
112
156
  def grant_read(principal, objects_key_pattern: "*")
113
- Constructs::Grant.add_to_principal(principal, READ_ACTIONS, [ arn, objects_arn(objects_key_pattern) ])
157
+ grant = Constructs::Grant.add_to_principal(principal, READ_ACTIONS, [ arn, objects_arn(objects_key_pattern) ])
158
+ KMS.grant_on_key(@encryption_key, principal, KEY_READ_ACTIONS) if @encryption_key
159
+ grant
114
160
  end
115
161
 
116
162
  # Grants read and write: the CDK's grantReadWrite (bucket-grants.ts,
117
163
  # readWrite, with the put actions its S3_GRANT_WRITE_WITHOUT_ACL flag
118
- # enables).
164
+ # enables). Under a customer-managed key, the key's read and write
165
+ # actions are granted the same way, after it.
119
166
  def grant_read_write(principal, objects_key_pattern: "*")
120
- Constructs::Grant.add_to_principal(principal, READ_WRITE_ACTIONS, [ arn, objects_arn(objects_key_pattern) ])
167
+ grant = Constructs::Grant.add_to_principal(principal, READ_WRITE_ACTIONS, [ arn, objects_arn(objects_key_pattern) ])
168
+ KMS.grant_on_key(@encryption_key, principal, KEY_READ_WRITE_ACTIONS) if @encryption_key
169
+ grant
121
170
  end
122
171
 
123
172
  private
124
173
 
174
+ # The mode when encryption: was given, else nil.
125
175
  def valid_encryption(value)
126
- return value if value.nil? || %i[s3_managed kms_managed].include?(value)
176
+ return value if value.nil? || %i[s3_managed kms_managed kms].include?(value)
177
+
178
+ raise UsageError, "#{path}: encryption takes :s3_managed, :kms_managed, :kms or nil, got #{value.inspect}"
179
+ end
180
+
181
+ # The port of parseEncryption (bucket.ts:2823-2955) over the modes this
182
+ # tool carries. Answers [the mode, the key]. The CDK's default is KMS
183
+ # for a key and UNENCRYPTED otherwise; here a bucket built without
184
+ # either is SSE-S3 (section 7), and a key still implies KMS.
185
+ def parse_encryption(encryption, key)
186
+ encryption = encryption.equal?(UNSET) ? (key ? :kms : DEFAULT_ENCRYPTION) : valid_encryption(encryption)
187
+ if encryption != :kms && key
188
+ raise UsageError, "#{path}: encryption_key is specified, so 'encryption' must be set to KMS or DSSE " \
189
+ "(value: #{ENCRYPTION_NAMES.fetch(encryption)})"
190
+ end
127
191
 
128
- raise UsageError, "#{path}: encryption takes :s3_managed, :kms_managed or nil, got #{value.inspect}"
192
+ key ||= KMS::Key.new(self, "Key", description: "Created by #{path}", enable_key_rotation: true) if encryption == :kms
193
+ [ encryption, key ]
129
194
  end
130
195
 
131
196
  # S3's own rules for a bucket name, as the CDK validates them
@@ -175,14 +240,17 @@ module RubyCdk
175
240
 
176
241
  # The CDK's rendering per mode (bucket.ts, parseEncryption): SSE-S3 is
177
242
  # the AES256 algorithm, KMS_MANAGED the aws:kms one with the AWS-managed
178
- # key, and nothing is written when encryption is nil.
243
+ # key, KMS the aws:kms one with the customer-managed key's ARN beside it
244
+ # (bucket.ts:2879-2890), and nothing is written when encryption is nil.
179
245
  def encryption_property
180
246
  return nil if @encryption.nil?
181
247
 
182
- algorithm = @encryption == :kms_managed ? "aws:kms" : "AES256"
248
+ algorithm = @encryption == :s3_managed ? "AES256" : "aws:kms"
249
+ by_default = { "SSEAlgorithm" => algorithm }
250
+ by_default = { "KMSMasterKeyID" => KMS.key_arn(@encryption_key), "SSEAlgorithm" => algorithm } if @encryption == :kms
183
251
  {
184
252
  "ServerSideEncryptionConfiguration" => [
185
- { "ServerSideEncryptionByDefault" => { "SSEAlgorithm" => algorithm } }
253
+ { "ServerSideEncryptionByDefault" => by_default }
186
254
  ]
187
255
  }
188
256
  end
@@ -0,0 +1,245 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../errors"
4
+ require_relative "../fn"
5
+ require_relative "../lazy"
6
+ require_relative "grant"
7
+ require_relative "schedule"
8
+
9
+ module RubyCdk
10
+ module Events
11
+ # An EventBridge rule: the port of the CDK's Rule (aws-events/lib/rule.ts),
12
+ # read at commit c070afb54b9e4dbddd52a85a21077fe970354985, Apache-2.0.
13
+ #
14
+ # rule = RubyCdk::Events::Rule.new(stack, "Schedule",
15
+ # schedule: RubyCdk::Events::Schedule.rate(10, :minutes))
16
+ # rule.add_event_pattern(source: [ "aws.ec2" ], detail_type: [ "EC2 Instance State-change Notification" ])
17
+ # rule.add_target(function)
18
+ #
19
+ # A schedule or an event pattern must be there - the CDK fails synthesis
20
+ # without either (rule.ts:354-356) - and here the check runs at resolve:
21
+ # a rule may be built bare and given its pattern after, and one without
22
+ # either fails the synthesis with the same words, from the Lazy that
23
+ # stands in for the EventPattern. A rule name, when given, is the CDK's
24
+ # physical name: 1 to 64 characters, letters, digits, periods, hyphens
25
+ # and underscores (rule.ts:345-352), checked at construction. schedule:
26
+ # takes a RubyCdk::Events::Schedule or the expression String.
27
+ #
28
+ # The event pattern is the CDK's EventPattern hash, written as given -
29
+ # the property is a verbatim zone, so the keys stay as CloudFormation
30
+ # reads them - with detail_type renamed "detail-type", as the CDK's
31
+ # renderEventPattern does (aws-events/lib/util.ts:59-76). add_event_pattern
32
+ # merges into the rule's pattern, as the CDK's does (util.ts:14-56):
33
+ # arrays are concatenated and de-duplicated in order, nested objects
34
+ # recurse, and a bare value is refused, as the CDK refuses one.
35
+ #
36
+ # Where this tool differs from the CDK (architecture section 7 wins; the
37
+ # row is in section 21): add_target records the target on the rule and
38
+ # writes the permission the delivery needs on the function's resource
39
+ # policy, as the CDK's Lambda target does - principal events.amazonaws.com,
40
+ # SourceArn the rule's ARN, one AWS::Lambda::Permission per rule and
41
+ # function (aws-events-targets/lib/lambda.ts:34, util.ts:90-108). The
42
+ # identity-based side is a separate grant: call function.grant_invoke on a
43
+ # role of your own when a role - not the events service - is to invoke.
44
+ class Rule < Construct
45
+ # The CDK's own limit (rule.ts:358-360).
46
+ MAX_TARGETS = 5
47
+
48
+ # The CDK's enabled default (rule.ts:165): a rule without the prop is
49
+ # enabled, and the State is written either way.
50
+ DEFAULT_ENABLED = true
51
+
52
+ attr_reader :schedule
53
+
54
+ def initialize(scope, id, rule_name: nil, description: nil, enabled: DEFAULT_ENABLED,
55
+ schedule: nil, event_pattern: nil, event_bus_name: nil, targets: [])
56
+ super(scope, id)
57
+ @rule_name = valid_name(rule_name)
58
+ if event_bus_name && schedule
59
+ raise UsageError, "#{path}: Cannot associate rule with 'eventBus' when using 'schedule'"
60
+ end
61
+ @schedule_expression = schedule_expression(schedule)
62
+ @event_bus_name = valid_bus(event_bus_name)
63
+ @targets = []
64
+ @granted = []
65
+ @pattern = {}
66
+
67
+ # The pattern and the targets stand behind Lazies, so that a pattern
68
+ # or a target added after the rule was built is on it, and a rule
69
+ # with neither a pattern nor a schedule fails the synthesis with the
70
+ # CDK's words (rule.ts:354-356).
71
+ @resource = resource("Resource", "AWS::Events::Rule",
72
+ Name: @rule_name,
73
+ Description: description,
74
+ State: enabled == false ? "DISABLED" : "ENABLED",
75
+ ScheduleExpression: @schedule_expression,
76
+ EventPattern: Lazy.new { rendered_pattern },
77
+ Targets: Lazy.new { @targets.empty? ? nil : @targets },
78
+ EventBusName: @event_bus_name)
79
+
80
+ add_event_pattern(event_pattern)
81
+ Array(targets).each { |target| add_target(target) }
82
+ end
83
+
84
+ # The logical ID of the AWS::Events::Rule under this construct, so that
85
+ # the rule can sit in another resource's depends_on:.
86
+ def logical_id
87
+ @resource.logical_id
88
+ end
89
+
90
+ # The rule's ARN.
91
+ def arn
92
+ Fn.get_att(@resource, "Arn")
93
+ end
94
+
95
+ # The rule's name: the one given, or the Ref of the resource.
96
+ def rule_name
97
+ @rule_name || Fn.ref(@resource)
98
+ end
99
+
100
+ # Adds an event pattern filter, merged into the rule's own: the CDK's
101
+ # addEventPattern (rule.ts:335-339) with its mergeEventPattern
102
+ # (util.ts:14-56). Arrays are concatenated and de-duplicated in order,
103
+ # objects recurse, and a bare value is refused, as the CDK refuses one.
104
+ def add_event_pattern(pattern)
105
+ return if pattern.nil?
106
+ unless pattern.is_a?(Hash)
107
+ raise UsageError, "#{path}: Invalid event pattern '#{pattern.inspect}', expecting an object or an array"
108
+ end
109
+
110
+ merge_pattern(@pattern, stringify_keys(pattern))
111
+ nil
112
+ end
113
+
114
+ # Adds a Lambda function as a target (aws-events-targets/lib/lambda.ts,
115
+ # bind): the Targets entry, Id Target0 and on, Arn the function's, plus
116
+ # the permission the delivery needs on the function's resource policy
117
+ # (util.ts:90-108) - principal events.amazonaws.com, SourceArn this
118
+ # rule's ARN, written once per function however many targets carry it,
119
+ # as the CDK writes it once (its tryFindChild guard). The permission's
120
+ # id names the rule, where the CDK's names the handler, because the
121
+ # resource sits under the function here (D-029).
122
+ def add_target(function)
123
+ unless function.respond_to?(:arn)
124
+ raise UsageError, "#{path}: add_target takes a function with an arn, got #{function.inspect}"
125
+ end
126
+ if @targets.length >= MAX_TARGETS
127
+ raise UsageError, "#{path}: Event rule cannot have more than #{MAX_TARGETS} targets."
128
+ end
129
+
130
+ @targets << { "Id" => "Target#{@targets.length}", "Arn" => function.arn }
131
+ unless @granted.include?(function)
132
+ function.add_permission("AllowEventRule#{logical_id}", principal: "events.amazonaws.com",
133
+ source_arn: arn)
134
+ @granted << function
135
+ end
136
+ nil
137
+ end
138
+
139
+ # The targets added so far, in order.
140
+ def targets
141
+ @targets.dup.freeze
142
+ end
143
+
144
+ private
145
+
146
+ # schedule: takes a Schedule or its expression String.
147
+ def schedule_expression(schedule)
148
+ return nil if schedule.nil?
149
+ return schedule.expression_string if schedule.is_a?(Schedule)
150
+ return schedule if schedule.is_a?(String) && !schedule.empty?
151
+
152
+ raise UsageError, "#{path}: schedule takes a RubyCdk::Events::Schedule or its expression String, " \
153
+ "got #{schedule.inspect}"
154
+ end
155
+
156
+ def valid_bus(event_bus_name)
157
+ return nil if event_bus_name.nil?
158
+ return event_bus_name if event_bus_name.is_a?(String) && !event_bus_name.empty?
159
+
160
+ raise UsageError, "#{path}: event_bus_name must be a non-empty String, got #{event_bus_name.inspect}"
161
+ end
162
+
163
+ # The CDK's validateRule name checks (rule.ts:345-352).
164
+ def valid_name(name)
165
+ return nil if name.nil?
166
+ raise UsageError, "#{path}: the rule name must be a String, got #{name.inspect}" unless name.is_a?(String)
167
+ if name.empty? || name.length > 64
168
+ raise UsageError, "#{path}: Event rule name must be between 1 and 64 characters. Received: #{name}"
169
+ end
170
+ # The CDK's /^[\.\-_A-Za-z0-9]+$/, written with the strict anchors:
171
+ # JavaScript's $ is the end of the string, and Ruby's $ would let a
172
+ # trailing line break through.
173
+ unless name.match?(/\A[.\-_A-Za-z0-9]+\z/)
174
+ raise UsageError, "#{path}: Event rule name #{name} can contain only letters, numbers, periods, " \
175
+ "hyphens, or underscores with no spaces."
176
+ end
177
+
178
+ name
179
+ end
180
+
181
+ # What the Lazy answers. The key is left out when the pattern is empty
182
+ # and the schedule carries the rule; neither is the CDK's synthesis
183
+ # failure, raised as this tool raises from a Lazy (the resolver makes
184
+ # it an issue at this place in the template).
185
+ def rendered_pattern
186
+ if @pattern.empty?
187
+ return nil if @schedule_expression
188
+
189
+ raise Error, "#{path}: Either 'eventPattern' or 'schedule' must be defined"
190
+ end
191
+
192
+ render_pattern
193
+ end
194
+
195
+ # The CDK's renderEventPattern (util.ts:59-76): detail_type becomes
196
+ # "detail-type"; every other key is written as given.
197
+ def render_pattern
198
+ @pattern.to_h do |key, value|
199
+ [ key == "detail_type" ? "detail-type" : key, value ]
200
+ end
201
+ end
202
+
203
+ # The CDK's mergeObject (util.ts:14-56): arrays are concatenated and
204
+ # de-duplicated by their JSON identity, order kept; objects recurse;
205
+ # a bare value is the CDK's EventPatternFieldsMustBeArrays. A nil field
206
+ # is skipped, as the CDK skips an undefined one (util.ts:31-32).
207
+ def merge_pattern(dest, src)
208
+ src.each do |field, value|
209
+ next if value.nil?
210
+
211
+ unless value.is_a?(Hash) || value.is_a?(Array)
212
+ raise UsageError, "#{path}: Invalid event pattern field { #{field}: #{JSON.generate(value)} }. " \
213
+ "All fields must be arrays"
214
+ end
215
+
216
+ existing = dest[field]
217
+ next dest[field] = value if existing.nil?
218
+
219
+ if existing.is_a?(Array) != value.is_a?(Array)
220
+ raise UsageError, "#{path}: Invalid event pattern field #{field}. Type mismatch between existing " \
221
+ "pattern #{JSON.generate(existing)} and added pattern #{JSON.generate(value)}"
222
+ end
223
+ dest[field] = existing.is_a?(Array) ? dedupe(existing + value) : merge_pattern(existing, value)
224
+ end
225
+ dest
226
+ end
227
+
228
+ # De-duplication by JSON identity, first occurrence kept, order kept
229
+ # (util.ts:45-50).
230
+ def dedupe(list)
231
+ seen = []
232
+ list.reject do |item|
233
+ json = JSON.generate(item)
234
+ take = seen.include?(json)
235
+ seen << json unless take
236
+ take
237
+ end
238
+ end
239
+
240
+ def stringify_keys(pattern)
241
+ pattern.to_h { |key, value| [ key.to_s, value ] }
242
+ end
243
+ end
244
+ end
245
+ end