standard_flags 0.1.0 → 0.2.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 (71) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +229 -0
  3. data/README.md +837 -33
  4. data/lib/generators/standard_flags/admin/admin_generator.rb +115 -0
  5. data/lib/generators/standard_flags/admin/templates/controller.rb.tt +103 -0
  6. data/lib/generators/standard_flags/admin/templates/index.tsx.tt +64 -0
  7. data/lib/generators/standard_flags/admin/templates/show.tsx.tt +275 -0
  8. data/lib/generators/standard_flags/install/install_generator.rb +16 -1
  9. data/lib/generators/standard_flags/install/templates/flags.rb.tt +3 -2
  10. data/lib/generators/standard_flags/install/templates/initializer.rb.tt +10 -0
  11. data/lib/generators/standard_flags/migrations/migrations_generator.rb +57 -0
  12. data/lib/generators/standard_flags/migrations/templates/create_standard_flags_tables.rb.tt +78 -0
  13. data/lib/standard_flags/actor.rb +50 -0
  14. data/lib/standard_flags/audit_trail.rb +56 -0
  15. data/lib/standard_flags/config.rb +78 -0
  16. data/lib/standard_flags/context.rb +5 -1
  17. data/lib/standard_flags/definition.rb +85 -13
  18. data/lib/standard_flags/diagnostics.rb +35 -3
  19. data/lib/standard_flags/engine.rb +10 -2
  20. data/lib/standard_flags/env_pin.rb +15 -4
  21. data/lib/standard_flags/errors.rb +4 -0
  22. data/lib/standard_flags/evaluation.rb +5 -4
  23. data/lib/standard_flags/evaluator.rb +14 -1
  24. data/lib/standard_flags/events.rb +49 -0
  25. data/lib/standard_flags/health_check.rb +12 -2
  26. data/lib/standard_flags/health_contribution.rb +65 -0
  27. data/lib/standard_flags/mcp/cohorts.rb +65 -0
  28. data/lib/standard_flags/mcp/flags.rb +143 -0
  29. data/lib/standard_flags/mcp/members.rb +154 -0
  30. data/lib/standard_flags/mcp/writes.rb +98 -0
  31. data/lib/standard_flags/mcp.rb +238 -0
  32. data/lib/standard_flags/memo.rb +15 -1
  33. data/lib/standard_flags/notifiers/logger.rb +14 -0
  34. data/lib/standard_flags/open_feature/provider.rb +232 -0
  35. data/lib/standard_flags/open_feature.rb +26 -0
  36. data/lib/standard_flags/operations/audit.rb +218 -0
  37. data/lib/standard_flags/operations/base.rb +290 -0
  38. data/lib/standard_flags/operations/cohorts.rb +80 -0
  39. data/lib/standard_flags/operations/failure.rb +16 -0
  40. data/lib/standard_flags/operations/members.rb +164 -0
  41. data/lib/standard_flags/operations/restore.rb +330 -0
  42. data/lib/standard_flags/operations/restore_target.rb +197 -0
  43. data/lib/standard_flags/operations/rules.rb +233 -0
  44. data/lib/standard_flags/operations/validation.rb +154 -0
  45. data/lib/standard_flags/operations.rb +43 -0
  46. data/lib/standard_flags/parser.rb +16 -0
  47. data/lib/standard_flags/purge_job.rb +14 -0
  48. data/lib/standard_flags/registry.rb +38 -5
  49. data/lib/standard_flags/reporting.rb +51 -7
  50. data/lib/standard_flags/resolvers.rb +14 -7
  51. data/lib/standard_flags/result.rb +43 -0
  52. data/lib/standard_flags/rspec.rb +67 -13
  53. data/lib/standard_flags/runtime/active_record_store.rb +428 -0
  54. data/lib/standard_flags/runtime/cache.rb +98 -0
  55. data/lib/standard_flags/runtime/evaluation_tracker.rb +93 -0
  56. data/lib/standard_flags/runtime/memory_store.rb +408 -0
  57. data/lib/standard_flags/runtime/models.rb +43 -0
  58. data/lib/standard_flags/runtime/resolver.rb +256 -0
  59. data/lib/standard_flags/runtime/rule_snapshot.rb +60 -0
  60. data/lib/standard_flags/runtime/store.rb +161 -0
  61. data/lib/standard_flags/runtime/values.rb +181 -0
  62. data/lib/standard_flags/runtime.rb +266 -0
  63. data/lib/standard_flags/sensor.rb +12 -5
  64. data/lib/standard_flags/subscribers.rb +6 -0
  65. data/lib/standard_flags/testing.rb +100 -1
  66. data/lib/standard_flags/tooling/changes.rb +196 -0
  67. data/lib/standard_flags/tooling.rb +232 -19
  68. data/lib/standard_flags/version.rb +1 -1
  69. data/lib/standard_flags.rb +33 -5
  70. data/lib/tasks/standard_flags.rake +45 -1
  71. metadata +41 -1
@@ -0,0 +1,115 @@
1
+ require "rails/generators"
2
+ require "pathname"
3
+
4
+ module StandardFlags
5
+ module Generators
6
+ # `rails g standard_flags:admin` writes an operator page the app owns:
7
+ #
8
+ # * a controller (default Admin::FlagsController < ApplicationController)
9
+ # with index, show and one action per operation. Pages read through
10
+ # StandardFlags::MCP, so `config.authorize` decides who sees what and
11
+ # unit keys stay masked; changes go through StandardFlags::Operations.
12
+ # It runs as the signed-in user (`--actor-method`, default
13
+ # current_user) and answers 401 when there is none, never falling back
14
+ # to config.actor_resolver.
15
+ # * routes under a path (default /admin/flags).
16
+ # * two Inertia pages, standard_flags/index.tsx and show.tsx, in plain
17
+ # semantic markup, typed from the `standard_flags:typescript` output.
18
+ #
19
+ # Restyle, move or cut down what it writes; the gem never reads it back.
20
+ class AdminGenerator < Rails::Generators::Base
21
+ OPERATIONS = %w[start pause stop ramp set_value add_members remove_members].freeze
22
+
23
+ source_root File.expand_path("templates", __dir__)
24
+
25
+ class_option :path, type: :string, default: "/admin/flags", desc: "Where the routes are mounted"
26
+ class_option :base_controller, type: :string, default: "ApplicationController",
27
+ desc: "The class the controller inherits from (where your admin authentication lives)"
28
+ class_option :controller, type: :string, default: nil,
29
+ desc: "The controller's name (default: from --path, e.g. Admin::FlagsController)"
30
+ class_option :pages_path, type: :string, default: "app/javascript/pages", desc: "Where your Inertia pages live"
31
+ class_option :actor_method, type: :string, default: "current_user",
32
+ desc: "The controller method returning the signed-in user (nil when signed out: the page answers 401)"
33
+
34
+ desc <<~DESC
35
+ Writes an admin page for flags: a controller, routes and two Inertia
36
+ pages (TSX). Run bin/rails standard_flags:typescript for the types
37
+ they import, then restyle the pages to fit your app.
38
+ DESC
39
+
40
+ def check_options
41
+ actor_method
42
+ end
43
+
44
+ def create_controller
45
+ template "controller.rb.tt", File.join("app/controllers", "#{controller_path}_controller.rb")
46
+ end
47
+
48
+ def add_routes
49
+ route routes_block
50
+ end
51
+
52
+ def create_pages
53
+ template "index.tsx.tt", File.join(options[:pages_path], "standard_flags/index.tsx")
54
+ template "show.tsx.tt", File.join(options[:pages_path], "standard_flags/show.tsx")
55
+ end
56
+
57
+ def explain
58
+ say "Admin page: #{mount_path}. It runs as `#{actor_method}` through config.authorize, so configure that " \
59
+ "first; with nobody signed in it answers 401 (see standard_flags_deny). Run bin/rails " \
60
+ "standard_flags:typescript for its types."
61
+ say "Unit keys are posted as `unit_keys`, which Rails' default config.filter_parameters (`_key`) keeps " \
62
+ "out of the request log. If your app's list doesn't match it, add :unit_keys."
63
+ end
64
+
65
+ private
66
+
67
+ # "/admin/flags", without a trailing slash.
68
+ def mount_path
69
+ "/#{options[:path].to_s.delete_prefix('/').delete_suffix('/')}"
70
+ end
71
+
72
+ # "admin/flags"
73
+ def controller_path
74
+ return options[:controller].to_s.delete_suffix("Controller").underscore if options[:controller]
75
+
76
+ mount_path.delete_prefix("/").tr("-", "_")
77
+ end
78
+
79
+ # "Admin::FlagsController"
80
+ def controller_class
81
+ "#{controller_path.camelize}Controller"
82
+ end
83
+
84
+ def base_controller
85
+ options[:base_controller]
86
+ end
87
+
88
+ def actor_method
89
+ name = options[:actor_method].to_s
90
+ raise Thor::Error, "--actor-method must be a method name, got #{name.inspect}" unless name.match?(/\A[a-z_][a-zA-Z0-9_]*[?!]?\z/)
91
+
92
+ name
93
+ end
94
+
95
+ def routes_block
96
+ lines = [ "# StandardFlags admin (bin/rails g standard_flags:admin)",
97
+ "scope path: #{mount_path.inspect}, controller: #{controller_path.inspect}, as: :standard_flags do",
98
+ " get \"/\", action: :index, as: :flags",
99
+ " get \"/:id\", action: :show, as: :flag" ]
100
+ OPERATIONS.each { |operation| lines << " post \"/:id/#{operation}\", action: :#{operation}, as: :#{operation}_flag" }
101
+ lines << "end"
102
+ lines.join("\n")
103
+ end
104
+
105
+ # The import path from the pages to the generated .d.ts, without its
106
+ # extension: "../../types/standard_flags".
107
+ def types_import
108
+ target = Pathname(StandardFlags.config.typescript_path.to_s.delete_suffix(".d.ts").delete_suffix(".ts"))
109
+ from = Pathname(File.join(options[:pages_path], "standard_flags"))
110
+ relative = target.relative_path_from(from).to_s
111
+ relative.start_with?(".") ? relative : "./#{relative}"
112
+ end
113
+ end
114
+ end
115
+ end
@@ -0,0 +1,103 @@
1
+ # Generated by `bin/rails g standard_flags:admin`. Yours to change.
2
+ #
3
+ # Pages read through StandardFlags::MCP, so `config.authorize` decides who
4
+ # may read ("flags:read") and unit keys stay masked. Every change goes
5
+ # through StandardFlags::Operations: authorised ("flags:write", or
6
+ # "flags:ramp" for ramps), refused for ENV-pinned flags, validated, audited,
7
+ # and checked against the revision the page was showing.
8
+ #
9
+ # Every request runs as the signed-in user (ACTOR_METHOD), never as
10
+ # config.actor_resolver: with nobody signed in it is denied before any tool
11
+ # runs. Unit keys are posted as `unit_keys`, which Rails' default
12
+ # filter_parameters (`_key`) keeps out of the request log.
13
+ class <%= controller_class %> < <%= base_controller %>
14
+ BASE_PATH = <%= mount_path.inspect %>.freeze
15
+ ACTOR_METHOD = :<%= actor_method %>
16
+
17
+ before_action :require_standard_flags_actor
18
+
19
+ def index
20
+ flags = tool("list_flags")
21
+ return refuse(flags) if flags["error"]
22
+
23
+ render inertia: "standard_flags/index", props: { base_path: BASE_PATH, flags: flags, flash: flash.to_hash }
24
+ end
25
+
26
+ def show
27
+ flag = tool("get_flag", "key" => params[:id])
28
+ return refuse(flag) if flag["error"]
29
+
30
+ render inertia: "standard_flags/show", props: {
31
+ base_path: BASE_PATH, flag: flag, members: members(flag), flash: flash.to_hash,
32
+ audit: (StandardFlags::AuditTrail.new.entries(flag["key"]) if StandardFlags::AuditTrail.available?)
33
+ }
34
+ end
35
+
36
+ def start = change(StandardFlags::Operations::Start)
37
+ def pause = change(StandardFlags::Operations::Pause)
38
+ def stop = change(StandardFlags::Operations::Stop, serve: params[:serve])
39
+ def ramp = change(StandardFlags::Operations::Ramp) { { bps: Integer(params[:bps].to_s, 10), **optional(:value) } }
40
+ def set_value = change(StandardFlags::Operations::SetValue, value: params[:value].presence)
41
+ def add_members = change(StandardFlags::Operations::AddMembers, keys: member_keys, **optional(:value))
42
+ def remove_members = change(StandardFlags::Operations::RemoveMembers, keys: member_keys)
43
+
44
+ private
45
+
46
+ # Who the page runs as: the signed-in user, or nil.
47
+ def standard_flags_actor
48
+ return @standard_flags_actor if defined?(@standard_flags_actor)
49
+
50
+ @standard_flags_actor = respond_to?(ACTOR_METHOD, true) ? __send__(ACTOR_METHOD) : nil
51
+ end
52
+
53
+ def require_standard_flags_actor
54
+ standard_flags_deny if standard_flags_actor.nil?
55
+ end
56
+
57
+ # Nobody is signed in. Redirect to your sign-in page here if you prefer.
58
+ def standard_flags_deny
59
+ head :unauthorized
60
+ end
61
+
62
+ def tool(name, arguments = {})
63
+ StandardFlags::MCP.tool(name).call(arguments, actor: standard_flags_actor)
64
+ end
65
+
66
+ # One page of the flag's members, keys masked; nil when it can have none.
67
+ def members(flag)
68
+ return unless flag["unit"] && flag["runtime_rules"]
69
+
70
+ page = tool("list_members", "key" => flag["key"], "offset" => [ params[:members_offset].to_i, 0 ].max)
71
+ page unless page["error"]
72
+ end
73
+
74
+ # Runs the operation as the signed-in user, then redirects back with a
75
+ # flash. A block builds arguments that can fail to parse.
76
+ def change(operation, **args)
77
+ args = yield if block_given?
78
+ result = operation.call(params[:id], actor: standard_flags_actor, reason: params[:reason].to_s,
79
+ expected_revision: params[:expected_revision].presence&.to_i, **args)
80
+ if result.success?
81
+ flash[:notice] = "#{operation.name.demodulize}: done (revision #{result.value[:revision]})"
82
+ else
83
+ flash[:alert] = "#{operation.name.demodulize} refused (#{result.code}): #{result.errors.join('; ')}"
84
+ end
85
+ redirect_to standard_flags_flag_path(params[:id])
86
+ rescue ArgumentError => e
87
+ flash[:alert] = e.message
88
+ redirect_to standard_flags_flag_path(params[:id])
89
+ end
90
+
91
+ def optional(*names)
92
+ names.filter_map { |name| [ name, params[name] ] if params[name].present? }.to_h
93
+ end
94
+
95
+ def member_keys
96
+ params[:unit_keys].to_s.split(/[\s,]+/).compact_blank
97
+ end
98
+
99
+ def refuse(result)
100
+ status = { "unauthorized" => :forbidden, "unknown_flag" => :not_found, "tombstoned_flag" => :not_found }
101
+ render plain: result.dig("error", "message"), status: status.fetch(result.dig("error", "code"), :unprocessable_entity)
102
+ end
103
+ end
@@ -0,0 +1,64 @@
1
+ // Generated by `bin/rails g standard_flags:admin`. Yours to restyle.
2
+ // Types come from `bin/rails standard_flags:typescript`.
3
+ import { Link } from "@inertiajs/react";
4
+ import type { FlagList, FlagSummary } from "<%= types_import %>";
5
+
6
+ interface Flash {
7
+ readonly notice?: string;
8
+ readonly alert?: string;
9
+ }
10
+
11
+ interface Props {
12
+ readonly base_path: string;
13
+ readonly flags: FlagList;
14
+ readonly flash: Flash;
15
+ }
16
+
17
+ function ruleText(flag: FlagSummary): string {
18
+ if (flag.rule === null) return "none";
19
+ const percentage = flag.rule.percentage_bps === null ? "" : `, ${flag.rule.percentage_bps / 100}%`;
20
+ return `${flag.rule.status}${percentage}`;
21
+ }
22
+
23
+ export default function StandardFlagsIndex({ base_path, flags, flash }: Props) {
24
+ return (
25
+ <main>
26
+ <h1>Feature flags</h1>
27
+ {flash.notice && <p role="status">{flash.notice}</p>}
28
+ {flash.alert && <p role="alert">{flash.alert}</p>}
29
+ <p>
30
+ Runtime rules are {flags.runtime_rules ? "on" : "off"}
31
+ {flags.store_revision !== null && ` (revision ${flags.store_revision})`}.
32
+ </p>
33
+ <table>
34
+ <thead>
35
+ <tr>
36
+ <th scope="col">Flag</th>
37
+ <th scope="col">Kind</th>
38
+ <th scope="col">Owner</th>
39
+ <th scope="col">Value</th>
40
+ <th scope="col">Decided by</th>
41
+ <th scope="col">Rule</th>
42
+ </tr>
43
+ </thead>
44
+ <tbody>
45
+ {flags.flags.map((flag) => (
46
+ <tr key={flag.key}>
47
+ <th scope="row">
48
+ <Link href={`${base_path}/${flag.key}`}>{flag.key}</Link>
49
+ {flag.description && <p>{flag.description}</p>}
50
+ </th>
51
+ <td>{flag.kind}</td>
52
+ <td>{flag.owner}</td>
53
+ <td>
54
+ <code>{flag.value ?? "none"}</code>
55
+ </td>
56
+ <td>{flag.pinned ? <strong>{flag.pinned.label}</strong> : `${flag.source} (${flag.reason})`}</td>
57
+ <td>{ruleText(flag)}</td>
58
+ </tr>
59
+ ))}
60
+ </tbody>
61
+ </table>
62
+ </main>
63
+ );
64
+ }
@@ -0,0 +1,275 @@
1
+ // Generated by `bin/rails g standard_flags:admin`. Yours to restyle.
2
+ // Types come from `bin/rails standard_flags:typescript`.
3
+ import type { FormEvent, ReactNode } from "react";
4
+ import { Link, useForm } from "@inertiajs/react";
5
+ import type { FlagAuditEntry, FlagDetail, FlagMemberPage } from "<%= types_import %>";
6
+
7
+ interface Flash {
8
+ readonly notice?: string;
9
+ readonly alert?: string;
10
+ }
11
+
12
+ interface Props {
13
+ readonly base_path: string;
14
+ readonly flag: FlagDetail;
15
+ readonly members: FlagMemberPage | null;
16
+ readonly audit: ReadonlyArray<FlagAuditEntry> | null;
17
+ readonly flash: Flash;
18
+ }
19
+
20
+ type Field =
21
+ | { readonly name: string; readonly label: string; readonly kind: "text" | "number" | "keys" }
22
+ | { readonly name: string; readonly label: string; readonly kind: "select"; readonly options: ReadonlyArray<string> };
23
+
24
+ interface OperationFormProps {
25
+ readonly action: string;
26
+ readonly title: string;
27
+ readonly revision: number | null;
28
+ readonly fields?: ReadonlyArray<Field>;
29
+ }
30
+
31
+ // One operation: its fields, a required reason, and the revision the page
32
+ // showed, so a change made meanwhile is refused rather than overwritten.
33
+ function OperationForm({ action, title, revision, fields = [] }: OperationFormProps) {
34
+ const initial: Record<string, string> = { reason: "", expected_revision: revision === null ? "" : String(revision) };
35
+ fields.forEach((field) => {
36
+ initial[field.name] = "";
37
+ });
38
+ const { data, setData, post, processing } = useForm<Record<string, string>>(initial);
39
+
40
+ function submit(event: FormEvent<HTMLFormElement>) {
41
+ event.preventDefault();
42
+ post(action);
43
+ }
44
+
45
+ return (
46
+ <form onSubmit={submit}>
47
+ <fieldset>
48
+ <legend>{title}</legend>
49
+ {fields.map((field) => (
50
+ <p key={field.name}>
51
+ <label>
52
+ {field.label}{" "}
53
+ {field.kind === "select" ? (
54
+ <select value={data[field.name]} onChange={(e) => setData(field.name, e.target.value)}>
55
+ <option value="">(none)</option>
56
+ {field.options.map((option) => (
57
+ <option key={option} value={option}>
58
+ {option}
59
+ </option>
60
+ ))}
61
+ </select>
62
+ ) : field.kind === "keys" ? (
63
+ <textarea value={data[field.name]} onChange={(e) => setData(field.name, e.target.value)} />
64
+ ) : (
65
+ <input
66
+ type={field.kind}
67
+ value={data[field.name]}
68
+ onChange={(e) => setData(field.name, e.target.value)}
69
+ />
70
+ )}
71
+ </label>
72
+ </p>
73
+ ))}
74
+ <p>
75
+ <label>
76
+ Reason (audited){" "}
77
+ <input type="text" required value={data.reason} onChange={(e) => setData("reason", e.target.value)} />
78
+ </label>
79
+ </p>
80
+ <button type="submit" disabled={processing}>
81
+ {title}
82
+ </button>
83
+ </fieldset>
84
+ </form>
85
+ );
86
+ }
87
+
88
+ function Row({ term, children }: { readonly term: string; readonly children: ReactNode }) {
89
+ return (
90
+ <>
91
+ <dt>{term}</dt>
92
+ <dd>{children}</dd>
93
+ </>
94
+ );
95
+ }
96
+
97
+ export default function StandardFlagsShow({ base_path, flag, members, audit, flash }: Props) {
98
+ const action = (operation: string) => `${base_path}/${flag.key}/${operation}`;
99
+ const revision = flag.rule?.revision ?? null;
100
+ const values = flag.values;
101
+ const rule = flag.rule;
102
+ const editable = flag.runtime_rules && flag.pinned === null;
103
+
104
+ return (
105
+ <main>
106
+ <p>
107
+ <Link href={base_path}>All flags</Link>
108
+ </p>
109
+ <h1>{flag.key}</h1>
110
+ {flash.notice && <p role="status">{flash.notice}</p>}
111
+ {flash.alert && <p role="alert">{flash.alert}</p>}
112
+ {flag.pinned && (
113
+ <p role="status">
114
+ <strong>{flag.pinned.label}</strong>: read-only here. Unset the variable to change it from this page.
115
+ </p>
116
+ )}
117
+
118
+ <section>
119
+ <h2>Declaration</h2>
120
+ <dl>
121
+ <Row term="Kind">{flag.kind}</Row>
122
+ <Row term="Owner">{flag.owner}</Row>
123
+ {flag.description && <Row term="Description">{flag.description}</Row>}
124
+ <Row term="Unit">{flag.unit ?? "none"}</Row>
125
+ <Row term="Values">{values.join(", ")}</Row>
126
+ <Row term="Code default">{flag.default}</Row>
127
+ </dl>
128
+ </section>
129
+
130
+ <section>
131
+ <h2>Value here</h2>
132
+ <dl>
133
+ <Row term="Value">
134
+ <code>{flag.evaluation.value ?? "none"}</code>
135
+ </Row>
136
+ <Row term="Reason">{flag.evaluation.reason}</Row>
137
+ <Row term="Decided by">{flag.evaluation.source}</Row>
138
+ {flag.evaluation.rule_id && <Row term="Rule part">{flag.evaluation.rule_id}</Row>}
139
+ </dl>
140
+ </section>
141
+
142
+ <section>
143
+ <h2>Runtime rule</h2>
144
+ {!flag.runtime_rules && <p>Runtime rules are off.</p>}
145
+ {flag.runtime_rules && rule === null && <p>No rule yet: the code default serves.</p>}
146
+ {rule && (
147
+ <dl>
148
+ <Row term="Status">{rule.status}</Row>
149
+ <Row term="Revision">{rule.revision}</Row>
150
+ <Row term="Percentage">
151
+ {rule.percentage_bps === null ? "none" : `${rule.percentage_bps / 100}%`}
152
+ {rule.rollout_value && ` → ${rule.rollout_value}`}
153
+ </Row>
154
+ <Row term="Variants">
155
+ {Object.entries(rule.variant_weights)
156
+ .map(([variant, weight]) => `${variant} ${weight / 100}%`)
157
+ .join(", ") || "none"}
158
+ </Row>
159
+ <Row term="Fallthrough">{rule.fallthrough_value ?? "none"}</Row>
160
+ {rule.status === "stopped" && <Row term="Serving">{rule.stop_value}</Row>}
161
+ <Row term="Cohorts">
162
+ {rule.cohorts.map((attachment) => `${attachment.cohort} → ${attachment.value}`).join(", ") || "none"}
163
+ </Row>
164
+ <Row term="Members">{rule.member_count}</Row>
165
+ </dl>
166
+ )}
167
+ </section>
168
+
169
+ {members && (
170
+ <section>
171
+ <h2>Members ({members.total})</h2>
172
+ <table>
173
+ <thead>
174
+ <tr>
175
+ <th scope="col">Unit key</th>
176
+ <th scope="col">Unit</th>
177
+ <th scope="col">Value</th>
178
+ <th scope="col">Expires</th>
179
+ </tr>
180
+ </thead>
181
+ <tbody>
182
+ {members.members.map((member, index) => (
183
+ <tr key={`${members.offset + index}`}>
184
+ <td>
185
+ <code>{member.unit_key}</code>
186
+ </td>
187
+ <td>{member.unit}</td>
188
+ <td>{member.value}</td>
189
+ <td>{member.expired ? "expired" : (member.expires_at ?? "never")}</td>
190
+ </tr>
191
+ ))}
192
+ </tbody>
193
+ </table>
194
+ <nav aria-label="Member pages">
195
+ {members.offset > 0 && (
196
+ <Link href={`${base_path}/${flag.key}?members_offset=${Math.max(members.offset - members.limit, 0)}`}>
197
+ Previous
198
+ </Link>
199
+ )}{" "}
200
+ {members.next_offset !== null && (
201
+ <Link href={`${base_path}/${flag.key}?members_offset=${members.next_offset}`}>Next</Link>
202
+ )}
203
+ </nav>
204
+ </section>
205
+ )}
206
+
207
+ {editable && (
208
+ <section>
209
+ <h2>Change</h2>
210
+ <OperationForm action={action("start")} title="Start" revision={revision} />
211
+ <OperationForm action={action("pause")} title="Pause" revision={revision} />
212
+ <OperationForm
213
+ action={action("ramp")}
214
+ title="Ramp"
215
+ revision={revision}
216
+ fields={[
217
+ { name: "bps", label: "Basis points (0-10000)", kind: "number" },
218
+ { name: "value", label: "Rollout value", kind: "select", options: values },
219
+ ]}
220
+ />
221
+ <OperationForm
222
+ action={action("set_value")}
223
+ title="Set fallthrough value"
224
+ revision={revision}
225
+ fields={[{ name: "value", label: "Value (none clears it)", kind: "select", options: values }]}
226
+ />
227
+ <OperationForm
228
+ action={action("stop")}
229
+ title="Stop"
230
+ revision={revision}
231
+ fields={[{ name: "serve", label: "Serve to everyone", kind: "select", options: values }]}
232
+ />
233
+ {flag.unit && (
234
+ <>
235
+ <OperationForm
236
+ action={action("add_members")}
237
+ title="Add members"
238
+ revision={revision}
239
+ fields={[
240
+ { name: "unit_keys", label: "Unit keys (comma or newline separated)", kind: "keys" },
241
+ { name: "value", label: "Value", kind: "select", options: values },
242
+ ]}
243
+ />
244
+ <OperationForm
245
+ action={action("remove_members")}
246
+ title="Remove members"
247
+ revision={revision}
248
+ fields={[{ name: "unit_keys", label: "Unit keys (comma or newline separated)", kind: "keys" }]}
249
+ />
250
+ </>
251
+ )}
252
+ </section>
253
+ )}
254
+
255
+ {audit && (
256
+ <section>
257
+ <h2>Recent changes</h2>
258
+ {audit.length === 0 ? (
259
+ <p>None recorded.</p>
260
+ ) : (
261
+ <ol>
262
+ {audit.map((entry, index) => (
263
+ <li key={`${entry.occurred_at}-${index}`}>
264
+ <time dateTime={entry.occurred_at ?? undefined}>{entry.occurred_at}</time> {entry.event} by{" "}
265
+ {entry.actor ?? "unknown"}
266
+ {entry.revision !== null && ` (revision ${entry.revision})`}: {entry.reason}
267
+ </li>
268
+ ))}
269
+ </ol>
270
+ )}
271
+ </section>
272
+ )}
273
+ </main>
274
+ );
275
+ }
@@ -6,15 +6,21 @@ module StandardFlags
6
6
  #
7
7
  # * config/initializers/standard_flags.rb — runtime settings, commented.
8
8
  # * config/flags.rb — the registry, with one commented example per kind.
9
+ # * with --runtime, the runtime-rule migration (see
10
+ # `standard_flags:migrations`).
9
11
  #
10
12
  # Idempotent: existing files are skipped. Pass --force to overwrite.
11
13
  class InstallGenerator < Rails::Generators::Base
12
14
  source_root File.expand_path("templates", __dir__)
13
15
 
16
+ class_option :runtime, type: :boolean, default: false,
17
+ desc: "Also write the migration for runtime rules (stored per-flag rules)"
18
+
14
19
  desc <<~DESC
15
20
  Installs StandardFlags: writes config/initializers/standard_flags.rb
16
21
  and config/flags.rb with commented examples. Existing files are
17
- skipped; pass --force to overwrite.
22
+ skipped; pass --force to overwrite. --runtime also writes the
23
+ migration for runtime rules.
18
24
  DESC
19
25
 
20
26
  def create_initializer_file
@@ -25,6 +31,15 @@ module StandardFlags
25
31
  write_template("flags.rb.tt", "config/flags.rb")
26
32
  end
27
33
 
34
+ def create_runtime_migration
35
+ return unless options[:runtime]
36
+
37
+ require "generators/standard_flags/migrations/migrations_generator"
38
+ invoke MigrationsGenerator, [], destination_root: destination_root
39
+ say "Runtime rules: run bin/rails db:migrate, then set config.runtime_rules = true " \
40
+ "in config/initializers/standard_flags.rb."
41
+ end
42
+
28
43
  private
29
44
 
30
45
  def write_template(source, path)
@@ -10,9 +10,10 @@ StandardFlags.define do
10
10
  # RAILS_ENV=production.
11
11
  # env_resolver -> { ENV.fetch("APP_ENVIRONMENT", Rails.env) }
12
12
 
13
- # Units a flag can target. Carried in the context today; used for targeting
14
- # once runtime rules arrive.
13
+ # Units a flag can target. Runtime rules match a unit by its key: by
14
+ # default record.id.to_s, or the value itself; key: normalises it.
15
15
  # unit :account, from: ->(ctx) { ctx.account }
16
+ # unit :phone, from: ->(ctx) { ctx.phone }, key: ->(phone) { phone.to_s.delete("^0-9+") }
16
17
 
17
18
  # A release flag: temporary, so it needs remove_by: and the final: value it
18
19
  # settles on.
@@ -23,6 +23,16 @@
23
23
  # # config.manifest_path = "config/flags.manifest.json"
24
24
  # # config.typescript_path = "app/javascript/types/standard_flags.d.ts"
25
25
  #
26
+ # # Runtime rules: per-flag rules stored in this app's database, read
27
+ # # between the ENV pin and the code default. Needs the migration from
28
+ # # bin/rails g standard_flags:migrations. Off by default.
29
+ # # config.runtime_rules = false
30
+ # # Seconds between checks of the stored revision (one query each).
31
+ # # config.refresh_interval = 5
32
+ # # Answers segment conditions: ->(segment_name, context) { true/false }.
33
+ # # config.segment_resolver = ->(name, context) { context.account&.in_segment?(name) }
34
+ # # (Through the OpenFeature provider, actors are keys (strings), not records.)
35
+ #
26
36
  # # Whose wire name requires_flag reports in meta.feature.
27
37
  # # config.default_audience = :web
28
38
  #