Class: Familia::Horreum
- Inherits:
-
Object
- Object
- Familia::Horreum
- Includes:
- Base, AtomicWrite, DatabaseCommands, DirtyTracking, Persistence, Serialization, Settings, Utils
- Defined in:
- lib/familia/horreum.rb,
lib/familia/horreum/utils.rb,
lib/familia/horreum/settings.rb,
lib/familia/horreum/connection.rb,
lib/familia/horreum/definition.rb,
lib/familia/horreum/management.rb,
lib/familia/horreum/persistence.rb,
lib/familia/horreum/atomic_write.rb,
lib/familia/horreum/serialization.rb,
lib/familia/horreum/dirty_tracking.rb,
lib/familia/horreum/related_fields.rb,
lib/familia/horreum/management/audit.rb,
lib/familia/horreum/database_commands.rb,
lib/familia/horreum/management/repair.rb,
lib/familia/horreum/management/audit_report.rb
Overview
Familia::Horreum
This module is included in classes that include Familia, providing instance-level functionality for Database operations and object management.
Defined Under Namespace
Modules: AtomicWrite, AuditMethods, Connection, DatabaseCommands, DefinitionMethods, DirtyTracking, ManagementMethods, Persistence, RelatedFieldsManagement, RepairMethods, Serialization, Settings, Utils Classes: AuditReport, ParentDefinition
Constant Summary
Constants included from AtomicWrite
AtomicWrite::OWNER_STATE_MUTEX
Class Attribute Summary collapse
-
.dbclient ⇒ Object
writeonly
TODO: Where are we calling dbclient= from now with connection pool?.
-
.has_related_fields ⇒ Object
readonly
Returns the value of attribute has_related_fields.
-
.parent ⇒ Object
Returns the value of attribute parent.
-
.valid_command_return_values ⇒ Object
readonly
Returns the value of attribute valid_command_return_values.
Instance Attribute Summary collapse
-
#dbclient ⇒ Object
writeonly
Sets the attribute dbclient.
Attributes included from Settings
Class Method Summary collapse
-
.dup_related_field_definitions(definitions, from_class, to_class) ⇒ Hash{Symbol => RelatedFieldDefinition}
Copies a related-field registry for a subclass.
-
.inherited(member) ⇒ Object
Extends ClassMethods to subclasses and tracks Familia members.
Instance Method Summary collapse
-
#generate_id ⇒ Redis
Returns the Database connection for the instance using Chain of Responsibility pattern.
-
#identifier ⇒ Object
Determines the unique identifier for the instance This method is used to generate dbkeys for the object Returns nil for unsaved objects (following standard ORM patterns).
-
#init ⇒ void
Initialization method called at the end of initialize.
-
#initialize(*args, **kwargs) ⇒ Horreum
constructor
Instance initialization This method sets up the object's state, including Valkey/Redis-related data.
-
#initialize_relatives ⇒ Object
Sets up related Database objects for the instance This method is crucial for establishing Valkey/Redis-based relationships.
- #initialize_with_keyword_args_deserialize_value(**fields) ⇒ Object
-
#naive_refresh(**fields) ⇒ Array
A thin wrapper around the private initialize method that accepts a field hash and refreshes the existing object.
-
#to_s ⇒ Object
The principle is: If Familia objects have
to_s, then they should work everywhere strings are expected, including as Database hash field names.
Methods included from Utils
Methods included from Settings
#logical_database, #logical_database=, #opts, #prefix
Methods included from DirtyTracking
#changed_fields, #clear_dirty!, #dirty?, #dirty_fields, #mark_dirty!, #record_dirty_warning!
Methods included from DatabaseCommands
#current_expiration, #data_type, #decr, #decrby, #delete!, #discard, #echo, #exists?, #expire, #field_count, #hget, #hgetall, #hkeys, #hmset, #hset, #hsetnx, #hstrlen, #hvals, #incr, #incrby, #incrbyfloat, #key?, #move, #remove_field, #unwatch, #watch
Methods included from Serialization
#debug_fields, #deserialize_value, #serialize_value, #to_a, #to_h, #to_h_for_storage
Methods included from AtomicWrite
#atomic_write, #atomic_write_mode?
Methods included from Persistence
#apply_fields, #clear_fields!, #commit_fields, #dbclient, #destroy!, #multi_field_fast_write, #multi_field_update, #pipelined, #refresh, #refresh!, #remove_from_instances!, #save, #save_fields, #save_if_not_exists, #save_if_not_exists!, #save_with_collections, #touch_instances!, #transaction
Methods included from Base
add_feature, #as_json, #expired?, #expires?, find_feature, #to_json, #ttl, #update_expiration, #uuid
Constructor Details
#initialize(*args, **kwargs) ⇒ Horreum
Instance initialization This method sets up the object's state, including Valkey/Redis-related data.
Usage:
Session.new("abc123", "user456") # positional (brittle)
Session.new(sessid: "abc123", custid: "user456") # hash (robust)
Session.new({sessid: "abc123", custid: "user456"}) # legacy hash (robust)
218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 |
# File 'lib/familia/horreum.rb', line 218 def initialize(*args, **kwargs) @dirty_fields = Concurrent::Map.new @warned_dirty_signatures = Concurrent::Map.new start_time = Familia.now_in_μs if Familia.debug? Familia.trace :INITIALIZE, nil, "Initializing #{self.class}" if Familia.debug? initialize_relatives # No longer auto-create a key field - the identifier method will # directly use the field specified by identifier_field # Detect if first argument is a hash (legacy support) if args.size == 1 && args.first.is_a?(Hash) && kwargs.empty? kwargs = args.first args = [] end # Initialize object with arguments using one of four strategies: # # 1. **Identifier** (Recommended for lookups): A single argument is # treated as the identifier. Robust and convenient for creating # objects from an ID. e.g. `Customer.new("cust_123")` # # 2. **Keyword Arguments** (Recommended for creation): Order-independent # field assignment # e.g. Customer.new(name: "John", email: "john@example.com") # # 3. **Positional Arguments** (Legacy): Field assignment by definition order # e.g. Customer.new("cust_123", "John", "john@example.com") # # 4. **No Arguments**: Object created with all fields as nil # if args.size == 1 && kwargs.empty? id_field = self.class.identifier_field send(:"#{id_field}=", args.first) elsif kwargs.any? initialize_with_keyword_args(**kwargs) elsif args.any? initialize_with_positional_args(*args) elsif Familia.debug? Familia.trace :INITIALIZE, nil, "#{self.class} initialized with no arguments" # Default values are intentionally NOT set here end # Implementing classes can define an init method to do any additional # initialization. Notice that this is called AFTER fields are set from # kwargs, so kwargs have been consumed and are no longer available. # # IMPORTANT: Use ||= in init to apply defaults without overriding: # def init # @email ||= email # Preserves value already set # @status ||= 'pending' # Applies default if nil # end # init # A freshly constructed object has no unsaved changes relative to its # initial state. Clear any dirty flags set during field assignment above. clear_dirty! # Structured lifecycle logging and instrumentation if Familia.debug? && start_time duration = Familia.now_in_μs - start_time Familia.debug "Horreum initialized", class: self.class.name, duration: duration, identifier: (identifier rescue nil) Familia::Instrumentation.notify_lifecycle(:initialize, self, duration: duration) end end |
Class Attribute Details
.dbclient=(value) ⇒ Object (writeonly)
TODO: Where are we calling dbclient= from now with connection pool?
92 93 94 |
# File 'lib/familia/horreum.rb', line 92 def dbclient=(value) @dbclient = value end |
.has_related_fields ⇒ Object (readonly)
Returns the value of attribute has_related_fields.
93 94 95 |
# File 'lib/familia/horreum.rb', line 93 def @has_related_fields end |
.parent ⇒ Object
Returns the value of attribute parent.
90 91 92 |
# File 'lib/familia/horreum.rb', line 90 def parent @parent end |
.valid_command_return_values ⇒ Object (readonly)
Returns the value of attribute valid_command_return_values.
33 34 35 |
# File 'lib/familia/horreum/persistence.rb', line 33 def valid_command_return_values @valid_command_return_values end |
Instance Attribute Details
#dbclient=(value) ⇒ Object (writeonly)
Sets the attribute dbclient
207 208 209 |
# File 'lib/familia/horreum.rb', line 207 def dbclient=(value) @dbclient = value end |
Class Method Details
.dup_related_field_definitions(definitions, from_class, to_class) ⇒ Hash{Symbol => RelatedFieldDefinition}
Copies a related-field registry for a subclass. Each definition's opts Hash is duplicated so that freezing (first materialization) or reconfiguring (configure_related_field) in one class never leaks into the other. transform_values preserves declaration order.
Class-level definitions carry opts[:parent] = the declaring class
(set by attach_class_related_field). That is re-pointed at the
subclass so an inherited, non-redeclared class_sorted_set/class_list
is keyed under the subclass rather than silently aliasing the
parent's Redis key. An explicit user-supplied parent: OtherClass
is left alone.
197 198 199 200 201 202 203 |
# File 'lib/familia/horreum.rb', line 197 def (definitions, from_class, to_class) definitions.transform_values do |definition| opts = definition.opts.dup opts[:parent] = to_class if opts[:parent].equal?(from_class) definition.with(opts: opts) end end |
.inherited(member) ⇒ Object
Extends ClassMethods to subclasses and tracks Familia members
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 |
# File 'lib/familia/horreum.rb', line 96 def inherited(member) Familia.trace :HORREUM, nil, "Welcome #{member} to the family" if Familia.debug? # Class-level functionality extensions: member.extend(Familia::Horreum::DefinitionMethods) # field(), identifier_field(), dbkey() member.extend(Familia::Horreum::ManagementMethods) # create(), find(), destroy!() member.extend(Familia::Horreum::Connection) # dbclient, connection management member.extend(Familia::Features) # feature() method for optional modules # Copy parent class configuration to child class # This implements conventional ORM inheritance behavior where child classes # automatically inherit all parent configuration without manual copying parent_class = member.superclass if parent_class.respond_to?(:identifier_field) && parent_class != Familia::Horreum # Copy essential configuration instance variables from parent if parent_class.identifier_field member.instance_variable_set(:@identifier_field, parent_class.identifier_field) end # Copy field system configuration member.instance_variable_set(:@fields, parent_class.fields.dup) if parent_class.fields&.any? if parent_class.respond_to?(:field_types) && parent_class.field_types&.any? # Copy field_types hash (FieldType instances are frozen/immutable and can be safely shared) copied_field_types = parent_class.field_types.dup member.instance_variable_set(:@field_types, copied_field_types) # Re-install field methods on the child class using proper method name detection parent_class.field_types.each_value do |field_type| # Collect all method names that field_type.install will create methods_to_check = [ field_type.method_name, (field_type.method_name ? :"#{field_type.method_name}=" : nil), field_type.fast_method_name, ].compact # Only install if none of the methods already exist methods_exist = methods_to_check.any? do |method_name| member.method_defined?(method_name) || member.private_method_defined?(method_name) end field_type.install(member) unless methods_exist end end # Copy features configuration if parent_class.respond_to?(:features_enabled) && parent_class.features_enabled&.any? member.instance_variable_set(:@features_enabled, parent_class.features_enabled.dup) end # Copy other configuration using consistent instance variable access if (prefix = parent_class.instance_variable_get(:@prefix)) member.instance_variable_set(:@prefix, prefix) end if (suffix = parent_class.instance_variable_get(:@suffix)) member.instance_variable_set(:@suffix, suffix) end if (logical_db = parent_class.instance_variable_get(:@logical_database)) member.instance_variable_set(:@logical_database, logical_db) end if (default_exp = parent_class.instance_variable_get(:@default_expiration)) member.instance_variable_set(:@default_expiration, default_exp) end # Copy DataType relationships (deep-copied, see dup_related_field_definitions) %i[class_related_fields related_fields].each do |registry| defs = parent_class.send(:"#{registry}_snapshot") next unless defs.any? member.instance_variable_set(:"@#{registry}", (defs, parent_class, member)) end if parent_class.instance_variable_get(:@has_related_fields) member.instance_variable_set(:@has_related_fields, parent_class.instance_variable_get(:@has_related_fields)) end end # Track all classes that inherit from Horreum Familia.members << member # Set up automatic instance tracking using built-in class_sorted_set member.class_sorted_set :instances, class: member, reference: true super end |
Instance Method Details
#generate_id ⇒ Redis
Returns the Database connection for the instance using Chain of Responsibility pattern.
This method uses a chain of handlers to resolve connections in priority order:
- FiberPipelineHandler - Fiber:familia_pipeline
- FiberTransactionHandler - Fiber:familia_transaction
- FiberConnectionHandler - Fiber:familia_connection
- ProviderConnectionHandler - connection_provider callback
- CachedConnectionHandler - @dbclient instance variable
- CreateConnectionHandler - creates new connection (fallback)
523 524 525 |
# File 'lib/familia/horreum.rb', line 523 def generate_id @objid ||= Familia.generate_id end |
#identifier ⇒ Object
Determines the unique identifier for the instance This method is used to generate dbkeys for the object Returns nil for unsaved objects (following standard ORM patterns)
491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 |
# File 'lib/familia/horreum.rb', line 491 def identifier definition = self.class.identifier_field return nil if definition.nil? # Call the identifier field or proc (validation already done at class definition time) unique_id = case definition when Symbol, String send(definition) when Proc definition.call(self) end # Return nil for unpopulated identifiers (like unsaved ActiveRecord objects) # Only raise errors when the identifier is actually needed for db operations return nil if unique_id.nil? || unique_id.to_s.empty? unique_id end |
#init ⇒ void
This method returns an undefined value.
Initialization method called at the end of initialize
Override this method to apply defaults, run validations, or setup callbacks. It's recommended to call super as other modules like features can also override init.
IMPORTANT: The init method receieves no arguments. By the time this runs, all arguments to initialize have already been consumed and used to set fields. Use the ||= operator to preserve values already set:
def init(email: nil, user_id: nil, **kwargs) @email ||= email # Preserves value from new() @user_id ||= user_id # Preserves value from new() @created_at ||= Familia.now # Applies default if not set
# Example of additional initialization logic
validate_email_format if @email
setup_callbacks
end
311 312 313 |
# File 'lib/familia/horreum.rb', line 311 def init # Default no-op - override in subclasses end |
#initialize_relatives ⇒ Object
Sets up related Database objects for the instance This method is crucial for establishing Valkey/Redis-based relationships
This needs to be called in the initialize method.
320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 |
# File 'lib/familia/horreum.rb', line 320 def initialize_relatives # Store initialization flag on singleton class to avoid polluting instance variables return if singleton_class.instance_variable_defined?(:@relatives_initialized) # Freeze every instance-level definition and take a snapshot of the # registry, both under the mutex configure_related_field and # declaration replace entries under. Once frozen, neither can replace # an entry (both check frozen? under the same lock), so the snapshot # holds exactly the definitions frozen here: a configure that took the # lock first is honored by every instance; one that arrives after # raises. Nothing can land in between. # # The build loop iterates the snapshot, never the live Hash. Declaring # a NEW field on a materialized class is allowed (participates_in does # it at load) and inserts into the live Hash; iterating that Hash here # would make the concurrent insert raise "can't add a new key into # hash during iteration". A declaration lands either before the # snapshot (this instance builds the field here) or after it (the # accessor builds it on first access; see materialize_related_field). # # There is no unlocked fast path: any check that walks the live Hash # has the same hazard, and a "frozen once" flag would be wrong because # late declarations add unfrozen entries. One uncontended mutex # acquire per instance is noise next to the rest of Klass.new. # # The build itself runs outside the lock: DataType#initialize calls # overridable setters and +init+, and a custom type that touches a # class-level collection there would deadlock on the non-reentrant # mutex if we still held it. definitions = self.class..synchronize do live = self.class. live.each_value { |definition| definition.opts.freeze } live.dup.freeze end definitions.each_pair { |name, definition| (name, definition) } # Mark relatives as initialized on singleton class to avoid polluting instance variables singleton_class.instance_variable_set(:@relatives_initialized, true) end |
#initialize_with_keyword_args_deserialize_value(**fields) ⇒ Object
453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 |
# File 'lib/familia/horreum.rb', line 453 def initialize_with_keyword_args_deserialize_value(**fields) # Deserialize Database string values back to their original types, then # hand each value to its field type's storage hook (FieldType#deserialize). # EncryptedFieldType uses the hook to wrap the stored envelope in # Familia::Encryption::StoredEnvelope, which is how its setter tells a # rehydrated envelope apart from caller-supplied plaintext that merely # looks like one (#405). This hydration path is the only caller of the # hook; the public constructor (initialize_with_keyword_args) never is. deserialized_fields = fields.each_with_object({}) do |(field_name, value), hsh| deserialized = deserialize_value(value, field_name: field_name) field_type = self.class.field_types[field_name.to_sym] deserialized = field_type.deserialize(deserialized, self) if field_type&.persistent? hsh[field_name] = deserialized end initialize_with_keyword_args(**deserialized_fields) end |
#naive_refresh(**fields) ⇒ Array
A thin wrapper around the private initialize method that accepts a field hash and refreshes the existing object.
This method is part of horreum.rb rather than serialization.rb because it operates solely on the provided values and doesn't query Database or other external sources. That's why it's called "naive" refresh: it assumes the provided values are correct and updates the object accordingly.
483 484 485 486 |
# File 'lib/familia/horreum.rb', line 483 def naive_refresh(**fields) Familia.debug "[naive_refresh] #{self.class} #{dbkey} #{fields.keys}" initialize_with_keyword_args_deserialize_value(**fields) end |
#to_s ⇒ Object
The principle is: If Familia objects have to_s, then they should work
everywhere strings are expected, including as Database hash field names.
529 530 531 532 533 534 535 536 |
# File 'lib/familia/horreum.rb', line 529 def to_s # Enable polymorphic string usage for Familia objects # This allows passing Familia objects directly where strings are expected # without requiring explicit .identifier calls return super if identifier.to_s.empty? identifier.to_s end |