star_gates 0.3.2 → 0.4.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.
@@ -1,17 +1,19 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require 'active_support/ordered_options'
4
3
  require 'active_support/core_ext/class/attribute'
5
4
  require 'active_support/core_ext/hash/deep_merge'
6
5
  require 'active_support/core_ext/hash/indifferent_access'
6
+ require 'active_support/core_ext/string/inflections'
7
7
  require 'active_support/concern'
8
8
  require 'active_support/notifications'
9
9
  require_relative 'configuration'
10
10
 
11
11
  module StarGates
12
12
  class ApplicationStarGate < Feature
13
- # Use ActiveSupport class attributes instead of custom implementation
14
- class_attribute :feature_name
13
+ # The configured name; nil until `configure(name)`. Instances answer
14
+ # #feature_name, which falls back to the class name, never nil.
15
+ class_attribute :feature_name, instance_accessor: false
16
+ class_attribute :options, default: {}.freeze, instance_accessor: false
15
17
  class_attribute :telemetry_tags, default: {}
16
18
  class_attribute :state_configs, default: {}
17
19
 
@@ -20,7 +22,7 @@ module StarGates
20
22
  @instance_config = ActiveSupport::HashWithIndifferentAccess.new(options)
21
23
 
22
24
  # Merge with class-level config using deep_merge
23
- @merged_config = self.class.config.to_h.with_indifferent_access.deep_merge(@instance_config)
25
+ @merged_config = self.class.options.with_indifferent_access.deep_merge(@instance_config)
24
26
 
25
27
  # Use configuration defaults if not provided
26
28
  rollout ||= @merged_config[:default_rollout] || 0
@@ -33,11 +35,9 @@ module StarGates
33
35
  @default_config = ActiveSupport::HashWithIndifferentAccess.new(state_configs[:disabled] || {})
34
36
  @canary_config = ActiveSupport::HashWithIndifferentAccess.new(state_configs[:canary] || {})
35
37
 
36
- # Setup telemetry if enabled
37
- setup_telemetry if telemetry_enabled?
38
-
39
- # Setup error handling
40
- setup_error_handling if error_reporting_enabled?
38
+ # Counters exist whatever telemetry says now: it is read per call and
39
+ # may be turned on after construction.
40
+ setup_counters
41
41
  end
42
42
 
43
43
  # Enhanced state-specific methods with instrumentation and telemetry
@@ -65,10 +65,6 @@ module StarGates
65
65
  end
66
66
  end
67
67
 
68
- def config
69
- @config ||= self.class.config.inheritable_copy
70
- end
71
-
72
68
  def timeout
73
69
  @merged_config[:timeout]
74
70
  end
@@ -103,10 +99,8 @@ module StarGates
103
99
  }
104
100
  end
105
101
 
106
- # Public method to get feature identifier
107
- def feature_identifier
108
- self.class.feature_name || self.class.name.demodulize.underscore
109
- end
102
+ # The configured name, else Feature's (the class name).
103
+ def feature_name = self.class.feature_name || super
110
104
 
111
105
  # Feature-specific configuration with state awareness
112
106
  def feature_config
@@ -128,10 +122,10 @@ module StarGates
128
122
 
129
123
  {
130
124
  average_execution_time: average_execution_time,
131
- median_execution_time: latency.quantile(0.5),
132
- p95_execution_time: latency.quantile(0.95),
133
- p99_execution_time: latency.quantile(0.99),
134
- total_executions: @execution_count || 0,
125
+ median_execution_time: latency_quantile(0.5),
126
+ p95_execution_time: latency_quantile(0.95),
127
+ p99_execution_time: latency_quantile(0.99),
128
+ total_executions: @execution_count,
135
129
  error_rate: calculate_error_rate,
136
130
  last_execution: @last_execution_time
137
131
  }
@@ -144,20 +138,11 @@ module StarGates
144
138
  configuration: configuration_summary,
145
139
  performance: performance_stats,
146
140
  environment: StarGates.configuration.environment,
147
- feature_name: self.class.feature_name || feature_name
141
+ feature_name: feature_name
148
142
  )
149
143
  end
150
144
 
151
145
  class << self
152
- # Each class reads through to its parent's options and writes only its own.
153
- def config
154
- @config ||= if superclass.respond_to?(:config)
155
- superclass.config.inheritable_copy
156
- else
157
- ActiveSupport::InheritableOptions.new
158
- end
159
- end
160
-
161
146
  def configure(name = nil, **options)
162
147
  self.feature_name = name if name
163
148
 
@@ -168,14 +153,12 @@ module StarGates
168
153
  # Extract telemetry tags
169
154
  self.telemetry_tags = extract_telemetry_tags(options)
170
155
 
171
- remaining_options = options.except(*state_specific[:extracted_keys])
172
- remaining_options.each do |key, value|
173
- config.send("#{key}=", value)
174
- end
156
+ self.options = self.options.merge(options.except(*state_specific[:extracted_keys])).freeze
175
157
  end
176
158
 
177
- def with_timeout(seconds, **options)
178
- configure(timeout: seconds, **options)
159
+ # `timeout` in Integer nanoseconds.
160
+ def with_timeout(timeout, **options)
161
+ configure(timeout: timeout, **options)
179
162
  end
180
163
 
181
164
  def with_circuit_breaker(threshold: 5, **options)
@@ -183,13 +166,13 @@ module StarGates
183
166
  end
184
167
 
185
168
  def for_team(team_name, **options)
186
- self.telemetry_tags = { team: team_name }
187
169
  configure(**options)
170
+ self.telemetry_tags = { team: team_name }.merge(telemetry_tags)
188
171
  end
189
172
 
190
173
  def critical_feature(**options)
191
174
  configure(
192
- timeout: 1.0,
175
+ timeout: 1_000_000_000,
193
176
  retry_count: 5,
194
177
  circuit_breaker_threshold: 10,
195
178
  performance_monitoring: true,
@@ -199,7 +182,7 @@ module StarGates
199
182
 
200
183
  def experimental_feature(**options)
201
184
  configure(
202
- timeout: 10.0,
185
+ timeout: 10_000_000_000,
203
186
  retry_count: 1,
204
187
  performance_monitoring: true,
205
188
  **options
@@ -241,52 +224,40 @@ module StarGates
241
224
  @merged_config[:error_reporting]
242
225
  end
243
226
 
244
- def setup_telemetry
227
+ def setup_counters
245
228
  @execution_count = 0
246
229
  @error_count = 0
247
230
  @last_execution_time = nil
248
231
  end
249
232
 
250
- def setup_error_handling
251
- # Setup error tracking and reporting
252
- end
253
-
254
233
  def instrument_execution(context)
255
234
  return yield unless telemetry_enabled?
256
235
 
257
- # Use ActiveSupport::Notifications for instrumentation
258
236
  ActiveSupport::Notifications.instrument('star_gates.feature.execute',
259
- feature: feature_identifier,
260
- status: status,
237
+ feature: feature_name, status: status,
261
238
  context: context) do |payload|
262
- start_time = Time.now
263
- begin
264
- result = yield
265
- execution_time = Time.now - start_time
266
- record_successful_execution(execution_time)
267
-
268
- payload[:success] = true
269
- payload[:execution_time_ms] = (execution_time * 1000).round(2)
270
-
271
- result
272
- rescue StandardError => e
273
- execution_time = Time.now - start_time
274
- record_failed_execution(execution_time, e)
275
-
276
- payload[:success] = false
277
- payload[:execution_time_ms] = (execution_time * 1000).round(2)
278
- payload[:error] = e.class.name
279
-
280
- raise
281
- ensure
282
- StarGates.telemetry&.record_feature_execution(
283
- feature_identifier,
284
- status,
285
- !defined?(e),
286
- payload[:execution_time_ms],
287
- context
288
- )
289
- end
239
+ timed_execution(payload, context) { yield }
240
+ end
241
+ end
242
+
243
+ # Times the block in monotonic Integer nanoseconds and reports it whether
244
+ # it returns or raises.
245
+ def timed_execution(payload, context)
246
+ started = StarGates.monotonic_time
247
+ succeeded = false
248
+ begin
249
+ result = yield
250
+ succeeded = true
251
+ result
252
+ rescue StandardError => e
253
+ payload[:error] = e.class.name
254
+ raise
255
+ ensure
256
+ execution_time = StarGates.monotonic_time - started
257
+ succeeded ? record_successful_execution(execution_time) : record_failed_execution(execution_time)
258
+ payload[:success] = succeeded
259
+ payload[:execution_time] = execution_time
260
+ StarGates.telemetry&.record_feature_execution(feature_name, status, succeeded, execution_time, context)
290
261
  end
291
262
  end
292
263
 
@@ -295,7 +266,7 @@ module StarGates
295
266
 
296
267
  # Use ActiveSupport::Notifications for UI access tracking
297
268
  ActiveSupport::Notifications.instrument('star_gates.ui_component.access',
298
- feature: feature_identifier,
269
+ feature: feature_name,
299
270
  context: context) do |payload|
300
271
  result = yield
301
272
  payload[:component] = result
@@ -303,7 +274,7 @@ module StarGates
303
274
  StarGates.telemetry&.record_counter(
304
275
  'star_gates.ui_component.access',
305
276
  1,
306
- tags: telemetry_tags.merge(component: result, feature: feature_identifier)
277
+ tags: telemetry_tags.merge(component: result, feature: feature_name)
307
278
  )
308
279
 
309
280
  result
@@ -315,7 +286,7 @@ module StarGates
315
286
 
316
287
  # Use ActiveSupport::Notifications for config access tracking
317
288
  ActiveSupport::Notifications.instrument('star_gates.config.access',
318
- feature: feature_identifier,
289
+ feature: feature_name,
319
290
  config_key: key,
320
291
  context: context) do |payload|
321
292
  result = yield
@@ -324,26 +295,36 @@ module StarGates
324
295
  StarGates.telemetry&.record_counter(
325
296
  'star_gates.config.access',
326
297
  1,
327
- tags: telemetry_tags.merge(config_key: key, feature: feature_identifier)
298
+ tags: telemetry_tags.merge(config_key: key, feature: feature_name)
328
299
  )
329
300
 
330
301
  result
331
302
  end
332
303
  end
333
304
 
334
- def with_timeout(seconds, &)
305
+ # Runs the block within `timeout` Integer nanoseconds (nil: no limit of
306
+ # its own), narrowed by the ambient deadline. A budget already spent does
307
+ # not run the block: Timeout.timeout(0) would mean no limit at all.
308
+ def with_timeout(timeout, &)
335
309
  DeadlineMachines.check!
336
- budget = DeadlineMachines.clamp_sleep(seconds)
337
- DeadlineMachines.with_deadline(budget) { Timeout.timeout(budget, &) }
310
+ budget = timeout.nil? ? DeadlineMachines.remaining : DeadlineMachines.clamp_sleep(timeout)
311
+ return yield if budget.nil?
312
+ raise timed_out(budget) unless budget.positive?
313
+
314
+ DeadlineMachines.with_deadline(budget) { Timeout.timeout(Rational(budget, NS_PER_SECOND), &) }
338
315
  rescue Timeout::Error
339
- raise StarGates::UnavailableError, "Feature #{feature_identifier} timed out after #{budget}s"
316
+ raise timed_out(budget)
317
+ end
318
+
319
+ def timed_out(budget)
320
+ UnavailableError.new(feature_name, :exceeded, "Feature #{feature_name} timed out after #{budget}ns")
340
321
  end
341
322
 
342
323
  def record_successful_execution(duration)
343
324
  record_execution(duration)
344
325
  end
345
326
 
346
- def record_failed_execution(duration, _error)
327
+ def record_failed_execution(duration)
347
328
  return unless performance_monitoring_enabled?
348
329
 
349
330
  @error_count += 1
@@ -352,6 +333,8 @@ module StarGates
352
333
 
353
334
  # Cluster budget for the latency digest; error is about one part in this.
354
335
  LATENCY_COMPRESSION = 100
336
+ NS_PER_SECOND = 1_000_000_000
337
+ private_constant :LATENCY_COMPRESSION, :NS_PER_SECOND
355
338
 
356
339
  def record_execution(duration)
357
340
  return unless performance_monitoring_enabled?
@@ -359,34 +342,41 @@ module StarGates
359
342
  latency.add(duration)
360
343
  @latency_total = latency_total + duration
361
344
  @execution_count += 1
362
- @last_execution_time = Time.now
345
+ @last_execution_time = StarGates.monotonic_time
363
346
  end
364
347
 
365
348
  def average_execution_time
366
- return 0 if @execution_count.nil? || @execution_count.zero?
349
+ return if @execution_count.zero?
367
350
 
368
351
  latency_total / @execution_count
369
352
  end
370
353
 
354
+ # A latency quantile in Integer nanoseconds, nil before any execution.
355
+ def latency_quantile(quantile)
356
+ return if @execution_count.zero?
357
+
358
+ latency.quantile(quantile).round
359
+ end
360
+
371
361
  # Telemetry and performance monitoring are separate switches, so the digest
372
362
  # is built where it is used rather than in either setup path.
373
363
  def latency
374
- @latency ||= ProbabilisticMachines::TDigest.new(compression: LATENCY_COMPRESSION)
364
+ @latency ||= ProbabilisticMachines::TDigest.new(LATENCY_COMPRESSION)
375
365
  end
376
366
 
377
367
  def latency_total
378
- @latency_total ||= 0.0
368
+ @latency_total ||= 0
379
369
  end
380
370
 
381
371
  def calculate_error_rate
382
- return 0 if @execution_count.nil? || @execution_count.zero?
372
+ return 0 if @execution_count.zero?
383
373
 
384
374
  (@error_count.to_f / @execution_count * 100).round(2)
385
375
  end
386
376
 
387
377
  def telemetry_tags
388
378
  base_tags = {
389
- feature: feature_identifier,
379
+ feature: feature_name,
390
380
  state: status,
391
381
  environment: StarGates.configuration.environment
392
382
  }
@@ -394,32 +384,5 @@ module StarGates
394
384
  class_tags = self.class.telemetry_tags || {}
395
385
  base_tags.merge(class_tags)
396
386
  end
397
-
398
- # State-specific configuration overrides
399
- def apply_state_specific_config
400
- case status
401
- when 'disabled'
402
- @current_config = @default_config
403
- when 'canary'
404
- @current_config = @canary_config.any? ? @canary_config : @feature_config
405
- when 'enabled'
406
- @current_config = @feature_config
407
- end
408
- end
409
- end
410
- end
411
-
412
- # Add string extensions for better naming
413
- unless String.method_defined?(:demodulize)
414
- class String
415
- def demodulize
416
- split('::').last
417
- end
418
-
419
- def underscore
420
- gsub(/([A-Z]+)([A-Z][a-z])/, '\1_\2')
421
- .gsub(/([a-z\d])([A-Z])/, '\1_\2')
422
- .downcase
423
- end
424
387
  end
425
388
  end
@@ -3,32 +3,53 @@
3
3
  require 'chrono_machines'
4
4
 
5
5
  module StarGates
6
+ # A breaker_machines circuit with optional chrono_machines retries, wired
7
+ # to a feature so an opening circuit rolls the feature back.
8
+ #
9
+ # `policy` (a BreakerMachines::Policy, spans in Integer nanoseconds) and
10
+ # `retry_policy` (a RetryPolicy or nil) are positional, as the cores take
11
+ # them. The keywords belong to this runtime and have no core counterpart:
12
+ #
13
+ # - `feature:` the feature to roll back when the circuit opens.
14
+ # - `auto_rollback:` whether to roll it back (true).
15
+ #
16
+ # A refused call (the circuit is open, busy or full) is never retried: the
17
+ # refusal is the circuit's answer, and waiting out a cooldown inside a
18
+ # request helps nobody. Exhausted retries re-raise the last exception.
6
19
  class Circuit
7
- attr_reader :breaker, :threshold, :within, :reset_after, :feature
8
- attr_accessor :retry_policy
20
+ HALT_ON_REFUSAL = lambda do |exception:, attempt:|
21
+ _ = attempt
22
+ :halt if exception.is_a?(BreakerMachines::CircuitRefusedError)
23
+ end
24
+ private_constant :HALT_ON_REFUSAL
25
+
26
+ attr_reader :breaker, :policy, :retry_policy, :feature
27
+
28
+ def initialize(policy, retry_policy = nil, feature: nil, auto_rollback: true)
29
+ unless retry_policy.nil? || retry_policy.instance_of?(RetryPolicy)
30
+ raise TypeError, "retry_policy must be a StarGates::RetryPolicy or nil, got #{retry_policy.inspect}"
31
+ end
32
+ unless [true, false].include?(auto_rollback)
33
+ raise TypeError, "auto_rollback must be true or false, got #{auto_rollback.inspect}"
34
+ end
9
35
 
10
- def initialize(threshold: 5, within: 30, reset_after: 60, retry_config: nil, feature: nil, auto_rollback: true)
11
- @threshold = threshold
12
- @within = parse_time(within)
13
- @reset_after = parse_time(reset_after)
36
+ @policy = policy
37
+ @retry_policy = retry_policy
14
38
  @feature = feature
15
39
  @auto_rollback = auto_rollback
16
- @breaker = create_breaker
17
- @retry_policy = build_retry_policy(retry_config)
40
+ @breaker = BreakerMachines::Circuit.new("star_gates_circuit_#{object_id}", policy,
41
+ exceptions: [StandardError], **rollback_hooks)
42
+ freeze
18
43
  end
19
44
 
20
45
  def call(&block)
21
- # Integrate ChronoMachines for exponential backoff retries
22
- # This prevents the "retry death spiral" by adding jittered delays
23
- if @retry_policy
24
- ChronoMachines.retry(@retry_policy) do
25
- breaker.call(&block)
26
- end
27
- else
46
+ return breaker.call(&block) unless retry_policy
47
+
48
+ ChronoMachines.retry(retry_policy.strategy, retry_policy.max_attempts,
49
+ delay_from: HALT_ON_REFUSAL, on_retry: method(:instrument_retry)) do
28
50
  breaker.call(&block)
29
51
  end
30
52
  rescue ChronoMachines::MaxRetriesExceededError => e
31
- # Re-raise the original exception after retries exhausted
32
53
  raise e.original_exception
33
54
  end
34
55
 
@@ -44,128 +65,72 @@ module StarGates
44
65
  breaker.half_open?
45
66
  end
46
67
 
47
- def last_failure_time
48
- # BreakerMachines stores this as last_failure_at in stats
49
- stats = breaker.stats
50
- stats.last_failure_at
68
+ # When the last failure was recorded, Integer nanoseconds on the
69
+ # breaker's clock, or nil.
70
+ def last_failure_at
71
+ breaker.stats.last_failure_at
51
72
  end
52
73
 
53
74
  def failure_count
54
- # BreakerMachines stores this in stats
55
- stats = breaker.stats
56
- stats.failure_count || 0
75
+ breaker.stats.failure_count
57
76
  end
58
77
 
59
78
  def success_count
60
- # BreakerMachines stores this in stats
61
- stats = breaker.stats
62
- stats.success_count || 0
79
+ breaker.stats.success_count
80
+ end
81
+
82
+ def to_h
83
+ { state: breaker.status_name, failure_count: failure_count, success_count: success_count,
84
+ last_failure_at: last_failure_at }
63
85
  end
64
86
 
65
- def reset!
87
+ # Closes the circuit and clears its failure window.
88
+ def reset
66
89
  breaker.reset
90
+ self
67
91
  end
68
92
 
69
93
  private
70
94
 
71
- def create_breaker
72
- # Generate a unique circuit name for this instance
73
- circuit_name = "star_gates_circuit_#{object_id}"
95
+ def rollback_hooks
96
+ return {} unless @feature && @auto_rollback
74
97
 
75
- config = {
76
- failure_threshold: threshold,
77
- failure_window: within,
78
- reset_timeout: reset_after,
79
- exceptions: [StandardError]
98
+ {
99
+ on_open: -> { handle_circuit_open },
100
+ on_half_open: -> { handle_circuit_half_open },
101
+ on_close: -> { handle_circuit_close }
80
102
  }
103
+ end
81
104
 
82
- # Self-healing: wire circuit state to feature state
83
- if @feature && @auto_rollback
84
- config[:on_open] = -> { handle_circuit_open }
85
- config[:on_half_open] = -> { handle_circuit_half_open }
86
- config[:on_close] = -> { handle_circuit_close }
87
- end
105
+ def instrument_retry(exception:, attempt:, next_delay:)
106
+ StarGates.instrument('circuit.retry', exception: exception.class.name, attempt: attempt, next_delay: next_delay)
107
+ end
88
108
 
89
- BreakerMachines::Circuit.new(circuit_name, config)
109
+ def feature_status
110
+ @feature.status if @feature.respond_to?(:status)
90
111
  end
91
112
 
92
- # Self-healing callbacks
113
+ # Enabled rolls back to canary; canary rolls back to disabled.
93
114
  def handle_circuit_open
94
115
  return unless @feature.respond_to?(:status)
95
116
 
96
- StarGates.instrument('circuit.auto_rollback', {
97
- feature_status: @feature.status,
98
- circuit_state: 'open',
99
- action: 'rolling_back'
100
- })
101
-
102
- # Auto-rollback feature state when circuit opens
103
- case @feature.status
104
- when 'enabled'
105
- # Circuit is failing → rollback to canary
106
- @feature.rollout_canary if @feature.respond_to?(:rollout_canary)
107
- when 'canary'
108
- # Circuit still failing in canary → disable completely
109
- @feature.disable if @feature.respond_to?(:disable)
117
+ StarGates.instrument('circuit.auto_rollback', feature_status: feature_status, circuit_state: 'open',
118
+ action: 'rolling_back')
119
+ case feature_status
120
+ when 'enabled' then @feature.rollout_canary if @feature.respond_to?(:rollout_canary)
121
+ when 'canary' then @feature.disable if @feature.respond_to?(:disable)
110
122
  end
111
123
  end
112
124
 
113
125
  def handle_circuit_half_open
114
- return unless @feature
115
-
116
- StarGates.instrument('circuit.half_open', {
117
- feature_status: @feature.status,
118
- circuit_state: 'half_open',
119
- action: 'testing_recovery'
120
- })
126
+ StarGates.instrument('circuit.half_open', feature_status: feature_status, circuit_state: 'half_open',
127
+ action: 'testing_recovery')
121
128
  end
122
129
 
130
+ # Recovery does not re-enable the feature: an operator decides that.
123
131
  def handle_circuit_close
124
- return unless @feature
125
-
126
- StarGates.instrument('circuit.recovered', {
127
- feature_status: @feature.status,
128
- circuit_state: 'closed',
129
- action: 'circuit_healthy'
130
- })
131
-
132
- # Optionally: auto-restore to canary when circuit closes
133
- # (conservative: don't auto-enable to 100%, just canary)
134
- # Uncomment if you want auto-restoration:
135
- # if @feature.status == 'disabled'
136
- # @feature.rollout_canary if @feature.respond_to?(:rollout_canary)
137
- # end
138
- end
139
-
140
- def parse_time(time)
141
- # Rails duration helpers can return fractional seconds.
142
- case time
143
- when Numeric then time
144
- when ActiveSupport::Duration then time.to_f
145
- else time.to_i
146
- end
147
- end
148
-
149
- def build_retry_policy(config)
150
- return nil unless config
151
-
152
- # Default retry policy for circuit breakers
153
- defaults = {
154
- max_attempts: 3,
155
- base_delay: 0.1,
156
- multiplier: 2,
157
- max_delay: 5,
158
- retryable_exceptions: [StandardError],
159
- on_retry: lambda { |exception:, attempt:, next_delay:|
160
- StarGates.instrument('circuit.retry', {
161
- exception: exception.class.name,
162
- attempt: attempt,
163
- next_delay: next_delay
164
- })
165
- }
166
- }
167
-
168
- defaults.merge(config)
132
+ StarGates.instrument('circuit.recovered', feature_status: feature_status, circuit_state: 'closed',
133
+ action: 'circuit_healthy')
169
134
  end
170
135
  end
171
136
  end