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"
DEFAULT_CDN_BASE =

CDN origin serving the static loader scripts (/sdk/bootstrap.js, /sdk/i18n/loader.js) — distinct from the edge API the blobs are fetched from.

"https://cdn.shipeasy.ai"
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.



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
70
71
72
73
# File 'lib/shipeasy/sdk/flags_client.rb', line 20

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.



79
80
81
82
83
84
85
86
# File 'lib/shipeasy/sdk/flags_client.rb', line 79

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.



99
100
101
102
# File 'lib/shipeasy/sdk/flags_client.rb', line 99

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.



106
107
108
109
110
# File 'lib/shipeasy/sdk/flags_client.rb', line 106

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

#bootstrap_script_tag(user, anon_id: nil, i18n_profile: "en:prod", base_url: nil) ⇒ Object

Return the cross-platform SSR bootstrap <script> tag for a request: se-bootstrap.js reads its data-* attributes and hydrates window.__SE_BOOTSTRAP (and writes the anon cookie). No key is embedded.



318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
# File 'lib/shipeasy/sdk/flags_client.rb', line 318

def bootstrap_script_tag(user, anon_id: nil, i18n_profile: "en:prod", base_url: nil)
  payload = evaluate(user)
  base = cdn_base(base_url)
  attrs = [
    "data-se-bootstrap",
    attr("data-flags", JSON.generate(payload["flags"])),
    attr("data-configs", JSON.generate(payload["configs"])),
    attr("data-experiments", JSON.generate(payload["experiments"])),
    attr("data-killswitches", JSON.generate(payload["killswitches"])),
    attr("data-i18n-profile", i18n_profile || "en:prod"),
    attr("data-api-url", base),
  ]
  attrs << attr("data-anon-id", anon_id) if anon_id && !anon_id.empty?
  %(<script src="#{CGI.escapeHTML("#{base}/sdk/bootstrap.js")}" #{attrs.join(' ')}></script>)
end

#clear_overridesObject



148
149
150
151
152
153
154
155
# File 'lib/shipeasy/sdk/flags_client.rb', line 148

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).



416
417
418
# File 'lib/shipeasy/sdk/flags_client.rb', line 416

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

#destroyObject



168
169
170
171
# File 'lib/shipeasy/sdk/flags_client.rb', line 168

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

#evaluate(user) ⇒ Object

Batch-evaluate every loaded gate, config and experiment for user into a bootstrap payload (+{ “flags” => …, “configs” => …, “experiments”

> …, “killswitches” => … }+) keyed to match the browser SDK’s

window.__SE_BOOTSTRAP shape. Local overrides win. Killswitches are folded into per-gate evaluation, so the standalone killswitches map is empty for this SDK. No telemetry (a batch evaluate is not a per-flag exposure).



284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
# File 'lib/shipeasy/sdk/flags_client.rb', line 284

def evaluate(user)
  u = with_anon_id(user)
  flags_blob, exps_blob, flag_ov, config_ov, exp_ov, sticky = @mutex.synchronize do
    [@flags_blob, @exps_blob, @flag_overrides.dup, @config_overrides.dup,
     @exp_overrides.dup, @sticky_store]
  end

  flags = {}
  (flags_blob&.dig("gates") || {}).each do |name, gate|
    flags[name] = flag_ov.key?(name) ? flag_ov[name] : Eval.eval_gate(gate, u)
  end

  configs = {}
  (flags_blob&.dig("configs") || {}).each do |name, entry|
    configs[name] = config_ov.key?(name) ? config_ov[name] : entry["value"]
  end

  experiments = {}
  (exps_blob&.dig("experiments") || {}).each do |name, exp|
    if exp_ov.key?(name)
      ov = exp_ov[name]
      experiments[name] = { "inExperiment" => true, "group" => ov[:group], "params" => ov[:params] }
      next
    end
    r = Eval.eval_experiment(exp, flags_blob, exps_blob, u, exp_name: name, sticky_store: sticky)
    experiments[name] = { "inExperiment" => r.in_experiment, "group" => r.group, "params" => r.params }
  end

  { "flags" => flags, "configs" => configs, "experiments" => experiments, "killswitches" => {} }
end

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



224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
# File 'lib/shipeasy/sdk/flags_client.rb', line 224

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



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
273
274
275
276
# File 'lib/shipeasy/sdk/flags_client.rb', line 240

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



215
216
217
218
219
220
221
222
# File 'lib/shipeasy/sdk/flags_client.rb', line 215

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.



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

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

#i18n_script_tag(client_key, profile: "en:prod", base_url: nil) ⇒ Object

Return the i18n loader <script> tag (framework-agnostic; the Rails view helper Shipeasy::I18n::ViewHelpers#i18n_script_tag is separate). The loader fetches translations for the profile using the PUBLIC client key.



337
338
339
340
341
# File 'lib/shipeasy/sdk/flags_client.rb', line 337

def i18n_script_tag(client_key, profile: "en:prod", base_url: nil)
  base = cdn_base(base_url)
  %(<script src="#{CGI.escapeHTML("#{base}/sdk/i18n/loader.js")}" ) +
    %(#{attr('data-key', client_key)} #{attr('data-profile', profile || 'en:prod')}></script>)
end

#initObject



112
113
114
115
116
117
# File 'lib/shipeasy/sdk/flags_client.rb', line 112

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

#init_onceObject



119
120
121
122
123
124
# File 'lib/shipeasy/sdk/flags_client.rb', line 119

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.



371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
# File 'lib/shipeasy/sdk/flags_client.rb', line 371

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)


161
162
163
164
165
166
# File 'lib/shipeasy/sdk/flags_client.rb', line 161

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



136
137
138
139
# File 'lib/shipeasy/sdk/flags_client.rb', line 136

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

#override_experiment(name, group, params) ⇒ Object



141
142
143
144
145
146
# File 'lib/shipeasy/sdk/flags_client.rb', line 141

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.



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

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")


403
404
405
# File 'lib/shipeasy/sdk/flags_client.rb', line 403

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.



409
410
411
# File 'lib/shipeasy/sdk/flags_client.rb', line 409

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

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



343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
# File 'lib/shipeasy/sdk/flags_client.rb', line 343

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