flipt_client 1.3.4 → 1.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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: cc6e05db5d629045ebd0e989009830ec89bdece6866b8e11a62c54e55d69371e
4
- data.tar.gz: 7640a1226b07a8d6faa19049f4ce18e10a7502f0a462ae09f29ab14020d60ba4
3
+ metadata.gz: 557558c4deb7009f0083aca1bcc8b1f152fa732aeed18e2bece3127c1f89f022
4
+ data.tar.gz: 62153639f038c37ec4fbc26cc90d58431f451d2a802bda2aa7850134d3d92eea
5
5
  SHA512:
6
- metadata.gz: d0096957dee8b6902174d92cffea478cc1cc2b5ae51728e2d9b8c637509b1c00945975b99dc27cb87212c1558bf7739fff17d5bd113338209caf8bfe802b4fe1
7
- data.tar.gz: af9ff7dc2b0ecbdacc8e8f6b848d54faa9e9eb26ef12ba5e65220021cb4c4b775553430160c143e950ae4ca2b07dcb6ceb5464e3ff6a686cbde726db8c873ffc
6
+ metadata.gz: 412b0e39560984b1e049f3bbf7062aa90725cb63e87830b4439650aec1785b08d65c92f1833e2050aa811c719510b74995152c520b8f81357dd384e328149acb
7
+ data.tar.gz: f67a7b06cc2dbfeba6792214a759ab63e4bc76c7f21c761e37daa61417837b7f4ace73c6fdb0c4b1716d612ce613a7f2c6c50bc973d57300018a5342f36fb543
data/README.md CHANGED
@@ -98,6 +98,9 @@ puts resp.reason # => 'MATCH_EVALUATION_REASON'
98
98
 
99
99
  resp = client.evaluate_boolean(flag_key: 'my-feature', entity_id: 'someentity')
100
100
  puts resp.enabled # => true
101
+
102
+ # Release the engine when you are done with the client
103
+ client.close
101
104
  ```
102
105
 
103
106
  ### Constructor Arguments
@@ -115,6 +118,7 @@ The `Flipt::Client` constructor accepts the following keyword arguments:
115
118
  - `error_strategy`: The error strategy to use. Defaults to fail. See [Error Strategies](#error-strategies).
116
119
  - `snapshot`: The snapshot to use when initializing the client. Defaults to no snapshot. See [Snapshotting](#snapshotting).
117
120
  - `tls_config`: The TLS configuration for connecting to servers with custom certificates. See [TLS Configuration](#tls-configuration).
121
+ - `on_state_update`: Anything that responds to `call` (for example a lambda), called with no arguments after the client applies changed flag state. See [State Update Listeners](#state-update-listeners).
118
122
 
119
123
  ### Authentication
120
124
 
@@ -291,6 +295,43 @@ You also may want to store the snapshot in a local file so that you can use it t
291
295
  > [!IMPORTANT]
292
296
  > If the Flipt server becomes reachable after the setting the snapshot, the client will replace the snapshot with the new flag state from the Flipt server.
293
297
 
298
+ ### State Update Listeners
299
+
300
+ The client can tell you when flag state changes, so you can re-read the flags you care about instead of re-evaluating them on a timer. This works in both polling and streaming mode.
301
+
302
+ Register a listener when you create the client:
303
+
304
+ ```ruby
305
+ client = Flipt::Client.new(
306
+ url: 'http://localhost:8080',
307
+ fetch_mode: :streaming,
308
+ on_state_update: -> { refresh_flags }
309
+ )
310
+ ```
311
+
312
+ Or add and remove listeners while the client is running, with a block or anything that responds to `call`:
313
+
314
+ ```ruby
315
+ subscription = client.add_state_update_listener { refresh_flags }
316
+
317
+ # Later, to stop listening:
318
+ subscription.close
319
+ ```
320
+
321
+ How listeners behave:
322
+
323
+ - **Only real changes.** A listener is called after the client applies flag state that differs from the current state. Unchanged polls and repeated streaming messages do not call it.
324
+ - **Not called for initial state.** The state loaded when the client is created doesn't trigger a listener, and a new listener hears about changes applied after it was added (occasionally with one extra call). Read the flags you need once when you register.
325
+ - **Errors don't trigger it.** A failed fetch does not call listeners. Recovering from a failure does.
326
+ - **One background thread.** Listeners run in the order they were added, on a single thread named `flipt-state-update` owned by the client. Updates that arrive while listeners run are merged into one follow-up call, so you always see the latest state but may not see every intermediate one.
327
+ - **Keep listeners fast.** A slow listener delays later notifications. Hand long work off to your own thread or job queue.
328
+ - **Safe to call back in.** A listener may evaluate flags, add or remove listeners, or call `close`.
329
+ - **`close` waits for a running listener.** When called from another thread, `close` lets a listener that is already running finish, then stops. A listener must not wait on a lock held by the thread that calls `close`, or the two will deadlock.
330
+ - **Errors are logged.** An exception raised by one listener is written to stderr and does not stop the other listeners.
331
+
332
+ > [!IMPORTANT]
333
+ > Always call `close` on a client that has listeners. The listener thread holds a reference to the client's listeners until it is closed, so it keeps running until you call `close`. No listener is called after `close` returns, and calling any client method after `close` raises `Flipt::Error`.
334
+
294
335
  ## Load Test
295
336
 
296
337
  1. To run the load test, you'll need to have Flipt running locally. You can do this by running the following command from the root of the repository:
@@ -13,6 +13,8 @@ Gem::Specification.new do |spec|
13
13
  spec.license = 'MIT'
14
14
  spec.required_ruby_version = Gem::Requirement.new('>= 2.7.0')
15
15
 
16
+ spec.add_dependency 'ffi', '~> 1.17'
17
+
16
18
  # spec.metadata['allowed_push_host'] = "TODO: Set to 'http://mygemserver.com'"
17
19
 
18
20
  spec.metadata['homepage_uri'] = spec.homepage
@@ -115,6 +115,92 @@ const char *update_authentication_ffi(void *engine_ptr, const char *auth_json);
115
115
  */
116
116
  const char *update_authentication(void *engine_ptr, const char *auth_json);
117
117
 
118
+ /**
119
+ * # Safety
120
+ *
121
+ * Subscribes to flag state changes applied after this call returns (a change
122
+ * applied just before may also be reported once), and returns a subscription
123
+ * handle, or null if `engine_ptr` is null. Pass the
124
+ * handle to `wait_for_state_update` from a thread the host owns.
125
+ *
126
+ * The handle holds its own reference to the engine's update state, so it
127
+ * stays valid after `destroy_engine`; waiting on it then reports `closed`.
128
+ * Free it with `destroy_state_subscription`.
129
+ */
130
+ void *subscribe_state_updates_ffi(void *engine_ptr);
131
+
132
+ /**
133
+ * # Safety
134
+ *
135
+ * Subscribes to flag state changes applied after this call returns (a change
136
+ * applied just before may also be reported once), and returns a subscription
137
+ * handle, or null if `engine_ptr` is null. Pass the
138
+ * handle to `wait_for_state_update` from a thread the host owns.
139
+ *
140
+ * The handle holds its own reference to the engine's update state, so it
141
+ * stays valid after `destroy_engine`; waiting on it then reports `closed`.
142
+ * Free it with `destroy_state_subscription`.
143
+ */
144
+ void *subscribe_state_updates(void *engine_ptr);
145
+
146
+ /**
147
+ * # Safety
148
+ *
149
+ * Blocks until flag state changes, or until the subscription or engine is
150
+ * closed. Returns a JSON response whose `result` is `"changed"` or
151
+ * `"closed"`. Changes that land while the host is busy are coalesced into
152
+ * one `"changed"`. Initial state and transitions into an error state are
153
+ * not reported; recovering from an error is. Once a wait returns `"closed"`,
154
+ * every later wait does too, without blocking.
155
+ */
156
+ const char *wait_for_state_update_ffi(void *subscription_ptr);
157
+
158
+ /**
159
+ * # Safety
160
+ *
161
+ * Blocks until flag state changes, or until the subscription or engine is
162
+ * closed. Returns a JSON response whose `result` is `"changed"` or
163
+ * `"closed"`. Changes that land while the host is busy are coalesced into
164
+ * one `"changed"`. Initial state and transitions into an error state are
165
+ * not reported; recovering from an error is. Once a wait returns `"closed"`,
166
+ * every later wait does too, without blocking.
167
+ */
168
+ const char *wait_for_state_update(void *subscription_ptr);
169
+
170
+ /**
171
+ * # Safety
172
+ *
173
+ * Wakes any thread blocked in `wait_for_state_update` on this subscription
174
+ * and makes every later wait return `"closed"`. Safe to call from any thread,
175
+ * and more than once. Does not free the handle.
176
+ */
177
+ void close_state_subscription_ffi(void *subscription_ptr);
178
+
179
+ /**
180
+ * # Safety
181
+ *
182
+ * Wakes any thread blocked in `wait_for_state_update` on this subscription
183
+ * and makes every later wait return `"closed"`. Safe to call from any thread,
184
+ * and more than once. Does not free the handle.
185
+ */
186
+ void close_state_subscription(void *subscription_ptr);
187
+
188
+ /**
189
+ * # Safety
190
+ *
191
+ * Closes and frees a subscription handle. No other thread may be using the
192
+ * handle, including waiting on it, when this is called.
193
+ */
194
+ void destroy_state_subscription_ffi(void *subscription_ptr);
195
+
196
+ /**
197
+ * # Safety
198
+ *
199
+ * Closes and frees a subscription handle. No other thread may be using the
200
+ * handle, including waiting on it, when this is called.
201
+ */
202
+ void destroy_state_subscription(void *subscription_ptr);
203
+
118
204
  /**
119
205
  * # Safety
120
206
  *
Binary file
Binary file
@@ -0,0 +1,128 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Flipt
4
+ # Subscription is a registered state update listener. Closing it unsubscribes; closing twice is a no-op.
5
+ class Subscription
6
+ def initialize(&unsubscribe)
7
+ @unsubscribe = unsubscribe
8
+ end
9
+
10
+ # Remove the listener
11
+ def close
12
+ @unsubscribe.call
13
+ nil
14
+ end
15
+ end
16
+
17
+ # StateUpdates owns the single thread that waits on the engine for flag state changes and fans
18
+ # out to the client's listeners. It is internal to Client.
19
+ class StateUpdates
20
+ def initialize(engine)
21
+ @engine = engine
22
+ # Guards everything below. Never held while running listeners or joining the thread.
23
+ @mutex = Mutex.new
24
+ @closed = false
25
+ # Replaced, never mutated, so the thread can iterate a snapshot without the mutex.
26
+ @listeners = [].freeze
27
+ # Started on the first listener. It owns the native subscription and frees it on exit.
28
+ @thread = nil
29
+ @subscription = nil
30
+ end
31
+
32
+ def add(listener)
33
+ # A distinct wrapper per call, so adding the same callable twice yields two independent
34
+ # subscriptions.
35
+ entry = proc { listener.call }
36
+ @mutex.synchronize do
37
+ raise Error, 'client is closed' if @closed
38
+
39
+ ensure_thread
40
+ @listeners = (@listeners + [entry]).freeze
41
+ end
42
+ Subscription.new { remove(entry) }
43
+ end
44
+
45
+ # Marks the client closed, wakes the thread and waits for a running listener to return, unless
46
+ # called from that listener. Returns false if already closed.
47
+ def close
48
+ thread = nil
49
+ @mutex.synchronize do
50
+ return false if @closed
51
+
52
+ @closed = true
53
+ thread = @thread
54
+ # Wakes the thread if it is waiting. It still owns and frees the handle.
55
+ Client.close_state_subscription(@subscription) if @subscription
56
+ end
57
+ # Let a running listener finish before the engine it may be evaluating against is freed.
58
+ thread.join if thread && !thread.equal?(Thread.current)
59
+ @listeners = [].freeze
60
+ true
61
+ end
62
+
63
+ private
64
+
65
+ def remove(entry)
66
+ @mutex.synchronize do
67
+ @listeners = @listeners.reject { |existing| existing.equal?(entry) }.freeze
68
+ end
69
+ end
70
+
71
+ # Called with the mutex held. The thread runs until close, so adding or removing listeners
72
+ # never calls into the engine, including from inside a listener.
73
+ def ensure_thread
74
+ return if @thread
75
+
76
+ subscription = Client.subscribe_state_updates(@engine)
77
+ raise EvaluationError, 'Failed to subscribe to state updates' if subscription.null?
78
+
79
+ begin
80
+ thread = Thread.new { run(subscription) }
81
+ rescue StandardError
82
+ Client.destroy_state_subscription(subscription)
83
+ raise
84
+ end
85
+ thread.name = 'flipt-state-update'
86
+ # The thread can't exit before these are set: its cleanup takes the mutex we hold.
87
+ @subscription = subscription
88
+ @thread = thread
89
+ end
90
+
91
+ def run(subscription)
92
+ until @closed
93
+ resp, ptr = Client.wait_for_state_update(subscription)
94
+ Client.destroy_string(ptr)
95
+ data = JSON.parse(resp)
96
+ if data['status'] != 'success'
97
+ warn "[flipt] Failed to wait for state update: #{data['error_message'] || 'Unknown error'}"
98
+ return
99
+ end
100
+ return if data['result'] != 'changed'
101
+
102
+ @listeners.each do |listener|
103
+ # Leaves the loop too, since the until condition sees @closed.
104
+ break if @closed
105
+
106
+ begin
107
+ listener.call
108
+ # Exception, so a listener raising NotImplementedError or calling exit is logged and does
109
+ # not silently stop notifications for the others.
110
+ rescue Exception => e # rubocop:disable Lint/RescueException
111
+ warn "[flipt] State update listener raised: #{e.class}: #{e.message}"
112
+ end
113
+ end
114
+ end
115
+ rescue StandardError => e
116
+ warn "[flipt] State update thread failed: #{e.class}: #{e.message}"
117
+ ensure
118
+ # This thread is the only one that waits on the subscription, so it frees it. Under the
119
+ # mutex, so close never wakes a handle that is already freed.
120
+ @mutex.synchronize do
121
+ @subscription = nil
122
+ Client.destroy_state_subscription(subscription)
123
+ # If this thread died early, the next listener starts a new one.
124
+ @thread = nil if @thread.equal?(Thread.current)
125
+ end
126
+ end
127
+ end
128
+ end
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Flipt
4
- VERSION = '1.3.4'
4
+ VERSION = '1.4.0'
5
5
  end
data/lib/flipt_client.rb CHANGED
@@ -2,6 +2,7 @@
2
2
 
3
3
  require 'flipt_client/version'
4
4
  require 'flipt_client/models'
5
+ require 'flipt_client/state_updates'
5
6
  require 'ffi'
6
7
  require 'json'
7
8
 
@@ -35,9 +36,11 @@ module Flipt
35
36
  ffi_lib File.expand_path(libfile, __dir__)
36
37
 
37
38
  # void *initialize_engine(const char *opts);
38
- attach_function :initialize_engine, [:string], :pointer
39
+ # Does the initial fetch, and destroy_engine stops the fetch thread, so both release the GVL
40
+ # to let other Ruby threads run while they wait on the network.
41
+ attach_function :initialize_engine, [:string], :pointer, blocking: true
39
42
  # void destroy_engine(void *engine_ptr);
40
- attach_function :destroy_engine, [:pointer], :void
43
+ attach_function :destroy_engine, [:pointer], :void, blocking: true
41
44
  # const char *evaluate_variant(void *engine_ptr, const char *evaluation_request);
42
45
  attach_function :evaluate_variant, %i[pointer string], :strptr
43
46
  # const char *evaluate_boolean(void *engine_ptr, const char *evaluation_request);
@@ -50,6 +53,15 @@ module Flipt
50
53
  attach_function :destroy_string, [:pointer], :void
51
54
  # const char *get_snapshot(void *engine_ptr);
52
55
  attach_function :get_snapshot, [:pointer], :strptr
56
+ # void *subscribe_state_updates(void *engine_ptr);
57
+ attach_function :subscribe_state_updates, [:pointer], :pointer
58
+ # const char *wait_for_state_update(void *subscription_ptr);
59
+ # Blocks until flag state changes or the subscription closes, so it releases the GVL.
60
+ attach_function :wait_for_state_update, [:pointer], :strptr, blocking: true
61
+ # void close_state_subscription(void *subscription_ptr);
62
+ attach_function :close_state_subscription, [:pointer], :void
63
+ # void destroy_state_subscription(void *subscription_ptr);
64
+ attach_function :destroy_state_subscription, [:pointer], :void
53
65
 
54
66
  # Create a new Flipt client
55
67
  #
@@ -66,8 +78,10 @@ module Flipt
66
78
  # @option opts [Symbol] :error_strategy error strategy to use for the client (:fail or :fallback).
67
79
  # @option opts [String] :snapshot snapshot to use when initializing the client
68
80
  # @option opts [TlsConfig] :tls_config TLS configuration for connecting to servers with custom certificates
81
+ # @option opts [#call] :on_state_update called with no arguments after the client applies changed flag state
69
82
  def initialize(**opts)
70
83
  @namespace = opts.fetch(:namespace, 'default')
84
+ on_state_update = opts.delete(:on_state_update)
71
85
 
72
86
  opts[:authentication] = validate_authentication(opts.fetch(:authentication, NoAuthentication.new))
73
87
  opts[:fetch_mode] = validate_fetch_mode(opts.fetch(:fetch_mode, :polling))
@@ -76,6 +90,49 @@ module Flipt
76
90
 
77
91
  @engine = self.class.initialize_engine(opts.to_json)
78
92
  ObjectSpace.define_finalizer(self, self.class.finalize(@engine))
93
+ @state_updates = StateUpdates.new(@engine)
94
+
95
+ return if on_state_update.nil?
96
+
97
+ begin
98
+ add_state_update_listener(on_state_update)
99
+ rescue StandardError
100
+ # The caller never gets a client to close, so tear the engine down here.
101
+ close
102
+ raise
103
+ end
104
+ end
105
+
106
+ # Close the client and release the engine. When called from a thread other than the state
107
+ # update thread, waits for a running listener to return first. Closing twice is a no-op.
108
+ def close
109
+ return unless @state_updates.close
110
+
111
+ # Clear the pointer before destroying: destroy_engine releases the GVL, so other threads
112
+ # keep running and must see a closed client rather than a pointer being freed.
113
+ engine = @engine
114
+ @engine = nil
115
+ ObjectSpace.undefine_finalizer(self)
116
+ self.class.destroy_engine(engine)
117
+ end
118
+
119
+ # Add a listener that is called after each change to flag state. Read the flags you care
120
+ # about once after adding a listener: it is called for changes applied after it was added,
121
+ # and may occasionally see one extra call.
122
+ #
123
+ # Listeners run in the order they were added, on a single thread named flipt-state-update.
124
+ # Updates that arrive while they run are coalesced into a single follow-up call. A listener
125
+ # may evaluate flags, add or remove listeners, or call close. close from another thread waits
126
+ # for a running listener to return. An error raised by one listener is logged and does not
127
+ # stop the others. The client must be closed to stop its update thread.
128
+ #
129
+ # @param listener [#call] the listener to call, or pass a block
130
+ # @return [Subscription] a subscription that removes the listener when closed
131
+ def add_state_update_listener(listener = nil, &block)
132
+ listener ||= block
133
+ raise ValidationError, 'listener must respond to call' unless listener.respond_to?(:call)
134
+
135
+ @state_updates.add(listener)
79
136
  end
80
137
 
81
138
  def self.finalize(engine)
@@ -90,7 +147,7 @@ module Flipt
90
147
  def evaluate_variant(flag_key:, entity_id:, context: {})
91
148
  validate_evaluation_request(flag_key, entity_id, context)
92
149
  req = { flag_key: flag_key, entity_id: entity_id, context: context }
93
- resp, ptr = self.class.evaluate_variant(@engine, req.to_json)
150
+ resp, ptr = self.class.evaluate_variant(open_engine, req.to_json)
94
151
  ptr = FFI::AutoPointer.new(ptr, Client.method(:destroy_string))
95
152
  data = JSON.parse(resp)
96
153
  raise EvaluationError, data['error_message'] if data['status'] != 'success'
@@ -114,7 +171,7 @@ module Flipt
114
171
  def evaluate_boolean(flag_key:, entity_id:, context: {})
115
172
  validate_evaluation_request(flag_key, entity_id, context)
116
173
  req = { flag_key: flag_key, entity_id: entity_id, context: context }
117
- resp, ptr = self.class.evaluate_boolean(@engine, req.to_json)
174
+ resp, ptr = self.class.evaluate_boolean(open_engine, req.to_json)
118
175
  ptr = FFI::AutoPointer.new(ptr, Client.method(:destroy_string))
119
176
  data = JSON.parse(resp)
120
177
  raise EvaluationError, data['error_message'] if data['status'] != 'success'
@@ -141,7 +198,7 @@ module Flipt
141
198
  requests.each do |request|
142
199
  validate_evaluation_request(request[:flag_key], request[:entity_id], request[:context] || {})
143
200
  end
144
- resp, ptr = self.class.evaluate_batch(@engine, requests.to_json)
201
+ resp, ptr = self.class.evaluate_batch(open_engine, requests.to_json)
145
202
  ptr = FFI::AutoPointer.new(ptr, Client.method(:destroy_string))
146
203
  data = JSON.parse(resp)
147
204
  raise EvaluationError, data['error_message'] if data['status'] != 'success'
@@ -183,7 +240,7 @@ module Flipt
183
240
 
184
241
  # List all flags in the namespace
185
242
  def list_flags
186
- resp, ptr = self.class.list_flags(@engine)
243
+ resp, ptr = self.class.list_flags(open_engine)
187
244
  ptr = FFI::AutoPointer.new(ptr, Client.method(:destroy_string))
188
245
  data = JSON.parse(resp)
189
246
  raise Error, data['error_message'] if data['status'] != 'success'
@@ -193,13 +250,20 @@ module Flipt
193
250
 
194
251
  # Get the snapshot of the current flag state
195
252
  def snapshot
196
- resp, ptr = self.class.get_snapshot(@engine)
253
+ resp, ptr = self.class.get_snapshot(open_engine)
197
254
  ptr = FFI::AutoPointer.new(ptr, Client.method(:destroy_string))
198
255
  resp
199
256
  end
200
257
 
201
258
  private
202
259
 
260
+ def open_engine
261
+ engine = @engine
262
+ raise Error, 'client is closed' if engine.nil?
263
+
264
+ engine
265
+ end
266
+
203
267
  def validate_evaluation_request(flag_key, entity_id, context)
204
268
  raise ValidationError, 'flag_key is required' if flag_key.nil? || flag_key.empty?
205
269
  raise ValidationError, 'entity_id is required' if entity_id.nil? || entity_id.empty?
metadata CHANGED
@@ -1,15 +1,29 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: flipt_client
3
3
  version: !ruby/object:Gem::Version
4
- version: 1.3.4
4
+ version: 1.4.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Flipt Devs
8
8
  autorequire:
9
9
  bindir: exe
10
10
  cert_chain: []
11
- date: 2026-08-28 00:00:00.000000000 Z
12
- dependencies: []
11
+ date: 2026-11-06 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: ffi
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '1.17'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '1.17'
13
27
  description: Flipt Client Evaluation SDK
14
28
  email:
15
29
  - dev@flipt.io
@@ -27,6 +41,7 @@ files:
27
41
  - lib/ext/windows_x86_64/fliptengine.dll
28
42
  - lib/flipt_client.rb
29
43
  - lib/flipt_client/models.rb
44
+ - lib/flipt_client/state_updates.rb
30
45
  - lib/flipt_client/version.rb
31
46
  homepage: https://www.flipt.io
32
47
  licenses: