standard_flags 0.2.2 → 0.3.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.
Files changed (51) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +158 -0
  3. data/README.md +566 -35
  4. data/conformance/README.md +166 -0
  5. data/conformance/bucket_vectors.json +46 -0
  6. data/conformance/guards_and_errors.json +35 -0
  7. data/conformance/legacy_env.json +38 -0
  8. data/conformance/legacy_exact.json +90 -0
  9. data/conformance/operations/write_path.json +723 -0
  10. data/conformance/permanent_flags.json +38 -0
  11. data/conformance/resolution.json +68 -0
  12. data/conformance/runtime/client.json +1431 -0
  13. data/conformance/runtime/rules.json +1305 -0
  14. data/conformance/schema/fixture.schema.json +1340 -0
  15. data/conformance/versions/legacy_ranges.json +183 -0
  16. data/conformance/versions/version_ranges.json +503 -0
  17. data/conformance/wire/client_state.json +1905 -0
  18. data/conformance/wire/delivery.json +1541 -0
  19. data/lib/standard_flags/audience.rb +49 -0
  20. data/lib/standard_flags/client.rb +157 -0
  21. data/lib/standard_flags/config.rb +21 -0
  22. data/lib/standard_flags/context.rb +70 -17
  23. data/lib/standard_flags/controller.rb +92 -10
  24. data/lib/standard_flags/definition.rb +71 -8
  25. data/lib/standard_flags/delivery.rb +195 -0
  26. data/lib/standard_flags/errors.rb +33 -0
  27. data/lib/standard_flags/job.rb +12 -1
  28. data/lib/standard_flags/mcp/flags.rb +3 -3
  29. data/lib/standard_flags/mcp/gating.rb +151 -0
  30. data/lib/standard_flags/mcp.rb +64 -5
  31. data/lib/standard_flags/notifiers/logger.rb +4 -0
  32. data/lib/standard_flags/ofrep/controller.rb +211 -0
  33. data/lib/standard_flags/ofrep.rb +115 -0
  34. data/lib/standard_flags/open_feature/provider.rb +1 -1
  35. data/lib/standard_flags/operations/rules.rb +17 -4
  36. data/lib/standard_flags/operations/validation.rb +25 -4
  37. data/lib/standard_flags/operations.rb +0 -2
  38. data/lib/standard_flags/payload.rb +8 -3
  39. data/lib/standard_flags/registry.rb +157 -12
  40. data/lib/standard_flags/runtime/cache.rb +1 -0
  41. data/lib/standard_flags/runtime/resolver.rb +26 -17
  42. data/lib/standard_flags/runtime/values.rb +8 -1
  43. data/lib/standard_flags/runtime.rb +42 -1
  44. data/lib/standard_flags/semantic_version.rb +141 -0
  45. data/lib/standard_flags/subscribers.rb +3 -0
  46. data/lib/standard_flags/testing.rb +4 -2
  47. data/lib/standard_flags/tooling.rb +25 -3
  48. data/lib/standard_flags/version.rb +1 -1
  49. data/lib/standard_flags/version_range.rb +309 -0
  50. data/lib/standard_flags.rb +38 -4
  51. metadata +24 -1
data/README.md CHANGED
@@ -8,10 +8,16 @@ guards, environment pins, then per-environment code defaults. Results have
8
8
  the [OpenFeature](https://openfeature.dev) shape (value, variant, reason,
9
9
  error code), so "why is this on?" is always a one-line answer.
10
10
 
11
- This is version 0.1.0 (Phase 1): registry, ENV layer and evaluation API. It
12
- needs no database tables. Unreleased on `main`: opt-in
13
- [runtime rules](#runtime-rules) stored in the app's own database (the read
14
- path; the audited write operations come next). See [Roadmap](#roadmap).
11
+ This is version 0.2.2: the registry, ENV layer and evaluation API (which
12
+ need no database tables), plus opt-in [runtime rules](#runtime-rules) stored
13
+ in the app's own database, the audited operations that change them,
14
+ [operator tools](#operator-tools-mcp), an admin page generator and an
15
+ [OpenFeature](#openfeature) provider. Unreleased on `main`:
16
+ [client context](#client-context) (who is calling, from request headers),
17
+ portable version ranges, build-number conditions, a raisable
18
+ `FeatureDisabled`, flag-gated MCP tools and [client delivery](#client-delivery)
19
+ (an OFREP endpoint mixin, bootstrap embeds, minimum client versions and
20
+ deprecated wires). See [Roadmap](#roadmap).
15
21
 
16
22
  - [Install](#install)
17
23
  - [Declaring flags](#declaring-flags)
@@ -21,7 +27,9 @@ path; the audited write operations come next). See [Roadmap](#roadmap).
21
27
  - [Environment variables](#environment-variables)
22
28
  - [Sensor rollouts](#sensor-rollouts)
23
29
  - [Controller and job guards](#controller-and-job-guards)
30
+ - [Client context](#client-context)
24
31
  - [Client payload](#client-payload)
32
+ - [Client delivery](#client-delivery)
25
33
  - [Rake tasks](#rake-tasks)
26
34
  - [Observability](#observability)
27
35
  - [Health check and diagnostics](#health-check-and-diagnostics)
@@ -102,7 +110,7 @@ end
102
110
  | `mode` | declared values | first value | Staged rollouts. Presets: `:sensor` (off/sensor/on), `:cutover` (off/allowlist/all), `:shadow` (off/shadow/enforce); or `values:`. May declare `remove_by:` with `final:`, or `permanent: true`. |
103
111
  | `experiment` | declared variants | first variant | Experiments. Resolves to its first variant (list `control` first) unless pinned by ENV or split by a runtime rule's variant weights. |
104
112
  | `compat` | on / off | on | Compatibility shims that stay on until they are removed. |
105
- | `tombstone` | — | — | A removed key. It can never be declared again. |
113
+ | `tombstone` | — | — | A removed key. It can never be declared again. `serve:` keeps its client wires answering a static value for a while ([Deprecated wires](#deprecated-wires)). |
106
114
 
107
115
  ### Attributes
108
116
 
@@ -117,7 +125,8 @@ end
117
125
  | `legacy_true:` | With `legacy_parser: :exact` on an on/off kind, the exact values that mean on. Default `%w[on]`. |
118
126
  | `forbidden_in:` | Environment name(s) where the flag is forced off. A pin that tries to turn it on is reported once per process. |
119
127
  | `fail:` | The value returned if evaluation raises. Kill switches default to on. |
120
- | `expose:` | `{ audience => wire_name }`, or a list of audiences to use the key. Default: not exposed. |
128
+ | `expose:` | `{ audience => wire_name }`, or a list of audiences to use the key. A Hash value may list several wire names (aliases), each serving the same evaluation: `expose: { mobile: %i[chat_enabled insights_enabled], web: :chat }`. Default: not exposed. |
129
+ | `min_client:` | `{ platform => "version" }`: client builds below it, or of unknown version, are not told about the flag. See [Minimum client versions](#minimum-client-versions). Needs `expose:`. |
121
130
  | `unit:` | The unit the flag targets. [Runtime rules](#runtime-rules) match members, cohorts and percentages on this unit's key. |
122
131
  | `bucketing:` | On `flag`, `mode` and `experiment`: `{ version: 1 \| 2, salt: "..." }`, for a flag migrated from another system that must keep its old buckets. Needs `unit:`. |
123
132
  | `remove_by:`, `final:` | On `flag` (required) and `mode` (optional, together): the date it should be gone, and the value it settles on. A mode's `final:` must be one of its values. |
@@ -209,7 +218,7 @@ also carry an environment override and client attributes
209
218
  - `variant`: the value as a string (`"on"`/`"off"` for booleans).
210
219
  - `reason`: `STATIC`, `DEFAULT`, `TARGETING_MATCH`, `SPLIT`, `DISABLED`, `ERROR`, plus `ENV_PIN` and `KILL_SWITCH`.
211
220
  - `error_code`: the OpenFeature set (`FLAG_NOT_FOUND`, `PARSE_ERROR`, `TYPE_MISMATCH`, `TARGETING_KEY_MISSING`, `INVALID_CONTEXT`, `PROVIDER_NOT_READY`, `PROVIDER_FATAL`, `GENERAL`), only when the reason is `ERROR`.
212
- - `rule_id`: the matching runtime rule. Always nil in 0.1.0.
221
+ - `rule_id`: the part of a runtime rule that decided (`allow`, `deny`, `cohort:<key>`, `segment:<name>`, `percentage`, `variants`, `fallthrough`, `stopped`), or nil when no runtime rule did.
213
222
  - `source_env_var`: the name of the variable that decided the value. Never its contents.
214
223
 
215
224
  ### Errors and strictness
@@ -265,7 +274,8 @@ Runtime rules change a flag without a redeploy, and let it differ per
265
274
  account, organisation, phone or other unit. Each flag has at most one rule,
266
275
  stored in the app's own database (Postgres). They are off by default: with
267
276
  `config.runtime_rules` false, nothing reads a database, ActiveRecord is never
268
- loaded by the gem, and every flag behaves exactly as in 0.1.0.
277
+ loaded by the gem, and every flag is decided by the test override, guards,
278
+ ENV pin and code default alone.
269
279
 
270
280
  Rules change only through audited operations (see
271
281
  [Changing flags](#changing-flags)), from the console, a rake task, or the
@@ -334,10 +344,11 @@ The rule's status decides first:
334
344
  wins; otherwise the first match in declared order. Rule `cohort:<key>`.
335
345
  3. **Segments**, each asked of `config.segment_resolver.call(name,
336
346
  context)` in order. Skipped when no resolver is set. Rule `segment:<name>`.
337
- 4. **Client conditions**: `platforms` and `versions` (`{ "android" =>
338
- ">= 1.4.0" }`, compared with `Gem::Requirement` against
339
- `context.client[:platform]` and `[:version]`). When they aren't met, the
340
- rule skips straight to the fallthrough.
347
+ 4. **Client conditions**: `platforms`, `versions` (`{ "android" =>
348
+ ">=1.4.0 <2.0.0" }`) and `builds` (`{ "android" => ">=120" }`), checked
349
+ against the context's [client](#client-context). Every condition set for
350
+ the client's platform must hold. When they aren't met, the rule skips
351
+ straight to the fallthrough. See [Versions and ranges](#versions-and-ranges).
341
352
  5. **Percentage and variants.** A unit whose rollout bucket is below
342
353
  `percentage_bps` gets `rollout_value` (on/off kinds default to `on`), reason
343
354
  `SPLIT`, rule `percentage`. With `variant_weights` (summing to 10,000),
@@ -357,7 +368,7 @@ the fallthrough or the code default with reason `ERROR` and error code
357
368
  `TARGETING_KEY_MISSING`. That emits `targeting_key_missing.standard_flags`
358
369
  but reports nothing, because reads with no unit are often legitimate. A
359
370
  stored value the flag can't take (an unknown mode value, weights that don't
360
- sum, a bad version range) fails only that flag: its `fail:` value with
371
+ sum, a bad version or build range) fails only that flag: its `fail:` value with
361
372
  `PARSE_ERROR`, reported once through the error reporter.
362
373
 
363
374
  ### What a read costs
@@ -520,7 +531,7 @@ leaves a draft a draft, so changes can be staged and started together.
520
531
  | `Ramp(bps:, value: nil)` | `flags:ramp` | Sets the percentage (0–10,000 basis points) and, for modes and experiments, the value it serves. At 10,000 it records `full_since`. |
521
532
  | `SetVariants(weights:)` | `flags:ramp` | Weights over the flag's variants or mode values, summing to 10,000. `{}` clears them. |
522
533
  | `SetValue(value:)` | `flags:write` | The fallthrough value, served to every unit nothing else matched. Moves a mode off → sensor → on and throws a kill switch. Starts a draft rule (above); a paused one stays paused, with a warning. `nil` clears it. |
523
- | `SetConditions(platforms:, versions:, segments:)` | `flags:write` | Replaces the conditions; omitted ones are cleared. |
534
+ | `SetConditions(platforms:, versions:, builds:, segments:)` | `flags:write` | Replaces the conditions; omitted ones are cleared. Version ranges are stored in the neutral syntax. |
524
535
  | `AddMembers(keys:, value:, unit:, expires_at:)` | `flags:write` | Adds units (records or keys) to a rule or a cohort. Adding an existing member with a new value or expiry keeps the old row as removed and adds a new one, so [Restore](#restore) can read it back; adding it unchanged writes nothing. |
525
536
  | `RemoveMembers(keys:, unit:)` | `flags:write` | Removes them (soft delete, see retention below). |
526
537
  | `CreateCohort(unit:, name:, description:)` / `ArchiveCohort` | `flags:write` | Named member lists of one unit. Archiving needs the cohort detached everywhere. |
@@ -822,6 +833,61 @@ end
822
833
  own copy holding that call's actor, arguments and store read.
823
834
  - A missing `actor:` falls back to `config.actor_resolver`. The generated
824
835
  admin page never relies on that (below).
836
+ - `list_flags` and `get_flag` evaluate with no client unless the tools are
837
+ built with one: `StandardFlags::MCP.tools(client: ...)` takes a
838
+ `StandardFlags::Client`, a Hash or a lambda (which may take the actor).
839
+
840
+ ### Gating your own tools
841
+
842
+ An app's own tools can require flags. Include `StandardFlags::MCP::Gated`
843
+ in any tool class with the same shape (`name`, `description`,
844
+ `input_schema`, `call(arguments, actor:)`):
845
+
846
+ ```ruby
847
+ class SummariseThread
848
+ include StandardFlags::MCP::Gated
849
+
850
+ requires_flag :ai_assistant # evaluated for the actor
851
+ requires_flag :thread_tools, for: ->(actor) { actor.account }, client: -> { Current.client }
852
+
853
+ def name = "summarise_thread"
854
+ # description, input_schema, call(arguments, actor:) ...
855
+ end
856
+ ```
857
+
858
+ While a required flag is off, `call` returns
859
+ `{ "error" => { "code" => "feature_disabled", "message" => "threadTools is disabled" } }`
860
+ without running the tool, and `StandardFlags::MCP.visible` leaves the tool
861
+ out of `tools/list`. The message names the flag's wire name for the `:mcp`
862
+ audience, else its first wire name, else the key. The gate holds in every
863
+ subclass, including one that defines its own `call`. A
864
+ `StandardFlags::FeatureDisabled` raised inside any tool (gated or not, the
865
+ gem's own included) comes back as the same error, and isn't reported as a
866
+ failure.
867
+
868
+ List and call through the same two helpers, with the same arguments, and
869
+ they agree by construction: a tool listed for a request is callable by it,
870
+ and one hidden from it is refused.
871
+
872
+ ```ruby
873
+ client = StandardFlags::Client.from_headers(request.headers)
874
+ tools = app_tools + StandardFlags::MCP.tools
875
+
876
+ server.on_list_tools { |user| StandardFlags::MCP.visible(tools, actor: user, client: client) }
877
+ server.on_call_tool do |user, name, arguments|
878
+ tool = tools.find { |candidate| candidate.name == name } or raise UnknownTool, name
879
+ StandardFlags::MCP.call(tool, arguments, actor: user, client: client)
880
+ end
881
+ ```
882
+
883
+ `visible(tools, actor:, context: nil, client: nil)` and
884
+ `call(tool, arguments, actor:, context: nil, client: nil)` evaluate each
885
+ gate for `context:` when given (else the gate's own `for:`, by default the
886
+ actor) and for `client:` when given (else the gate's own `client:`). A nil
887
+ `actor:` resolves through `config.actor_resolver`, as the gem's own tools
888
+ do. Calling `tool.call(arguments, actor:)` directly evaluates as `visible`
889
+ does with no `context:` or `client:`. Ungated tools always appear. The gem's
890
+ own tools are not gated.
825
891
 
826
892
  ## Admin page
827
893
 
@@ -1009,6 +1075,55 @@ The denial carries `key`, `error`, `status` (from `error:`/`status:`),
1009
1075
  `feature` and `body` (the default JSON:API document). The responder must
1010
1076
  render or redirect so the action doesn't run.
1011
1077
 
1078
+ ### Raising FeatureDisabled
1079
+
1080
+ Code deeper than a `before_action` can raise the same denial:
1081
+
1082
+ ```ruby
1083
+ StandardFlags.require!(:ai_assistant, for: Current.account) # raises StandardFlags::FeatureDisabled when off
1084
+ raise StandardFlags::FeatureDisabled.new(:ai_assistant) # or raise it yourself
1085
+ ```
1086
+
1087
+ Inside an action, evaluate for the same context the guards use (this
1088
+ request's `standard_flags_context` plus its client):
1089
+
1090
+ ```ruby
1091
+ StandardFlags.require!(:ai_assistant, for: standard_flags_request_context)
1092
+ standard_flags_reader.on?(:ai_assistant)
1093
+ ```
1094
+
1095
+ `StandardFlags::FeatureDisabled` (a `StandardFlags::Error`) carries `key`,
1096
+ `feature` (the wire name, found as for `meta.feature`) and `status` (403
1097
+ unless given). `StandardFlags::Controller` rescues it and renders it exactly
1098
+ like a `requires_flag :key` denial: through `config.controller_responder`
1099
+ when one is set, else the JSON:API body above. One raised with
1100
+ `status: 404` answers like `error: :not_found`, with no `meta.feature`.
1101
+
1102
+ This holds even when the app declares `rescue_from StandardError` after
1103
+ including the module (Rails would otherwise try that handler first, since
1104
+ it tries the last declared first). An app takes `FeatureDisabled` over only
1105
+ by naming it, `rescue_from StandardFlags::FeatureDisabled, with: ...`;
1106
+ `config.controller_responder` is usually the better hook. Nothing is
1107
+ rendered for one raised after the action has already rendered.
1108
+
1109
+ An app whose API already has its own error envelope renders every denial,
1110
+ from guards and from the exception alike, with one responder:
1111
+
1112
+ ```ruby
1113
+ StandardFlags.configure do |config|
1114
+ config.controller_responder = lambda do |controller, denial|
1115
+ controller.render json: { error: { code: denial.error.to_s.upcase, feature: denial.feature } },
1116
+ status: denial.status
1117
+ end
1118
+ end
1119
+ # => 403 {"error":{"code":"FEATURE_DISABLED","feature":"assistant"}}
1120
+ ```
1121
+
1122
+ Keep client-facing denials in the 4xx range. Some hosting edges and proxies
1123
+ replace 5xx response bodies with their own error page, so a client may
1124
+ never see a 503's body; 4xx bodies pass through. `status: 503` still works
1125
+ for server-to-server endpoints that only read the status.
1126
+
1012
1127
  ```ruby
1013
1128
  class ReplyJob < ApplicationJob
1014
1129
  include StandardFlags::Job
@@ -1021,6 +1136,14 @@ end
1021
1136
  With `retry: true` a disabled flag raises `StandardFlags::Disabled` so
1022
1137
  `retry_on` can reschedule. Without it the job is discarded unrun.
1023
1138
 
1139
+ `client:` evaluates the flag for a client as well (a `StandardFlags::Client`,
1140
+ a Hash, or a lambda run in the job instance). Jobs never read request
1141
+ headers; pass along the client the request saw (`client.to_h` serialises):
1142
+
1143
+ ```ruby
1144
+ requires_flag :new_importer, for: -> { arguments.first }, client: -> { arguments.second }
1145
+ ```
1146
+
1024
1147
  Jobs that already `retry_on` (or `discard_on`) their own exception can
1025
1148
  raise it instead with `error:`, a class or a proc:
1026
1149
 
@@ -1048,6 +1171,152 @@ options combine:
1048
1171
  | `error:` with `retry: true` | Same as `error:` alone. |
1049
1172
  | `error:` with `retry: false` | `ArgumentError` at declaration: `error:` always raises, so it cannot also discard. |
1050
1173
 
1174
+ ## Client context
1175
+
1176
+ Clients (mobile apps, desktop apps, devices, browsers) say who they are on
1177
+ every request with three headers:
1178
+
1179
+ ```
1180
+ X-Client-Platform: android
1181
+ X-Client-Version: 1.4.0
1182
+ X-Client-Build: 381
1183
+ ```
1184
+
1185
+ `StandardFlags::Controller` reads them once per request into
1186
+ `standard_flags_client`, a `StandardFlags::Client`, and evaluates every
1187
+ guard and payload for `standard_flags_context` plus that client. If your
1188
+ `standard_flags_context` returns a context that already has a client, it is
1189
+ kept.
1190
+
1191
+ ```ruby
1192
+ client = StandardFlags::Client.from_headers(request.headers)
1193
+ client.platform # => "android"
1194
+ client.version # => #<StandardFlags::Version 1.4.0>
1195
+ client.build # => 381
1196
+ ```
1197
+
1198
+ - **Platform** is downcased and must be one of `config.client_platforms`
1199
+ (default `%w[android ios web desktop]`).
1200
+ - **Version** must parse as a [version](#versions-and-ranges).
1201
+ - **Build** must be 1 to 18 ASCII digits.
1202
+
1203
+ A version or build that fails is dropped, as if the header were missing. A
1204
+ platform that fails becomes `"unknown"`. Each emits
1205
+ `client_invalid.standard_flags` (with the field and header name, never the
1206
+ value). Nothing raises, whatever bytes arrive (invalid UTF-8 included), and
1207
+ nothing is reported as an error, because the headers come from outside.
1208
+
1209
+ Version and build ranges are scoped to a platform, and a rule reads the
1210
+ client like this:
1211
+
1212
+ | Client | Platform list | That platform's version and build ranges |
1213
+ |--------|---------------|------------------------------------------|
1214
+ | Recognised platform | must list it | must hold |
1215
+ | No platform (no headers, as in 0.2.2) | fails | don't apply |
1216
+ | `"unknown"` platform (sent but not recognised) | fails | fail |
1217
+
1218
+ So a request with no headers is evaluated exactly as 0.2.2 evaluated an
1219
+ empty client: a rule with only `versions: { android: ">=9.0.0" }` still
1220
+ reaches it. Add `platforms:` to a rule that must reach only the listed
1221
+ platforms. A misspelt platform header (`andriod`) can't step around a
1222
+ version floor, because an unknown platform fails every platform-scoped
1223
+ condition.
1224
+
1225
+ ```ruby
1226
+ StandardFlags.configure do |config|
1227
+ config.client_headers = { platform: "X-App-Platform", version: "X-App-Version", build: "X-App-Build" }
1228
+ config.client_platforms = %w[android ios]
1229
+ config.read_client_headers = false # opt out: controllers never read the headers
1230
+ end
1231
+ ```
1232
+
1233
+ Outside a controller, pass a client explicitly. Nothing else reads headers.
1234
+
1235
+ ```ruby
1236
+ StandardFlags.on?(:new_checkout, for: StandardFlags::Context.wrap(account, client: client))
1237
+ StandardFlags.on?(:new_checkout, for: StandardFlags::Context.new(actors: { account: account },
1238
+ client: { platform: "ios", version: "2.1.0" }))
1239
+ ```
1240
+
1241
+ `Context.new(client:)` still takes the Hash form, which keeps its values as
1242
+ given (no allowlist). `context.client` is a `StandardFlags::Client`, a
1243
+ frozen Hash subclass, so 0.2.2's reads (`[:platform]`, `fetch`, `dig`,
1244
+ `key?`, `each`, `to_h`) work unchanged. The typed readers `platform`,
1245
+ `version` and `build` parse the values: a version given as a
1246
+ `Gem::Version` or a Float is read through `to_s`. Jobs and MCP tools take
1247
+ `client:` too (see [Controller and job guards](#controller-and-job-guards)
1248
+ and [Operator tools](#operator-tools-mcp)).
1249
+
1250
+ ### Versions and ranges
1251
+
1252
+ `StandardFlags::Version` is SemVer 2.0: `MAJOR.MINOR.PATCH`, an optional
1253
+ `-prerelease` and an ignored `+build`. The shorthands `MAJOR.MINOR` and
1254
+ `MAJOR` mean the missing parts are 0 (`1.4` is `1.4.0`); they take no
1255
+ suffix. Ordering is SemVer precedence: a prerelease sorts before its release
1256
+ (`1.4.0-rc.1 < 1.4.0`), numeric prerelease identifiers compare by value and
1257
+ below alphanumeric ones, and build metadata never counts
1258
+ (`1.4.0+381 == 1.4.0`). `v1.4`, `1.4.0.1` and leading zeros don't parse.
1259
+ Numbers have no size limit; a version is at most 128 characters.
1260
+
1261
+ Version ranges are comparators (`>=`, `>`, `<=`, `<`, `=`) separated by
1262
+ spaces, all of which must hold, with optional `||` alternatives.
1263
+ Whitespace after an operator is optional, and means ASCII spaces and tabs
1264
+ only. A range is at most 1024 characters:
1265
+
1266
+ ```
1267
+ >=1.4.0 <2.0.0
1268
+ >=0.9.0 || =0.8.5-beta.1
1269
+ >= 1.4 < 2
1270
+ ```
1271
+
1272
+ The syntax is deliberately small so the Kotlin and TypeScript clients can
1273
+ implement it; `version_ranges.json` in the [conformance suite](#conformance-suite)
1274
+ pins its meaning. Comparison is plain ordering, so `<2.0.0` admits
1275
+ `2.0.0-beta.1`, and a shorthand is an exact version rather than a wildcard:
1276
+ `>1.4` admits `1.4.1`, and `<=1.4` excludes `1.4.5`. A client version that
1277
+ doesn't parse meets no neutral range.
1278
+
1279
+ Build ranges use the same comparators over build numbers (1 to 18 digits,
1280
+ leading zeros allowed, no sign): `>=120 <200`. A rule's `builds` sit beside
1281
+ its `versions`, per platform, and both must hold:
1282
+
1283
+ ```ruby
1284
+ StandardFlags::Operations::SetConditions.call(:new_checkout, actor: admin, reason: "needs the new SDK",
1285
+ platforms: %w[android ios], versions: { android: ">=1.4.0" }, builds: { android: ">=120" })
1286
+ ```
1287
+
1288
+ Ranges written with 0.2.x used RubyGems syntax (`">= 1.4.0"`, `"~> 1.4"`,
1289
+ `">= 1.4, < 2"`). Stored ones that only RubyGems can read keep evaluating
1290
+ exactly as `Gem::Requirement` evaluates them, prerelease client versions
1291
+ included. A string valid in both syntaxes (`">= 1.4.0"`,
1292
+ `">= 1.0.0-alpha"`) is read as neutral, so a SemVer client version is
1293
+ compared by SemVer (for release operands the answer is the same).
1294
+
1295
+ - One with a neutral equivalent is translated: `~> 1.4` reads as
1296
+ `>=1.4.0 <2.0.0-0`, `~> 1.4.2` as `>=1.4.2 <1.5.0-0`, and `!= 1.5` as
1297
+ `<1.5.0 || >1.5.0`. The `-0` is SemVer's lowest prerelease, so
1298
+ `<2.0.0-0` excludes `2.0.0-beta.1` as well as `2.0.0`, matching RubyGems,
1299
+ whose `~>` compares only the release part.
1300
+ - One the neutral syntax can't hold is evaluated with `Gem::Requirement` and
1301
+ doesn't block operations on the rule. That covers more than three release
1302
+ segments (`>= 1.4.0.1`), more than 64 alternatives' worth of `!=`, and any
1303
+ prerelease operand (`= 1.4.0.beta`, `~> 2.0.0.pre`), because RubyGems
1304
+ orders prereleases differently from SemVer: it reads a client's
1305
+ `1.4.0-beta` as `1.4.0.pre.beta`.
1306
+ - A client version outside SemVer (`1.4.0.1`, `1.4.0.beta`, passed in the
1307
+ Hash form; headers require SemVer) is read by RubyGems against any range
1308
+ RubyGems can read, `">= 1.4.0"` and `">=0.0.0"` included, as 0.2.2 did.
1309
+ This is the one place the server and the portable fixture differ (see
1310
+ [Conformance suite](#conformance-suite)). Ranges only the neutral syntax
1311
+ can read compare SemVer only.
1312
+ - Build metadata in a client version is ignored, as SemVer says: a Hash-form
1313
+ `version: "1.4.0+381"` meets `~> 1.4`, where 0.2.2 refused it.
1314
+
1315
+ `SetConditions` accepts either syntax and stores the neutral form: a
1316
+ neutral range as given, a RubyGems one translated, and one the neutral
1317
+ syntax can't hold as given. `StandardFlags::VersionRange.translate`
1318
+ converts one by hand.
1319
+
1051
1320
  ## Client payload
1052
1321
 
1053
1322
  Clients see evaluated values only, never rules or the names of flags they
@@ -1062,7 +1331,11 @@ Only flags with `expose:` for that audience appear, keyed by wire name. Wire
1062
1331
  names are separate from keys, so renaming or removing a flag doesn't break a
1063
1332
  shipped client. Booleans stay booleans; modes and variants are strings. The
1064
1333
  digest hashes the evaluated result, so it changes whenever the answers do,
1065
- which makes it a safe ETag.
1334
+ which makes it a safe ETag. Each alias of a flag gets the same value.
1335
+
1336
+ This flat payload is for pages the server renders: it ignores `min_client:`
1337
+ and tombstones' static wires. Clients with builds of their own (mobile apps,
1338
+ devices) use [client delivery](#client-delivery) instead.
1066
1339
 
1067
1340
  With Inertia:
1068
1341
 
@@ -1073,12 +1346,240 @@ class ApplicationController < ActionController::Base
1073
1346
  end
1074
1347
  ```
1075
1348
 
1349
+ ## Client delivery
1350
+
1351
+ Mobile apps, devices and MCP clients learn what is on from the same
1352
+ evaluation the server uses, in the shape of OpenFeature's Remote Evaluation
1353
+ Protocol (OFREP, validated against its OpenAPI document 0.4.0). One builder,
1354
+ `StandardFlags::Delivery`, feeds two outlets: an OFREP endpoint the app
1355
+ mounts behind its own authentication, and an embed for responses the client
1356
+ already fetches (a bootstrap `/me`, a device check-in, MCP whoami).
1357
+
1358
+ ### Audiences
1359
+
1360
+ `expose:` names audiences. Declare them per app to have the registry check
1361
+ every name, and to mark the ones served before sign-in:
1362
+
1363
+ ```ruby
1364
+ StandardFlags.configure do |config|
1365
+ config.audiences = { web: {}, mobile: {}, pre_auth: { public: true, unit: :install } }
1366
+ end
1367
+ ```
1368
+
1369
+ Without `config.audiences`, every audience a flag exposes to is a private
1370
+ audience, as in 0.2. When it is set, an undeclared `expose:` or `serve:`
1371
+ audience fails boot, and building a payload for an undeclared audience raises
1372
+ when `config.strict` is on (and is empty otherwise).
1373
+
1374
+ ### The OFREP endpoint
1375
+
1376
+ ```ruby
1377
+ # config/routes.rb
1378
+ post "ofrep/v1/evaluate/flags", to: "flags#ofrep_evaluate_flags"
1379
+ post "ofrep/v1/evaluate/flags/:key", to: "flags#ofrep_evaluate_flag"
1380
+
1381
+ # app/controllers/flags_controller.rb
1382
+ class FlagsController < Api::BaseController # ActionController::API
1383
+ include StandardFlags::OFREP::Controller
1384
+ standard_flags_ofrep audience: :mobile # on ::Base, add csrf: (below)
1385
+
1386
+ before_action :authenticate! # your own; 401/403 stay yours
1387
+
1388
+ private
1389
+
1390
+ def standard_flags_context = current_account
1391
+ end
1392
+ ```
1393
+
1394
+ ```http
1395
+ POST /ofrep/v1/evaluate/flags
1396
+ Authorization: Bearer …
1397
+ X-Client-Platform: android
1398
+ X-Client-Version: 0.5.0
1399
+ Content-Type: application/json
1400
+
1401
+ { "context": { "targetingKey": "ignored", "platform": "android", "appVersion": "0.5.0" } }
1402
+ ```
1403
+
1404
+ ```http
1405
+ 200 OK
1406
+ ETag: "4b2eec86…"
1407
+ Cache-Control: no-cache, private
1408
+ Vary: Authorization, X-Client-Platform, X-Client-Version, X-Client-Build
1409
+
1410
+ { "flags": [
1411
+ { "key": "chat_enabled", "value": false, "reason": "KILL_SWITCH", "variant": "off" },
1412
+ { "key": "chat_v1", "value": false, "reason": "STATIC", "variant": "off" },
1413
+ { "key": "homeHero", "value": "savings", "reason": "SPLIT", "variant": "savings" },
1414
+ { "key": "insights_enabled", "value": false, "reason": "KILL_SWITCH", "variant": "off" },
1415
+ { "key": "brokenFlag", "errorCode": "PARSE_ERROR", "errorDetails": "the flag could not be evaluated; use the code default" }
1416
+ ],
1417
+ "metadata": { "version": "4b2eec86…" } }
1418
+ ```
1419
+
1420
+ - **Who it evaluates for.** Units come from `standard_flags_context`, the
1421
+ authenticated caller. The body's `targetingKey` is ignored, so a client
1422
+ can't choose who it is evaluated as. The body may only add client
1423
+ attributes (`platform`, `appVersion` or `app_version`, `build`). They are
1424
+ checked like the X-Client-* headers, and a header wins over the same body
1425
+ attribute. A context that already names a client keeps it. With
1426
+ `config.read_client_headers` off, the request contributes no client at
1427
+ all, from headers or body.
1428
+ - **Entries.** One entry per wire name, ordered by it. An entry carries a
1429
+ value, a variant and a reason (STATIC, DEFAULT, TARGETING_MATCH, SPLIT,
1430
+ DISABLED, ENV_PIN or KILL_SWITCH; KILL_SWITCH lets a client say
1431
+ "temporarily unavailable"). A flag whose evaluation failed gets OFREP's
1432
+ error entry instead, and the client uses its code default; the other flags
1433
+ are unaffected. No flag key, rule ID, env var name, unit key or unexposed
1434
+ flag ever appears.
1435
+ - **Statuses.** A Content-Type other than `application/json` (any charset)
1436
+ gets 415, and a malformed body gets 400, both as
1437
+ `{"errorCode":"INVALID_CONTEXT","errorDetails":…}`. On the single-flag path, a wire the audience isn't told
1438
+ about (a server-only flag, another audience's wire, a flag the client is
1439
+ too old for) gets 404 `FLAG_NOT_FOUND`, so server-only keys stay invisible.
1440
+ A flag whose evaluation failed gets 400 with its error code. Every status
1441
+ the mixin sends is 2xx, 304 or 4xx: some edges replace 5xx bodies, so a
1442
+ client would never see them.
1443
+ - **The request is checked first.** Before Rails' instrumentation (which
1444
+ decodes a JSON body), your filters, authentication and forgery protection
1445
+ run, the mixin checks the media type and reads the body itself. It refuses
1446
+ a declared Content-Length over 64 KiB without reading, reads at most
1447
+ 64 KiB otherwise, and checks UTF-8 and JSON. The bytes it read are what
1448
+ Rails parses afterwards, if anything asks for `params`. These 415 and 400
1449
+ answers say nothing about the caller, and come outside the rescue chain,
1450
+ so an app's `rescue_from StandardError` can't turn them into a 5xx. Put
1451
+ your own request-size limit in the web server too: the cap bounds what the
1452
+ mixin reads, not what the server buffers.
1453
+
1454
+ #### Forgery protection on `ActionController::Base`
1455
+
1456
+ Rails protects `::Base` controllers from cross-site request forgery by
1457
+ default, and a bearer-token client sends no CSRF token, so on such a
1458
+ controller you must choose:
1459
+
1460
+ ```ruby
1461
+ standard_flags_ofrep audience: :mobile, csrf: :skip # bearer-token APIs
1462
+ standard_flags_ofrep audience: :mobile, csrf: :protect # cookie sessions; clients send the token
1463
+ ```
1464
+
1465
+ - `csrf: :skip` skips forgery protection for the two OFREP actions only. It
1466
+ is safe because the endpoints accept only `Content-Type:
1467
+ application/json`, which a cross-site form can't send without a CORS
1468
+ preflight, and because the responses aren't readable cross-origin. Use it
1469
+ when requests authenticate with a bearer token or API key.
1470
+ - `csrf: :protect` keeps Rails' check: use it when the endpoint
1471
+ authenticates with a session cookie, and have the client send the token
1472
+ (or use the [embed](#embeds) instead).
1473
+
1474
+ Leaving `csrf:` out on a controller with forgery protection raises
1475
+ `StandardFlags::ConfigurationError` when the class is declared, or on the
1476
+ first request if `protect_from_forgery` comes later, instead of answering
1477
+ every request 422. `ActionController::API` controllers have no forgery
1478
+ protection and need neither.
1479
+
1480
+ OFREP's schema lists only STATIC, TARGETING_MATCH, SPLIT, DISABLED and
1481
+ UNKNOWN as success reasons. OpenFeature treats reasons as an open set, and the
1482
+ gem also sends DEFAULT, ENV_PIN and KILL_SWITCH. OFREP providers pass the
1483
+ string through.
1484
+
1485
+ ### Caching and ETags
1486
+
1487
+ The ETag is the SHA-256 of the audience plus the RFC 8785 canonical JSON of
1488
+ the entries (sorted keys, no whitespace, strings as raw UTF-8). It depends only on what this client is
1489
+ told, never on the config revision, so a client that switches user never gets
1490
+ a 304 for answers that differ. Two users told the same thing share an ETag,
1491
+ and a 304 is then correct. `If-None-Match` naming it (quoted or bare, weak or
1492
+ strong, never `*`) gets 304 with no body. `metadata.version` carries the same
1493
+ value, so a client bootstrapped from an embed can send it as If-None-Match.
1494
+ A single-flag 200 carries a strong ETag over its one entry and honours
1495
+ If-None-Match the same way.
1496
+
1497
+ ### Embeds
1498
+
1499
+ ```ruby
1500
+ render json: { profile: profile, features: standard_flags_payload(:mobile, format: :ofrep) }
1501
+ StandardFlags.payload(:device, for: device, client: { platform: "android", version: "2.1.0" }, format: :ofrep)
1502
+ # => { "flags" => [...], "metadata" => { "version" => "…" } }
1503
+ ```
1504
+
1505
+ The embed returns the bulk endpoint's body, built the same way. The flat
1506
+ format stays the default, and `payload_digest` still hashes the flat payload.
1507
+
1508
+ ### Minimum client versions
1509
+
1510
+ ```ruby
1511
+ flag :new_checkout, owner: "payments", remove_by: "2027-06-01", final: true,
1512
+ expose: { mobile: :checkoutV2 }, min_client: { android: "0.4.0", ios: "0.4.0" }
1513
+ ```
1514
+
1515
+ A client on a listed platform below the minimum is not told about the flag.
1516
+ Neither is one whose version is missing or unparseable, nor one that sends
1517
+ no platform: an unknown build never receives a `min_client` flag. Platforms
1518
+ the declaration doesn't list are unaffected. Platforms come from
1519
+ `config.client_platforms`, and precedence is SemVer's (`0.4.0-rc.1` is below
1520
+ `0.4.0`).
1521
+
1522
+ A kill switch can't declare `min_client:` (the registry refuses it): a
1523
+ withheld entry means the client's code default, which for a kill switch is
1524
+ "available", so an old build would never see the feature pulled.
1525
+
1526
+ ### Deprecated wires
1527
+
1528
+ When a flag a shipped client reads is removed, keep its wire answering until
1529
+ those builds are gone:
1530
+
1531
+ ```ruby
1532
+ tombstone :chat_v1, removed: "2026-12-01", serve: { mobile: { chat_v1: false } },
1533
+ until: "2027-03-01", until_clients: { android: "0.6.0" }
1534
+ ```
1535
+
1536
+ The wire is served with reason STATIC through `until:` and disappears the
1537
+ day after. `until:` is required with `serve:`, and is compared with today's
1538
+ date in UTC, so every host switches the wire off at the same moment. With
1539
+ `until_clients:`, a client on that platform at or above the version stops
1540
+ receiving it sooner. A client of unknown version keeps receiving it until
1541
+ `until:`; `until_clients:` never extends it. A static wire can't reuse a
1542
+ live wire name. Once `until:` has passed, `flags:stale` lists
1543
+ the `serve:` block as removable.
1544
+
1545
+ ### Before sign-in
1546
+
1547
+ ```ruby
1548
+ class PreAuthFlagsController < ActionController::API
1549
+ include StandardFlags::OFREP::Controller
1550
+ standard_flags_ofrep audience: :pre_auth, anonymous: true
1551
+ end
1552
+ ```
1553
+
1554
+ An `anonymous: true` controller serves only a `public: true` audience, and
1555
+ never calls `standard_flags_context`. Flags exposed to a public audience may
1556
+ target by client attributes, and by the audience's `unit:` (an install ID,
1557
+ say), whose key is the body's `targetingKey`. Every other unit resolves to
1558
+ nothing. Runtime rules skip segments, since an app's segment resolver may
1559
+ read whoever is signed in. The registry refuses a public-audience flag on any
1560
+ other unit. Everything else is invisible before sign-in.
1561
+
1562
+ Pre-auth answers are public: anyone who sends an install ID reads what that
1563
+ install gets, memberships included. Use install IDs the client generates at
1564
+ random (a UUID, say), never guessable ones. When a public-audience flag's
1565
+ runtime rule has members or cohorts, the gem logs a warning when rules load
1566
+ (`public_targeting.standard_flags`) and lists it in the diagnostics.
1567
+
1568
+ ### Trust model
1569
+
1570
+ The server decides. Clients receive only evaluated values for their
1571
+ audience, never rules, allowlists, env names or the existence of server-only
1572
+ flags. Client attributes (headers or body) only shape what a client is told
1573
+ (`min_client:`, rule conditions). They never choose the user, so a forged
1574
+ version can at most withhold a flag or show a value meant for another build.
1575
+ Never gate authorisation on a client-reported version.
1576
+
1076
1577
  ## Rake tasks
1077
1578
 
1078
1579
  | Task | What it does |
1079
1580
  |------|--------------|
1080
1581
  | `bin/rails flags:list` | Every flag with its value, reason, deciding env var and remove_by (`permanent` for permanent flags). |
1081
- | `bin/rails flags:stale` | Flags and modes past `remove_by`, with the `final:` value to keep. Permanent ones never appear. With runtime rules on, also stale rules and memberships due for purge ([Stale rules](#stale-rules)). |
1582
+ | `bin/rails flags:stale` | Flags and modes past `remove_by`, with the `final:` value to keep. Permanent ones never appear. Tombstones whose `serve:` block is past `until:`. With runtime rules on, also stale rules and memberships due for purge ([Stale rules](#stale-rules)). |
1082
1583
  | `bin/rails flags:show KEY=` | One flag's declaration, value here, ENV pin and stored rule; `KEY=cohort:<key>` for a cohort. |
1083
1584
  | `bin/rails flags:set` / `ramp` / `start` / `pause` / `stop` / `members:add` / `members:remove` / `purge` | Break-glass changes through the audited operations ([Rake tasks for break-glass changes](#rake-tasks-for-break-glass-changes)). |
1084
1585
  | `bin/rails flags:restore AT=` | Rules and memberships as they were at `AT`, from the audit log; a dry run unless `APPLY=1` ([Restore](#restore)). |
@@ -1140,14 +1641,8 @@ those environments whenever they pin the flag on. Other pins are optional,
1140
1641
  which the env spec has no level for, so they aren't declared. The app's own
1141
1642
  `env_spec` entry for a name wins.
1142
1643
 
1143
- On older standard_health, or without `register_default_checks`, register it
1144
- yourself:
1145
-
1146
- ```ruby
1147
- StandardHealth.configure do |c|
1148
- c.register_check :flags, StandardFlags::HealthCheck
1149
- end
1150
- ```
1644
+ Without `register_default_checks` (or on standard_health older than 0.9),
1645
+ register it by hand: `c.register_check :flags, StandardFlags::HealthCheck`.
1151
1646
 
1152
1647
  The check fails when a `forbidden_in` flag is pinned on, or when runtime
1153
1648
  rules are on and their tables are missing. It warns on unparseable pins,
@@ -1337,7 +1832,12 @@ way the pin goes through the same parser and guard as in production.
1337
1832
 
1338
1833
  ## Conformance suite
1339
1834
 
1340
- `spec/fixtures/conformance/*.json` holds the evaluation contract as data.
1835
+ `conformance/` (shipped in the gem) holds the contract as data, with a JSON
1836
+ Schema (`conformance/schema/fixture.schema.json`) every fixture validates
1837
+ against, and [its own README](conformance/README.md). Each file is tagged
1838
+ `scope: "server"` (ENV pins, legacy variables, runtime rules, the write path,
1839
+ bucketing) or `"wire"` (what clients run). `conformance/*.json` holds the
1840
+ evaluation contract.
1341
1841
  Each file has a registry snippet and cases: environment variables and a
1342
1842
  context in, the expected value, variant, reason, error code and deciding
1343
1843
  variable out. `bucket_vectors.json` pins test vectors for every bucketing
@@ -1346,7 +1846,32 @@ Kotlin or TypeScript client, say) run the same files, so they cannot drift
1346
1846
  from the server on what a flag evaluates to. `runtime/*.json` adds runtime
1347
1847
  rules: each case's rule, cohorts and memberships plus a context (unit keys,
1348
1848
  client, segments) in; value, variant, reason, error code and `rule_id` out,
1349
- including the v1 and v2 bucket boundaries.
1849
+ including the v1 and v2 bucket boundaries. `runtime/client.json` covers
1850
+ client conditions: neutral version ranges, prerelease ordering, shorthand
1851
+ versions, build ranges, and clients with no platform or an unknown one.
1852
+ Cases marked `"scope": "server"` exercise the RubyGems compatibility only
1853
+ the Ruby server keeps; other evaluators skip them.
1854
+
1855
+ `versions/version_ranges.json` is for clients: a version and a range in,
1856
+ `matched` true or false out, the same for build numbers, plus ranges every
1857
+ implementation must refuse, with the length and whitespace limits in its
1858
+ description. It uses only the neutral syntax. The Ruby suite runs every case
1859
+ through both the client reading (`VersionRange.neutral`) and the server's
1860
+ read path. The five cases marked `server_matched` are where they differ: the
1861
+ server reads a client version that isn't SemVer (`1.4.0.1`) through RubyGems
1862
+ against a range RubyGems can also read (`>=0.0.0`), for 0.2.2
1863
+ compatibility. That only applies to versions an app passes in a context's
1864
+ client Hash, since client headers drop versions that aren't SemVer.
1865
+ `versions/legacy_ranges.json` (`"scope": "server"`) pins how RubyGems
1866
+ ranges stored by 0.2.x translate and evaluate, against `Gem::Requirement`.
1867
+
1868
+ `wire/delivery.json` pins what the server sends: registry, context and
1869
+ client in, OFREP entries and ETag out (aliases, `min_client:` with known,
1870
+ unknown and older versions, deprecated wires, errored flags, ETag equality
1871
+ across users and clients). `wire/client_state.json` pins what a client does
1872
+ with a payload: on, off and not loaded, a missing value meaning the code
1873
+ default, ceilings, and payloads refused by size or shape. Neither needs Ruby
1874
+ to run.
1350
1875
 
1351
1876
  ## Bucketing
1352
1877
 
@@ -1368,15 +1893,21 @@ every vector.
1368
1893
 
1369
1894
  ## Roadmap
1370
1895
 
1371
- Phase 2 adds runtime rules stored in the database (changes without a
1372
- redeploy, allow and deny lists, cohorts, sticky percentage rollouts with
1373
- per-flag salts), audited write operations and an admin generator. The read
1374
- path, the operations, the rake tasks, the MCP tools, the admin generator
1375
- and `flags:restore` are done; an OpenFeature provider comes next. Phase 3
1376
- adds client delivery: an OpenFeature remote-evaluation (OFREP) endpoint,
1377
- client version targeting, a minimum-version endpoint and the manifest
1378
- contract checked in client CI. Phase 4 adds experiment exposure tracking and
1379
- staged rollout plans with automatic halts.
1896
+ Phase 1 (0.1.0) shipped the registry, the ENV layer and the evaluation API.
1897
+ Phase 2 (0.2.x) shipped runtime rules stored in the database (allow and
1898
+ deny lists, cohorts, segments, client conditions, sticky percentage rollouts
1899
+ and variants), the audited write operations and rake tasks, the MCP
1900
+ operator tools, the admin generator, `flags:restore` and the OpenFeature
1901
+ provider.
1902
+
1903
+ Phase 3 is client delivery. On `main` now: client context from request
1904
+ headers, portable version ranges, build conditions, `FeatureDisabled` and
1905
+ gated MCP tools, an OFREP endpoint mixin and an embeddable payload with
1906
+ ETags, minimum client versions and deprecated wires, and the portable
1907
+ conformance suite. Next: an upgrade endpoint, compatibility windows, and the
1908
+ manifest contract checked in client CI. Phase 4 adds
1909
+ experiment exposure tracking and staged rollout plans with automatic
1910
+ halts.
1380
1911
 
1381
1912
  ## License
1382
1913