### Familia Registry System Setup Source: https://github.com/delano/familia/blob/main/docs/guides/Implementation-Guide.md Demonstrates the Ruby code for setting up the Familia encryption registry, including methods for auto-registering providers, getting a provider by algorithm, and retrieving the default provider. ```ruby module Familia::Encryption::Registry # Auto-register available providers by priority def self.setup! # Get provider instance by algorithm def self.get(algorithm) # Get highest-priority available provider def self.default_provider end ``` -------------------------------- ### Quantum Calculation Examples: Understanding Boundaries Source: https://github.com/delano/familia/blob/main/docs/guides/Quantization-Feature-Guide.md This Ruby code provides examples of using the `qstamp` method to understand quantum boundaries with different time intervals (1-hour and 15-minute). It demonstrates how timestamps are rounded down to the nearest quantum boundary. ```ruby # Example with 1-hour quantum time1 = Time.utc(2023, 6, 15, 14, 15, 30) # 14:15:30 time2 = Time.utc(2023, 6, 15, 14, 45, 12) # 14:45:12 hour_stamp1 = AnalyticsEvent.qstamp(1.hour, time: time1) hour_stamp2 = AnalyticsEvent.qstamp(1.hour, time: time2) # Both timestamps round down to 14:00:00 Time.at(hour_stamp1).strftime('%H:%M:%S') # => "14:00:00" Time.at(hour_stamp2).strftime('%H:%M:%S') # => "14:00:00" hour_stamp1 == hour_stamp2 # => true # Example with 15-minute quantum quarter1 = AnalyticsEvent.qstamp(15.minutes, time: time1) # 14:15:30 -> 14:15:00 quarter2 = AnalyticsEvent.qstamp(15.minutes, time: time2) # 14:45:12 -> 14:45:00 Time.at(quarter1).strftime('%H:%M:%S') # => "14:15:00" Time.at(quarter2).strftime('%H:%M:%S') # => "14:45:00" quarter1 == quarter2 # => false (different 15-minute buckets) ``` -------------------------------- ### Familia Feature: My Feature Setup and Validation Source: https://github.com/delano/familia/blob/main/docs/guides/Features-System-Developer-Guide.md This snippet demonstrates the setup and validation logic for the 'MyFeature' within the Familia framework. It checks for Familia version compatibility and ensures the base class has required methods. ```Ruby module Familia module Features module MyFeature FEATURE_VERSION = '1.0.0' REQUIRED_FAMILIA_VERSION = '>= 2.0.0' def self.included(base) validate_environment!(base) Familia.ld "[#{base}] Loading #{self} v#{FEATURE_VERSION}" base.extend ClassMethods base.prepend InstanceMethods base.include HelperMethods configure_feature(base) end def self.validate_environment!(base) familia_version = Gem::Version.new(Familia::VERSION) required_version = Gem::Requirement.new(REQUIRED_FAMILIA_VERSION) unless required_version.satisfied_by?(familia_version) raise Familia::Problem, "#{self} requires Familia #{REQUIRED_FAMILIA_VERSION}, " \ "got #{familia_version}" end required_methods = [:identifier_field, :field] missing_methods = required_methods.reject { |m| base.respond_to?(m) } if missing_methods.any? raise Familia::Problem, "#{base} missing required methods: #{missing_methods.join(', ')}" end end def self.configure_feature(base) base.instance_variable_set(:@my_feature_config, { enabled: true, options: {} }) base.class_eval do @my_feature_data ||= {} end end Familia::Base.add_feature self, :my_feature, depends_on: [:required_feature] end end end ``` -------------------------------- ### Install RbNaCl Gem for Familia Source: https://github.com/delano/familia/blob/main/docs/guides/Implementation-Guide.md Shows the bash commands to add the RbNaCl gem to the Gemfile and install it using Bundler, which is recommended for Familia's encryption performance and security. ```bash # Add to Gemfile gem 'rbnacl', '~> 7.1', '>= 7.1.1' # Install $ bundle install ``` -------------------------------- ### Runtime Feature Inclusion Example Source: https://github.com/delano/familia/blob/main/docs/guides/Features-System-Developer-Guide.md Shows how a class can declare and include features at runtime using the `feature` method. This example includes features like `:expiration`, `:encrypted_fields`, and `:safe_dump`. ```ruby class MyModel < Familia::Horreum feature :expiration feature :encrypted_fields feature :safe_dump end ``` -------------------------------- ### Query Organization Structure and User Lookups Source: https://github.com/delano/familia/blob/main/docs/guides/Relationships-Guide.md Provides examples of querying organization member counts and project memberships. Also demonstrates user lookups by email using a fast lookup mechanism. ```ruby org.members.size org.projects.members user_id = User.email_lookup.get('john@acme.com') found_user = User.find_by_email('john@acme.com') ``` -------------------------------- ### Familia Basic Connection Pool Setup Source: https://github.com/delano/familia/blob/main/docs/guides/Connection-Pooling-Guide.md Sets up a basic connection pool using Familia and the 'connection_pool' gem. It configures a provider that creates and manages Redis connections, ensuring connections are on the correct logical database upon creation. ```Ruby require 'connection_pool' class ConnectionManager @pools = {} # Configure provider at application startup def self.setup! Familia.connection_provider = lambda do |uri| parsed = URI.parse(uri) pool_key = "#{parsed.host}:#{parsed.port}/#{parsed.db || 0}" @pools[pool_key] ||= ConnectionPool.new(size: 10, timeout: 5) do Redis.new( host: parsed.host, port: parsed.port, db: parsed.db || 0 # CRITICAL: Set DB on connection creation ) end @pools[pool_key].with { |conn| conn } end end end # Initialize at app startup ConnectionManager.setup! ``` -------------------------------- ### Implement Lazy Feature Loading in Familia Source: https://github.com/delano/familia/blob/main/docs/guides/Features-System-Developer-Guide.md This Ruby code demonstrates a lazy loading strategy for Familia features to optimize performance. It includes a mechanism to defer expensive setup operations until a feature is actually used, ensuring that initialization costs are only incurred when necessary. The code defines methods for ensuring setup completion and accessing feature functionality. ```ruby module Familia::Features::LazyFeature def self.included(base) # Minimal setup at include time base.extend ClassMethods # Defer expensive setup until first use @setup_complete = false end module ClassMethods def ensure_lazy_feature_setup! return if @setup_complete # Expensive setup operations perform_expensive_setup @setup_complete = true end def lazy_feature_method ensure_lazy_feature_setup! # Method implementation end private def perform_expensive_setup # Heavy initialization work @expensive_data = load_expensive_data @compiled_templates = compile_templates end end Familia::Base.add_feature self, :lazy_feature end ``` -------------------------------- ### Creating Time-Based Cache Keys Source: https://github.com/delano/familia/blob/main/docs/guides/Quantization-Feature-Guide.md Provides an example of using quantization to generate time-based cache keys for different granularities (hourly and daily). It defines methods within a Familia model to create these keys. ```Ruby class MetricsCache < Familia::Horreum feature :quantization identifier_field :cache_key field :cache_key, :data, :computed_at hashkey :hourly_metrics def self.hourly_cache_key(metric_type, time = nil) timestamp = qstamp(1.hour, pattern: '%Y%m%d%H', time: time) "metrics:#{metric_type}:#{timestamp}" end def self.daily_cache_key(metric_type, time = nil) timestamp = qstamp(1.day, pattern: '%Y%m%d', time: time) "metrics:#{metric_type}:daily:#{timestamp}" end end # Usage hourly_key = MetricsCache.hourly_cache_key('page_views') # => "metrics:page_views:2023061514" daily_key = MetricsCache.daily_cache_key('signups') # => "metrics:signups:daily:20230615" ``` -------------------------------- ### Basic Permission Encoding Source: https://github.com/delano/familia/blob/main/docs/migrating/v2.0.0-pre7.md Provides examples of basic permission encoding using bitwise operations in Ruby. It defines constants for different permission levels and shows how to combine them. ```ruby # Permission levels (bit-encoded) READ = 1 # 001 WRITE = 4 # 100 DELETE = 32 # 100000 ADMIN = 128 # 10000000 # Combine permissions user_permissions = READ | WRITE # Can read and write admin_permissions = ADMIN # All permissions via hierarchy ``` -------------------------------- ### Familia Batch Operations for Encrypted Fields Source: https://github.com/delano/familia/blob/main/docs/guides/Implementation-Guide.md Shows an example of using Familia's batch creation feature to efficiently encrypt multiple records with sensitive data. ```ruby # Efficient bulk encryption customers = Customer.batch_create([ { email: 'user1@example.com', favorite_snack: 'chocolate chip cookies' }, { email: 'user2@example.com', favorite_snack: 'leftover pizza' } ]) ``` -------------------------------- ### Ruby: Testing Identifier Migrations Source: https://github.com/delano/familia/blob/main/docs/migrating/v2.0.0-pre12.md Provides Ruby code examples for testing the migration of ObjectIdentifier and VerifiableIdentifier features. It covers generating identifiers, verifying them, and testing scoped identifiers. ```ruby # Test ObjectIdentifier changes model = YourModel.new objid = model.generate_object_identifier extid = model.derive_external_identifier puts "Generator: #{model.object_identifier_generator_type}" # Test VerifiableIdentifier (if using) vid = model.generate_verifiable_id puts "Verifiable: #{YourModel.verified_identifier?(vid)}" # Test scoped identifiers (if using) scoped_vid = model.generate_verifiable_id(scope: 'production') puts "Scoped valid: #{YourModel.verified_identifier?(scoped_vid, scope: 'production')}" puts "Wrong scope: #{YourModel.verified_identifier?(scoped_vid, scope: 'development')}" ``` -------------------------------- ### Install Familia Gem Source: https://github.com/delano/familia/blob/main/README.md Instructions for installing the Familia gem using Bundler or directly via the gem command. This is the first step to using Familia in a Ruby project. ```bash # Add to Gemfile gem 'familia', '>= 2.0.0' # Or install directly gem install familia ``` -------------------------------- ### Generating Formatted Quantized Timestamps Source: https://github.com/delano/familia/blob/main/docs/guides/Quantization-Feature-Guide.md Demonstrates how to generate formatted timestamp strings using the `qstamp` method with different patterns. Examples include hourly, daily, and weekly formats. ```Ruby # Generate formatted timestamp strings hourly_key = AnalyticsEvent.qstamp(1.hour, pattern: '%Y%m%d%H') # => "2023061514" (YYYYMMDDHH format) daily_key = AnalyticsEvent.qstamp(1.day, pattern: '%Y-%m-%d') # => "2023-06-15" (ISO date format) weekly_key = AnalyticsEvent.qstamp(1.week, pattern: '%Y-W%U') # => "2023-W24" (Year-Week format) ``` -------------------------------- ### Feature Self-Registration Example Source: https://github.com/delano/familia/blob/main/docs/guides/Features-System-Developer-Guide.md Demonstrates how a feature module can self-register with the Familia system upon definition. It extends and prepends necessary methods and calls `Familia::Base.add_feature`. ```ruby module Familia::Features::MyFeature def self.included(base) base.extend ClassMethods base.prepend InstanceMethods end module ClassMethods # Class-level functionality end module InstanceMethods # Instance-level functionality end Familia::Base.add_feature self, :my_feature, depends_on: [:other_feature] end ``` -------------------------------- ### Dependency Validation Errors in Ruby Source: https://github.com/delano/familia/blob/main/docs/guides/Feature-System-Guide.md Illustrates how Familia handles feature dependency validation, showing an example of an error raised when dependencies are not met and the correct order to satisfy them. ```ruby # This will raise an error: class BadModel < Familia::Horreum feature :my_feature # Error: requires safe_dump, expiration end # => Familia::Problem: my_feature requires: safe_dump, expiration # Correct order: class GoodModel < Familia::Horreum feature :safe_dump feature :expiration feature :my_feature # ✅ Dependencies satisfied end ``` -------------------------------- ### Basic Redis Connection Setup in Ruby Source: https://github.com/delano/familia/blob/main/docs/overview.md Shows the basic configuration for connecting Familia to a Redis instance using a URI and a hash-based configuration. ```ruby # Simple connection Familia.uri = 'redis://localhost:6379/0' # Multiple databases Familia.redis_config = { host: 'localhost', port: 6379, db: 0, timeout: 5 } ``` -------------------------------- ### Implement Fast Database Methods in Ruby Source: https://github.com/delano/familia/blob/main/docs/guides/Field-System-Guide.md This example demonstrates how to implement fast methods for immediate database persistence in Familia::Horreum. Fast methods, denoted with a '!', write directly to the database, bypassing instance variable updates. It also shows how to read directly from the database using the fast method. ```ruby class UserProfile < Familia::Horreum identifier_field :user_id field :user_id, :name, :email, :last_login_at end profile = UserProfile.new(user_id: 'user_123') profile.save # Regular setter: updates instance variable only profile.last_login_at = Time.now # Not yet in database # Fast method: immediate database write profile.last_login_at!(Time.now) # Written to database immediately # Reading from database profile.last_login_at # => reads from instance variable profile.last_login_at! # => reads directly from database ``` -------------------------------- ### Configure RSpec for Encryption Testing Source: https://github.com/delano/familia/blob/main/docs/guides/Implementation-Guide.md This RSpec configuration block includes helper methods for encryption testing and sets up aaround hook to manage test encryption keys for each example. This ensures a clean state for encryption-related tests. ```ruby RSpec.configure do |config| config.include Familia::EncryptionTestHelpers config.around(:each, :encryption) do |example| with_test_encryption_keys { example.run } end end ``` -------------------------------- ### Simple Connection Pool Setup in Ruby Source: https://github.com/delano/familia/blob/main/docs/connection_pooling.md Demonstrates a basic setup for a connection pool using the `connection_pool` gem and Familia's `connection_provider` lambda. It creates a pool for Redis connections based on URI parsing. ```ruby require 'connection_pool' class MyApp @pools = {} Familia.connection_provider = lambda do |uri| parsed = URI.parse(uri) pool_key = "#{parsed.host}:#{parsed.port}/#{parsed.db || 0}" @pools[pool_key] ||= ConnectionPool.new(size: 10, timeout: 5) do Redis.new( host: parsed.host, port: parsed.port, db: parsed.db || 0 ) end @pools[pool_key].with { |conn| conn } end end ``` -------------------------------- ### Load Familia Features Automatically and Manually in Ruby Source: https://github.com/delano/familia/blob/main/docs/guides/Feature-System-Guide.md Explains how Familia features are automatically loaded from a specified directory (`lib/familia/features/`) in Ruby. It also provides an example of manually registering features that are located outside the standard directory. ```ruby # lib/familia/features.rb automatically loads: features_dir = File.join(__dir__, 'features') Dir.glob(File.join(features_dir, '*.rb')).each do |feature_file| require_relative feature_file end ``` ```ruby # For features outside the standard directory class ExternalFeature # Feature implementation... end # Register manually Familia::Base.add_feature ExternalFeature, :external_feature, depends_on: [] ``` -------------------------------- ### Test Familia Features with RSpec in Ruby Source: https://github.com/delano/familia/blob/main/docs/guides/Feature-System-Guide.md Provides examples of how to test Familia features using RSpec in Ruby. It covers testing feature inclusion, method availability, dependency validation, and integration testing of combined features. ```ruby RSpec.describe MyCustomFeature do let(:test_class) do Class.new(Familia::Horreum) do feature :my_custom_feature field :name end end it "includes feature methods" instance = test_class.new expect(instance).to respond_to(:custom_instance_method) expect(test_class).to respond_to(:custom_class_method) end it "validates dependencies" expect do Class.new(Familia::Horreum) do feature :advanced_audit # Missing safe_dump dependency end end.to raise_error(Familia::Problem, /requires.*safe_dump/) end end ``` ```ruby RSpec.describe "Feature Integration" do it "combines features correctly" combined_class = Class.new(Familia::Horreum) do feature :safe_dump feature :expiration feature :encrypted_fields field :name encrypted_field :secret safe_dump_fields :name default_expiration 1.hour end instance = combined_class.new(name: "test", secret: "hidden") # All features work together expect(instance.safe_dump).to eq(name: "test") expect(instance.secret).to eq("hidden") # Decrypted expect(instance.ttl).to be > 0 # Has expiration end end ``` -------------------------------- ### Test SafeDump DSL Changes Source: https://github.com/delano/familia/blob/main/docs/migrating/v2.0.0-pre11.md Provides a code example for testing the updated SafeDump DSL in Delano Familia. It shows how to instantiate a model with defined fields and use the `safe_dump` method to verify that the fields are correctly included in the output. ```ruby # Verify SafeDump DSL works model = YourModel.new(field1: 'value') result = model.safe_dump puts result.keys # Should include your defined fields ``` -------------------------------- ### Configure Familia for Testing in Ruby Source: https://github.com/delano/familia/blob/main/docs/overview.md Provides a Ruby example for setting up Familia in a testing environment, including specifying a test database and configuring encryption keys. ```ruby # test_helper.rb or spec_helper.rb require 'familia' # Use separate test database Familia.uri = 'redis://localhost:6379/15' # Setup encryption for tests test_keys = { v1: Base64.strict_encode64('a' * 32), v2: Base64.strict_encode64('b' * 32) } Familia.config.encryption_keys = test_keys Familia.config.current_key_version = :v1 # Clear data between tests def clear_redis Familia.redis.flushdb end ``` -------------------------------- ### Declaring Feature Dependencies in Ruby Source: https://github.com/delano/familia/blob/main/docs/guides/Feature-System-Guide.md Shows how to declare dependencies for a feature using `Familia::Base.add_feature` and how to ensure these dependencies are met when defining a model. ```ruby # Feature with dependencies Familia::Base.add_feature MyFeature, :my_feature, depends_on: [:safe_dump, :expiration] # Will verify dependencies when feature is activated: class Model < Familia::Horreum feature :safe_dump # Must be loaded first feature :expiration # Must be loaded first feature :my_feature # Dependencies satisfied end ``` -------------------------------- ### Use a Feature Method at Runtime Source: https://github.com/delano/familia/blob/main/docs/guides/Feature-System-Guide.md Illustrates how to call a method provided by an activated feature at runtime in a Familia Horreum class instance. ```ruby customer = Customer.new customer.my_feature_method # Available after feature inclusion ``` -------------------------------- ### Efficient Permission Queries Source: https://github.com/delano/familia/blob/main/docs/migrating/v2.0.0-pre7.md Demonstrates how to perform efficient permission filtering on relationships, allowing retrieval of items based on minimum required permission levels. ```ruby # Efficient permission filtering accessible_docs = document.accessible_items( collection_key: customer.documents.key, minimum_permissions: READ ) ``` -------------------------------- ### Create Feature Testing Infrastructure with RSpec Source: https://github.com/delano/familia/blob/main/docs/guides/Features-System-Developer-Guide.md This Ruby code provides a testing infrastructure for Familia features using RSpec. It includes helper methods for setting up test classes with specific features, checking feature enablement, and asserting the presence of expected methods. Examples demonstrate testing feature configuration and dependency validation. ```ruby # Test helpers for feature development module FeatureTestHelpers def with_feature(feature_name, config = {}) # Create temporary test class with feature test_class = Class.new(Familia::Horreum) do def self.name 'FeatureTestClass' end identifier_field :test_id field :test_id end # Configure feature if needed if config.any? test_class.define_singleton_method(:feature_config) do |name| config end end # Enable the feature test_class.feature feature_name yield test_class end def feature_enabled?(klass, feature_name) klass.features_enabled.include?(feature_name) end def assert_feature_methods(klass, expected_methods) expected_methods.each do |method| assert klass.method_defined?(method), "Expected #{klass} to have method #{method}" end end end # RSpec helper RSpec.configure do |config| config.include FeatureTestHelpers end # Feature test example RSpec.describe Familia::Features::MyFeature do it "adds expected methods to class" with_feature(:my_feature) do |test_class| expect(test_class).to respond_to(:my_feature_config) expect(test_class.new).to respond_to(:my_feature_helper) end end it "respects feature configuration" config = { enabled: false } with_feature(:my_feature, config) do |test_class| expect(test_class.my_feature_enabled?).to be false end end it "validates dependencies" expect { Class.new(Familia::Horreum) do feature :my_feature # Missing :required_feature dependency end }.to raise_error(Familia::Problem, /requires.*required_feature/) end end ``` -------------------------------- ### Optimizing for Common Use Cases with Familia Source: https://github.com/delano/familia/blob/main/docs/guides/Field-System-Guide.md Shows how to provide convenience methods for common field patterns in Familia, such as defining timestamps or implementing soft delete functionality. ```Ruby # Provide convenience methods for common patterns class BaseModel < Familia::Horreum def self.timestamps timestamp_field :created_at, as: :created_at timestamp_field :updated_at, as: :updated_at end def self.soft_delete boolean_field :deleted, as: :deleted timestamp_field :deleted_at, as: :deleted_at end end ``` -------------------------------- ### Implement Multi-Tenant Applications with Familia Source: https://github.com/delano/familia/blob/main/docs/guides/Relationships-Guide.md Demonstrates how to build multi-tenant applications using Familia. It covers defining organizations, users, and projects, establishing relationships between them using clean syntax, and leveraging automatic indexing and tracking for efficient data management in a shared environment. ```ruby class Organization < Familia::Horreum feature :relationships identifier_field :org_id field :org_id, :name, :plan # Organization collections set :members set :projects sorted_set :activity_feed end class User < Familia::Horreum feature :relationships identifier_field :user_id field :user_id, :email, :role # Multi-tenant membership member_of Organization, :members, type: :set class_tracked_in :global_activity, score: :created_at class_indexed_by :email, :email_lookup end class Project < Familia::Horreum feature :relationships identifier_field :project_id field :project_id, :name, :status member_of Organization, :projects, type: :set class_tracked_in :status_timeline, score: ->(proj) { "#{Time.now.to_i}.#{proj.status.hash}" } end # Usage org = Organization.new(org_id: 'org123', name: 'Acme Corp') user = User.new(user_id: 'user456', email: 'john@acme.com') project = Project.new(project_id: 'proj789', name: 'Website') # Establish relationships with clean syntax org.members << user # Clean Ruby-like syntax org.projects << project # Save objects to trigger automatic indexing user.save # Automatically added to class-level indexes project.save # Automatically added to class-level tracking ``` -------------------------------- ### Development Setup Commands Source: https://github.com/delano/familia/blob/main/CLAUDE.md Commands for setting up the development environment, including installing dependencies, generating documentation, and performing code linting. ```Shell bundle install bundle exec yard bundle exec rubocop ``` -------------------------------- ### Conditional Expiration Logic in Familia Source: https://github.com/delano/familia/blob/main/docs/guides/Expiration-Feature-Guide.md Provides an example of implementing conditional expiration logic for Familia objects based on custom criteria. ```ruby class AnalyticsEvent < Familia::Horreum feature :expiration identifier_field :event_id field :event_id, :event_type, :user_id, :timestamp, :data def should_expire? event_type == 'temporary' || timestamp < 1.day.ago end def save_with_conditional_expiration save if should_expire? update_expiration(default_expiration: 1.hour) else update_expiration(default_expiration: 30.days) end end end ``` -------------------------------- ### Organize Ruby Methods with Modules Source: https://github.com/delano/familia/blob/main/docs/guides/Feature-System-Guide.md Demonstrates how to organize Ruby methods into modules for class and instance level functionality, including the use of `extend` and `prepend` for class and instance methods respectively, and `include` for helper utilities. ```ruby module MyFeature def self.included(base) base.extend ClassMethods base.prepend InstanceMethods # For interception base.include HelperMethods # For additional utilities end module ClassMethods # Class-level functionality end module InstanceMethods # Instance method interception/override end module HelperMethods # Additional utility methods end end ``` -------------------------------- ### Safe Dump User Object Source: https://github.com/delano/familia/blob/main/README.md Example of using 'safe_dump' to get a serialized representation of a user object, including custom fields. ```ruby user = User.create(username: "rosedog", first_name: "Rose", last_name: "Dog") user.safe_dump # => {id: "user:rosedog", username: "rosedog", full_name: "Rose Dog"} ``` -------------------------------- ### Familia Connection Priority Configuration Source: https://github.com/delano/familia/blob/main/docs/guides/Connection-Pooling-Guide.md Demonstrates how to configure Familia's connection priority system, including setting thread-local connections, defining a connection provider, and controlling fallback behavior. ```Ruby # Priority 1: Thread-local (set by middleware) Thread.current[:familia_connection] = redis_client # Priority 2: Connection provider Familia.connection_provider = ->(uri) { pool.checkout(uri) } # Priority 3: Fallback (can be disabled) Familia.connection_required = true # Disable fallback ``` -------------------------------- ### Familia Provider Performance Benchmarking Source: https://github.com/delano/familia/blob/main/docs/guides/Implementation-Guide.md Shows how to benchmark the performance of different encryption providers in Familia using Ruby, outputting results including time, operations per second, and priority. ```ruby # Compare provider performance results = Familia::Encryption.benchmark(iterations: 1000) puts results # => { # "xchacha20poly1305" => { time: 0.45, ops_per_sec: 4444, priority: 100 }, # "aes-256-gcm" => { time: 0.52, ops_per_sec: 3846, priority: 50 } # } ``` -------------------------------- ### Time Bucketing with Quantization Source: https://github.com/delano/familia/blob/main/docs/guides/Quantization-Feature-Guide.md Demonstrates how to use the `qstamp` method with different time intervals and patterns to bucket timestamps. It shows how timestamps within a specific hour are rounded down to the beginning of that hour. ```Ruby qstamp(1.hour, pattern: '%H:%M:%S', time: Time.parse('14:30:45')) # => "14:00:00" qstamp(1.hour, pattern: '%H:%M:%S', time: Time.parse('14:05:12')) # => "14:00:00" qstamp(1.hour, pattern: '%H:%M:%S', time: Time.parse('14:55:33')) # => "14:00:00" ``` -------------------------------- ### Analytics Data Bucketing with Quantization Source: https://github.com/delano/familia/blob/main/docs/guides/Quantization-Feature-Guide.md Demonstrates using quantization to create time-based buckets for analytics data, such as user activity. It includes methods to record activity within 15-minute buckets and retrieve all buckets for a given hour. ```Ruby class UserActivity < Familia::Horreum feature :quantization identifier_field :bucket_id field :bucket_id, :user_count, :event_count, :bucket_time def self.record_activity(user_id, event_type) # Create 15-minute activity buckets bucket_key = qstamp(15.minutes, pattern: '%Y%m%d%H%M') bucket_id = "activity:#{bucket_key}" # Find or create bucket bucket = find(bucket_id) || new(bucket_id: bucket_id, bucket_time: bucket_key) # Update metrics bucket.user_count ||= 0 bucket.event_count ||= 0 # Use Redis sets/hashes for precise counting bucket_users = bucket.related_set("users") bucket_users.add(user_id) bucket.user_count = bucket_users.count bucket.event_count += 1 bucket.save end def self.activity_for_hour(hour_time) # Get all 15-minute buckets for the hour hour_start = qstamp(1.hour, time: hour_time) hour_pattern = Time.at(hour_start).strftime('%Y%m%d%H') # Find buckets matching the hour pattern bucket_keys = (0..3).map do |quarter| minute = quarter * 15 Time.at(hour_start + (minute * 60)).strftime('%Y%m%d%H%M') end bucket_keys.map { |key| find("activity:#{key}") }.compact end end # Usage UserActivity.record_activity('user_123', 'page_view') hourly_buckets = UserActivity.activity_for_hour(Time.now) ``` -------------------------------- ### Implement Quantization for Time-Series Data Source: https://github.com/delano/familia/blob/main/docs/guides/Feature-System-Guide.md Illustrates the 'quantization' feature in Familia for automatically bucketing data into time intervals. It shows how to define quantized fields for hourly and daily statistics. ```ruby class Metric < Familia::Horreum feature :quantization field :value quantized_field :hourly_stats, interval: 1.hour quantized_field :daily_stats, interval: 1.day end # Automatically buckets data by time intervals metric = Metric.new(value: 42) metric.hourly_stats # Bucketed by hour metric.daily_stats # Bucketed by day ``` -------------------------------- ### Test Encrypted Fields with RSpec Source: https://github.com/delano/familia/blob/main/docs/guides/Implementation-Guide.md An example of an RSpec test that verifies sensitive fields are encrypted. It creates a user record, checks Redis for the encrypted value, and asserts that the plaintext is not present, but ciphertext is. ```ruby it "encrypts sensitive fields", :encryption do user = User.create(favorite_snack: "leftover pizza") # Verify encryption in Redis raw_value = redis.hget(user.rediskey, "favorite_snack") expect(raw_value).not_to include("leftover pizza") expect(JSON.parse(raw_value)).to have_key("ciphertext") end ``` -------------------------------- ### Monitor and Reset Encryption Derivation Count Source: https://github.com/delano/familia/blob/main/docs/guides/Implementation-Guide.md This snippet shows how to retrieve the current derivation count for encryption and how to reset it, primarily for testing purposes. It accesses a class method to get the value and another to reset it. ```ruby puts Familia::Encryption.derivation_count.value Familia::Encryption.reset_derivation_count! ``` -------------------------------- ### Set Up Auto-loading for Project Features Source: https://github.com/delano/familia/blob/main/docs/migrating/v2.0.0-pre11.md Demonstrates how to set up auto-loading for project-specific features in Delano Familia. This involves creating a `features.rb` file within the model's directory and including `Familia::Features::Autoloader` to enable automatic discovery and loading of features. ```ruby # Create: models/[model_name]/features.rb module YourProject module ModelName module Features include Familia::Features::Autoloader end end end # Require this file before your model definitions require_relative 'model_name/features' ``` -------------------------------- ### Troubleshoot: Prevent Connection Leaks Source: https://github.com/delano/familia/blob/main/docs/guides/Connection-Pooling-Guide.md Highlights the best practice of using `.with` for managing connections within a pool to ensure they are properly returned after use, thereby preventing connection leaks. It contrasts this with manually checking out connections without returning them. ```ruby # Always use .with for pool connections pool.with do |conn| # Use connection end # Never checkout without returning conn = pool.checkout # ❌ Can leak ``` -------------------------------- ### Manage Multi-Context Membership Patterns Source: https://github.com/delano/familia/blob/main/docs/guides/Relationships-Guide.md Illustrates how to define and manage multiple membership contexts for a single model. This allows a document, for example, to belong to different organizational contexts like Customers, Projects, or Teams, each with potentially different relationship types (set, list, sorted_set). ```ruby class Document < Familia::Horreum feature :relationships identifier_field :doc_id field :doc_id, :title # Multiple membership contexts member_of Customer, :documents, type: :set member_of Project, :documents, type: :list member_of Team, :shared_docs, type: :sorted_set end # Usage - same document can belong to multiple contexts doc = Document.new(doc_id: 'doc123', title: 'Requirements') # Add to different organizational contexts doc.add_to_customer_documents(customer.custid) doc.add_to_project_documents(project.project_id) doc.add_to_team_shared_docs(team.team_id, score: Time.now.to_i) # Query membership across contexts doc.in_customer_documents?(customer.custid) # => true doc.in_project_documents?(project.project_id) # => true doc.in_team_shared_docs?(team.team_id) # => true ``` -------------------------------- ### Familia Manager Class Initialization and Operations Source: https://github.com/delano/familia/blob/main/docs/guides/Implementation-Guide.md Shows the Ruby code for the Familia::Encryption::Manager class, including initialization with an optional algorithm, encrypting data with context-specific key derivation, and decrypting data with automatic algorithm detection. ```ruby class Familia::Encryption::Manager # Use specific algorithm or auto-select best def initialize(algorithm: nil) # Encrypt with context-specific key derivation def encrypt(plaintext, context:, additional_data: nil) # Decrypt with automatic algorithm detection def decrypt(encrypted_json, context:, additional_data: nil) end ``` -------------------------------- ### Ruby Common Issue: Session Expiration Not Applied Source: https://github.com/delano/familia/blob/main/docs/guides/Expiration-Feature-Guide.md Highlights a common issue where session expiration is not applied because the session object was not saved first. It provides an example of the incorrect approach (calling `update_expiration` before `save`) and the correct approach (saving the session before updating its expiration). ```ruby session = UserSession.new # ❌ Won't work - object must be saved first session.update_expiration(default_expiration: 1.hour) # ✅ Correct - save first, then expire session.save session.update_expiration(default_expiration: 1.hour) ``` -------------------------------- ### Implement Key Rotation Procedures in Familia Source: https://github.com/delano/familia/blob/main/docs/migrating/v2.0.0-pre5.md Provides an example script for implementing key rotation in Familia. This involves adding a new key version, updating the current key version, and re-encrypting existing data. Old keys can be removed after the migration is complete. ```ruby # Add new key version Familia.config.encryption_keys[:v3] = 'new-key' Familia.config.current_key_version = :v3 # Re-encrypt existing records Vault.all.each do |vault| vault.save # Automatically uses new key version end ``` -------------------------------- ### Ruby Efficient TTL Updates using Pipelining Source: https://github.com/delano/familia/blob/main/docs/guides/Expiration-Feature-Guide.md Compares inefficient single-round-trip TTL updates with efficient batch operations using Redis pipelining. The efficient example demonstrates updating the expiration for multiple sessions and their related fields in a single batch, reducing network overhead. ```ruby # ❌ Inefficient: Multiple round trips sessions.each do |session| session.update_expiration(default_expiration: 1.hour) end # ✅ Efficient: Batch operations redis = Familia.dbclient pipeline = redis.pipelined do |pipe| sessions.each do |session| pipe.expire(session.dbkey, 3600) # Also expire related fields if needed session.class.related_fields.each do |name, _| related_key = "#{session.dbkey}:#{name}" pipe.expire(related_key, 3600) end end end ``` -------------------------------- ### Troubleshoot: Pool Exhaustion Source: https://github.com/delano/familia/blob/main/docs/guides/Connection-Pooling-Guide.md Provides guidance on addressing connection pool exhaustion, suggesting monitoring pool usage (e.g., using `ConnectionPool.stats` if available) and increasing the pool size or reducing the time connections are held. ```ruby # Monitor pool usage ConnectionPool.stats # If available # Increase pool size or reduce hold time ``` -------------------------------- ### Debug Logging for Feature Loading in Ruby Source: https://github.com/delano/familia/blob/main/docs/guides/Features-System-Developer-Guide.md Adds debug logging for feature loading and method calls within Familia. It logs the start and end times of feature loading and method executions, providing insights into performance and potential issues when Familia's debug mode is enabled. ```ruby module Familia::Features::DebugLogging def self.included(base) return unless Familia.debug? base.extend ClassMethods original_feature_method = base.method(:feature) base.define_singleton_method(:feature) do |name| Familia.ld "[DEBUG] Loading feature #{name} on #{self}" start_time = Time.now result = original_feature_method.call(name) load_time = (Time.now - start_time) * 1000 Familia.ld "[DEBUG] Feature #{name} loaded in #{load_time.round(2)}ms" result end end module ClassMethods def log_feature_method_call(method_name, &block) return block.call unless Familia.debug? Familia.ld "[DEBUG] Calling #{method_name} on #{self}" start_time = Time.now result = block.call duration = (Time.now - start_time) * 1000 Familia.ld "[DEBUG] #{method_name} completed in #{duration.round(2)}ms" result end end Familia::Base.add_feature self, :debug_logging end ``` -------------------------------- ### Customize Fast Method Behavior with Auditing in Ruby Source: https://github.com/delano/familia/blob/main/docs/guides/Field-System-Guide.md This example shows how to customize the behavior of fast methods in Familia::Horreum, specifically adding an audit trail for changes. It defines a custom field type, AuditedFieldType, that overrides the default fast writer to include audit logging. It stores audit entries in Redis. ```ruby class AuditedFieldType < Familia::FieldType def define_fast_writer(klass) return unless @fast_method_name field_name = @name method_name = @method_name fast_method_name = @fast_method_name handle_method_conflict(klass, fast_method_name) do klass.define_method fast_method_name do |*args| if args.empty? # Read from database hget(field_name) else # Write to database with audit trail value = args.first old_value = hget(field_name) # Update the field prepared = serialize_value(value) send(:"#{method_name}=", value) if method_name result = hset(field_name, prepared) # Create audit entry audit_entry = { field: field_name, old_value: old_value, new_value: value, changed_at: Time.now.to_f, changed_by: Thread.current[:current_user]&.id } # Store audit trail audit_key = "#{dbkey}:audit" Familia.dbclient.lpush(audit_key, audit_entry.to_json) Familia.dbclient.ltrim(audit_key, 0, 99) # Keep last 100 changes result end end end end end class AuditedDocument < Familia::Horreum def self.audited_field(name, **options) field_type = AuditedFieldType.new(name, **options) register_field_type(field_type) end identifier_field :doc_id field :doc_id, :title audited_field :content audited_field :status end # Usage creates audit trail doc = AuditedDocument.new(doc_id: 'doc_123') doc.save Thread.current[:current_user] = OpenStruct.new(id: 'user_456') doc.content!("Initial content") # Audited change doc.status!("draft") # Audited change # View audit trail audit_key = "#{doc.dbkey}:audit" audit_entries = Familia.dbclient.lrange(audit_key, 0, -1) audit_entries.map { |entry| JSON.parse(entry) } ``` -------------------------------- ### Ruby Common Issue: Related Fields Not Expiring Source: https://github.com/delano/familia/blob/main/docs/guides/Expiration-Feature-Guide.md Addresses the issue where related fields do not automatically cascade expiration when using Familia's `feature :expiration`. The example shows a `Customer` model with a `list :orders` field, indicating that without explicit relation definitions for cascading expiration, these related fields might not expire as expected. ```ruby class Customer < Familia::Horreum feature :expiration field :name list :orders # ❌ Won't cascade without proper relation definition end ``` -------------------------------- ### Update Queries: Manual vs. Relationship Methods Source: https://github.com/delano/familia/blob/main/docs/migrating/v2.0.0-pre7.md Compares manual Redis operations for managing relationships before the new system with the automatic method generation provided by the relationships system after migration. ```ruby # Before (manual Redis operations) redis.zadd("all_customers", customer.created_at, customer.custid) customers = redis.zrange("all_customers", 0, -1) # After (relationship methods) Customer.add_to_all_customers(customer) customers = Customer.all_customers.to_a ``` -------------------------------- ### Ruby: Complete Familia API Example Source: https://github.com/delano/familia/blob/main/docs/guides/relationships-methods.md A comprehensive example demonstrating the integration of member_of, class_tracked_in, and class_indexed_by relationships in Familia models. ```ruby # Domain declares membership in Customer collections class Domain < Familia::Horreum member_of Customer, :domains class_tracked_in :active_domains, score: -> { status == 'active' ? Time.now.to_i : 0 } end class Customer < Familia::Horreum class_indexed_by :email, :email_lookup class_tracked_in :all_customers, score: :created_at end ```