railtracks 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.
@@ -0,0 +1,136 @@
1
+ # Migrating from the demo application
2
+
3
+ Before 0.1.0 the retention track lived directly in the demonstration
4
+ application:
5
+
6
+ - `app/models/railtracks/*.rb` defined the domain objects and services;
7
+ - the table was `erasure_receipts`;
8
+ - the receipt model inherited from the application's `ApplicationRecord`;
9
+ - `ErasureExecution` defaulted to `User`.
10
+
11
+ 0.1.0 moves that code into the gem:
12
+
13
+ | Before (demo application) | After (railtracks 0.1.0) |
14
+ | --- | --- |
15
+ | `app/models/railtracks/registry.rb` | `Railtracks::Registry` in the gem |
16
+ | `app/models/railtracks/erasure_execution.rb` | `Railtracks::ErasureExecution` in the gem |
17
+ | `app/models/railtracks/receipt_store.rb` | `Railtracks::ReceiptStore` in the gem |
18
+ | `app/models/railtracks/recorded_erasure_execution.rb` | `Railtracks::RecordedErasureExecution` in the gem |
19
+ | `app/models/railtracks/due_for_erasure.rb` | `Railtracks::DueForErasure` in the gem |
20
+ | `app/models/railtracks/erasure_receipt.rb` | `Railtracks::ErasureReceipt < Railtracks::ApplicationRecord` |
21
+ | `erasure_receipts` table | `railtracks_erasure_receipts` table |
22
+ | `ErasureExecution.new(...).call(ref)` defaulted to `User` | target model comes from `target_model` or `model:` |
23
+
24
+ `AssociationErasureExecution` stays in the demo application because it encodes
25
+ the concrete `User has_many :notes` shape. A host that needs association erasure
26
+ should write the same small adapter around its own associations.
27
+
28
+ ## Step 1: point the Gemfile at the gem
29
+
30
+ ```ruby
31
+ # Gemfile
32
+ gem "railtracks"
33
+ ```
34
+
35
+ For a checkout under development:
36
+
37
+ ```ruby
38
+ gem "railtracks", path: "railtracks"
39
+ ```
40
+
41
+ Run `bundle install`.
42
+
43
+ ## Step 2: delete the duplicated application files
44
+
45
+ Remove the files listed above from `app/models/railtracks/`. Zeitwerk must not
46
+ see two definitions of the same constant. Keep only host-specific adapters, such
47
+ as the demo's `AssociationErasureExecution`.
48
+
49
+ ## Step 3: configure the track
50
+
51
+ ```ruby
52
+ # config/initializers/railtracks.rb
53
+ Rails.application.config.to_prepare do
54
+ Railtracks.configure do |config|
55
+ config.track :retention do |retention|
56
+ retention.receipt_secret = ENV.fetch("RAILTRACKS_RECEIPT_SECRET")
57
+ retention.registry = Railtracks::Registry.from_yaml(
58
+ Rails.root.join("config/erasure.demo.yml")
59
+ )
60
+ retention.model_classes = [ User, Note ]
61
+ retention.target_model = User
62
+ end
63
+ end
64
+ end
65
+ ```
66
+
67
+ The old script built `ErasureExecution`, `ReceiptStore` and
68
+ `RecordedErasureExecution` by hand. It can now use the configured accessor:
69
+
70
+ ```ruby
71
+ receipt = Railtracks.retention.recorded_execution.call(
72
+ subject_ref,
73
+ idempotency_key: "demo-#{SecureRandom.hex(8)}"
74
+ )
75
+ ```
76
+
77
+ ## Step 4: install the engine migration
78
+
79
+ ```sh
80
+ bin/rails railtracks:install:migrations
81
+ bin/rails db:migrate
82
+ ```
83
+
84
+ The migration version in this repository is `20261204000000`. It creates
85
+ `railtracks_erasure_receipts` with the check constraints, unique indexes and
86
+ append-only triggers for the current adapter.
87
+
88
+ ### Existing demo data
89
+
90
+ If the old `erasure_receipts` table is empty, drop it or leave it unused and
91
+ install the new migration normally.
92
+
93
+ If it contains receipts you must keep, migrate the table before relying on the
94
+ new model. The exact SQL is adapter-specific; the shape is:
95
+
96
+ ```sql
97
+ ALTER TABLE erasure_receipts RENAME TO railtracks_erasure_receipts;
98
+ ```
99
+
100
+ Then recreate the index and trigger names the gem expects:
101
+
102
+ - `index_railtracks_erasure_receipts_on_plan_key`
103
+ - `index_railtracks_erasure_receipts_on_idempotency_key`
104
+ - `railtracks_erasure_receipts_row_append_only`
105
+ - `railtracks_erasure_receipts_delete_guard` (SQLite)
106
+ - `railtracks_erasure_receipts_truncate_guard` (PostgreSQL)
107
+
108
+ Do not edit the `actions`, `fingerprint` or `signature` values. Renaming the
109
+ table and objects keeps the canonical payload unchanged, so existing receipts
110
+ still verify with the same secret.
111
+
112
+ ## Step 5: move the tests
113
+
114
+ The receipt tests still run through the dummy application, but they now assert
115
+ against the gem's classes and the prefixed table. In particular:
116
+
117
+ - raw SQL uses `railtracks_erasure_receipts`;
118
+ - trigger and index assertions use the prefixed names;
119
+ - `ErasureExecution` receives `model: "User"` or is built through
120
+ `Railtracks.retention`;
121
+ - `RecordedErasureExecution` receives a model (or wraps an execution that has
122
+ one).
123
+
124
+ Add a boundary test like `test/models/railtracks/gem_extraction_test.rb` so a
125
+ future move cannot silently reintroduce a second definition or a hardcoded demo
126
+ model in the gem.
127
+
128
+ ## Step 6: verify
129
+
130
+ ```sh
131
+ bin/rails db:test:prepare test
132
+ bin/rails runner script/core_loop.rb
133
+ ```
134
+
135
+ The demo's `script/core_loop.rb` now uses `Railtracks.retention`, so it exercises
136
+ the same configuration path a host uses.
@@ -0,0 +1,100 @@
1
+ # Security model
2
+
3
+ Railtracks produces **technical evidence**. It is not a legal certificate and it
4
+ does not make a database operator trustworthy. This page states the assumptions
5
+ plainly so a reviewer can decide whether they hold.
6
+
7
+ ## What a receipt proves
8
+
9
+ A receipt proves that this application, with this declaration set and schema
10
+ fingerprint, ran the recorded actions and stored a row whose SHA-256 fingerprint
11
+ and HMAC-SHA256 signature match the configured secret.
12
+
13
+ It does not prove that:
14
+
15
+ - the declaration was complete or lawful;
16
+ - every copy in every system was erased;
17
+ - a backup, replica, snapshot, WAL segment or free page no longer contains the
18
+ value;
19
+ - a privileged operator did not drop triggers, edit rows and recompute the HMAC;
20
+ - the retention period satisfies a regulator or a contract.
21
+
22
+ ## Integrity controls
23
+
24
+ Three independent layers protect a receipt:
25
+
26
+ 1. **Active Record guard.** `ErasureReceipt#readonly?` returns true for a
27
+ persisted row, so `save` and `destroy` through the model fail.
28
+ 2. **Unique indexes.** `(subject_token, model, schema_fingerprint)` allows one
29
+ receipt per plan; `idempotency_key` allows one receipt per request key. A
30
+ retry returns the stored row or raises `ReceiptStore::PlanConflict`; it never
31
+ overwrites evidence.
32
+ 3. **Database triggers and constraints.** The engine migration rejects row
33
+ `UPDATE` and `DELETE` on SQLite and PostgreSQL, and rejects `TRUNCATE` on a
34
+ non-empty PostgreSQL table. Check constraints reject malformed tokens, model
35
+ names, fingerprints, signatures and idempotency keys, including raw SQL that
36
+ bypasses the model.
37
+
38
+ The append-only objects are ordinary database objects. A migration, a superuser
39
+ or a `DROP TRIGGER` can remove them. The tests prove they are present and reject
40
+ probed statements in the tested schema; they do not prevent an administrator
41
+ from changing the schema.
42
+
43
+ ## Cryptographic choices
44
+
45
+ - **Subject token**: `railtracks:` plus HMAC-SHA256(secret, subject_ref) in
46
+ lowercase hex. The original reference is never stored. A value already in the
47
+ token format is passed through; any other string is hashed, so a caller cannot
48
+ smuggle a chosen token-shaped value into the table.
49
+ - **Receipt fingerprint**: SHA-256 of the canonical JSON payload.
50
+ - **Receipt signature**: HMAC-SHA256 of the same canonical JSON payload.
51
+ - **Comparison**: `ActiveSupport::SecurityUtils.secure_compare` for both digests.
52
+ - **Timestamp**: UTC, truncated to microseconds before hashing and storing so
53
+ the PostgreSQL round trip does not change the payload.
54
+
55
+ There is no key ID, key ring or historical verification path. Rotating the
56
+ secret makes receipts created with the old secret unverifiable. Keep old secrets
57
+ for as long as old receipts must verify.
58
+
59
+ If the secret and a subject token are both exposed, a low-entropy reference
60
+ (email address, customer number) can be guessed offline. Use a high-entropy
61
+ subject reference and protect the secret like any other production credential.
62
+
63
+ ## Canonical payload
64
+
65
+ ```json
66
+ {
67
+ "domain": "railtracks.erasure-receipt.v1",
68
+ "subject_token": "railtracks:<64 hex>",
69
+ "model": "User",
70
+ "schema_fingerprint": "<64 hex>",
71
+ "actions": [
72
+ { "column": "email", "action": "pseudonymized" }
73
+ ],
74
+ "completed_at": "2026-12-02T17:42:51.553401Z"
75
+ }
76
+ ```
77
+
78
+ Actions are sorted by `[column, action]` and their values are strings, so the
79
+ payload does not depend on Ruby hash order or symbol/string input.
80
+
81
+ ## Trust boundaries
82
+
83
+ - Callers are trusted application code. There is no HTTP endpoint that erases,
84
+ reads or deletes receipts, no operator console and no multi-tenant
85
+ authorization.
86
+ - The secret is supplied by the host through configuration. Railtracks does not
87
+ provide a KMS, HSM, envelope encryption or secret storage.
88
+ - The database is assumed to enforce its own constraints and triggers. A
89
+ compromised database administrator is outside the threat model.
90
+ - `SchemaAudit` covers only the model classes passed to it. A sibling service or
91
+ warehouse is invisible to it.
92
+
93
+ ## Operational guidance
94
+
95
+ - Store the receipt secret in credentials or a secret manager, not in source.
96
+ - Keep `schema_format = :sql` and review SQL dumps for trigger drift.
97
+ - Run the database-boundary tests against every adapter you deploy.
98
+ - Treat a report with `complete? == false` as inconclusive, not as "nothing
99
+ due".
100
+ - Retain old secrets for the verification horizon of old receipts.
data/docs/upgrade.md ADDED
@@ -0,0 +1,69 @@
1
+ # Upgrade
2
+
3
+ Railtracks follows semantic versioning for its public API. Tracks are opt-in and
4
+ are introduced behind an explicit `config.track` call.
5
+
6
+ ## Before upgrading
7
+
8
+ 1. Read `CHANGELOG.md`.
9
+ 2. Run `bundle update railtracks` (or your pinned version change) in a branch.
10
+ 3. Run `bin/rails railtracks:install:migrations` and inspect any new migration.
11
+ 4. Run `bin/rails db:migrate` against a copy of production first.
12
+ 5. Run the host test suite and the database-boundary checks on every adapter you
13
+ deploy.
14
+
15
+ ## Version policy
16
+
17
+ | Change | Version |
18
+ | --- | --- |
19
+ | New track or additive configuration | minor |
20
+ | Bug fix, documentation, internal refactor | patch |
21
+ | Renamed service, changed receipt payload, changed table | major |
22
+
23
+ The receipt canonical payload includes `railtracks.erasure-receipt.v1`. A change
24
+ to its shape must introduce a new domain version and a verification path for old
25
+ receipts; it must not silently invalidate existing evidence.
26
+
27
+ ## Schema changes
28
+
29
+ The engine migration is copied into the host. Do not edit the host copy after it
30
+ has run in production; add a new migration instead.
31
+
32
+ The receipt table is append-only. A migration that needs to change it must:
33
+
34
+ - create a new table or column rather than rewriting evidence in place;
35
+ - preserve the check constraints, unique indexes and triggers;
36
+ - keep the old rows verifiable, or provide an explicit re-signing procedure that
37
+ is documented and audited.
38
+
39
+ The test suite fails when triggers or indexes disappear from the loaded schema.
40
+ Keep `schema_format = :sql` and run those tests against PostgreSQL before
41
+ release.
42
+
43
+ ## Secret rotation
44
+
45
+ There is no key ID or key ring in 0.1.0. To rotate:
46
+
47
+ 1. Keep the old secret available for verification of existing receipts.
48
+ 2. Introduce the new secret for new receipts only after you have a verification
49
+ path for both.
50
+ 3. Do not re-sign or rewrite old rows; the table is append-only.
51
+
52
+ A future release may add a key-ring abstraction. Until then, treat rotation as a
53
+ manual, documented operation.
54
+
55
+ ## Rails and Ruby support
56
+
57
+ 0.1.0 is tested on Rails 7.2, 8.0 and 8.1 with Ruby 3.2, 3.3 and 3.4. A Rails or
58
+ Ruby version outside that matrix may work, but it is not covered by CI.
59
+
60
+ ## Removing the gem
61
+
62
+ Because every track is opt-in:
63
+
64
+ 1. Disable the track in `config/initializers/railtracks.rb`.
65
+ 2. Remove `Railtracks.configure` calls and application references.
66
+ 3. Keep the receipt table and its triggers if you need the evidence. Dropping
67
+ the table destroys evidence and is not reversible.
68
+ 4. Remove the gem from the Gemfile only after you have decided what to do with
69
+ the evidence.
@@ -0,0 +1,18 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "rails/generators"
4
+
5
+ module Railtracks
6
+ module Generators
7
+ class InstallGenerator < Rails::Generators::Base
8
+ source_root File.expand_path("templates", __dir__)
9
+
10
+ desc "Creates the Railtracks initializer. Copy the engine migrations with " \
11
+ "`bin/rails railtracks:install:migrations`."
12
+
13
+ def create_initializer
14
+ template "initializer.rb", "config/initializers/railtracks.rb"
15
+ end
16
+ end
17
+ end
18
+ end
@@ -0,0 +1,18 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Railtracks is opt-in. Only the tracks enabled here are active.
4
+ #
5
+ # Wrap configuration in to_prepare when model_classes references application
6
+ # classes, so development reloads keep the list current.
7
+ Rails.application.config.to_prepare do
8
+ Railtracks.configure do |config|
9
+ # config.track :retention do |retention|
10
+ # retention.receipt_secret = Rails.application.credentials.railtracks_secret
11
+ # retention.registry = Railtracks::Registry.from_yaml(
12
+ # Rails.root.join("config/railtracks.yml")
13
+ # )
14
+ # retention.model_classes = [User, Note]
15
+ # retention.target_model = User
16
+ # end
17
+ end
18
+ end
@@ -0,0 +1,101 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Railtracks
4
+ # Configuration is the whole public surface of the framework. A host app
5
+ # enables only the tracks it wants and supplies the models and secrets each
6
+ # track needs. Nothing is enabled by default.
7
+ class Configuration
8
+ class Error < StandardError; end
9
+
10
+ TRACKS = %i[retention].freeze
11
+
12
+ attr_accessor :receipt_secret, :registry, :model_classes, :target_model
13
+
14
+ def initialize
15
+ @enabled_tracks = {}
16
+ @model_classes = []
17
+ @registry = nil
18
+ @receipt_secret = nil
19
+ @target_model = nil
20
+ end
21
+
22
+ # Enables a track and optionally yields this configuration to the block.
23
+ #
24
+ # Railtracks.configure do |config|
25
+ # config.track :retention do |retention|
26
+ # retention.receipt_secret = Rails.application.credentials.railtracks_secret
27
+ # retention.registry = Railtracks::Registry.from_yaml("config/railtracks.yml")
28
+ # retention.model_classes = [User, Note]
29
+ # retention.target_model = User
30
+ # end
31
+ # end
32
+ def track(name)
33
+ key = name.to_sym
34
+ unless TRACKS.include?(key)
35
+ raise ArgumentError, "Unknown Railtracks track: #{name.inspect}. " \
36
+ "Available tracks: #{TRACKS.join(", ")}"
37
+ end
38
+
39
+ @enabled_tracks[key] = true
40
+ yield self if block_given?
41
+ self
42
+ end
43
+
44
+ def track?(name)
45
+ @enabled_tracks.key?(name.to_sym)
46
+ end
47
+
48
+ def enabled_tracks
49
+ @enabled_tracks.keys.freeze
50
+ end
51
+
52
+ # The configured target model as a canonical class name, or nil when the
53
+ # host has not chosen one. Services that erase data require a target.
54
+ def target_model_name
55
+ case target_model
56
+ when nil
57
+ nil
58
+ when String
59
+ target_model
60
+ when Class
61
+ target_model.name
62
+ else
63
+ raise Error, "target_model must be a model class or a class name, got #{target_model.inspect}"
64
+ end
65
+ end
66
+
67
+ def validate!
68
+ return self unless track?(:retention)
69
+
70
+ unless registry.is_a?(Registry)
71
+ raise Error, "The retention track requires a Railtracks::Registry"
72
+ end
73
+ if receipt_secret.to_s.strip.empty?
74
+ raise Error, "The retention track requires a receipt_secret"
75
+ end
76
+ unless model_classes.is_a?(Array) && model_classes.any?
77
+ raise Error, "The retention track requires at least one model class"
78
+ end
79
+ unless model_classes.all? { |klass| model_class?(klass) }
80
+ raise Error, "model_classes must contain Active Record model classes"
81
+ end
82
+ if target_model
83
+ name = target_model_name
84
+ unless model_classes.any? { |klass| klass.name == name }
85
+ raise Error, "target_model #{name.inspect} must be included in model_classes"
86
+ end
87
+ end
88
+
89
+ self
90
+ end
91
+
92
+ private
93
+
94
+ def model_class?(value)
95
+ value.is_a?(Class) &&
96
+ value.name &&
97
+ value.respond_to?(:column_names) &&
98
+ value.respond_to?(:find_by)
99
+ end
100
+ end
101
+ end
@@ -0,0 +1,17 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Railtracks
4
+ # The engine exists so the gem can ship models, migrations, generators and
5
+ # initializers the Rails way. It does not replace the host application's
6
+ # engine, routes, or asset pipeline.
7
+ class Engine < ::Rails::Engine
8
+ isolate_namespace Railtracks
9
+
10
+ # Engine migrations live in db/migrate and are copied into the host with
11
+ # `bin/rails railtracks:install:migrations`. They are not run automatically
12
+ # so the host controls when the append-only table is created.
13
+ config.generators do |g|
14
+ g.test_framework :minitest, fixture: false
15
+ end
16
+ end
17
+ end
@@ -0,0 +1,72 @@
1
+ require "yaml"
2
+
3
+ module Railtracks
4
+ class Registry
5
+ Category = Data.define(:model, :column, :category, :action, :retention, :justification)
6
+ ACTIONS = %i[delete pseudonymize retain].freeze
7
+
8
+ class Error < StandardError; end
9
+ class InvalidDeclaration < Error; end
10
+ class RetentionJustificationRequired < Error; end
11
+
12
+ def initialize(declarations)
13
+ @declarations = declarations.map { |d| Category.new(**d) }
14
+ validate!
15
+ @periods = @declarations.to_h { |d| [ [ d.model, d.column ], RetentionPeriod.parse(d.retention) ] }
16
+ end
17
+
18
+ def self.from_yaml(path)
19
+ raw = YAML.safe_load_file(path, permitted_classes: [ Symbol ], aliases: false)
20
+ new(raw.fetch("declarations").map do |entry|
21
+ declaration = entry.transform_keys(&:to_sym)
22
+ declaration[:category] = declaration[:category].to_sym if declaration[:category].is_a?(String)
23
+ declaration[:action] = declaration[:action].to_sym if declaration[:action].is_a?(String)
24
+ declaration
25
+ end)
26
+ end
27
+
28
+ def actions_for(model)
29
+ @declarations.select { |d| d.model == model }
30
+ end
31
+
32
+ def plan(subject:, as_of: nil)
33
+ @declarations.map do |declaration|
34
+ {
35
+ model: declaration.model,
36
+ column: declaration.column,
37
+ category: declaration.category,
38
+ action: declaration.action,
39
+ subject: subject,
40
+ retention: declaration.retention,
41
+ due_at: as_of && @periods.fetch([ declaration.model, declaration.column ]).due_at(as_of).utc.iso8601,
42
+ justification: declaration.justification
43
+ }.freeze
44
+ end.freeze
45
+ end
46
+
47
+ private
48
+
49
+ def validate!
50
+ @declarations.each do |d|
51
+ unless d.model.is_a?(String) && d.model.match?(/\A[A-Z][A-Za-z0-9_:]*\z/)
52
+ raise InvalidDeclaration, "Invalid model name: #{d.model.inspect}"
53
+ end
54
+ unless d.column.is_a?(String) && d.column.match?(/\A[a-z_][a-z0-9_]*\z/)
55
+ raise InvalidDeclaration, "Invalid column name: #{d.column.inspect}"
56
+ end
57
+ unless d.category.is_a?(Symbol) && d.category.match?(/\A[a-z_][a-z0-9_]*\z/)
58
+ raise InvalidDeclaration, "Invalid category: #{d.category.inspect}"
59
+ end
60
+ unless ACTIONS.include?(d.action)
61
+ raise InvalidDeclaration, "Unknown erasure action: #{d.action.inspect}"
62
+ end
63
+ if d.retention.nil? || !d.retention.is_a?(String) || d.retention.empty?
64
+ raise InvalidDeclaration, "A retention period is required for #{d.model}.#{d.column}"
65
+ end
66
+ if d.action == :retain && (d.justification.nil? || d.justification.strip.empty?)
67
+ raise RetentionJustificationRequired, "Retention of #{d.model}.#{d.column} requires a justification"
68
+ end
69
+ end
70
+ end
71
+ end
72
+ end
@@ -0,0 +1,74 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Railtracks
4
+ # The configured services of the retention track.
5
+ #
6
+ # `Railtracks.retention` returns this object after the host has configured
7
+ # the retention track. It is a thin factory over the domain services so
8
+ # application code does not have to repeat the registry, secret, model list
9
+ # and target model at every call site.
10
+ #
11
+ # receipt = Railtracks.retention.recorded_execution.call(subject_ref)
12
+ # report = Railtracks.retention.due_for_erasure.call
13
+ class Retention
14
+ attr_reader :configuration
15
+
16
+ def initialize(configuration = Railtracks.configuration)
17
+ @configuration = configuration
18
+ unless configuration.track?(:retention)
19
+ raise Configuration::Error, "The retention track is not enabled"
20
+ end
21
+ end
22
+
23
+ def registry
24
+ configuration.registry
25
+ end
26
+
27
+ def receipt_secret
28
+ configuration.receipt_secret
29
+ end
30
+
31
+ def model_classes
32
+ configuration.model_classes
33
+ end
34
+
35
+ def target_model
36
+ configuration.target_model_name
37
+ end
38
+
39
+ def store
40
+ ReceiptStore.new(secret: receipt_secret)
41
+ end
42
+
43
+ def execution(model: target_model)
44
+ require_target!(model)
45
+ ErasureExecution.new(
46
+ registry: registry,
47
+ model_classes: model_classes,
48
+ secret: receipt_secret,
49
+ model: model
50
+ )
51
+ end
52
+
53
+ def recorded_execution(model: target_model)
54
+ require_target!(model)
55
+ RecordedErasureExecution.new(
56
+ execution: execution(model: model),
57
+ store: store,
58
+ model: model
59
+ )
60
+ end
61
+
62
+ def due_for_erasure(now: Time.now.utc)
63
+ DueForErasure.new(registry: registry, secret: receipt_secret, now: now)
64
+ end
65
+
66
+ private
67
+
68
+ def require_target!(model)
69
+ return unless model.nil?
70
+
71
+ raise Configuration::Error, "The retention track requires a target_model or an explicit model:"
72
+ end
73
+ end
74
+ end
@@ -0,0 +1,39 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Railtracks
4
+ class RetentionPeriod
5
+ UNITS = {
6
+ "day" => 86_400,
7
+ "days" => 86_400,
8
+ "week" => 604_800,
9
+ "weeks" => 604_800,
10
+ "month" => 2_592_000,
11
+ "months" => 2_592_000,
12
+ "year" => 31_536_000,
13
+ "years" => 31_536_000
14
+ }.freeze
15
+
16
+ attr_reader :seconds, :text
17
+
18
+ def self.parse(value)
19
+ text = value.to_s.strip
20
+ match = /\A(\d+)\s+(day|days|week|weeks|month|months|year|years)\z/.match(text)
21
+ raise Registry::InvalidDeclaration, "Unsupported retention period: #{value.inspect}" unless match
22
+ amount = Integer(match[1], 10)
23
+ raise Registry::InvalidDeclaration, "Retention period must be positive" if amount <= 0
24
+ seconds = amount * UNITS.fetch(match[2])
25
+ raise Registry::InvalidDeclaration, "Retention period is too large" if seconds > 100 * UNITS.fetch("year")
26
+ new(seconds, text)
27
+ end
28
+
29
+ def initialize(seconds, text)
30
+ @seconds = seconds
31
+ @text = text.freeze
32
+ freeze
33
+ end
34
+
35
+ def due_at(time)
36
+ time + seconds
37
+ end
38
+ end
39
+ end
@@ -0,0 +1,43 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "active_support/core_ext/enumerable"
4
+
5
+ module Railtracks
6
+ class SchemaAudit
7
+ Finding = Data.define(:kind, :model, :column, :message)
8
+ ORDER = { unknown_model: 0, unknown_column: 1, undeclared_column: 2 }.freeze
9
+
10
+ def initialize(registry, model_classes)
11
+ @registry = registry
12
+ @model_classes = model_classes.index_by(&:name)
13
+ end
14
+
15
+ def findings
16
+ declared = @registry.plan(subject: "schema-audit")
17
+ unknown_models = declared.reject { |d| @model_classes.key?(d[:model]) }
18
+ findings = unknown_models.map do |d|
19
+ Finding.new(:unknown_model, d[:model], d[:column], "Declared model is not loaded")
20
+ end
21
+
22
+ declared.reject { |d| unknown_models.include?(d) }.each do |d|
23
+ klass = @model_classes.fetch(d[:model])
24
+ columns = klass.column_names
25
+ unless columns.include?(d[:column])
26
+ findings << Finding.new(:unknown_column, d[:model], d[:column], "Declared column does not exist")
27
+ end
28
+ end
29
+ @model_classes.each do |model, klass|
30
+ (klass.column_names - declared_for_model(model).map { |item| item[:column] }).each do |column|
31
+ findings << Finding.new(:undeclared_column, model, column, "Column has no erasure declaration")
32
+ end
33
+ end
34
+ findings.sort_by { |f| [ ORDER.fetch(f.kind), f.model, f.column ].freeze }.freeze
35
+ end
36
+
37
+ private
38
+
39
+ def declared_for_model(model)
40
+ @registry.plan(subject: "schema-audit").select { |d| d[:model] == model }
41
+ end
42
+ end
43
+ end