Class: Familia::Migration::Registry

Inherits:
Object
  • Object
show all
Defined in:
lib/familia/migration/registry.rb

Overview

Registry provides Redis-backed tracking for migration state.

Storage Schema (Redis keys): #prefix:applied - Sorted Set (member=migration_id, score=timestamp) #prefix:metadata - Hash (field=migration_id, value=JSON metadata) #prefix:schema - Hash (field=model_name, value=schema_digest) #prefix:backup:id - Hash with TTL for rollback data

Examples:

Basic usage

registry = Familia::Migration::Registry.new
registry.applied?('20260131_add_status_field')  # => false
registry.record_applied(migration, stats)
registry.applied?('20260131_add_status_field')  # => true

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(redis: nil, prefix: nil) ⇒ Registry

Initialize a new Registry instance.

Parameters:

  • redis (Redis, nil) (defaults to: nil) —

    Redis client (defaults to Familia.dbclient)

  • prefix (String, nil) (defaults to: nil) —

    Key prefix (defaults to config.migrations_key)



43
44
45
46
# File 'lib/familia/migration/registry.rb', line 43

def initialize(redis: nil, prefix: nil)
  @redis = redis
  @prefix = prefix || Familia::Migration.config.migrations_key
end

Instance Attribute Details

#prefix ⇒ String (readonly)

Returns The key prefix for all registry data.

Returns:

  • (String) —

    The key prefix for all registry data



36
37
38
# File 'lib/familia/migration/registry.rb', line 36

def prefix
  @prefix
end

Instance Method Details

#all_applied ⇒ Array<Hash>, Redis::Future

Get all applied migrations with their timestamps.

Returns:

  • (Array<Hash>, Redis::Future) —

    Array of hashes with :migration_id and :applied_at keys. On a transaction or pipeline connection, the ZRANGE Future.



108
109
110
# File 'lib/familia/migration/registry.rb', line 108

def all_applied
  applied_entries(client)
end

#applied?(migration_id) ⇒ Boolean, Redis::Future

Check if a migration has been applied.

Parameters:

  • migration_id (String) —

    The migration identifier

Returns:

  • (Boolean, Redis::Future) —

    true if the migration is in the applied set. On a transaction or pipeline connection, the ZSCORE Future.



85
86
87
# File 'lib/familia/migration/registry.rb', line 85

def applied?(migration_id)
  Familia.transform_reply(client.zscore(applied_key, migration_id.to_s)) { |score| !score.nil? }
end

#applied_at(migration_id) ⇒ Time, ...

Get the timestamp when a migration was applied.

Parameters:

  • migration_id (String) —

    The migration identifier

Returns:

  • (Time, nil, Redis::Future) —

    The time the migration was applied, or nil if not applied. On a transaction or pipeline connection, the ZSCORE Future.



96
97
98
99
100
# File 'lib/familia/migration/registry.rb', line 96

def applied_at(migration_id)
  Familia.transform_reply(client.zscore(applied_key, migration_id.to_s)) do |score|
    score.nil? ? nil : Time.at(score)
  end
end

#backup_field(migration_id, key, field, value) ⇒ Object

Store a backup of a field value for potential rollback.

Parameters:

  • migration_id (String) —

    The migration identifier

  • key (String) —

    The Redis key being modified

  • field (String) —

    The field name within the key

  • value (String) —

    The original value to preserve



313
314
315
316
317
318
# File 'lib/familia/migration/registry.rb', line 313

def backup_field(migration_id, key, field, value)
  bkey = backup_key(migration_id)
  conn = client
  conn.hset(bkey, "#{key}:#{field}", value)
  conn.expire(bkey, Familia::Migration.config.backup_ttl)
end

#clear_backup(migration_id) ⇒ Object

Clear the backup data for a migration.

Parameters:

  • migration_id (String) —

    The migration identifier



354
355
356
# File 'lib/familia/migration/registry.rb', line 354

def clear_backup(migration_id)
  client.del(backup_key(migration_id))
end

#client ⇒ Redis, Redis::PipelinedConnection

Get the Redis client: the one passed to #initialize, or else Familia.dbclient.

Outside a transaction or pipeline the fallback is resolved once and kept, so a registry reuses one connection across its method calls even when Familia.dbclient creates a new one per call. Inside a Familia transaction or pipeline block the fallback is the block's connection, returned without being kept: a kept one would keep queueing commands on it after the block completed. Each registry method resolves the client once and issues all of its commands on it.

The block's connection is on the logical database the block was opened on: inside a block every Familia.dbclient lookup returns it, whatever database is asked for. A registry used inside a block that a model with another logical_database opened (+Order.transaction+ with +logical_database 7+) reads and writes its keys in that database, and #applied? outside the block, on the registry's own database, does not see a #record_applied made there. Pass +redis:+ for a registry that must stay on its database inside such a block.

Returns:

  • (Redis, Redis::PipelinedConnection) —

    The Redis client



70
71
72
73
74
75
# File 'lib/familia/migration/registry.rb', line 70

def client
  return @redis if @redis
  return Familia.dbclient if Familia.transaction_or_pipeline?

  @default_client ||= Familia.dbclient
end

#metadata(migration_id) ⇒ Hash, ...

Get metadata for a specific migration.

Parameters:

  • migration_id (String) —

    The migration identifier

Returns:

  • (Hash, nil, Redis::Future) —

    Parsed JSON metadata or nil if not found. On a transaction or pipeline connection, the HGET Future.



138
139
140
# File 'lib/familia/migration/registry.rb', line 138

def (migration_id)
  (client, migration_id)
end

#pending(all_migrations) ⇒ Array<Class>

Filter a list of migrations to only those not yet applied.

Parameters:

  • all_migrations (Array<Class>) —

    All migration classes

Returns:

  • (Array<Class>) —

    Migration classes that haven't been applied



117
118
119
120
121
122
123
124
125
126
127
128
129
130
# File 'lib/familia/migration/registry.rb', line 117

def pending(all_migrations)
  return [] if all_migrations.nil? || all_migrations.empty?

  conn = client
  assert_replies_available!(:pending, conn)

  # Batch fetch all applied migration IDs in a single Redis call
  applied_ids = conn.zrange(applied_key, 0, -1).to_set

  all_migrations.reject do |migration|
    migration_id = extract_migration_id(migration)
    applied_ids.include?(migration_id)
  end
end

#record_applied(migration, stats = {}) ⇒ Object

Record that a migration has been applied.

Parameters:

  • migration (Class, Object) —

    The migration class or instance

  • stats (Hash) (defaults to: {}) —

    Statistics from the migration run

Options Hash (stats):

  • :duration_ms (Float) —

    Duration in milliseconds

  • :keys_scanned (Integer) —

    Number of keys scanned

  • :keys_modified (Integer) —

    Number of keys modified

  • :errors (Integer) —

    Number of errors

  • :reversible (Boolean) —

    Whether the migration is reversible



182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
# File 'lib/familia/migration/registry.rb', line 182

def record_applied(migration, stats = {})
  migration_id = extract_migration_id(migration)
  now = Time.now
  conn = client

  # ZADD to applied set with current timestamp
  conn.zadd(applied_key, now.to_f, migration_id)

  # Build metadata
  meta = {
    status: 'applied',
    applied_at: now.iso8601,
    duration_ms: stats[:duration_ms] || 0,
    keys_scanned: stats[:keys_scanned] || 0,
    keys_modified: stats[:keys_modified] || 0,
    errors: stats[:errors] || 0,
    reversible: stats[:reversible] || false,
  }

  # HSET metadata JSON
  conn.hset(, migration_id, JSON.generate(meta))
end

#record_rollback(migration_id) ⇒ Object

Record that a migration has been rolled back.

Parameters:

  • migration_id (String) —

    The migration identifier



209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
# File 'lib/familia/migration/registry.rb', line 209

def record_rollback(migration_id)
  conn = client
  assert_replies_available!(:record_rollback, conn)
  migration_id = migration_id.to_s

  # Remove from applied set
  conn.zrem(applied_key, migration_id)

  # Update metadata to show rolled_back status
  existing = (conn, migration_id)
  meta = existing || {}
  meta[:status] = 'rolled_back'
  meta[:rolled_back_at] = Time.now.iso8601

  conn.hset(, migration_id, JSON.generate(meta))
end

#redis ⇒ Redis?

The Redis client for this registry: the one passed as +redis:+, or else the Familia.dbclient fallback #client resolved and kept outside a block (nil until then). A transaction or pipeline connection is never returned, because #client does not keep one.

Returns:

  • (Redis, nil)


31
32
33
# File 'lib/familia/migration/registry.rb', line 31

def redis
  @redis || @default_client
end

#restore_backup(migration_id) ⇒ Integer

Restore all backed up fields for a migration.

Parameters:

  • migration_id (String) —

    The migration identifier

Returns:

  • (Integer) —

    Number of fields restored



325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
# File 'lib/familia/migration/registry.rb', line 325

def restore_backup(migration_id)
  conn = client
  assert_replies_available!(:restore_backup, conn)
  bkey = backup_key(migration_id)
  backup_data = conn.hgetall(bkey)
  return 0 if backup_data.empty?

  count = 0

  backup_data.each do |composite_key, value|
    # Parse "redis_key:field_name" format
    # Note: field_name might contain colons, so we only split on the last colon
    parts = composite_key.rpartition(':')
    redis_key = parts[0]
    field_name = parts[2]

    next if redis_key.empty? || field_name.empty?

    conn.hset(redis_key, field_name, value)
    count += 1
  end

  count
end

#schema_changed?(model_class) ⇒ Boolean

Check if the schema has changed for a model class.

Parameters:

  • model_class (Class) —

    A Familia::Horreum subclass

Returns:

  • (Boolean) —

    true if schema differs from stored version



270
271
272
273
274
275
276
277
# File 'lib/familia/migration/registry.rb', line 270

def schema_changed?(model_class)
  conn = client
  assert_replies_available!(:schema_changed?, conn)
  stored = read_stored_schema(conn, model_class)
  return false if stored.nil? # No stored schema = no drift

  stored != schema_digest(model_class)
end

#schema_digest(model_class) ⇒ String

Calculate the schema digest for a model class.

Parameters:

  • model_class (Class) —

    A Familia::Horreum subclass

Returns:

  • (String) —

    SHA256 hex digest of the field schema



233
234
235
236
237
238
239
240
241
242
243
# File 'lib/familia/migration/registry.rb', line 233

def schema_digest(model_class)
  fields = model_class.fields.sort
  field_types = model_class.field_types

  field_strings = fields.map do |field|
    type = field_types[field] || 'unknown'
    "#{field}:#{type}"
  end

  Digest::SHA256.hexdigest(field_strings.join('|'))
end

#schema_drift ⇒ Array<String>

Get a list of model classes with changed schemas.

Returns:

  • (Array<String>) —

    Model names with schema drift



283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
# File 'lib/familia/migration/registry.rb', line 283

def schema_drift
  conn = client
  assert_replies_available!(:schema_drift, conn)
  # Get all stored schemas
  stored = conn.hgetall(schema_key)
  return [] if stored.empty?

  drifted = []

  stored.each do |model_name, stored_digest|
    # Try to find the model class
    model_class = find_model_class(model_name)
    next if model_class.nil?

    current_digest = schema_digest(model_class)
    drifted << model_name if stored_digest != current_digest
  end

  drifted
end

#status(all_migrations) ⇒ Array<Hash>

Get the status of all migrations.

Parameters:

  • all_migrations (Array<Class>) —

    All migration classes

Returns:

  • (Array<Hash>) —

    Array of status hashes with :migration_id, :status, :applied_at



147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
# File 'lib/familia/migration/registry.rb', line 147

def status(all_migrations)
  return [] if all_migrations.nil? || all_migrations.empty?

  conn = client
  assert_replies_available!(:status, conn)

  # Batch fetch all applied migrations with timestamps in a single Redis call
  applied_info = applied_entries(conn).each_with_object({}) do |entry, hash|
    hash[entry[:migration_id]] = entry[:applied_at]
  end

  all_migrations.map do |migration|
    migration_id = extract_migration_id(migration)
    timestamp = applied_info[migration_id]

    {
      migration_id: migration_id,
      status: timestamp ? :applied : :pending,
      applied_at: timestamp,
    }
  end
end

#store_schema(model_class) ⇒ Object

Store the current schema digest for a model class.

Parameters:

  • model_class (Class) —

    A Familia::Horreum subclass



249
250
251
252
253
# File 'lib/familia/migration/registry.rb', line 249

def store_schema(model_class)
  model_name = model_class.name || model_class.to_s
  digest = schema_digest(model_class)
  client.hset(schema_key, model_name, digest)
end

#stored_schema(model_class) ⇒ String, ...

Get the stored schema digest for a model class.

Parameters:

  • model_class (Class) —

    A Familia::Horreum subclass

Returns:

  • (String, nil, Redis::Future) —

    The stored digest or nil if not found. On a transaction or pipeline connection, the HGET Future.



261
262
263
# File 'lib/familia/migration/registry.rb', line 261

def stored_schema(model_class)
  read_stored_schema(client, model_class)
end