flipper 1.4.2 → 1.5.0.rc2

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 (249) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +70 -10
  3. data/lib/flipper/adapter.rb +24 -0
  4. data/lib/flipper/adapter_builder.rb +12 -1
  5. data/lib/flipper/adapters/actor_limit.rb +4 -3
  6. data/lib/flipper/adapters/cache_base.rb +17 -0
  7. data/lib/flipper/adapters/dual_write.rb +12 -0
  8. data/lib/flipper/adapters/failover.rb +15 -0
  9. data/lib/flipper/adapters/failsafe.rb +16 -0
  10. data/lib/flipper/adapters/http/client.rb +7 -3
  11. data/lib/flipper/adapters/http/redacted_debug_output.rb +70 -0
  12. data/lib/flipper/adapters/http.rb +42 -8
  13. data/lib/flipper/adapters/instrumented.rb +28 -0
  14. data/lib/flipper/adapters/memoizable.rb +21 -5
  15. data/lib/flipper/adapters/memory.rb +63 -31
  16. data/lib/flipper/adapters/poll.rb +51 -6
  17. data/lib/flipper/adapters/pstore.rb +15 -0
  18. data/lib/flipper/adapters/read_only.rb +1 -1
  19. data/lib/flipper/adapters/strict.rb +17 -1
  20. data/lib/flipper/adapters/sync/feature_synchronizer.rb +3 -1
  21. data/lib/flipper/adapters/sync/synchronizer.rb +20 -1
  22. data/lib/flipper/adapters/sync.rb +8 -0
  23. data/lib/flipper/adapters/wrapper.rb +7 -0
  24. data/lib/flipper/cli.rb +87 -22
  25. data/lib/flipper/cloud/configuration.rb +149 -19
  26. data/lib/flipper/cloud/dsl.rb +6 -0
  27. data/lib/flipper/cloud/memory_adapter.rb +43 -0
  28. data/lib/flipper/cloud/message_verifier.rb +1 -0
  29. data/lib/flipper/cloud/middleware.rb +8 -3
  30. data/lib/flipper/cloud/migrate.rb +3 -1
  31. data/lib/flipper/cloud/routes.rb +24 -2
  32. data/lib/flipper/cloud/shared_memory.rb +111 -0
  33. data/lib/flipper/cloud/telemetry.rb +56 -28
  34. data/lib/flipper/cloud/url_validator.rb +26 -0
  35. data/lib/flipper/cloud.rb +22 -4
  36. data/lib/flipper/configuration.rb +86 -3
  37. data/lib/flipper/dsl.rb +47 -3
  38. data/lib/flipper/engine.rb +64 -8
  39. data/lib/flipper/errors.rb +18 -0
  40. data/lib/flipper/export.rb +4 -0
  41. data/lib/flipper/exporters/json/export.rb +6 -0
  42. data/lib/flipper/exporters/json/v1.rb +5 -9
  43. data/lib/flipper/expression/constant.rb +6 -0
  44. data/lib/flipper/expression.rb +105 -1
  45. data/lib/flipper/expressions/comparable.rb +5 -0
  46. data/lib/flipper/expressions/feature_enabled.rb +11 -7
  47. data/lib/flipper/expressions/number.rb +2 -0
  48. data/lib/flipper/expressions/percentage.rb +3 -1
  49. data/lib/flipper/expressions/percentage_of_actors.rb +9 -0
  50. data/lib/flipper/expressions/random.rb +2 -0
  51. data/lib/flipper/expressions/sem_ver.rb +24 -0
  52. data/lib/flipper/expressions/time.rb +9 -1
  53. data/lib/flipper/feature.rb +153 -43
  54. data/lib/flipper/feature_check_context.rb +19 -1
  55. data/lib/flipper/gates/actor.rb +4 -1
  56. data/lib/flipper/gates/expression.rb +17 -2
  57. data/lib/flipper/gates/group.rb +1 -1
  58. data/lib/flipper/gates/percentage_of_actors.rb +19 -2
  59. data/lib/flipper/gates/percentage_of_time.rb +4 -1
  60. data/lib/flipper/groups.rb +66 -0
  61. data/lib/flipper/instrumentation/log_subscriber.rb +6 -1
  62. data/lib/flipper/instrumentation/subscriber.rb +21 -2
  63. data/lib/flipper/middleware/memoizer.rb +5 -2
  64. data/lib/flipper/named_configuration.rb +194 -0
  65. data/lib/flipper/named_proxy.rb +46 -0
  66. data/lib/flipper/poller.rb +39 -17
  67. data/lib/flipper/sem_ver.rb +84 -0
  68. data/lib/flipper/spec/shared_adapter_specs.rb +40 -0
  69. data/lib/flipper/sync_version.rb +61 -0
  70. data/lib/flipper/test_help.rb +50 -0
  71. data/lib/flipper/typecast.rb +15 -0
  72. data/lib/flipper/types/group.rb +2 -2
  73. data/lib/flipper/version.rb +1 -1
  74. data/lib/flipper.rb +183 -65
  75. data/lib/generators/flipper/setup_generator.rb +18 -0
  76. data/lib/generators/flipper/table_prefix.rb +44 -0
  77. data/lib/generators/flipper/templates/initializer.rb +7 -0
  78. data/lib/generators/flipper/templates/update/migrations/01_create_flipper_tables.rb.erb +13 -7
  79. data/lib/generators/flipper/templates/update/migrations/02_change_flipper_gates_value_to_text.rb.erb +12 -7
  80. data/lib/generators/flipper/update_generator.rb +3 -0
  81. metadata +42 -171
  82. data/.codeclimate.yml +0 -3
  83. data/.github/FUNDING.yml +0 -1
  84. data/.github/dependabot.yml +0 -6
  85. data/.github/workflows/ci.yml +0 -110
  86. data/.github/workflows/examples.yml +0 -105
  87. data/.github/workflows/release.yml +0 -54
  88. data/.rspec +0 -1
  89. data/.superset/config.json +0 -4
  90. data/CLAUDE.md +0 -93
  91. data/CODE_OF_CONDUCT.md +0 -46
  92. data/Dockerfile +0 -27
  93. data/Gemfile +0 -41
  94. data/Rakefile +0 -54
  95. data/benchmark/enabled_ips.rb +0 -10
  96. data/benchmark/enabled_multiple_actors_ips.rb +0 -20
  97. data/benchmark/enabled_profile.rb +0 -20
  98. data/benchmark/instrumentation_ips.rb +0 -21
  99. data/benchmark/typecast_ips.rb +0 -27
  100. data/docker-compose.yml +0 -37
  101. data/docs/DockerCompose.md +0 -18
  102. data/docs/README.md +0 -1
  103. data/docs/images/banner.jpg +0 -0
  104. data/docs/images/flipper_cloud.png +0 -0
  105. data/examples/api/basic.ru +0 -18
  106. data/examples/api/custom_memoized.ru +0 -36
  107. data/examples/api/memoized.ru +0 -42
  108. data/examples/basic.rb +0 -19
  109. data/examples/cloud/app.ru +0 -12
  110. data/examples/cloud/backoff_policy.rb +0 -13
  111. data/examples/cloud/basic.rb +0 -22
  112. data/examples/cloud/cloud_setup.rb +0 -20
  113. data/examples/cloud/forked.rb +0 -36
  114. data/examples/cloud/import.rb +0 -17
  115. data/examples/cloud/poll_interval/README.md +0 -111
  116. data/examples/cloud/poll_interval/client.rb +0 -108
  117. data/examples/cloud/poll_interval/server.rb +0 -98
  118. data/examples/cloud/threaded.rb +0 -33
  119. data/examples/configuring_default.rb +0 -19
  120. data/examples/dsl.rb +0 -57
  121. data/examples/enabled_for_actor.rb +0 -37
  122. data/examples/expressions.rb +0 -237
  123. data/examples/group.rb +0 -38
  124. data/examples/group_dynamic_lookup.rb +0 -75
  125. data/examples/group_with_members.rb +0 -83
  126. data/examples/importing.rb +0 -29
  127. data/examples/individual_actor.rb +0 -28
  128. data/examples/instrumentation.rb +0 -42
  129. data/examples/instrumentation_last_accessed_at.rb +0 -38
  130. data/examples/memoizing.rb +0 -35
  131. data/examples/mirroring.rb +0 -59
  132. data/examples/percentage_of_actors.rb +0 -31
  133. data/examples/percentage_of_actors_enabled_check.rb +0 -35
  134. data/examples/percentage_of_actors_group.rb +0 -35
  135. data/examples/percentage_of_time.rb +0 -27
  136. data/examples/strict.rb +0 -18
  137. data/flipper-cloud.gemspec +0 -19
  138. data/flipper.gemspec +0 -42
  139. data/package-lock.json +0 -41
  140. data/package.json +0 -10
  141. data/spec/fixtures/environment.rb +0 -1
  142. data/spec/fixtures/feature.json +0 -31
  143. data/spec/fixtures/flipper_pstore_1679087600.json +0 -46
  144. data/spec/flipper/actor_spec.rb +0 -56
  145. data/spec/flipper/adapter_builder_spec.rb +0 -72
  146. data/spec/flipper/adapter_spec.rb +0 -166
  147. data/spec/flipper/adapters/actor_limit_spec.rb +0 -75
  148. data/spec/flipper/adapters/dual_write_spec.rb +0 -82
  149. data/spec/flipper/adapters/failover_spec.rb +0 -141
  150. data/spec/flipper/adapters/failsafe_spec.rb +0 -58
  151. data/spec/flipper/adapters/http/client_spec.rb +0 -61
  152. data/spec/flipper/adapters/http_spec.rb +0 -596
  153. data/spec/flipper/adapters/instrumented_spec.rb +0 -167
  154. data/spec/flipper/adapters/memoizable_spec.rb +0 -377
  155. data/spec/flipper/adapters/memory_spec.rb +0 -36
  156. data/spec/flipper/adapters/operation_logger_spec.rb +0 -128
  157. data/spec/flipper/adapters/poll_spec.rb +0 -41
  158. data/spec/flipper/adapters/pstore_spec.rb +0 -16
  159. data/spec/flipper/adapters/read_only_spec.rb +0 -100
  160. data/spec/flipper/adapters/strict_spec.rb +0 -122
  161. data/spec/flipper/adapters/sync/feature_synchronizer_spec.rb +0 -247
  162. data/spec/flipper/adapters/sync/interval_synchronizer_spec.rb +0 -33
  163. data/spec/flipper/adapters/sync/synchronizer_spec.rb +0 -175
  164. data/spec/flipper/adapters/sync_spec.rb +0 -213
  165. data/spec/flipper/cli_spec.rb +0 -217
  166. data/spec/flipper/cloud/configuration_spec.rb +0 -251
  167. data/spec/flipper/cloud/dsl_spec.rb +0 -82
  168. data/spec/flipper/cloud/message_verifier_spec.rb +0 -104
  169. data/spec/flipper/cloud/middleware_spec.rb +0 -289
  170. data/spec/flipper/cloud/migrate_spec.rb +0 -160
  171. data/spec/flipper/cloud/telemetry/backoff_policy_spec.rb +0 -107
  172. data/spec/flipper/cloud/telemetry/metric_spec.rb +0 -87
  173. data/spec/flipper/cloud/telemetry/metric_storage_spec.rb +0 -58
  174. data/spec/flipper/cloud/telemetry/submitter_spec.rb +0 -145
  175. data/spec/flipper/cloud/telemetry_spec.rb +0 -208
  176. data/spec/flipper/cloud_spec.rb +0 -186
  177. data/spec/flipper/configuration_spec.rb +0 -50
  178. data/spec/flipper/dsl_spec.rb +0 -346
  179. data/spec/flipper/engine_spec.rb +0 -374
  180. data/spec/flipper/export_spec.rb +0 -13
  181. data/spec/flipper/exporter_spec.rb +0 -16
  182. data/spec/flipper/exporters/json/export_spec.rb +0 -60
  183. data/spec/flipper/exporters/json/v1_spec.rb +0 -33
  184. data/spec/flipper/expression/builder_spec.rb +0 -248
  185. data/spec/flipper/expression_spec.rb +0 -188
  186. data/spec/flipper/expressions/all_spec.rb +0 -15
  187. data/spec/flipper/expressions/any_spec.rb +0 -15
  188. data/spec/flipper/expressions/boolean_spec.rb +0 -15
  189. data/spec/flipper/expressions/equal_spec.rb +0 -24
  190. data/spec/flipper/expressions/greater_than_or_equal_to_spec.rb +0 -28
  191. data/spec/flipper/expressions/greater_than_spec.rb +0 -28
  192. data/spec/flipper/expressions/less_than_or_equal_to_spec.rb +0 -28
  193. data/spec/flipper/expressions/less_than_spec.rb +0 -32
  194. data/spec/flipper/expressions/not_equal_spec.rb +0 -15
  195. data/spec/flipper/expressions/now_spec.rb +0 -11
  196. data/spec/flipper/expressions/number_spec.rb +0 -21
  197. data/spec/flipper/expressions/percentage_of_actors_spec.rb +0 -20
  198. data/spec/flipper/expressions/percentage_spec.rb +0 -15
  199. data/spec/flipper/expressions/property_spec.rb +0 -13
  200. data/spec/flipper/expressions/random_spec.rb +0 -9
  201. data/spec/flipper/expressions/string_spec.rb +0 -11
  202. data/spec/flipper/expressions/time_spec.rb +0 -29
  203. data/spec/flipper/feature_check_context_spec.rb +0 -65
  204. data/spec/flipper/feature_spec.rb +0 -1227
  205. data/spec/flipper/gate_spec.rb +0 -39
  206. data/spec/flipper/gate_values_spec.rb +0 -103
  207. data/spec/flipper/gates/actor_spec.rb +0 -7
  208. data/spec/flipper/gates/boolean_spec.rb +0 -74
  209. data/spec/flipper/gates/expression_spec.rb +0 -190
  210. data/spec/flipper/gates/group_spec.rb +0 -62
  211. data/spec/flipper/gates/percentage_of_actors_spec.rb +0 -131
  212. data/spec/flipper/gates/percentage_of_time_spec.rb +0 -37
  213. data/spec/flipper/identifier_spec.rb +0 -12
  214. data/spec/flipper/instrumentation/log_subscriber_spec.rb +0 -122
  215. data/spec/flipper/instrumentation/statsd_subscriber_spec.rb +0 -95
  216. data/spec/flipper/instrumenters/memory_spec.rb +0 -43
  217. data/spec/flipper/instrumenters/noop_spec.rb +0 -27
  218. data/spec/flipper/middleware/memoizer_spec.rb +0 -518
  219. data/spec/flipper/middleware/setup_env_spec.rb +0 -94
  220. data/spec/flipper/model/active_record_spec.rb +0 -72
  221. data/spec/flipper/poller_spec.rb +0 -390
  222. data/spec/flipper/registry_spec.rb +0 -140
  223. data/spec/flipper/serializers/gzip_spec.rb +0 -13
  224. data/spec/flipper/serializers/json_spec.rb +0 -13
  225. data/spec/flipper/typecast_spec.rb +0 -232
  226. data/spec/flipper/types/actor_spec.rb +0 -132
  227. data/spec/flipper/types/boolean_spec.rb +0 -23
  228. data/spec/flipper/types/group_spec.rb +0 -112
  229. data/spec/flipper/types/percentage_of_actors_spec.rb +0 -5
  230. data/spec/flipper/types/percentage_of_time_spec.rb +0 -5
  231. data/spec/flipper/types/percentage_spec.rb +0 -46
  232. data/spec/flipper_integration_spec.rb +0 -783
  233. data/spec/flipper_spec.rb +0 -422
  234. data/spec/spec_helper.rb +0 -112
  235. data/spec/support/actor_names.yml +0 -1
  236. data/spec/support/descriptions.yml +0 -1
  237. data/spec/support/fail_on_output.rb +0 -8
  238. data/spec/support/fake_backoff_policy.rb +0 -15
  239. data/spec/support/fake_udp_socket.rb +0 -27
  240. data/spec/support/skippable.rb +0 -18
  241. data/spec/support/spec_helpers.rb +0 -111
  242. data/test/adapters/actor_limit_test.rb +0 -20
  243. data/test/adapters/memory_test.rb +0 -9
  244. data/test/adapters/pstore_test.rb +0 -17
  245. data/test/test_helper.rb +0 -7
  246. data/test_rails/generators/flipper/setup_generator_test.rb +0 -69
  247. data/test_rails/generators/flipper/update_generator_test.rb +0 -96
  248. data/test_rails/helper.rb +0 -31
  249. data/test_rails/system/test_help_test.rb +0 -52
@@ -5,6 +5,9 @@ require "flipper/adapters/poll"
5
5
  require "flipper/poller"
6
6
  require "flipper/adapters/dual_write"
7
7
  require "flipper/adapters/sync/synchronizer"
8
+ require "flipper/cloud/memory_adapter"
9
+ require "flipper/cloud/shared_memory"
10
+ require "flipper/cloud/url_validator"
8
11
  require "flipper/cloud/telemetry"
9
12
  require "flipper/cloud/telemetry/instrumenter"
10
13
  require "flipper/cloud/telemetry/submitter"
@@ -20,13 +23,21 @@ module Flipper
20
23
 
21
24
  DEFAULT_URL = "https://www.flippercloud.io/adapter".freeze
22
25
 
26
+ # Seconds between polls when syncing by poll.
27
+ DEFAULT_POLL_SYNC_INTERVAL = 10
28
+
29
+ # Seconds between polls when syncing by webhook. Webhooks keep the local
30
+ # adapter current; this slow poll only catches missed webhooks.
31
+ DEFAULT_WEBHOOK_SYNC_INTERVAL = 300
32
+
23
33
  # Public: The token corresponding to an environment on flippercloud.io.
24
34
  attr_accessor :token
25
35
 
26
36
  # Public: The url for http adapter. Really should only be customized for
27
37
  # development work if you are me and you are not me. Feel free to
28
- # forget you ever saw this.
29
- attr_accessor :url
38
+ # forget you ever saw this. Must be https so the cloud token is
39
+ # never transmitted in cleartext (local development uses https too).
40
+ attr_reader :url
30
41
 
31
42
  # Public: net/http read timeout for all http requests (default: 5).
32
43
  attr_accessor :read_timeout
@@ -52,18 +63,19 @@ module Flipper
52
63
  # configuration.instrumenter = ActiveSupport::Notifications
53
64
  attr_accessor :instrumenter
54
65
 
55
- # Public: Local adapter that all reads should go to in order to ensure
56
- # latency is low and resiliency is high. This adapter is automatically
57
- # kept in sync with cloud.
66
+ # Public: Local adapter that is automatically kept in sync with cloud.
67
+ # Reads go to it to keep latency low and resiliency high. When Cloud is
68
+ # Flipper's default (Flipper::Cloud.set_default or the Rails engine),
69
+ # reads go to a Memory adapter in front of it instead.
58
70
  #
59
71
  # # for example, to use active record you could do:
60
72
  # configuration = Flipper::Cloud::Configuration.new
61
73
  # configuration.local_adapter = Flipper::Adapters::ActiveRecord.new
62
74
  attr_accessor :local_adapter
63
75
 
64
- # Public: The Integer or Float number of seconds between attempts to bring
65
- # the local in sync with cloud (default: 10).
66
- attr_accessor :sync_interval
76
+ # Public: Sets the Integer or Float number of seconds between attempts to
77
+ # bring the local in sync with cloud.
78
+ attr_writer :sync_interval
67
79
 
68
80
  # Public: The secret used to verify if syncs in the middleware should
69
81
  # occur or not.
@@ -109,18 +121,40 @@ module Flipper
109
121
  end
110
122
  end
111
123
 
124
+ # Public: The Integer or Float number of seconds between attempts to bring
125
+ # the local in sync with cloud (default: 10 when syncing by poll, 300
126
+ # when syncing by webhook).
127
+ def sync_interval
128
+ @sync_interval || (sync_method == :webhook ? DEFAULT_WEBHOOK_SYNC_INTERVAL : DEFAULT_POLL_SYNC_INTERVAL)
129
+ end
130
+
112
131
  # Public: Force a sync.
113
132
  def sync(cache_bust: false)
114
- Flipper::Adapters::Sync::Synchronizer.new(local_adapter, http_adapter, {
115
- instrumenter: instrumenter,
116
- cache_bust: cache_bust,
117
- }).call
133
+ remote = http_adapter
134
+ return synchronize(remote, cache_bust: cache_bust) unless @memory
135
+
136
+ # Fetch once for both the local adapter and memory.
137
+ snapshot = Flipper::Adapters::Memory.new(remote.get_all(cache_bust: cache_bust))
138
+ snapshot.sync_version = remote.sync_version
139
+ # Tracked like a poll's sync, so one that fails partway is synced again.
140
+ @memory.sync(snapshot.sync_version) { sync_memory(snapshot) }
141
+ nil
118
142
  end
119
143
 
120
144
  # Public: The method that will be used to synchronize local adapter with
121
- # cloud. (default: :poll, will be :webhook if sync_secret is set).
145
+ # cloud. (default: :poll, will be :webhook if sync_secret is non-empty).
122
146
  def sync_method
123
- sync_secret ? :webhook : :poll
147
+ if !sync_secret || sync_secret.empty?
148
+ :poll
149
+ else
150
+ :webhook
151
+ end
152
+ end
153
+
154
+ # Internal: Returns true when reads are served from the Memory adapter
155
+ # that every thread in the process shares.
156
+ def memory_reads?
157
+ !@memory.nil?
124
158
  end
125
159
 
126
160
  # Internal: The http client used by the http adapter. Exposed so we can
@@ -139,15 +173,71 @@ module Flipper
139
173
  instrumenter.instrument(name, payload, &block)
140
174
  end
141
175
 
176
+ def url=(value)
177
+ @url = UrlValidator.validate(value)
178
+ end
179
+
180
+ # Internal: Immutable identity for registries shared by Cloud endpoints.
181
+ def endpoint_key
182
+ [url.dup.freeze, token.dup.freeze].freeze
183
+ end
184
+
142
185
  private
143
186
 
144
187
  def app_adapter
145
- read_adapter = sync_method == :webhook ? local_adapter : poll_adapter
146
- Flipper::Adapters::DualWrite.new(read_adapter, http_adapter)
188
+ Flipper::Adapters::DualWrite.new(poll_adapter, http_adapter)
189
+ end
190
+
191
+ def synchronize(remote, options = {})
192
+ Flipper::Adapters::Sync::Synchronizer.new(local_adapter, remote, {
193
+ instrumenter: instrumenter,
194
+ }.merge(options)).call
195
+ end
196
+
197
+ # Syncs the local adapter, where the version check uses the version other
198
+ # processes share, then memory. Memory is updated even if the local
199
+ # adapter fails, and the next sync writes the local adapter again.
200
+ def sync_memory(snapshot)
201
+ synchronize(snapshot)
202
+ ensure
203
+ import_memory(snapshot)
204
+ end
205
+
206
+ # The sync skips a snapshot older than the local adapter, which another
207
+ # process synced, so memory takes the stored flags instead. It reads the
208
+ # storage itself, because a use adapter such as a cache can be behind.
209
+ def import_memory(snapshot)
210
+ if snapshot.sync_version&.older_than?(@store.sync_version)
211
+ @memory.import(@store, recopy: true)
212
+ else
213
+ @memory.import(snapshot)
214
+ end
215
+ rescue StandardError
216
+ @memory.import(snapshot)
217
+ end
218
+
219
+ # Builds the adapter Flipper.configure would, with memory in front of its
220
+ # storage for reads. Syncs go to the storage, and the adapters added with
221
+ # use wrap both.
222
+ def memory_adapter
223
+ fill_memory
224
+ # In webhook mode, other processes pick up a webhook's sync from the
225
+ # local adapter.
226
+ refresh_interval = DEFAULT_POLL_SYNC_INTERVAL if sync_method == :webhook
227
+ @adapter_builder.wrap(MemoryAdapter.new(@store, @memory, refresh_interval: refresh_interval))
228
+ end
229
+
230
+ # Memory starts empty in each process. Fill it from the local adapter
231
+ # until it has flags, so a Cloud outage at boot still has flags to read.
232
+ def fill_memory
233
+ return unless @memory.sync_version.nil? && @memory.features.empty?
234
+ @memory.import(@store, recopy: true)
235
+ rescue StandardError
236
+ # The local adapter is down. Poll fills memory from Cloud instead.
147
237
  end
148
238
 
149
239
  def poller
150
- Flipper::Poller.get(@url + @token, {
240
+ Flipper::Poller.get(endpoint_key, {
151
241
  interval: sync_interval,
152
242
  remote_adapter: http_adapter,
153
243
  instrumenter: instrumenter,
@@ -155,7 +245,32 @@ module Flipper
155
245
  end
156
246
 
157
247
  def poll_adapter
158
- Flipper::Adapters::Poll.new(poller, local_adapter)
248
+ poller = poller()
249
+ return Flipper::Adapters::Poll.new(poller, local_adapter) unless @memory
250
+
251
+ Flipper::Adapters::Poll.new(poller, memory_adapter, synchronizer: -> {
252
+ sync_poll(poller.adapter, poller.synced_at)
253
+ })
254
+ end
255
+
256
+ # Every thread's Poll calls this after each poll. Threads don't wait on
257
+ # each other, so ones that read while a new version syncs sync it too.
258
+ # Once the version is synced, one thread per poll checks whether another
259
+ # process stored a different one, so the rest don't query the local
260
+ # adapter. A check that fails gives the poll back to the next thread.
261
+ def sync_poll(snapshot, polled_at)
262
+ version = snapshot.sync_version
263
+ claimed = false
264
+ if @memory.synced?(version)
265
+ claimed = @memory.claim_store_check(polled_at)
266
+ return unless claimed
267
+ return if @store.sync_version == version
268
+ end
269
+
270
+ @memory.sync(version) { sync_memory(snapshot) }
271
+ rescue StandardError
272
+ # Reads keep working from memory if the local adapter is down.
273
+ @memory.release_store_check(polled_at) if claimed
159
274
  end
160
275
 
161
276
  def http_adapter
@@ -202,12 +317,27 @@ module Flipper
202
317
  end
203
318
 
204
319
  def setup_sync(options)
205
- set_option :sync_interval, options, default: 10, typecast: :float, minimum: 10
206
320
  set_option :sync_secret, options
321
+
322
+ # Left unset, sync_interval follows sync_method, which can change if
323
+ # sync_secret is set after initialize.
324
+ if options.key?(:sync_interval) || ENV.key?("FLIPPER_CLOUD_SYNC_INTERVAL")
325
+ set_option :sync_interval, options, typecast: :float, minimum: 10
326
+ end
207
327
  end
208
328
 
209
329
  def setup_adapter(options)
210
330
  set_option :local_adapter, options, default: -> { Adapters::Memory.new }, from_env: false
331
+ # Internal: Flipper::Cloud.set_default passes the Memory adapter that
332
+ # every thread shares and the Flipper::Configuration to build reads with.
333
+ @memory = options[:memory]
334
+ @adapter_builder = options[:adapter_builder]
335
+ if @adapter_builder
336
+ # One storage adapter: wrapped by the use adapters for syncs here,
337
+ # and behind memory for reads in memory_adapter.
338
+ @store = @adapter_builder.build_store
339
+ self.local_adapter = @adapter_builder.wrap(@store)
340
+ end
211
341
  @adapter_block = ->(adapter) { adapter }
212
342
  end
213
343
 
@@ -18,6 +18,12 @@ module Flipper
18
18
  @cloud_configuration.sync_secret
19
19
  end
20
20
 
21
+ # Internal: Reads served from memory leave a preload nothing to save,
22
+ # and it would copy every flag on every request.
23
+ def preload?
24
+ !@cloud_configuration.memory_reads?
25
+ end
26
+
21
27
  def inspect
22
28
  inspect_id = ::Kernel::format "%x", (object_id * 2)
23
29
  %(#<#{self.class}:0x#{inspect_id} @cloud_configuration=#{cloud_configuration.inspect}, flipper=#{__getobj__.inspect}>)
@@ -0,0 +1,43 @@
1
+ require "flipper/adapters/memory"
2
+ require "flipper/adapters/sync"
3
+ require "flipper/cloud/shared_memory"
4
+
5
+ module Flipper
6
+ module Cloud
7
+ # Internal: Serves reads from a Memory adapter that every thread in the
8
+ # process shares, so checking a feature never queries the local adapter.
9
+ # Writes go to the local adapter, then to Memory. The sync version is the
10
+ # local adapter's, because that is the one other processes share.
11
+ class MemoryAdapter < Adapters::Sync
12
+ # adapter - The local adapter, such as ActiveRecord.
13
+ # memory - The Flipper::Cloud::SharedMemory.
14
+ # refresh_interval - Seconds between reloads of memory from adapter, or
15
+ # nil to only copy adapter again after a copy that may
16
+ # have caught a sync partway. Webhook mode sets it,
17
+ # because only the process that gets a webhook syncs it.
18
+ def initialize(adapter, memory, refresh_interval: nil)
19
+ @reload = !refresh_interval.nil?
20
+ synchronizer = Adapters::Sync::IntervalSynchronizer.new(method(:refresh),
21
+ interval: refresh_interval || SharedMemory::RECOPY_INTERVAL)
22
+ super(memory, adapter, synchronizer: synchronizer)
23
+ end
24
+
25
+ def sync_version
26
+ @remote.sync_version
27
+ end
28
+
29
+ def sync_version=(version)
30
+ @remote.sync_version = version
31
+ @local.sync_version = version
32
+ end
33
+
34
+ private
35
+
36
+ def refresh
37
+ @reload ? @local.reload(@remote) : @local.recopy(@remote)
38
+ rescue StandardError
39
+ # Keep serving memory while the local adapter is down.
40
+ end
41
+ end
42
+ end
43
+ end
@@ -19,6 +19,7 @@ module Flipper
19
19
  @version = version || DEFAULT_VERSION
20
20
 
21
21
  raise ArgumentError, "secret should be a string" unless @secret.is_a?(String)
22
+ raise ArgumentError, "secret should not be empty" if @secret.empty?
22
23
  raise ArgumentError, "version should be a string" unless @version.is_a?(String)
23
24
  end
24
25
 
@@ -9,10 +9,15 @@ module Flipper
9
9
  WEBHOOK_PATH = %r{\A/webhooks\/?\Z}
10
10
  # Internal: The root path to match for requests.
11
11
  ROOT_PATH = %r{\A/\Z}
12
+ # Internal: Number of seconds a signed webhook remains valid. Bounds the
13
+ # window in which a captured, validly-signed request can be replayed,
14
+ # while staying loose enough to tolerate delivery retries and clock skew.
15
+ DEFAULT_SIGNATURE_TOLERANCE = 60 * 5
12
16
 
13
17
  def initialize(app, options = {})
14
18
  @app = app
15
19
  @env_key = options.fetch(:env_key, 'flipper')
20
+ @signature_tolerance = options.fetch(:signature_tolerance, DEFAULT_SIGNATURE_TOLERANCE)
16
21
  end
17
22
 
18
23
  def call(env)
@@ -27,17 +32,17 @@ module Flipper
27
32
  Rack::CONTENT_TYPE => "application/json",
28
33
  }
29
34
  body = "{}"
30
- payload = request.body.read
35
+ payload = request.body&.read || "" # rack.input is optional since Rack 3.1
31
36
  signature = request.env["HTTP_FLIPPER_CLOUD_SIGNATURE"]
32
37
  flipper = env.fetch(@env_key)
33
38
 
34
39
  begin
35
40
  message_verifier = MessageVerifier.new(secret: flipper.sync_secret)
36
- if message_verifier.verify(payload, signature)
41
+ if message_verifier.verify(payload, signature, tolerance: @signature_tolerance)
37
42
  begin
38
43
  flipper.sync(cache_bust: true)
39
44
  body = JSON.generate({
40
- groups: Flipper.group_names.map { |name| {name: name}}
45
+ groups: flipper.group_names.map { |name| {name: name}}
41
46
  })
42
47
  rescue Flipper::Adapters::Http::Error => error
43
48
  status = error.response.code.to_i == 402 ? 402 : 500
@@ -1,4 +1,5 @@
1
1
  require "flipper/adapters/http/client"
2
+ require "flipper/cloud/url_validator"
2
3
  require "flipper/typecast"
3
4
 
4
5
  module Flipper
@@ -55,7 +56,7 @@ module Flipper
55
56
 
56
57
  # Private: Build an HTTP client for Cloud API requests.
57
58
  def self.build_client(path, headers: {})
58
- base_url = ENV.fetch("FLIPPER_CLOUD_URL", DEFAULT_CLOUD_URL)
59
+ base_url = UrlValidator.validate(ENV.fetch("FLIPPER_CLOUD_URL", DEFAULT_CLOUD_URL))
59
60
 
60
61
  Flipper::Adapters::Http::Client.new(
61
62
  url: "#{base_url}#{path}",
@@ -67,5 +68,6 @@ module Flipper
67
68
  )
68
69
  end
69
70
  private_class_method :build_client
71
+
70
72
  end
71
73
  end
@@ -1,6 +1,8 @@
1
1
  # Default routes loaded by Flipper::Cloud::Engine
2
2
  Rails.application.routes.draw do
3
- if ENV["FLIPPER_CLOUD_TOKEN"] && ENV["FLIPPER_CLOUD_SYNC_SECRET"]
3
+ cloud_mounts = []
4
+
5
+ if ENV["FLIPPER_CLOUD_TOKEN"] && !ENV.fetch("FLIPPER_CLOUD_SYNC_SECRET", "").empty?
4
6
  require 'flipper/cloud'
5
7
  config = Rails.application.config.flipper
6
8
 
@@ -9,6 +11,26 @@ Rails.application.routes.draw do
9
11
  memoizer_options: { preload: config.preload }
10
12
  )
11
13
 
12
- mount cloud_app, at: config.cloud_path
14
+ cloud_mounts << [config.cloud_path, cloud_app]
15
+ end
16
+
17
+ unless Rails.application.config.flipper.test_help
18
+ Flipper.send(:named_configurations).each do |named|
19
+ path = named.cloud_webhook_path
20
+ next unless path
21
+
22
+ require "flipper/cloud"
23
+ cloud_app = Flipper::Cloud.app(Flipper.named(named.name),
24
+ env_key: named.env_key,
25
+ memoizer_options: { preload: named.preload }
26
+ )
27
+ cloud_mounts << [path, cloud_app]
28
+ end
29
+ end
30
+
31
+ cloud_mounts.sort_by do |path, _|
32
+ -Flipper::Engine.normalize_cloud_path(path).length
33
+ end.each do |path, cloud_app|
34
+ mount cloud_app, at: path
13
35
  end
14
36
  end
@@ -0,0 +1,111 @@
1
+ require "flipper/adapters/memory"
2
+
3
+ module Flipper
4
+ module Cloud
5
+ # Internal: The Memory adapter that every thread in a process reads from.
6
+ # It also remembers the last Cloud version the process synced, so threads
7
+ # skip syncing the local adapter after a poll that changed nothing.
8
+ class SharedMemory < Adapters::Memory
9
+ # Seconds a copy of the local adapter must match memory's last change
10
+ # from one to show that no sync was still writing it.
11
+ RECOPY_INTERVAL = 1
12
+
13
+ def initialize(source = nil, threadsafe: true)
14
+ super
15
+ @syncing = Hash.new(0)
16
+ @overlaps = 0
17
+ @recopy = false
18
+ @changed_at = 0
19
+ end
20
+
21
+ # Public: Imports flags. Pass recopy: true when source is the local
22
+ # adapter, which another process may be syncing. A sync writes its
23
+ # version before its flags, so the copy can have only some of them under
24
+ # the new version. reload then copies again until a copy changes nothing
25
+ # RECOPY_INTERVAL after the last one that did.
26
+ def import(source, recopy: false)
27
+ super(source) do |features, version|
28
+ @changed_at = now if recopy && (version != @sync_version || features != @source)
29
+ @recopy = recopy && now - @changed_at < RECOPY_INTERVAL
30
+ end
31
+ end
32
+
33
+ # Public: Imports the local adapter if another process synced a new
34
+ # version, or if the last copy may have caught a sync partway.
35
+ def reload(store)
36
+ version = store.sync_version
37
+ return if version.nil?
38
+
39
+ import(store, recopy: true) if version != sync_version || recopy_due?
40
+ end
41
+
42
+ # Public: Imports the local adapter again only if the last copy may have
43
+ # caught a sync partway. Reads nothing from it otherwise.
44
+ def recopy(store)
45
+ import(store, recopy: true) if recopy_due?
46
+ end
47
+
48
+ # Public: Returns true if a sync of version finished in this process.
49
+ def synced?(version)
50
+ !version.nil? && synchronize { @synced_version == version }
51
+ end
52
+
53
+ # Public: Returns true for the first thread to ask about the poll at
54
+ # polled_at, and false for the rest, so one thread per poll checks the
55
+ # local adapter's version. A thread still on an older poll gets false.
56
+ def claim_store_check(polled_at)
57
+ synchronize do
58
+ return false if @store_checked_at && polled_at <= @store_checked_at
59
+ @store_checked_at = polled_at
60
+ true
61
+ end
62
+ end
63
+
64
+ # Public: Gives back a claim whose check failed, so the next thread to
65
+ # read checks the poll at polled_at again.
66
+ def release_store_check(polled_at)
67
+ synchronize { @store_checked_at = nil if @store_checked_at == polled_at }
68
+ end
69
+
70
+ # Public: Runs the block that syncs version, then records it as synced.
71
+ # Records nothing if the block raises or a sync of another version ran at
72
+ # the same time, because an older sync can write its flags after a newer
73
+ # one. The next poll then syncs again and repairs them. Threads syncing
74
+ # the same version write the same flags, so they can still record it,
75
+ # but one that raises may have left flags half written, so it forgets
76
+ # the recorded version and keeps syncs still running from recording.
77
+ def sync(version)
78
+ alone, overlaps = synchronize do
79
+ other_version = @syncing.any? { |syncing_version, _| syncing_version != version }
80
+ @overlaps += 1 if other_version
81
+ @syncing[version] += 1
82
+ [!other_version, @overlaps]
83
+ end
84
+ finished = false
85
+ yield
86
+ finished = true
87
+ ensure
88
+ synchronize do
89
+ @syncing[version] -= 1
90
+ @syncing.delete(version) if @syncing[version] <= 0
91
+ if finished
92
+ @synced_version = version if alone && overlaps == @overlaps
93
+ else
94
+ @overlaps += 1
95
+ @synced_version = nil
96
+ end
97
+ end
98
+ end
99
+
100
+ private
101
+
102
+ def recopy_due?
103
+ synchronize { @recopy && now - @changed_at >= RECOPY_INTERVAL }
104
+ end
105
+
106
+ def now
107
+ Process.clock_gettime(Process::CLOCK_MONOTONIC, :second)
108
+ end
109
+ end
110
+ end
111
+ end
@@ -19,11 +19,11 @@ module Flipper
19
19
  instances.each { |_, instance| instance.stop }.clear
20
20
  end
21
21
 
22
- # Internal: Fetch an instance of telemetry once per process per url +
23
- # token (aka cloud endpoint). Should only ever be one instance unless you
22
+ # Internal: Fetch an instance of telemetry once per process per cloud
23
+ # endpoint. Should only ever be one instance unless you
24
24
  # are doing some funky stuff.
25
25
  def self.instance_for(cloud_configuration)
26
- instances.compute_if_absent(cloud_configuration.url + cloud_configuration.token) do
26
+ instances.compute_if_absent(cloud_configuration.endpoint_key) do
27
27
  new(cloud_configuration)
28
28
  end
29
29
  end
@@ -51,6 +51,7 @@ module Flipper
51
51
 
52
52
  def initialize(cloud_configuration)
53
53
  @pid = $$
54
+ @mutex = Mutex.new
54
55
  @cloud_configuration = cloud_configuration
55
56
  self.interval = ENV.fetch("FLIPPER_TELEMETRY_INTERVAL", 60).to_f
56
57
  self.shutdown_timeout = ENV.fetch("FLIPPER_TELEMETRY_SHUTDOWN_TIMEOUT", 5).to_f
@@ -71,6 +72,37 @@ module Flipper
71
72
 
72
73
  # Public: Start all the tasks and setup new metric storage.
73
74
  def start
75
+ @mutex.synchronize { start! }
76
+ end
77
+
78
+ # Public: Shuts down all the tasks and tries to flush any remaining info to Cloud.
79
+ def stop
80
+ @mutex.synchronize { stop! }
81
+ end
82
+
83
+ # Public: Restart all the tasks and reset the storage.
84
+ def restart
85
+ @mutex.synchronize { restart! }
86
+ end
87
+
88
+ # Internal: Sets the interval in seconds for how often telemetry should be sent to cloud.
89
+ def interval=(value)
90
+ new_interval = [Typecast.to_float(value), 10].max
91
+ @timer&.execution_interval = new_interval
92
+ @interval = new_interval
93
+ end
94
+
95
+ # Internal: Sets the timeout in seconds for how long to wait for the pool to shutdown.
96
+ def shutdown_timeout=(value)
97
+ new_shutdown_timeout = [Typecast.to_float(value), 0.1].max
98
+ @shutdown_timeout = new_shutdown_timeout
99
+ end
100
+
101
+ private
102
+
103
+ # Internal: Start all the tasks and setup new metric storage. Callers must
104
+ # hold @mutex.
105
+ def start!
74
106
  info "action=start"
75
107
 
76
108
  @metric_storage = MetricStorage.new
@@ -87,8 +119,9 @@ module Flipper
87
119
  }) { post_to_pool }
88
120
  end
89
121
 
90
- # Public: Shuts down all the tasks and tries to flush any remaining info to Cloud.
91
- def stop
122
+ # Internal: Shuts down all the tasks and tries to flush any remaining info
123
+ # to Cloud. Callers must hold @mutex.
124
+ def stop!
92
125
  info "action=stop"
93
126
 
94
127
  if @timer
@@ -111,31 +144,22 @@ module Flipper
111
144
  end
112
145
  end
113
146
 
114
- # Public: Restart all the tasks and reset the storage.
115
- def restart
116
- stop
117
- start
118
- end
119
-
120
- # Internal: Sets the interval in seconds for how often telemetry should be sent to cloud.
121
- def interval=(value)
122
- new_interval = [Typecast.to_float(value), 10].max
123
- @timer&.execution_interval = new_interval
124
- @interval = new_interval
125
- end
126
-
127
- # Internal: Sets the timeout in seconds for how long to wait for the pool to shutdown.
128
- def shutdown_timeout=(value)
129
- new_shutdown_timeout = [Typecast.to_float(value), 0.1].max
130
- @shutdown_timeout = new_shutdown_timeout
147
+ # Internal: Restart all the tasks and reset the storage. Callers must hold
148
+ # @mutex.
149
+ def restart!
150
+ stop!
151
+ start!
131
152
  end
132
153
 
133
- private
134
-
135
154
  def detect_forking
136
- if @pid != $$
137
- info "action=fork_detected pid_was#{@pid} pid_is=#{$$}"
138
- restart
155
+ # Lock-free fast path: only contend for @mutex when a fork is actually
156
+ # detected. The inner check ensures just one thread performs the restart.
157
+ return if @pid == $$
158
+
159
+ @mutex.synchronize do
160
+ return if @pid == $$
161
+ info "action=fork_detected pid_was=#{@pid} pid_is=#{$$}"
162
+ restart!
139
163
  @pid = $$
140
164
  end
141
165
  end
@@ -163,7 +187,11 @@ module Flipper
163
187
  if response
164
188
  if Flipper::Typecast.to_boolean(response["telemetry-shutdown"])
165
189
  debug "action=telemetry_shutdown message=The server has requested that telemetry be shut down."
166
- stop
190
+ # Stop from a separate thread to avoid a deadlock: this code runs on
191
+ # the pool worker, and stop acquires @mutex and then waits for that
192
+ # same worker to terminate. Calling stop inline would block the
193
+ # worker on @mutex while the mutex holder waits on the worker.
194
+ Thread.new { stop }
167
195
  return
168
196
  end
169
197
 
@@ -0,0 +1,26 @@
1
+ require "uri"
2
+
3
+ module Flipper
4
+ module Cloud
5
+ module UrlValidator
6
+ def self.validate(value)
7
+ url = value.to_s.dup
8
+ uri = URI(url)
9
+
10
+ return url.freeze if uri.is_a?(URI::HTTPS) && !uri.host.to_s.empty?
11
+
12
+ raise_invalid_url(value)
13
+ rescue URI::InvalidURIError
14
+ raise_invalid_url(value)
15
+ end
16
+
17
+ def self.raise_invalid_url(value)
18
+ raise ArgumentError,
19
+ "Flipper::Cloud url must use https but was #{value.inspect}. " \
20
+ "https is required so your token is never sent in cleartext."
21
+ end
22
+ private_class_method :raise_invalid_url
23
+ end
24
+ private_constant :UrlValidator
25
+ end
26
+ end