belt 0.6.12 → 0.6.13

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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 5c14e759e93bb681bd3a6731e88b373a27fe7b31a16a2da03de2e481d1e45be5
4
- data.tar.gz: a6e7fbbc0c17f3f5fe25b79683d95831468fe6b24e2869b86ea82c7d27b5ce03
3
+ metadata.gz: 6ade807d379d6c17989f8b4e15363f5616b1429e72c709f43bd98b99206ca929
4
+ data.tar.gz: c075c8e052e661a06637b0974266f4d69653a1abb410084ea4aff99553f77752
5
5
  SHA512:
6
- metadata.gz: '039b10e91eeb5c05b14f04e3f1cf1869f184ad91639363d2c03f66d6c0a40da305da07052789a030c805f8070e680ec5652bafed0fcd755755a24c16a2086b2b'
7
- data.tar.gz: ffc6d215e223fee7179fe5918f31683de8a90ff0376a0495a0f2041d1f83a12cc6aff5756c62aab6a89b21d0ba8b6a91d083d6e4d0e7f58d4807d4d57a7e436b
6
+ metadata.gz: bc607607b2fc6e52523614928c139e6e946d5a2f0b3ddb0b6913bef53043cedc16d8cf017a2976e1e1d42080e9972ff65fea369a99b276311ef11bd7d41ab0a3
7
+ data.tar.gz: cf014b618dcbd8311eddbb55291d07049d24ad00931ce47567d004e716eff75c6caab9f4a128b6697c6d5cd0db0e25a8d96c920e0862f8f042e0628279c438d3
data/CHANGELOG.md CHANGED
@@ -1,5 +1,48 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.6.13
4
+
5
+ ### Added
6
+
7
+ - **A model can choose a GSI's projection.** An `indexes(...)` entry takes
8
+ `projection: :keys_only` or `projection: { include: %w[warnTurn] }`, and
9
+ `belt setup tables` writes `projection_type = "KEYS_ONLY"` / `"INCLUDE"` (with
10
+ `non_key_attributes`) instead of always `"ALL"`. `belt generate index` takes
11
+ `--projection keys_only|all|include:a,b`. `ALL` stays the default, so existing
12
+ apps regenerate the same file. A narrower index stops every write to a row from
13
+ rewriting its full copy in the index; queries on it return only the projected
14
+ attributes, so read the rest with `find`. A projection the generator can't read
15
+ aborts instead of falling back to `ALL`, and a regen that would turn a
16
+ hand-set `KEYS_ONLY`/`INCLUDE` back into `ALL` is treated like a dropped GSI
17
+ (prompt, or skip on generator sync). See `belt explain models`.
18
+
19
+ ### Added
20
+
21
+ - **`throttle:` cascades in routes.rb.** `gateway :api, throttle: { rate:, burst: }`
22
+ sets a default for every route; `scope`, `namespace`, `function` and
23
+ `resources` blocks pass theirs down to the routes inside (nested resources,
24
+ `member` / `collection` included). The nearest one wins, and `throttle: false`
25
+ on a route or block opts out. A bad value now fails on the line that declares
26
+ it. A gateway default is a route-level throttle, so it wins over
27
+ `config/lambda/<fn>.yml` `throttle:` and the provider's stage `throttle`.
28
+ (Fizzy #2010)
29
+ - `belt explain routing` has a Throttling section. It explains that API Gateway
30
+ limits are per route, not per caller, and includes a WAF rate-based-rule recipe
31
+ (REGIONAL web ACL, scoped down to the routes that cost money, attached through
32
+ conveyor-belt's `waf_web_acl_arn`) for per-IP limits. `belt explain throttle`,
33
+ `rate_limit` and `waf` open it.
34
+
35
+ ### Security
36
+
37
+ - **A deployed stack no longer puts exception details in error responses.** A
38
+ 500 from a stack whose `ENVIRONMENT` started with `dev` carried the exception
39
+ class, message and backtrace in the body. A deployed dev stack is as public as
40
+ prod, and that output hands a stranger file paths, gem versions and internal
41
+ messages. Inside Lambda the details now stay in the logs (`belt logs`) unless
42
+ the function sets `BELT_VERBOSE_ERRORS=true`. Outside Lambda (`belt server`,
43
+ specs) nothing changes: `dev*`, `local` and `test` are still verbose.
44
+ `BELT_VERBOSE_ERRORS=false` turns the details off everywhere. See UPGRADING.md.
45
+
3
46
  ## 0.6.12
4
47
 
5
48
  ### Security
data/README.md CHANGED
@@ -209,12 +209,13 @@ end
209
209
 
210
210
  **Key point:** `namespace` and `scope` are purely organizational — they affect URL paths and controller module resolution but never change which Lambda handles the request. Use `function` when you need routes to go to a different Lambda.
211
211
 
212
- **Per-route throttling:** any route or resource accepts `throttle: { rate:, burst: }` (steady-state requests per second plus the burst the token bucket absorbs). `belt routes -f json` emits it and the conveyor-belt provider (0.0.20+) applies it as API Gateway stage method settings. A route's `throttle` wins over the serving Lambda's `throttle:` in `config/lambda/<fn>.yml`, which in turn wins over the provider's stage-level `throttle` block.
212
+ **Per-route throttling:** any route, `resources`, `scope`, `namespace`, `function` or the `gateway` itself accepts `throttle: { rate:, burst: }` (steady-state requests per second plus the burst the token bucket absorbs). Routes inherit it from the nearest enclosing block; `throttle: false` opts a route out. `belt routes -f json` emits it and the conveyor-belt provider (0.0.20+) applies it as API Gateway stage method settings. A route-level `throttle` (including one inherited from the gateway) wins over the serving Lambda's `throttle:` in `config/lambda/<fn>.yml`, which in turn wins over the provider's stage-level `throttle` block. The limit is per route for all callers together, not per caller; `belt explain routing` has a WAF rate-rule recipe for per-IP limits.
213
213
 
214
214
  ```ruby
215
- gateway :api, auth: :none do
215
+ gateway :api, auth: :none, throttle: { rate: 50, burst: 100 } do
216
216
  post '/connect/chat', to: 'chat#create', throttle: { rate: 2, burst: 5 }
217
217
  resources :leads, only: [:create], throttle: { rate: 1, burst: 3 }
218
+ get '/health', to: 'health#show', throttle: false
218
219
  end
219
220
  ```
220
221
 
@@ -396,7 +397,8 @@ Belt::Observability::Metrics.track_event("OrderCreated", model: "Order")
396
397
 
397
398
  | Variable | Purpose |
398
399
  |----------|---------|
399
- | `ENVIRONMENT` | Controls verbose error responses (`dev*`, `local`, `test`) |
400
+ | `ENVIRONMENT` | Outside Lambda, `dev*`, `local`, `test` get verbose error responses |
401
+ | `BELT_VERBOSE_ERRORS` | `true` = verbose error responses on a deployed stack (off by default); `false` = off everywhere |
400
402
  | `BELT_METRICS_NAMESPACE` | CloudWatch metrics namespace (default: `Belt`) |
401
403
  | `ACTION` | Service name for logging (falls back to function name) |
402
404
  | `ERROR_NOTIFICATION_TOPIC_ARN` | SNS topic for error alerts |
@@ -13,6 +13,10 @@ module Belt
13
13
  'routes' => 'routing',
14
14
  'route' => 'routing',
15
15
  'router' => 'routing',
16
+ 'throttle' => 'routing',
17
+ 'throttling' => 'routing',
18
+ 'rate_limit' => 'routing',
19
+ 'waf' => 'routing',
16
20
  'controller' => 'controllers',
17
21
  'model' => 'models',
18
22
  'activeitem' => 'models',
@@ -114,6 +118,7 @@ module Belt
114
118
 
115
119
  Aliases:
116
120
  routes, route, router → routing
121
+ throttle, rate_limit, waf → routing
117
122
  controller → controllers
118
123
  model, activeitem → models
119
124
  deploy, terraform → deployment
@@ -0,0 +1,87 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative '../inflector'
4
+
5
+ module Belt
6
+ module CLI
7
+ # Which attributes a GSI copies from the base table. Shared by `belt setup tables`
8
+ # (reads `projection:` off a model's indexes() entry) and `belt g index`
9
+ # (reads `--projection`), so both write the same Terraform.
10
+ #
11
+ # A projection is nil (the default, ALL) or a hash:
12
+ # { type: 'KEYS_ONLY' }
13
+ # { type: 'INCLUDE', non_key_attributes: ['warnTurn'] }
14
+ module GsiProjection
15
+ TYPES = %w[ALL KEYS_ONLY INCLUDE].freeze
16
+
17
+ class Error < ArgumentError; end
18
+
19
+ module_function
20
+
21
+ # The `projection:` value inside one indexes() entry's options, as source text:
22
+ # projection: :keys_only
23
+ # projection: { include: %w[warnTurn] }
24
+ # Returns nil when the entry doesn't declare one.
25
+ def from_model_options(opts, index_name)
26
+ return nil unless opts.match?(/\bprojection:/)
27
+
28
+ if (match = opts.match(/\bprojection:\s*:?['"]?(\w+)['"]?/))
29
+ return build(match[1], [], index_name)
30
+ end
31
+
32
+ if (match = opts.match(/\bprojection:\s*\{\s*include:\s*(%w\[[^\]]*\]|\[[^\]]*\])\s*\}/))
33
+ return build('include', list_items(match[1]), index_name)
34
+ end
35
+
36
+ raise Error, "#{index_name}: can't read projection. Use projection: :keys_only, " \
37
+ ':all, or { include: %w[attrA attrB] }'
38
+ end
39
+
40
+ # `--projection keys_only`, `--projection all`, `--projection include:a,b`.
41
+ # Attribute names are camelCased like the CLI's --partition-key/--sort-key.
42
+ def from_cli(value, index_name)
43
+ type, attrs = value.to_s.split(':', 2)
44
+ attrs = attrs.to_s.split(',').map(&:strip).reject(&:empty?)
45
+ build(type, attrs.map { |a| Belt::Inflector.camelize_lower(a) }, index_name)
46
+ end
47
+
48
+ def build(type, attrs, index_name)
49
+ type = type.to_s.upcase
50
+ unless TYPES.include?(type)
51
+ raise Error, "#{index_name}: unknown projection #{type.downcase.inspect} " \
52
+ '(expected keys_only, all, or include)'
53
+ end
54
+ if type == 'INCLUDE' && attrs.empty?
55
+ raise Error, "#{index_name}: an include projection needs at least one attribute"
56
+ end
57
+ raise Error, "#{index_name}: only an include projection takes attributes" if type != 'INCLUDE' && attrs.any?
58
+
59
+ return nil if type == 'ALL'
60
+
61
+ type == 'INCLUDE' ? { type: type, non_key_attributes: attrs } : { type: type }
62
+ end
63
+
64
+ # HCL lines for the projection inside a global_secondary_index block. The blank
65
+ # line keeps `terraform fmt` from realigning the other arguments around the
66
+ # longer `non_key_attributes` name.
67
+ def hcl_lines(projection)
68
+ type = projection ? projection[:type] : 'ALL'
69
+ lines = [" projection_type = \"#{type}\""]
70
+ if projection && projection[:non_key_attributes]
71
+ attrs = projection[:non_key_attributes].map { |a| "\"#{a}\"" }.join(', ')
72
+ lines << ''
73
+ lines << " non_key_attributes = [#{attrs}]"
74
+ end
75
+ lines
76
+ end
77
+
78
+ def list_items(source)
79
+ if source.start_with?('%w')
80
+ source[3..-2].split
81
+ else
82
+ source[1..-2].scan(/['"]([^'"]+)['"]|:(\w+)/).map { |quoted, sym| quoted || sym }
83
+ end
84
+ end
85
+ end
86
+ end
87
+ end
@@ -1,6 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require_relative 'tables_command'
4
+ require_relative 'gsi_projection'
4
5
  require_relative '../inflector'
5
6
 
6
7
  module Belt
@@ -28,6 +29,7 @@ module Belt
28
29
  def self.usage
29
30
  <<~USAGE
30
31
  Usage: belt generate index <table> <IndexName> --partition-key <key> [--sort-key <key>]
32
+ [--projection keys_only|all|include:attrA,attrB]
31
33
  belt destroy index <table> <IndexName>
32
34
 
33
35
  Add or remove a Global Secondary Index (GSI) from dynamodb.tf.
@@ -35,16 +37,22 @@ module Belt
35
37
  Examples:
36
38
  belt generate index messages ConversationIndex --partition-key conversation_id
37
39
  belt generate index messages RecentByUserIndex --partition-key user_id --sort-key created_at
40
+ belt generate index matches WarningIndex -p warn_due -s warn_at --projection keys_only
38
41
  belt destroy index messages ConversationIndex
39
42
 
43
+ --projection defaults to all. keys_only copies only the keys into the index;
44
+ include:a,b also copies the named attributes (DynamoDB names, e.g. warnTurn).
45
+ A narrower projection makes writes cheaper, but reading any other attribute
46
+ of a hit needs a GetItem on the table.
47
+
40
48
  Note: After modifying indexes, run `belt deploy` to apply changes to AWS.
41
49
  Adding a GSI to an existing table takes ~5-10 minutes (AWS limitation).
42
50
  USAGE
43
51
  end
44
52
 
45
53
  def self.add(args)
46
- table, index_name, partition_key, sort_key = parse_add_args(args)
47
- new(table, index_name, partition_key: partition_key, sort_key: sort_key).add
54
+ table, index_name, partition_key, sort_key, projection = parse_add_args(args)
55
+ new(table, index_name, partition_key: partition_key, sort_key: sort_key, projection: projection).add
48
56
  end
49
57
 
50
58
  def self.remove(args)
@@ -64,6 +72,7 @@ module Belt
64
72
  index_name = args.shift
65
73
  partition_key = nil
66
74
  sort_key = nil
75
+ projection = nil
67
76
 
68
77
  i = 0
69
78
  while i < args.length
@@ -74,6 +83,11 @@ module Belt
74
83
  when '--sort-key', '-s'
75
84
  i += 1
76
85
  sort_key = args[i]
86
+ when '--projection'
87
+ i += 1
88
+ projection = args[i] || abort('Error: --projection needs a value (keys_only, all, or include:a,b)')
89
+ when /\A--projection=(.*)\z/
90
+ projection = Regexp.last_match(1)
77
91
  end
78
92
  i += 1
79
93
  end
@@ -83,14 +97,23 @@ module Belt
83
97
  'Example: belt generate index messages ConversationIndex --partition-key conversation_id'
84
98
  end
85
99
 
86
- [table, index_name, partition_key, sort_key]
100
+ [table, index_name, partition_key, sort_key, parse_projection(projection, index_name)]
101
+ end
102
+
103
+ def self.parse_projection(value, index_name)
104
+ return nil if value.nil?
105
+
106
+ GsiProjection.from_cli(value, index_name)
107
+ rescue GsiProjection::Error => e
108
+ abort "Error: #{e.message}"
87
109
  end
88
110
 
89
- def initialize(table, index_name, partition_key: nil, sort_key: nil)
111
+ def initialize(table, index_name, partition_key: nil, sort_key: nil, projection: nil)
90
112
  @table = table
91
113
  @index_name = index_name
92
114
  @partition_key = partition_key
93
115
  @sort_key = sort_key
116
+ @projection = projection
94
117
  end
95
118
 
96
119
  def add
@@ -156,7 +179,7 @@ module Belt
156
179
  lines << " name = \"#{@index_name}\""
157
180
  lines << " hash_key = \"#{dynamo_pk}\""
158
181
  lines << " range_key = \"#{dynamo_sk}\"" if dynamo_sk
159
- lines << ' projection_type = "ALL"'
182
+ lines.concat(GsiProjection.hcl_lines(@projection))
160
183
  lines << ' }'
161
184
  lines.join("\n")
162
185
  end
@@ -134,7 +134,7 @@ module Belt
134
134
  end
135
135
 
136
136
  def inject_welcome_route!(routes, gateway)
137
- routes << {
137
+ welcome = {
138
138
  name: 'root',
139
139
  verb: 'GET',
140
140
  path: '/',
@@ -147,6 +147,8 @@ module Belt
147
147
  request_model: '',
148
148
  response_model: ''
149
149
  }
150
+ welcome[:throttle] = gateway.default_throttle if gateway.default_throttle
151
+ routes << welcome
150
152
  end
151
153
 
152
154
  def build_route_hash(route, gateway)
@@ -2,6 +2,7 @@
2
2
 
3
3
  require_relative 'env_resolver'
4
4
  require_relative 'terraform_command'
5
+ require_relative 'gsi_projection'
5
6
  require_relative '../inflector'
6
7
 
7
8
  module Belt
@@ -42,6 +43,8 @@ module Belt
42
43
  return unless validate!
43
44
 
44
45
  models = parse_models
46
+ return unless models
47
+
45
48
  if models.empty?
46
49
  puts "No models found in #{MODELS_DIR}/" unless @quiet
47
50
  return
@@ -75,6 +78,18 @@ module Belt
75
78
  .sort
76
79
 
77
80
  model_files.filter_map { |f| parse_model_file(f) }
81
+ rescue GsiProjection::Error => e
82
+ unreadable_model(e.message)
83
+ end
84
+
85
+ # A projection the generator can't read must not quietly become ALL — that's
86
+ # the silent revert this option exists to stop. Leave dynamodb.tf alone: abort
87
+ # an explicit run, and skip (don't kill the generator) on an auto-sync.
88
+ def unreadable_model(message)
89
+ abort "Error: #{message}" unless @quiet
90
+
91
+ puts " ⚠ skipped dynamodb.tf — #{message}"
92
+ nil
78
93
  end
79
94
 
80
95
  # Parse a model file to extract its name and index declarations.
@@ -90,7 +105,7 @@ module Belt
90
105
  model_name = Belt::Inflector.underscore(class_name)
91
106
 
92
107
  # Extract indexes() declaration
93
- indexes = extract_indexes(content)
108
+ indexes = extract_indexes(content, file_path)
94
109
 
95
110
  # cognito_authenticatable installs a GSI without an indexes() call
96
111
  indexes += extract_cognito_indexes(content)
@@ -113,7 +128,7 @@ module Belt
113
128
  match[1] ? Belt::Inflector.camelize_lower(match[1]) : match[2]
114
129
  end
115
130
 
116
- def extract_indexes(content)
131
+ def extract_indexes(content, file_path = nil)
117
132
  indexes = []
118
133
 
119
134
  # Match the indexes() DSL: indexes('Name' => { partition_key: 'pk' }, ...)
@@ -123,18 +138,26 @@ module Belt
123
138
 
124
139
  index_content = index_block[1]
125
140
 
126
- # Parse each index entry: 'IndexName' => { partition_key: 'key', sort_key: 'key' }
127
- index_content.scan(/'([^']+)'\s*=>\s*\{([^}]+)\}/) do |name, opts|
141
+ # Parse each index entry: 'IndexName' => { partition_key: 'key', sort_key: 'key' }.
142
+ # The options may hold one nested hash: projection: { include: %w[a b] }.
143
+ index_content.scan(/'([^']+)'\s*=>\s*\{((?:[^{}]|\{[^{}]*\})*)\}/) do |name, opts|
128
144
  partition_key = opts.match(/partition_key:\s*'([^']+)'/)&.captures&.first
129
145
  sort_key = opts.match(/sort_key:\s*'([^']+)'/)&.captures&.first
130
146
  next unless partition_key
131
147
 
132
- indexes << { name: name, partition_key: partition_key, sort_key: sort_key }
148
+ indexes << { name: name, partition_key: partition_key, sort_key: sort_key,
149
+ projection: model_projection(opts, name, file_path) }
133
150
  end
134
151
 
135
152
  indexes
136
153
  end
137
154
 
155
+ def model_projection(opts, index_name, file_path)
156
+ GsiProjection.from_model_options(opts, index_name)
157
+ rescue GsiProjection::Error => e
158
+ raise GsiProjection::Error, [file_path, e.message].compact.join(': ')
159
+ end
160
+
138
161
  # `cognito_authenticatable` installs an EmailIndex GSI without the model ever
139
162
  # calling indexes() — see Belt::Authentication::CognitoAuthenticatable. The
140
163
  # generator has to know that, or the table would be created without the GSI and
@@ -228,12 +251,37 @@ module Belt
228
251
  old_gsis = gsi_names(existing_content, label)
229
252
  new_gsis = gsi_names(new_content, label)
230
253
  dropped.concat((old_gsis - new_gsis).map { |gsi| "GSI \"#{gsi}\" on table \"#{label}\"" })
254
+ dropped.concat(reverted_projections(existing_content, new_content, label))
231
255
  dropped.concat(dropped_table_settings(existing_content, new_content, label))
232
256
  end
233
257
 
234
258
  dropped
235
259
  end
236
260
 
261
+ # A GSI hand-tuned to KEYS_ONLY or INCLUDE that the regen would put back to ALL.
262
+ # The index survives, so the name check above misses it, but every write to the
263
+ # table starts paying for the full copy again.
264
+ def reverted_projections(existing_content, new_content, label)
265
+ old_types = gsi_projection_types(existing_content, label)
266
+ new_types = gsi_projection_types(new_content, label)
267
+
268
+ old_types.filter_map do |gsi, type|
269
+ next if type == 'ALL' || new_types[gsi] != 'ALL'
270
+
271
+ "#{type} projection on GSI \"#{gsi}\" on table \"#{label}\" (would become ALL)"
272
+ end
273
+ end
274
+
275
+ # GSI name → projection_type for every GSI in the given table's block.
276
+ def gsi_projection_types(content, label)
277
+ block = table_block(content, label)
278
+ return {} unless block
279
+
280
+ block.scan(/global_secondary_index\s*\{([^}]*)\}/m).to_h do |(body)|
281
+ [body[/name\s*=\s*"([^"]+)"/, 1], body[/projection_type\s*=\s*"([^"]+)"/, 1]]
282
+ end
283
+ end
284
+
237
285
  # Nested blocks (`ttl`, `server_side_encryption`, …) and settings (`stream_enabled`,
238
286
  # …) a table has today that the regenerated table wouldn't. A hand-added ttl block
239
287
  # is the usual one — dropping it turns expiry off and rows quietly pile up.
@@ -346,8 +394,8 @@ module Belt
346
394
  puts "\n⚠ Regenerating #{dest} would DROP infrastructure not derived from your models:"
347
395
  dropped.each { |d| puts " • #{d}" }
348
396
  puts "\n This usually means a table, GSI, or setting (e.g. ttl) was added to dynamodb.tf by hand."
349
- puts ' Belt only tracks what it can read from lambda/models/*.rb (indexes, belongs_to,'
350
- puts ' cognito_authenticatable, ttl_attribute),'
397
+ puts ' Belt only tracks what it can read from lambda/models/*.rb (indexes and their'
398
+ puts ' projection:, belongs_to, cognito_authenticatable, ttl_attribute),'
351
399
  puts ' so a hand-added definition is invisible to the generator and gets overwritten.'
352
400
  end
353
401
 
@@ -430,7 +478,7 @@ module Belt
430
478
  lines << " name = \"#{idx[:name]}\""
431
479
  lines << " hash_key = \"#{idx[:partition_key]}\""
432
480
  lines << " range_key = \"#{idx[:sort_key]}\"" if idx[:sort_key]
433
- lines << ' projection_type = "ALL"'
481
+ lines.concat(GsiProjection.hcl_lines(idx[:projection]))
434
482
  lines << ' }'
435
483
  end
436
484
 
@@ -91,7 +91,8 @@ Belt::Observability::Metrics.track_event("OrderCreated", model: "Order")
91
91
 
92
92
  | Variable | Purpose |
93
93
  |----------|---------|
94
- | `ENVIRONMENT` | Controls error verbosity (`dev*`, `local`, `test` = verbose) |
94
+ | `ENVIRONMENT` | Outside Lambda, `dev*`, `local`, `test` = verbose error responses |
95
+ | `BELT_VERBOSE_ERRORS` | `true` = verbose error responses on a deployed stack (off by default); `false` = off everywhere |
95
96
  | `BELT_METRICS_NAMESPACE` | CloudWatch namespace (default: `Belt`) |
96
97
  | `ACTION` | Service name for logging |
97
98
  | `ERROR_NOTIFICATION_TOPIC_ARN` | SNS topic for error alerts |
@@ -91,6 +91,53 @@ Post.where(
91
91
  )
92
92
  ```
93
93
 
94
+ ### Declaring Indexes
95
+
96
+ `belt setup tables` writes `infrastructure/modules/app/dynamodb.tf` from your
97
+ models. Declare each GSI with `indexes(...)`, using DynamoDB attribute names:
98
+
99
+ ```ruby
100
+ class Match < ApplicationRecord
101
+ indexes(
102
+ 'PlayerIndex' => { partition_key: 'playerId', sort_key: 'createdAt' },
103
+ 'WarningIndex' => { partition_key: 'warnDue', sort_key: 'warnAt', projection: :keys_only },
104
+ 'TurnIndex' => { partition_key: 'turnDue', projection: { include: %w[warnTurn] } }
105
+ )
106
+ end
107
+ ```
108
+
109
+ Write lists with brackets (`%w[a b]`, `['a']`), not parentheses: the generator
110
+ reads `indexes(...)` as text and stops at the first `)`.
111
+
112
+ `projection:` picks which attributes DynamoDB copies into the index:
113
+
114
+ | Value | Terraform | Index holds |
115
+ |-------|-----------|-------------|
116
+ | omitted or `:all` | `projection_type = "ALL"` | the whole row |
117
+ | `:keys_only` | `projection_type = "KEYS_ONLY"` | table key (`id`) + index keys |
118
+ | `{ include: %w[a b] }` | `projection_type = "INCLUDE"` + `non_key_attributes` | keys + the listed attributes |
119
+
120
+ With `ALL`, every write to a row in the index rewrites its index copy, even when
121
+ no index key changed. A sparse index that only a sweep reads usually needs keys
122
+ only. The catch: a query on a `KEYS_ONLY` or `INCLUDE` index returns records with
123
+ just those attributes set. Read anything else with a `find` per hit:
124
+
125
+ ```ruby
126
+ Match.where(warn_due: 'Y', index: 'WarningIndex').each do |hit|
127
+ match = Match.find(hit.id) # GetItem for the full row
128
+ end
129
+ ```
130
+
131
+ Changing a projection on an existing table makes Terraform delete and rebuild
132
+ that GSI. Queries against it fail until the backfill finishes.
133
+
134
+ `belt generate index` takes the same choice: `--projection keys_only`,
135
+ `--projection all` (default), or `--projection include:warnTurn,seatId`.
136
+
137
+ If `dynamodb.tf` has a projection the models don't declare (a hand edit),
138
+ `belt setup tables` won't silently put it back to `ALL`: it asks first, and the
139
+ automatic sync after a generator skips the write.
140
+
94
141
  ### Count and Existence
95
142
 
96
143
  ```ruby
@@ -85,7 +85,8 @@ belt logs worker -e prod # specific environment
85
85
  | `BELT_METRICS_NAMESPACE` | CloudWatch metrics namespace (default: `Belt`) |
86
86
  | `ACTION` | Service name in log entries (falls back to function name) |
87
87
  | `ERROR_NOTIFICATION_TOPIC_ARN` | SNS topic for error alerts |
88
- | `ENVIRONMENT` | Controls verbose errors (`dev*`/`local`/`test` = verbose) |
88
+ | `ENVIRONMENT` | Outside Lambda (`belt server`, specs), `dev*`/`local`/`test` put the exception class, message and backtrace in error responses |
89
+ | `BELT_VERBOSE_ERRORS` | `true` puts those details in error responses on a deployed stack (off by default: a dev stack is public too); `false` turns them off everywhere |
89
90
 
90
91
  ## See Also
91
92
 
@@ -209,6 +209,152 @@ Declare which DynamoDB tables a route accesses (used by Terraform for IAM):
209
209
  resources :posts, tables: [:posts, :comments]
210
210
  ```
211
211
 
212
+ ## Throttling
213
+
214
+ Cap how many requests API Gateway lets through to a route with `throttle:`:
215
+ `rate` is the steady requests per second, `burst` is how many it absorbs at once.
216
+ Over the limit, callers get a `429` before the Lambda runs.
217
+
218
+ ```ruby
219
+ gateway :api, auth: :none, throttle: { rate: 50, burst: 100 } do # default for every route
220
+ post "/reports", to: "reports#create", throttle: { rate: 5, burst: 10 }
221
+ get "/health", to: "health#show", throttle: false # opt out of the default
222
+
223
+ scope path: "family", throttle: { rate: 1, burst: 2 } do # scope, namespace, function
224
+ resources :devices, only: [:create] # and nested resources inherit
225
+ end
226
+ end
227
+ ```
228
+
229
+ A route's own `throttle:` wins, then the nearest enclosing `scope` / `namespace` /
230
+ `function` / `resources` block, then the gateway's. `throttle: false` means "no
231
+ route-level throttle". `belt routes -f json` puts the result on each route, and the
232
+ conveyor-belt provider (0.0.20+) applies it as API Gateway stage method settings.
233
+
234
+ Where routes.rb sets no throttle, the provider falls back to the serving Lambda's
235
+ `throttle:` in `config/lambda/<fn>.yml`, then to the provider's stage-level
236
+ `throttle` block. Note that a **gateway-level default in routes.rb is a route-level
237
+ throttle**: it beats both of those. Use `throttle: false` on a route if the Lambda
238
+ YAML should decide it.
239
+
240
+ **Throttles are per route, not per caller.** API Gateway keeps one bucket per
241
+ route, shared by everyone. `throttle: { rate: 5, burst: 10 }` on `POST /reports`
242
+ stops a script from running up the bill, but that same script also uses up the
243
+ limit for real players. For per-caller limits (what Rails' controller
244
+ `rate_limit to:, within:` gives you), put a WAF rate-based rule in front of the
245
+ gateway (see below).
246
+
247
+ Throttling is approximate, so expect a few requests either side of the limit.
248
+ Method settings override the stage's `*/*` setting. Anything that throttles "the
249
+ whole stage" by patching only `*/*` (an emergency kill switch, for example) no
250
+ longer covers routes that have their own `throttle`. It has to patch those
251
+ method settings too, or cut Lambda concurrency instead.
252
+
253
+ ### Per-caller limits: WAF rate rule recipe
254
+
255
+ WAF counts requests per client IP over a window and blocks an IP that goes over.
256
+ Attach a REGIONAL web ACL to the gateway stage with the provider's
257
+ `waf_web_acl_arn`. WAF bills per web ACL, per rule and per million requests,
258
+ so one ACL with a few rules is the usual shape.
259
+
260
+ ```hcl
261
+ # infrastructure/modules/app/waf.tf
262
+ resource "aws_wafv2_web_acl" "api" {
263
+ name = "${var.app_name}-${var.environment}-api"
264
+ scope = "REGIONAL" # API Gateway stage; CLOUDFRONT scope is only for distributions (us-east-1)
265
+
266
+ default_action {
267
+ allow {}
268
+ }
269
+
270
+ # 20 POST /reports per IP per minute
271
+ rule {
272
+ name = "reports-per-ip"
273
+ priority = 1
274
+
275
+ action {
276
+ block {}
277
+ }
278
+
279
+ statement {
280
+ rate_based_statement {
281
+ limit = 20 # requests per window, minimum 10
282
+ evaluation_window_sec = 60 # 60, 120, 300 or 600
283
+ aggregate_key_type = "IP"
284
+
285
+ scope_down_statement {
286
+ and_statement {
287
+ statement {
288
+ byte_match_statement {
289
+ search_string = "/reports"
290
+ positional_constraint = "ENDS_WITH"
291
+ field_to_match {
292
+ uri_path {}
293
+ }
294
+ text_transformation {
295
+ priority = 0
296
+ type = "NONE"
297
+ }
298
+ }
299
+ }
300
+ statement {
301
+ byte_match_statement {
302
+ search_string = "POST"
303
+ positional_constraint = "EXACTLY"
304
+ field_to_match {
305
+ method {}
306
+ }
307
+ text_transformation {
308
+ priority = 0
309
+ type = "NONE"
310
+ }
311
+ }
312
+ }
313
+ }
314
+ }
315
+ }
316
+ }
317
+
318
+ visibility_config {
319
+ cloudwatch_metrics_enabled = true
320
+ metric_name = "reports-per-ip"
321
+ sampled_requests_enabled = true
322
+ }
323
+ }
324
+
325
+ visibility_config {
326
+ cloudwatch_metrics_enabled = true
327
+ metric_name = "${var.app_name}-${var.environment}-api"
328
+ sampled_requests_enabled = true
329
+ }
330
+ }
331
+ ```
332
+
333
+ ```hcl
334
+ resource "conveyor_belt" "main" {
335
+ # ...
336
+ waf_web_acl_arn = aws_wafv2_web_acl.api.arn
337
+ }
338
+ ```
339
+
340
+ - **Scope the rule down** to the routes that cost money (public writes). An
341
+ unscoped rule counts every request, including page loads and polling.
342
+ - **Key on `IP`.** That is the address that connected to whatever the ACL is
343
+ attached to. If clients call the gateway directly, attach a REGIONAL ACL to the
344
+ stage as above. If a CloudFront distribution sits in front of the API, a
345
+ regional ACL only sees CloudFront's edge addresses. Attach a `CLOUDFRONT`-scope
346
+ ACL (created in us-east-1) to the distribution instead, still keyed on `IP`.
347
+ Don't key on `X-Forwarded-For` (`FORWARDED_IP`): WAF takes the first address in
348
+ that header, and the client chooses it, so a script can rotate it to get around
349
+ the limit.
350
+ - **Watch the path WAF sees.** On the `execute-api` URL the path starts with the
351
+ stage name (`/dev/reports`), and on a custom domain it doesn't. `ENDS_WITH` matches
352
+ both.
353
+ - Try a new rule with `action { count {} }` first, check the CloudWatch metric, then
354
+ switch to `block {}`.
355
+ - Keep the route `throttle:` as well. WAF stops one noisy IP, and the throttle caps
356
+ the total when many IPs push at once.
357
+
212
358
  ## Inspecting Routes
213
359
 
214
360
  ```bash
@@ -108,7 +108,16 @@ module Belt
108
108
  Belt::HttpStatus.resolve(status)
109
109
  end
110
110
 
111
+ # Whether an error response carries the exception class, message and backtrace.
112
+ # A deployed stack is on the internet whatever it is called, so inside Lambda
113
+ # this is off unless BELT_VERBOSE_ERRORS=true. Outside Lambda (belt server,
114
+ # specs) it follows the environment name. BELT_VERBOSE_ERRORS=false turns it
115
+ # off everywhere. The details are always in the logs.
111
116
  def verbose_errors_enabled?
117
+ setting = ENV['BELT_VERBOSE_ERRORS'].to_s.strip.downcase
118
+ return setting == 'true' unless setting.empty?
119
+ return false if ENV.key?('AWS_LAMBDA_FUNCTION_NAME')
120
+
112
121
  env = ENV['ENVIRONMENT']&.downcase || ''
113
122
  env.start_with?('dev') || env == 'local' || env == 'test'
114
123
  end
@@ -30,9 +30,10 @@ module Belt
30
30
  # Per-route API Gateway limit: `throttle: { rate: 2, burst: 5 }` (requests per
31
31
  # second, token bucket). Emitted by `belt routes -f json` and applied by the
32
32
  # conveyor-belt provider (0.0.20+) as stage method settings; it wins over the
33
- # Lambda's `throttle:` in config/lambda/<fn>.yml. Returns nil when unset.
33
+ # Lambda's `throttle:` in config/lambda/<fn>.yml. Returns nil when unset or
34
+ # `false` (a route opting out of an inherited gateway/scope throttle).
34
35
  def self.normalize_throttle(raw)
35
- return nil if raw.nil?
36
+ return nil if raw.nil? || raw == false
36
37
 
37
38
  unless raw.is_a?(Hash)
38
39
  raise ArgumentError, "throttle must be a Hash like { rate: 2, burst: 5 } (got #{raw.inspect})"
@@ -116,7 +117,7 @@ module Belt
116
117
  inherited_controller: controller_name,
117
118
  inherited_lambda: @inherited_lambda,
118
119
  scope_module: @scope_module)
119
- nested_builder.instance_eval(&block)
120
+ @gateway.with_throttle(options) { nested_builder.instance_eval(&block) }
120
121
  end
121
122
 
122
123
  # Singular resource inside nested context (e.g. resource :billing inside resources :projects)
@@ -200,7 +201,7 @@ module Belt
200
201
  @inherited_tables = (@inherited_tables + Array(options[:tables] || [])).uniq
201
202
  @inherited_controller = options[:controller]&.to_s || @inherited_controller
202
203
 
203
- instance_eval(&) if block_given?
204
+ @gateway.with_throttle(options) { instance_eval(&) } if block_given?
204
205
 
205
206
  @prefix = previous_prefix
206
207
  @collection_prefix = previous_collection_prefix
@@ -415,7 +416,7 @@ module Belt
415
416
  end
416
417
 
417
418
  class ApiGateway
418
- attr_reader :name, :routes, :default_auth, :default_lambda, :default_cors, :default_tables
419
+ attr_reader :name, :routes, :default_auth, :default_lambda, :default_cors, :default_tables, :default_throttle
419
420
 
420
421
  def initialize(name, options = {})
421
422
  @name = name.to_s
@@ -424,7 +425,24 @@ module Belt
424
425
  @default_lambda = options[:lambda] || name
425
426
  @default_cors = options.fetch(:cors, true)
426
427
  @default_tables = Array(options[:tables] || [])
428
+ @default_throttle = Belt::Route.normalize_throttle(options[:throttle])
427
429
  @current_lambda_context = nil
430
+ @throttle_context = nil
431
+ end
432
+
433
+ # Runs the block with `options[:throttle]` as the throttle for every route it
434
+ # adds that doesn't set its own (scope, namespace, function, nested resources).
435
+ # `throttle: false` opts the block out of the gateway default.
436
+ def with_throttle(options)
437
+ return yield unless options.key?(:throttle)
438
+
439
+ previous = @throttle_context
440
+ @throttle_context = Belt::Route.normalize_throttle(options[:throttle]) || false
441
+ begin
442
+ yield
443
+ ensure
444
+ @throttle_context = previous
445
+ end
428
446
  end
429
447
 
430
448
  def lambda(name, &)
@@ -467,7 +485,7 @@ module Belt
467
485
  inherited_auth: inherited_auth,
468
486
  inherited_controller: inherited_controller,
469
487
  inherited_lambda: inherited_lambda)
470
- nested_builder.instance_eval(&)
488
+ with_throttle(options) { nested_builder.instance_eval(&) }
471
489
  end
472
490
 
473
491
  def resource(name, options = {})
@@ -521,12 +539,20 @@ module Belt
521
539
  request_model: options[:request_model],
522
540
  response_model: options[:response_model],
523
541
  response_context: options[:response_context],
524
- throttle: options[:throttle]
542
+ throttle: resolve_throttle(options)
525
543
  }
526
544
 
527
545
  @routes << Belt::Route.new(method, path, route_options)
528
546
  end
529
547
 
548
+ # Route's own `throttle:` (false opts out) → enclosing scope/resource block → gateway default.
549
+ def resolve_throttle(options)
550
+ return options[:throttle] if options.key?(:throttle)
551
+ return @throttle_context unless @throttle_context.nil?
552
+
553
+ @default_throttle
554
+ end
555
+
530
556
  def auto_infer_tables(resource_name, options)
531
557
  return options if options.key?(:tables)
532
558
 
@@ -678,7 +704,7 @@ module Belt
678
704
  @scope_tables = (@scope_tables + Array(options[:tables] || [])).uniq
679
705
  @scope_controller = options[:controller] || @scope_controller
680
706
 
681
- instance_eval(&) if block_given?
707
+ @gateway.with_throttle(options) { instance_eval(&) } if block_given?
682
708
 
683
709
  @scope_prefix = previous_prefix
684
710
  @scope_module = previous_module
@@ -712,7 +738,7 @@ module Belt
712
738
  @scope_auth = options[:auth] if options[:auth]
713
739
  @scope_tables = (@scope_tables + Array(options[:tables] || [])).uniq
714
740
 
715
- instance_eval(&) if block_given?
741
+ @gateway.with_throttle(options) { instance_eval(&) } if block_given?
716
742
 
717
743
  @lambda_target = previous_lambda
718
744
  @scope_auth = previous_auth
@@ -780,8 +806,8 @@ module Belt
780
806
  auth_override = options[:auth]
781
807
  route_definitions = mountable.respond_to?(:routes) ? mountable.routes : []
782
808
 
783
- route_definitions.each do |route_def|
784
- mount_route(route_def, prefix, extra_tables, auth_override)
809
+ @gateway.with_throttle(options) do
810
+ route_definitions.each { |route_def| mount_route(route_def, prefix, extra_tables, auth_override) }
785
811
  end
786
812
  end
787
813
 
@@ -913,7 +939,7 @@ module Belt
913
939
  inherited_auth: inherited_auth,
914
940
  inherited_controller: controller,
915
941
  inherited_lambda: @lambda_target)
916
- nested_builder.instance_eval(&)
942
+ @gateway.with_throttle(options) { nested_builder.instance_eval(&) }
917
943
  end
918
944
 
919
945
  def build_scoped_resource(name, options)
data/lib/belt/version.rb CHANGED
@@ -1,7 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Belt
4
- VERSION = '0.6.12'
4
+ VERSION = '0.6.13'
5
5
 
6
6
  # Ruby version new apps run on in Lambda. Rendered into the conveyor-belt
7
7
  # provider block (`ruby_version`) by `belt new` / `belt generate environment`.
@@ -58,9 +58,10 @@ belt apply <env>
58
58
  This creates: model, controller (with all CRUD actions), route entry, and DynamoDB schema.
59
59
 
60
60
  `infrastructure/modules/app/dynamodb.tf` is generated. Declare everything on the model:
61
- GSIs via `indexes(...)` / `belongs_to`, TTL via `ttl_attribute :expires_at`. Anything
62
- you add to the `.tf` by hand (a `ttl` block, a comment) gets dropped the next time it's
63
- regenerated.
61
+ GSIs via `indexes(...)` / `belongs_to` (with `projection: :keys_only` or
62
+ `projection: { include: %w[attr] }` for a narrower GSI), TTL via
63
+ `ttl_attribute :expires_at`. Anything you add to the `.tf` by hand (a `ttl` block, a
64
+ projection, a comment) gets dropped the next time it's regenerated.
64
65
 
65
66
  ### Add a model only (no API endpoint)
66
67
 
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: belt
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.6.12
4
+ version: 0.6.13
5
5
  platform: ruby
6
6
  authors:
7
7
  - Stowzilla
@@ -144,6 +144,7 @@ files:
144
144
  - lib/belt/cli/frontend_setup_command.rb
145
145
  - lib/belt/cli/generate_command.rb
146
146
  - lib/belt/cli/generator_registry.rb
147
+ - lib/belt/cli/gsi_projection.rb
147
148
  - lib/belt/cli/index_command.rb
148
149
  - lib/belt/cli/lambda_config_command.rb
149
150
  - lib/belt/cli/logs_command.rb