flipper_trail 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 425a200f7f1adfd2189e635fd5ac6f8222c3ee378ed16b37ccf619b73b0afa08
4
+ data.tar.gz: 78ae88629c4ac213ff0f19c3ac1b965d05dadf4b1ee453d0412700245538665b
5
+ SHA512:
6
+ metadata.gz: 4dfa66bd8e0eb5d91765b8f414036c5b8963026e954894b07081a8ebb1578d142366aefe1897ef6a66efb621d9d645406b1bbe40ba0219a590782f1015d763ba
7
+ data.tar.gz: bde74d0cbac33836944937627571f6d67857219a14f505dd7bdbb58e215340643151d28ca385ecd94d6b9b6ece030788d83dc320831611730643c5e69135e09b
data/CHANGELOG.md ADDED
@@ -0,0 +1,23 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project will be documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
+
8
+ ## [Unreleased]
9
+
10
+ ### Changed
11
+
12
+ - Audit store is now inferred from the wrapped Flipper adapter (`ActiveRecord` → `:active_record`, `Mongo` → `:mongoid`); `config.storage` is an optional override (previously required for non-ActiveRecord apps). Wrapping an un-inferable adapter without setting `config.storage` raises a clear error.
13
+ - Added an `actor_id`/`created_at` index to both storage backends (the `history(actor_id:)` filter was previously unindexed). Documented that Mongoid audit indexes must be built once via `create_indexes` (declaration does not auto-create them).
14
+
15
+ ### Added
16
+
17
+ - Flipper adapter decorator capturing before/after state on enable/disable/add/remove/clear.
18
+ - Actor attribution via thread-local Current + Rack middleware, with a system-actor fallback.
19
+ - No-op diff suppression to collapse Flipper's internal double-writes.
20
+ - ActiveRecord and Mongoid storage backends.
21
+ - `FlipperTrail.history` query API.
22
+ - `FlipperTrail.wrap(adapter)` convenience helper for wiring the audit decorator.
23
+ - Rails install generator (migration + initializer).
@@ -0,0 +1,89 @@
1
+ # Contributor Covenant 3.0 Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We pledge to make our community welcoming, safe, and equitable for all.
6
+
7
+ We are committed to fostering an environment that respects and promotes the dignity, rights, and contributions of all individuals, regardless of characteristics including race, ethnicity, caste, color, age, physical characteristics, neurodiversity, disability, sex or gender, gender identity or expression, sexual orientation, language, philosophy or religion, national or social origin, socio-economic position, level of education, or other status. The same privileges of participation are extended to everyone who participates in good faith and in accordance with this Covenant.
8
+
9
+
10
+ ## Encouraged Behaviors
11
+
12
+ While acknowledging differences in social norms, we all strive to meet our community's expectations for positive behavior. We also understand that our words and actions may be interpreted differently than we intend based on culture, background, or native language.
13
+
14
+ With these considerations in mind, we agree to behave mindfully toward each other and act in ways that center our shared values, including:
15
+
16
+ 1. Respecting the **purpose of our community**, our activities, and our ways of gathering.
17
+ 2. Engaging **kindly and honestly** with others.
18
+ 3. Respecting **different viewpoints** and experiences.
19
+ 4. **Taking responsibility** for our actions and contributions.
20
+ 5. Gracefully giving and accepting **constructive feedback**.
21
+ 6. Committing to **repairing harm** when it occurs.
22
+ 7. Behaving in other ways that promote and sustain the **well-being of our community**.
23
+
24
+
25
+ ## Restricted Behaviors
26
+
27
+ We agree to restrict the following behaviors in our community. Instances, threats, and promotion of these behaviors are violations of this Code of Conduct.
28
+
29
+ 1. **Harassment.** Violating explicitly expressed boundaries or engaging in unnecessary personal attention after any clear request to stop.
30
+ 2. **Character attacks.** Making insulting, demeaning, or pejorative comments directed at a community member or group of people.
31
+ 3. **Stereotyping or discrimination.** Characterizing anyone's personality or behavior on the basis of immutable identities or traits.
32
+ 4. **Sexualization.** Behaving in a way that would generally be considered inappropriately intimate in the context or purpose of the community.
33
+ 5. **Violating confidentiality**. Sharing or acting on someone's personal or private information without their permission.
34
+ 6. **Endangerment.** Causing, encouraging, or threatening violence or other harm toward any person or group.
35
+ 7. Behaving in other ways that **threaten the well-being** of our community.
36
+
37
+ ### Other Restrictions
38
+
39
+ 1. **Misleading identity.** Impersonating someone else for any reason, or pretending to be someone else to evade enforcement actions.
40
+ 2. **Failing to credit sources.** Not properly crediting the sources of content you contribute.
41
+ 3. **Promotional materials**. Sharing marketing or other commercial content in a way that is outside the norms of the community.
42
+ 4. **Irresponsible communication.** Failing to responsibly present content which includes, links or describes any other restricted behaviors.
43
+
44
+
45
+ ## Reporting an Issue
46
+
47
+ Tensions can occur between community members even when they are trying their best to collaborate. Not every conflict represents a code of conduct violation, and this Code of Conduct reinforces encouraged behaviors and norms that can help avoid conflicts and minimize harm.
48
+
49
+ When an incident does occur, it is important to report it promptly. To report a possible violation, email the project maintainer privately at **saygunicyuz@gmail.com**. Reports are handled confidentially.
50
+
51
+ Community Moderators take reports of violations seriously and will make every effort to respond in a timely manner. They will investigate all reports of code of conduct violations, reviewing messages, logs, and recordings, or interviewing witnesses and other participants. Community Moderators will keep investigation and enforcement actions as transparent as possible while prioritizing safety and confidentiality. In order to honor these values, enforcement actions are carried out in private with the involved parties, but communicating to the whole community may be part of a mutually agreed upon resolution.
52
+
53
+
54
+ ## Addressing and Repairing Harm
55
+
56
+ If an investigation by the Community Moderators finds that this Code of Conduct has been violated, the following enforcement ladder may be used to determine how best to repair harm, based on the incident's impact on the individuals involved and the community as a whole. Depending on the severity of a violation, lower rungs on the ladder may be skipped.
57
+
58
+ 1) Warning
59
+ 1) Event: A violation involving a single incident or series of incidents.
60
+ 2) Consequence: A private, written warning from the Community Moderators.
61
+ 3) Repair: Examples of repair include a private written apology, acknowledgement of responsibility, and seeking clarification on expectations.
62
+ 2) Temporarily Limited Activities
63
+ 1) Event: A repeated incidence of a violation that previously resulted in a warning, or the first incidence of a more serious violation.
64
+ 2) Consequence: A private, written warning with a time-limited cooldown period designed to underscore the seriousness of the situation and give the community members involved time to process the incident. The cooldown period may be limited to particular communication channels or interactions with particular community members.
65
+ 3) Repair: Examples of repair may include making an apology, using the cooldown period to reflect on actions and impact, and being thoughtful about re-entering community spaces after the period is over.
66
+ 3) Temporary Suspension
67
+ 1) Event: A pattern of repeated violation which the Community Moderators have tried to address with warnings, or a single serious violation.
68
+ 2) Consequence: A private written warning with conditions for return from suspension. In general, temporary suspensions give the person being suspended time to reflect upon their behavior and possible corrective actions.
69
+ 3) Repair: Examples of repair include respecting the spirit of the suspension, meeting the specified conditions for return, and being thoughtful about how to reintegrate with the community when the suspension is lifted.
70
+ 4) Permanent Ban
71
+ 1) Event: A pattern of repeated code of conduct violations that other steps on the ladder have failed to resolve, or a violation so serious that the Community Moderators determine there is no way to keep the community safe with this person as a member.
72
+ 2) Consequence: Access to all community spaces, tools, and communication channels is removed. In general, permanent bans should be rarely used, should have strong reasoning behind them, and should only be resorted to if working through other remedies has failed to change the behavior.
73
+ 3) Repair: There is no possible repair in cases of this severity.
74
+
75
+ This enforcement ladder is intended as a guideline. It does not limit the ability of Community Managers to use their discretion and judgment, in keeping with the best interests of our community.
76
+
77
+
78
+ ## Scope
79
+
80
+ This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public or other spaces. Examples of representing our community include using an official email address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
81
+
82
+
83
+ ## Attribution
84
+
85
+ This Code of Conduct is adapted from the Contributor Covenant, version 3.0, permanently available at [https://www.contributor-covenant.org/version/3/0/](https://www.contributor-covenant.org/version/3/0/).
86
+
87
+ Contributor Covenant is stewarded by the Organization for Ethical Source and licensed under CC BY-SA 4.0. To view a copy of this license, visit [https://creativecommons.org/licenses/by-sa/4.0/](https://creativecommons.org/licenses/by-sa/4.0/)
88
+
89
+ For answers to common questions about Contributor Covenant, see the FAQ at [https://www.contributor-covenant.org/faq](https://www.contributor-covenant.org/faq). Translations are provided at [https://www.contributor-covenant.org/translations](https://www.contributor-covenant.org/translations). Additional enforcement and community guideline resources can be found at [https://www.contributor-covenant.org/resources](https://www.contributor-covenant.org/resources). The enforcement ladder was inspired by the work of [Mozilla's code of conduct team](https://github.com/mozilla/inclusion).
data/CONTRIBUTING.md ADDED
@@ -0,0 +1,65 @@
1
+ # Contributing to flipper_trail
2
+
3
+ Thanks for your interest in improving flipper_trail! This document covers how to
4
+ get set up locally, run the test suite, and what we expect in a pull request.
5
+
6
+ By participating in this project you agree to abide by our
7
+ [Code of Conduct](CODE_OF_CONDUCT.md).
8
+
9
+ ## Local setup
10
+
11
+ The gem installs its dependencies into `vendor/bundle` (configured via
12
+ `.bundle/config`). After cloning, install everything with:
13
+
14
+ ```bash
15
+ bin/setup # wraps `bundle install`
16
+ # or directly:
17
+ bundle install
18
+ ```
19
+
20
+ ## Running the suite
21
+
22
+ The specs run against two storage backends:
23
+
24
+ ```bash
25
+ bundle exec rspec # 45 examples — ActiveRecord on an in-memory SQLite database
26
+ MONGOID=1 bundle exec rspec # 50 examples — adds the Mongoid backend
27
+ ```
28
+
29
+ The Mongoid run requires a running `mongod` reachable at `127.0.0.1:27017`. The
30
+ default (SQLite) run has no external service dependency.
31
+
32
+ ## Linting
33
+
34
+ ```bash
35
+ bundle exec rubocop
36
+ ```
37
+
38
+ RuboCop must report **zero** offenses. The configuration lives in `.rubocop.yml`.
39
+
40
+ ## The full gate
41
+
42
+ `bundle exec rake` runs both the spec suite and RuboCop, and is the single
43
+ command CI mirrors. Run it before opening a pull request:
44
+
45
+ ```bash
46
+ bundle exec rake
47
+ ```
48
+
49
+ ## Backends are optional, host-provided
50
+
51
+ ActiveRecord (`activerecord`) and Mongoid (`mongoid`) are **optional** storage
52
+ backends. They are declared as development dependencies so the suite can exercise
53
+ both, but they are **not** runtime dependencies of the gem — your application
54
+ provides whichever ORM it already uses. The only runtime dependencies are
55
+ `activesupport` and `flipper`.
56
+
57
+ ## Pull request expectations
58
+
59
+ - **Add tests** covering your change; keep `bundle exec rspec` and
60
+ `MONGOID=1 bundle exec rspec` green.
61
+ - **Update the [CHANGELOG](CHANGELOG.md)** under the `## [Unreleased]` heading.
62
+ - **Keep RuboCop clean** — no new offenses (`bundle exec rubocop`).
63
+ - Make sure `bundle exec rake` passes locally before pushing.
64
+
65
+ Thanks again for contributing!
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Saygun Icyuz
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,139 @@
1
+ # flipper_trail
2
+
3
+ [![CI](https://github.com/saygun/flipper_trail/actions/workflows/ci.yml/badge.svg)](https://github.com/saygun/flipper_trail/actions/workflows/ci.yml)
4
+ [![Gem Version](https://img.shields.io/gem/v/flipper_trail.svg)](https://rubygems.org/gems/flipper_trail)
5
+ [![Downloads](https://img.shields.io/gem/dt/flipper_trail.svg)](https://rubygems.org/gems/flipper_trail)
6
+ [![License: MIT](https://img.shields.io/github/license/saygun/flipper_trail.svg)](LICENSE.txt)
7
+
8
+ An append-only **audit trail for [Flipper](https://github.com/flippercloud/flipper) feature-flag changes** — who changed which flag, when, and the before/after state. A free, MIT-licensed alternative to Flipper Cloud's audit history, built on Flipper's public OSS adapter interface.
9
+
10
+ > Not affiliated with or endorsed by Flipper or Flipper Cloud. "Flipper" is used only to describe compatibility.
11
+
12
+ ## Install
13
+
14
+ ```ruby
15
+ gem "flipper_trail"
16
+ ```
17
+
18
+ ActiveRecord and Mongoid are supported storage backends; install whichever your app already uses.
19
+
20
+ ## Setup (Rails + ActiveRecord)
21
+
22
+ ```bash
23
+ bin/rails g flipper_trail:install
24
+ bin/rails db:migrate
25
+ ```
26
+
27
+ Wrap the decorator around your real Flipper adapter:
28
+
29
+ ```ruby
30
+ require "flipper/adapters/active_record"
31
+
32
+ Flipper.configure do |config|
33
+ config.adapter { FlipperTrail.wrap(Flipper::Adapters::ActiveRecord.new) }
34
+ end
35
+ ```
36
+
37
+ (`FlipperTrail.wrap(x)` is shorthand for `FlipperTrail::Adapter.new(x)`.) The audit store is inferred from the adapter you wrap — here, `:active_record` — so there's nothing else to configure.
38
+
39
+ Capture the acting user per request:
40
+
41
+ ```ruby
42
+ class ApplicationController < ActionController::Base
43
+ before_action { FlipperTrail::Current.actor = current_user }
44
+ end
45
+ ```
46
+
47
+ For a mounted `Flipper::UI`, insert the middleware ahead of the mount so UI toggles are attributed:
48
+
49
+ ```ruby
50
+ config.middleware.use FlipperTrail::Middleware, resolver: ->(env) { resolve_admin(env) }
51
+ ```
52
+
53
+ ## Mongoid
54
+
55
+ Wrap your Flipper Mongo adapter exactly the same way — the audit store is **inferred** from it (`:mongoid`), so there's nothing else to configure:
56
+
57
+ ```ruby
58
+ Flipper.configure do |config|
59
+ config.default do
60
+ collection = Mongoid.default_client["flipper"]
61
+ Flipper.new(FlipperTrail.wrap(Flipper::Adapters::Mongo.new(collection)))
62
+ end
63
+ end
64
+ ```
65
+
66
+ No migration needed — audit entries are stored as Mongoid documents (`flipper_trail_entries`) in your default Mongoid database.
67
+
68
+ Mongoid **declares** the indexes on the document but does not build them automatically. Create them once (e.g. in a deploy or seed step):
69
+
70
+ ```bash
71
+ bin/rails runner 'require "flipper_trail/storage/mongoid"; FlipperTrail::Storage::Mongoid::Entry.create_indexes'
72
+ ```
73
+
74
+ (If you `require "flipper_trail/storage/mongoid"` in your initializer, the standard `bin/rails db:mongoid:create_indexes` will include the audit collection too.)
75
+
76
+ ## Where things are stored
77
+
78
+ flipper_trail has two independent storage concerns:
79
+
80
+ - **Your flags** live wherever your Flipper adapter puts them — you wrap that adapter with `FlipperTrail.wrap(...)`.
81
+ - **The audit trail** is written to an audit store that **defaults to match the adapter you wrap**: an `ActiveRecord` Flipper adapter → audit via ActiveRecord; a `Mongo` adapter → audit via Mongoid. So you only configure your storage choice once.
82
+
83
+ Override the audit store when you want them to differ (e.g. flags in Redis, audit in Postgres), or when you wrap an adapter flipper_trail can't infer:
84
+
85
+ ```ruby
86
+ FlipperTrail.configure { |c| c.storage = :active_record } # :active_record | :mongoid | any object responding to #record/#query
87
+ ```
88
+
89
+ If you wrap an adapter flipper_trail can't infer (Redis, Memory, HTTP/Cloud, …) and don't set `config.storage`, it raises a clear error telling you to pick one.
90
+
91
+ ## Query the trail
92
+
93
+ ```ruby
94
+ FlipperTrail.history(feature: "new_checkout", actor_id: 42, since: 1.week.ago, limit: 100)
95
+ # => newest-first array of entries (feature_name, operation, gate_name, before, after, actor, created_at)
96
+ ```
97
+
98
+ ## How it works
99
+
100
+ `FlipperTrail::Adapter` decorates your Flipper adapter. On each write (`enable`/`disable`/`add`/`remove`/`clear`) it reads gate state before and after, attributes the change to `FlipperTrail::Current.actor` (falling back to a configurable `system` actor), and persists an entry. No-op diffs are suppressed, so Flipper's internal `add`+`enable` double-write collapses to one meaningful entry for existing flags.
101
+
102
+ ## Reliability
103
+
104
+ Audit writes are isolated from your flag writes. If the audit store is unavailable and `record` raises, the error goes to `config.on_error` (default: logged) and the flag operation still succeeds. Set `config.raise_on_audit_error = true` to fail closed instead.
105
+
106
+ ## Performance
107
+
108
+ Recording is synchronous on the thread performing the toggle, and each audited write reads gate state before and after (a few extra adapter reads per `Flipper.enable`). Feature toggles are low-frequency admin operations, so this is normally negligible. For high-volume or remote (HTTP/Cloud) flag adapters, supply a custom storage backend (any object responding to `#record`/`#query`) whose `#record` enqueues a background job to move persistence off the request path.
109
+
110
+ ## Privacy & data captured
111
+
112
+ Each entry stores the actor (`actor_label` commonly holds an email) and the full before/after gate state — which, when a feature is targeted at specific actors or groups, contains those actor/group identifiers. The trail is append-only, so plan retention accordingly (e.g. a TTL index on `created_at` for Mongoid, or a scheduled prune on the `created_at` index for ActiveRecord) and account for it when handling data-erasure requests. A pluggable redaction hook is planned for a future release.
113
+
114
+ ## Compatibility
115
+
116
+ - **Ruby** >= 3.1.
117
+ - **Runtime dependencies:** `activesupport` >= 6.1 and `flipper` >= 1.0.
118
+ - **Optional, host-provided backends:** `activerecord` >= 6.1 and `mongoid` >= 8.0. These are *not* runtime dependencies — your application supplies whichever ORM it already uses, and you pick the matching storage backend.
119
+
120
+ ## Development
121
+
122
+ ```bash
123
+ git clone https://github.com/saygun/flipper_trail.git
124
+ cd flipper_trail
125
+ bin/setup # installs dependencies into vendor/bundle
126
+ bundle exec rake # runs the spec suite + RuboCop (the full gate)
127
+ ```
128
+
129
+ The default `bundle exec rspec` run uses an in-memory SQLite database. The Mongoid suite (`MONGOID=1 bundle exec rspec`) requires a running `mongod` reachable at `127.0.0.1:27017`.
130
+
131
+ See [CONTRIBUTING.md](CONTRIBUTING.md) for the full contributor guide.
132
+
133
+ ## License
134
+
135
+ MIT. See `LICENSE.txt`. The audit-log concept is reimplemented clean-room from public documentation; this gem contains no Flipper Cloud code.
136
+
137
+ ---
138
+
139
+ [Code of Conduct](CODE_OF_CONDUCT.md) · [Contributing](CONTRIBUTING.md) · [Security](SECURITY.md)
data/SECURITY.md ADDED
@@ -0,0 +1,29 @@
1
+ # Security Policy
2
+
3
+ ## Supported versions
4
+
5
+ flipper_trail is pre-1.0. Security fixes are released only against the latest
6
+ `0.x` release; please upgrade to the most recent version before reporting.
7
+
8
+ | Version | Supported |
9
+ | ------- | --------- |
10
+ | 0.x | ✅ |
11
+
12
+ ## Reporting a vulnerability
13
+
14
+ Please report security vulnerabilities **privately** — do not open a public
15
+ issue.
16
+
17
+ Preferred: use GitHub's [Private Vulnerability Reporting](https://docs.github.com/en/code-security/security-advisories/guidance-on-reporting-and-writing-information-about-vulnerabilities/privately-reporting-a-security-vulnerability)
18
+ on this repository ("Security" tab → "Report a vulnerability").
19
+
20
+ If that is unavailable, email **saygunicyuz@gmail.com** as a fallback.
21
+
22
+ You can expect an acknowledgement of your report, and we will coordinate a fix
23
+ and disclosure timeline with you.
24
+
25
+ ## Privacy note
26
+
27
+ This gem records actor identity and before/after gate state, which may include
28
+ personal data (PII). See the README ["Privacy & data captured"](README.md#privacy--data-captured)
29
+ section for what is stored and how to manage retention.
@@ -0,0 +1,51 @@
1
+ # frozen_string_literal: true
2
+
3
+ module FlipperTrail
4
+ # The party a flag change is attributed to, normalized to a `type`, `id`, and
5
+ # `label`. Build one with {wrap}.
6
+ class Actor
7
+ # @!attribute [r] type
8
+ # @return [String, nil] the actor type (e.g. `"user"`, `"system"`)
9
+ # @!attribute [r] id
10
+ # @return [String, nil] the actor id, coerced to a string
11
+ # @!attribute [r] label
12
+ # @return [String, nil] a human-readable label (email, name, or to_s)
13
+ attr_reader :type, :id, :label
14
+
15
+ def initialize(type:, id:, label:)
16
+ @type = type
17
+ @id = id&.to_s
18
+ @label = label
19
+ end
20
+
21
+ # Coerces an arbitrary object into an {Actor}.
22
+ #
23
+ # @param object [Actor, Hash, Object, nil] an Actor (returned as-is), a Hash
24
+ # with `:type`/`:id`/`:label`, a model (deriving id and label), or nil
25
+ # @return [Actor, nil] the wrapped actor, or nil when given nil
26
+ def self.wrap(object)
27
+ case object
28
+ when nil then nil
29
+ when Actor then object
30
+ when Hash then new(type: object[:type] || object['type'],
31
+ id: object[:id] || object['id'],
32
+ label: object[:label] || object['label'])
33
+ else from_model(object)
34
+ end
35
+ end
36
+
37
+ def self.from_model(object)
38
+ id = object.respond_to?(:id) ? object.id : object.to_s
39
+ label =
40
+ if object.respond_to?(:email) then object.email
41
+ elsif object.respond_to?(:name) then object.name
42
+ else object.to_s
43
+ end
44
+ new(type: 'user', id: id, label: label)
45
+ end
46
+
47
+ def to_h
48
+ { type: type, id: id, label: label }
49
+ end
50
+ end
51
+ end
@@ -0,0 +1,108 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'set'
4
+ require 'flipper'
5
+
6
+ module FlipperTrail
7
+ # A Flipper adapter decorator that captures the before/after state of every
8
+ # write (add, remove, clear, enable, disable) and records it as an audit entry.
9
+ # Reads and bulk operations pass straight through unaudited.
10
+ #
11
+ # @example Wrap your Flipper adapter
12
+ # Flipper.configure do |config|
13
+ # config.adapter { FlipperTrail::Adapter.new(Flipper::Adapters::ActiveRecord.new) }
14
+ # end
15
+ class Adapter
16
+ include ::Flipper::Adapter
17
+
18
+ # @param adapter [Flipper::Adapter] the underlying adapter to decorate
19
+ # @param recorder [Recorder, nil] the recorder to use; defaults to
20
+ # {FlipperTrail.recorder} when nil
21
+ def initialize(adapter, recorder: nil)
22
+ @adapter = adapter
23
+ @recorder = recorder
24
+ FlipperTrail.configuration.infer_storage_from(adapter)
25
+ end
26
+
27
+ # Public reader so Flipper::Adapter#adapter_stack recurses into us (matches Flipper's own Wrapper/Memoizable).
28
+ attr_reader :adapter
29
+
30
+ def name
31
+ @adapter.name
32
+ end
33
+
34
+ # --- reads / bulk ops: pass straight through (not audited) ---
35
+ # NOTE: get_all/export take kwargs in Flipper 1.x (Synchronizer/Memoizable/Cache call get_all(**kwargs));
36
+ # the override MUST keep that arity or it raises ArgumentError on import/sync/cloud paths.
37
+ def features = @adapter.features
38
+ def get(feature) = @adapter.get(feature)
39
+ def get_multi(features) = @adapter.get_multi(features)
40
+ def get_all(**kwargs) = @adapter.get_all(**kwargs)
41
+ def read_only? = @adapter.read_only?
42
+ def import(source) = @adapter.import(source)
43
+ def export(*args, **kwargs) = @adapter.export(*args, **kwargs)
44
+
45
+ # --- writes: capture before/after ---
46
+ def add(feature)
47
+ existed = @adapter.features.include?(feature.key)
48
+ before = existed ? snapshot(feature) : nil
49
+ result = @adapter.add(feature)
50
+ record(feature, :add, nil, before, snapshot(feature))
51
+ result
52
+ end
53
+
54
+ def remove(feature)
55
+ before = snapshot(feature)
56
+ result = @adapter.remove(feature)
57
+ record(feature, :remove, nil, before, nil)
58
+ result
59
+ end
60
+
61
+ def clear(feature)
62
+ before = snapshot(feature)
63
+ result = @adapter.clear(feature)
64
+ record(feature, :clear, nil, before, snapshot(feature))
65
+ result
66
+ end
67
+
68
+ def enable(feature, gate, thing)
69
+ before = snapshot(feature)
70
+ result = @adapter.enable(feature, gate, thing)
71
+ record(feature, :enable, gate.name, before, snapshot(feature))
72
+ result
73
+ end
74
+
75
+ def disable(feature, gate, thing)
76
+ before = snapshot(feature)
77
+ result = @adapter.disable(feature, gate, thing)
78
+ record(feature, :disable, gate.name, before, snapshot(feature))
79
+ result
80
+ end
81
+
82
+ private
83
+
84
+ def snapshot(feature)
85
+ normalize(@adapter.get(feature))
86
+ end
87
+
88
+ def normalize(gate_values)
89
+ gate_values.each_with_object({}) do |(key, value), memo|
90
+ memo[key.to_s] = value.is_a?(Set) ? value.to_a.map(&:to_s).sort : value
91
+ end
92
+ end
93
+
94
+ def record(feature, operation, gate_name, before, after)
95
+ recorder.record(
96
+ feature_name: feature.key,
97
+ operation: operation,
98
+ gate_name: gate_name,
99
+ before: before,
100
+ after: after
101
+ )
102
+ end
103
+
104
+ def recorder
105
+ @recorder || FlipperTrail.recorder
106
+ end
107
+ end
108
+ end
@@ -0,0 +1,96 @@
1
+ # frozen_string_literal: true
2
+
3
+ module FlipperTrail
4
+ # Holds the global settings for the gem. Mutate it through {FlipperTrail.configure}.
5
+ class Configuration
6
+ # Maps a wrapped Flipper adapter's class name to the audit store it implies.
7
+ INFERRED_STORAGE = {
8
+ 'Flipper::Adapters::ActiveRecord' => :active_record,
9
+ 'Flipper::Adapters::Mongo' => :mongoid
10
+ }.freeze
11
+
12
+ # @!attribute [rw] storage
13
+ # The audit store. Defaults to `:auto`, which is inferred from the Flipper
14
+ # adapter you wrap (`ActiveRecord` → `:active_record`, `Mongo` → `:mongoid`).
15
+ # Set it to `:active_record`, `:mongoid`, or any object responding to
16
+ # `#record`/`#query` to override the inference.
17
+ # @return [Symbol, #record]
18
+ # @!attribute [rw] actor_resolver
19
+ # A **zero-arity** callable returning the current actor when none is set on
20
+ # {Current}. It must take no arguments because it is also invoked off-request
21
+ # (console, background jobs) where there is no Rack env.
22
+ # @return [#call, nil]
23
+ # @!attribute [rw] system_actor
24
+ # The actor attributed to changes when no other actor can be resolved.
25
+ # @return [Hash]
26
+ # @!attribute [rw] ignored_features
27
+ # Feature keys whose changes are never recorded.
28
+ # @return [Array<String, Symbol>]
29
+ # @!attribute [rw] on_error
30
+ # A callable `->(error, entry)` invoked when persisting an audit entry
31
+ # fails (unless {#raise_on_audit_error} is set). Defaults to warning on
32
+ # stderr.
33
+ # @return [#call, nil]
34
+ # @!attribute [rw] raise_on_audit_error
35
+ # When `true`, a failed audit write re-raises instead of being swallowed,
36
+ # so the originating flag write fails too (fail-closed).
37
+ # @return [Boolean]
38
+ attr_accessor :storage, :actor_resolver, :system_actor, :ignored_features,
39
+ :on_error, :raise_on_audit_error
40
+
41
+ def initialize
42
+ @storage = :auto
43
+ @actor_resolver = nil
44
+ @system_actor = { type: 'system', id: nil, label: 'system' }
45
+ @ignored_features = []
46
+ @on_error = nil
47
+ @raise_on_audit_error = false
48
+ @inferred_storage = nil
49
+ end
50
+
51
+ # Records the audit store implied by a wrapped Flipper adapter. Used only when
52
+ # `storage` is left as :auto; an explicit `storage` always takes precedence.
53
+ # @api private
54
+ def infer_storage_from(adapter)
55
+ return unless storage == :auto
56
+
57
+ @inferred_storage = INFERRED_STORAGE.fetch(adapter.class.name, :unknown)
58
+ end
59
+
60
+ def storage_backend
61
+ @storage_backend ||= build_storage_backend(resolved_storage)
62
+ end
63
+
64
+ private
65
+
66
+ def resolved_storage
67
+ return storage unless storage == :auto
68
+
69
+ case @inferred_storage
70
+ when nil
71
+ :active_record
72
+ when :unknown
73
+ raise ArgumentError,
74
+ 'FlipperTrail could not infer an audit store from the wrapped Flipper adapter. ' \
75
+ 'Set it explicitly, e.g. FlipperTrail.configure { |c| c.storage = :active_record } (or :mongoid).'
76
+ else
77
+ @inferred_storage
78
+ end
79
+ end
80
+
81
+ def build_storage_backend(store)
82
+ case store
83
+ when :active_record
84
+ require 'flipper_trail/storage/active_record'
85
+ Storage::ActiveRecord.new
86
+ when :mongoid
87
+ require 'flipper_trail/storage/mongoid'
88
+ Storage::Mongoid.new
89
+ else
90
+ return store if store.respond_to?(:record)
91
+
92
+ raise ArgumentError, "Unknown FlipperTrail storage: #{store.inspect}"
93
+ end
94
+ end
95
+ end
96
+ end
@@ -0,0 +1,13 @@
1
+ # frozen_string_literal: true
2
+
3
+ # `require "active_support"` is REQUIRED before current_attributes: on ActiveSupport 7.2/8.0,
4
+ # requiring only "active_support/current_attributes" leaves ActiveSupport::CodeGenerator (load time)
5
+ # and ActiveSupport::IsolatedExecutionState (runtime) unresolved, so `attribute :actor` raises NameError.
6
+ require 'active_support'
7
+ require 'active_support/current_attributes'
8
+
9
+ module FlipperTrail
10
+ class Current < ActiveSupport::CurrentAttributes
11
+ attribute :actor
12
+ end
13
+ end