Class: Shipeasy::SDK::FlagsClient

Inherits:
Object
  • Object
show all
Defined in:
lib/shipeasy/sdk/flags_client.rb

Defined Under Namespace

Classes: FlagDetail

Constant Summary collapse

DEFAULT_BASE_URL =
"https://edge.shipeasy.dev"
REASON_CLIENT_NOT_READY =

Reason constants for FlagDetail#reason / get_flag_detail.

"CLIENT_NOT_READY"
REASON_FLAG_NOT_FOUND =

no blob fetched/loaded yet

"FLAG_NOT_FOUND"
REASON_OFF =

blob present, gate absent

"OFF"
REASON_OVERRIDE =

gate present but disabled/killed

"OVERRIDE"
REASON_RULE_MATCH =

answered by a local override

"RULE_MATCH"
REASON_DEFAULT =

evaluated true

"DEFAULT"

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(api_key:, base_url: nil, env: "prod", disable_telemetry: false, telemetry_url: nil, test_mode: false, private_attributes: nil, sticky_store: nil) ⇒ FlagsClient

Returns a new instance of FlagsClient.



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/shipeasy/sdk/flags_client.rb', line 16

def initialize(api_key:, base_url: nil, env: "prod", disable_telemetry: false, telemetry_url: nil, test_mode: false, private_attributes: nil, sticky_store: nil)
  @api_key     = api_key
  @base_url    = (base_url || DEFAULT_BASE_URL).chomp("/")
  # Read-env tag. Used by telemetry below and stamped onto see() error
  # events so reports are attributable to an environment.
  @env         = env
  # Attribute names usable for targeting but stripped from every outbound
  # /collect payload (LD/Statsig privateAttributes). The server evaluates
  # locally so private attrs never leave for evaluation; the only egress is
  # track(), where the listed keys are dropped from the props bag.
  @private_attributes = (private_attributes || []).map(&:to_s)
  # Pluggable sticky-bucketing store (doc 20 §2). Absent ⇒ deterministic.
  # Threaded into get_experiment so an enrolled unit locks to its first
  # assigned variant. Built-in: InMemoryStickyStore.
  @sticky_store = sticky_store
  # Test mode: no network, ever. init/init_once/track become no-ops and
  # evaluation answers come purely from local overrides. Built via the
  # FlagsClient.for_testing factory; see clear_overrides / override_*.
  @test_mode   = test_mode
  # Per-evaluation usage telemetry. ON by default; pass
  # disable_telemetry: true to opt out. See telemetry.rb.
  @telemetry = Telemetry.new(
    endpoint: telemetry_url || Telemetry::DEFAULT_TELEMETRY_URL,
    sdk_key: api_key,
    side: "server",
    env: env,
    disabled: disable_telemetry,
  )
  @flags_blob  = nil
  @exps_blob   = nil
  @flags_etag  = nil
  @exps_etag   = nil
  @poll_interval = 30
  @mutex       = Mutex.new
  @timer       = nil
  @initialized = false
  # Statsig-style local overrides. Keyed by resource name; an override,
  # when present, short-circuits the corresponding getter. Usable on any
  # client (test or live) for deterministic tests / local development.
  @flag_overrides   = {}
  @config_overrides = {}
  @exp_overrides    = {}
  # Change listeners — fired after a background poll returns NEW data
  # (HTTP 200, not 304). Never fired in test/offline mode. Guarded by
  # @mutex; see on_change / notify_change.
  @change_listeners = []
  # see() structured error reporting. Per-process spam guard, bound here so
  # repeated reports of the same issue collapse to one send. See see.rb.
  @see_limiter = See::Limiter.new
  # Register as the default client backing the module-level Shipeasy::SDK
  # .see/.see_violation funcs (last constructed wins — the server-SDK
  # analog of TS's shipeasy({key}) configure call).
  Shipeasy::SDK.set_default_client(self)
end

Class Method Details

.for_testing(env: "prod") ⇒ Object

Build a no-network, immediately-usable client for tests. Telemetry is disabled, init/init_once/track are no-ops (never fetch), and no api_key is required. Seed it with override_flag / override_config / override_experiment, then call the normal getters.



75
76
77
78
79
80
81
82
# File 'lib/shipeasy/sdk/flags_client.rb', line 75

def self.for_testing(env: "prod")
  new(
    api_key: "test",
    env: env,
    disable_telemetry: true,
    test_mode: true,
  )
end

.from_file(path, env: "prod") ⇒ Object

Build an offline client from a JSON snapshot file. The file holds the raw response bodies of the two SDK endpoints under “flags” and “experiments” keys:

{ "flags": <body of /sdk/flags>, "experiments": <body of /sdk/experiments> }

The returned client does ZERO network (reuses test_mode plumbing: init/init_once/track are no-ops, telemetry off) but, unlike a bare for_testing client, runs the REAL evaluator against the loaded blobs. Local overrides still apply on top. Handy for CI, air-gapped runs, and reproducing a production decision from a captured blob.



95
96
97
98
# File 'lib/shipeasy/sdk/flags_client.rb', line 95

def self.from_file(path, env: "prod")
  data = JSON.parse(File.read(path))
  from_snapshot(flags: data["flags"], experiments: data["experiments"], env: env)
end

.from_snapshot(flags: nil, experiments: nil, env: "prod") ⇒ Object

Build an offline client directly from already-parsed blobs (same shape as the /sdk/flags and /sdk/experiments response bodies). See from_file.



102
103
104
105
106
# File 'lib/shipeasy/sdk/flags_client.rb', line 102

def self.from_snapshot(flags: nil, experiments: nil, env: "prod")
  client = for_testing(env: env)
  client.send(:load_snapshot, flags, experiments)
  client
end

Instance Method Details

#clear_overridesObject



144
145
146
147
148
149
150
151
# File 'lib/shipeasy/sdk/flags_client.rb', line 144

def clear_overrides
  @mutex.synchronize do
    @flag_overrides.clear
    @config_overrides.clear
    @exp_overrides.clear
  end
  self
end

#control_flow_exception(err) ⇒ Object Also known as: controlFlowException

Mark an exception as expected control flow — reports nothing. Returns a ‘.because(reason)` tail (with optional `.extras` for local debug only).



347
348
349
# File 'lib/shipeasy/sdk/flags_client.rb', line 347

def control_flow_exception(err)
  See::ControlFlowChain.new(err)
end

#destroyObject



164
165
166
167
# File 'lib/shipeasy/sdk/flags_client.rb', line 164

def destroy
  @timer&.kill
  @timer = nil
end

#get_config(name, decode = nil, default: nil) ⇒ Object



220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
# File 'lib/shipeasy/sdk/flags_client.rb', line 220

def get_config(name, decode = nil, default: nil)
  key = name.to_s
  has_override, override = @mutex.synchronize do
    [@config_overrides.key?(key), @config_overrides[key]]
  end
  if has_override
    return decode ? decode.call(override) : override
  end

  @telemetry.emit("config", name)
  entry = @mutex.synchronize { @flags_blob&.dig("configs", name) }
  return default unless entry
  value = entry["value"]
  decode ? decode.call(value) : value
end

#get_experiment(name, user, default_params, decode = nil) ⇒ Object



236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
# File 'lib/shipeasy/sdk/flags_client.rb', line 236

def get_experiment(name, user, default_params, decode = nil)
  key = name.to_s
  override = @mutex.synchronize { @exp_overrides[key] }
  if override
    params = override[:params]
    params = decode.call(params) if decode
    return Eval::ExperimentResult.new(
      in_experiment: true,
      group: override[:group],
      params: params,
    )
  end

  @telemetry.emit("experiment", name)
  flags_blob, exps_blob = @mutex.synchronize { [@flags_blob, @exps_blob] }
  exp = exps_blob&.dig("experiments", name)
  result = Eval.eval_experiment(
    exp, flags_blob, exps_blob, with_anon_id(user),
    exp_name: name.to_s, sticky_store: @sticky_store,
  )
  result.params ||= default_params

  if result.in_experiment && decode
    begin
      result = Eval::ExperimentResult.new(
        in_experiment: true,
        group: result.group,
        params: decode.call(result.params),
      )
    rescue => e
      warn "[shipeasy] get_experiment('#{name}') decode failed: #{e.message}"
      return Eval::ExperimentResult.new(in_experiment: false, group: "control", params: default_params)
    end
  end

  result
end

#get_flag(name, user, default: false) ⇒ Object



211
212
213
214
215
216
217
218
# File 'lib/shipeasy/sdk/flags_client.rb', line 211

def get_flag(name, user, default: false)
  detail = get_flag_detail(name, user)
  if detail.reason == REASON_CLIENT_NOT_READY || detail.reason == REASON_FLAG_NOT_FOUND
    default
  else
    detail.value
  end
end

#get_flag_detail(name, user) ⇒ Object

Evaluate a flag and return why. Telemetry (“gate” beacon) is emitted exactly once here (steps 2–5), never on the OVERRIDE short-circuit.



183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
# File 'lib/shipeasy/sdk/flags_client.rb', line 183

def get_flag_detail(name, user)
  key = name.to_s

  # 1. Override short-circuits before any telemetry (mirrors get_config).
  override = @mutex.synchronize { @flag_overrides[key] if @flag_overrides.key?(key) }
  return FlagDetail.new(value: override, reason: REASON_OVERRIDE) unless override.nil?

  @telemetry.emit("gate", name)

  flags_blob, gate = @mutex.synchronize { [@flags_blob, @flags_blob&.dig("gates", name)] }

  # 2. Not initialized — no blob fetched or loaded yet.
  return FlagDetail.new(value: false, reason: REASON_CLIENT_NOT_READY) if flags_blob.nil?

  # 3. Blob present but this gate isn't in it.
  return FlagDetail.new(value: false, reason: REASON_FLAG_NOT_FOUND) unless gate

  # 4. Gate present but disabled (or killswitched) — eval_gate would also
  #    return false here, but the reason is OFF, not a rollout DEFAULT.
  if Eval.enabled?(gate["killswitch"]) || !Eval.enabled?(gate["enabled"])
    return FlagDetail.new(value: false, reason: REASON_OFF)
  end

  # 5. Run the canonical evaluator; reason follows the boolean result.
  result = Eval.eval_gate(gate, with_anon_id(user))
  FlagDetail.new(value: result, reason: result ? REASON_RULE_MATCH : REASON_DEFAULT)
end

#initObject



108
109
110
111
112
113
# File 'lib/shipeasy/sdk/flags_client.rb', line 108

def init
  return if @test_mode
  fetch_all
  @initialized = true
  start_poll
end

#init_onceObject



115
116
117
118
119
120
# File 'lib/shipeasy/sdk/flags_client.rb', line 115

def init_once
  return if @test_mode
  return if @initialized
  fetch_all
  @initialized = true
end

#log_exposure(user_or_user_id, experiment_name) ⇒ Object

Emit an exposure event for an experiment at the server-side decision point (parity with the browser’s auto-exposure). The server is stateless and never auto-logs, so call this when you actually present the treatment. Re-evaluates the experiment for the user (a bare user_id string is wrapped as { “user_id” => id }); if enrolled, POSTs a single exposure to /collect. No-op in test mode or when the user isn’t enrolled.



302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
# File 'lib/shipeasy/sdk/flags_client.rb', line 302

def log_exposure(user_or_user_id, experiment_name)
  return if @test_mode

  user = user_or_user_id.is_a?(Hash) ? user_or_user_id : { "user_id" => user_or_user_id.to_s }
  result = get_experiment(experiment_name, user, {})
  return unless result.in_experiment

  u = user.transform_keys(&:to_s)
  payload = JSON.generate({
    events: [{
      type: "exposure",
      experiment: experiment_name.to_s,
      group: result.group,
      user_id: (u["user_id"] || u["anonymous_id"]).to_s,
      ts: (Time.now.to_f * 1000).to_i,
    }],
  })

  Thread.new do
    post("/collect", payload)
  rescue => e
    warn "[shipeasy] log_exposure failed: #{e.message}"
  end
end

#on_change(callable = nil, &block) ⇒ Object

Register a listener fired after a background poll fetches NEW flag/config data (HTTP 200, not 304). Accepts either a block or any callable (an object responding to #call). Returns an unsubscribe proc — call it to remove the listener. Never fires in test/offline mode (no poll thread).

Raises:

  • (ArgumentError)


157
158
159
160
161
162
# File 'lib/shipeasy/sdk/flags_client.rb', line 157

def on_change(callable = nil, &block)
  listener = callable || block
  raise ArgumentError, "on_change requires a block or callable" unless listener.respond_to?(:call)
  @mutex.synchronize { @change_listeners << listener }
  proc { @mutex.synchronize { @change_listeners.delete(listener) } }
end

#override_config(name, value) ⇒ Object



132
133
134
135
# File 'lib/shipeasy/sdk/flags_client.rb', line 132

def override_config(name, value)
  @mutex.synchronize { @config_overrides[name.to_s] = value }
  self
end

#override_experiment(name, group, params) ⇒ Object



137
138
139
140
141
142
# File 'lib/shipeasy/sdk/flags_client.rb', line 137

def override_experiment(name, group, params)
  @mutex.synchronize do
    @exp_overrides[name.to_s] = { group: group, params: params }
  end
  self
end

#override_flag(name, value) ⇒ Object

— Local overrides ————————————————- An override wins over the fetched blob in the matching getter. Setters are mutex-guarded so they’re safe to call alongside background polling on a live client.



127
128
129
130
# File 'lib/shipeasy/sdk/flags_client.rb', line 127

def override_flag(name, value)
  @mutex.synchronize { @flag_overrides[name.to_s] = (value ? true : false) }
  self
end

#see(problem) ⇒ Object

Report a caught exception (or thrown non-exception). Fire-and-forget; never blocks or throws into the request path. Terminate with ‘.to(outcome)`:

client.see(e).causes_the("checkout").to("use cached prices")


334
335
336
# File 'lib/shipeasy/sdk/flags_client.rb', line 334

def see(problem)
  See::Chain.new(problem, method(:dispatch_see))
end

#see_violation(name) ⇒ Object Also known as: seeViolation

Report a non-exception problem. The name is a stable fingerprint key —put variable data in ‘.extras`, never in the name.



340
341
342
# File 'lib/shipeasy/sdk/flags_client.rb', line 340

def see_violation(name)
  See::Chain.new(See::Violation.new(name), method(:dispatch_see))
end

#track(user_id, event_name, props = {}) ⇒ Object



274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
# File 'lib/shipeasy/sdk/flags_client.rb', line 274

def track(user_id, event_name, props = {})
  return if @test_mode

  safe_props = strip_private(props)

  payload = JSON.generate({
    events: [{
      type: "metric",
      event_name: event_name,
      user_id: user_id.to_s,
      ts: (Time.now.to_f * 1000).to_i,
      **(safe_props.empty? ? {} : { properties: safe_props }),
    }],
  })

  Thread.new do
    post("/collect", payload)
  rescue => e
    warn "[shipeasy] track failed: #{e.message}"
  end
end