predicate-rb 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +7 -0
- data/CHANGELOG.md +64 -0
- data/EXAMPLES.md +4183 -0
- data/LICENSE.txt +21 -0
- data/README.md +764 -0
- data/lib/predicate/combinators.rb +322 -0
- data/lib/predicate/core.rb +403 -0
- data/lib/predicate/dsl.rb +355 -0
- data/lib/predicate/model_integration.rb +410 -0
- data/lib/predicate/railtie.rb +19 -0
- data/lib/predicate/util.rb +36 -0
- data/lib/predicate/validation.rb +244 -0
- data/lib/predicate/version.rb +5 -0
- data/lib/predicate-rb.rb +6 -0
- data/lib/predicate.rb +279 -0
- metadata +85 -0
|
@@ -0,0 +1,403 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Predicate
|
|
4
|
+
# Core Engine
|
|
5
|
+
#
|
|
6
|
+
# The central engine for managing and executing predicates.
|
|
7
|
+
#
|
|
8
|
+
# Features::
|
|
9
|
+
# * Predicate registration and execution
|
|
10
|
+
# * State management
|
|
11
|
+
# * Caching with SHA256 keys
|
|
12
|
+
# * Performance monitoring
|
|
13
|
+
# * Section-based organization
|
|
14
|
+
# * Validation helpers (via Validation module)
|
|
15
|
+
#
|
|
16
|
+
# Usage::
|
|
17
|
+
# core = Predicate::Core.new(:user)
|
|
18
|
+
# core.add_predicate(:active) { |s| s[:active] == true }
|
|
19
|
+
# core.call(:active, { active: true })
|
|
20
|
+
#
|
|
21
|
+
# @author Nauman Tariq
|
|
22
|
+
# @version 1.0.0
|
|
23
|
+
class Core
|
|
24
|
+
include Predicate::Validation
|
|
25
|
+
|
|
26
|
+
attr_reader :entity, :predicates, :sections
|
|
27
|
+
|
|
28
|
+
# Initialize a new predicate core
|
|
29
|
+
# @param entity [Symbol, String] The entity name
|
|
30
|
+
# @param cache_ttl [Numeric, nil] Cache time-to-live in seconds (nil = no expiration)
|
|
31
|
+
# @param thread_safe [Boolean] Enable thread-safe cache operations (default: false)
|
|
32
|
+
def initialize(entity, cache_ttl: nil, thread_safe: false)
|
|
33
|
+
@entity = entity.to_sym
|
|
34
|
+
@predicates = {}
|
|
35
|
+
@sections = {}
|
|
36
|
+
@memoized_results = {} # Cache for predicate results
|
|
37
|
+
@cache_timestamps = {} # Track cache entry creation times (for TTL)
|
|
38
|
+
@cache_ttl = cache_ttl # nil = no expiration, number = seconds
|
|
39
|
+
@performance_stats = {} # Track performance metrics
|
|
40
|
+
@cache_hits = 0
|
|
41
|
+
@cache_misses = 0
|
|
42
|
+
@cache_size_limit = 1000 # Prevent memory bloat
|
|
43
|
+
@cache_writes = 0 # Track writes for periodic cleanup
|
|
44
|
+
@thread_safe = thread_safe # Enable thread-safe operations
|
|
45
|
+
@cache_mutex = thread_safe ? Mutex.new : nil # Mutex for thread-safety
|
|
46
|
+
end
|
|
47
|
+
|
|
48
|
+
# Add a predicate to the core
|
|
49
|
+
# @param name [Symbol, String] The predicate name
|
|
50
|
+
# @param block [Proc] The predicate logic
|
|
51
|
+
# @example
|
|
52
|
+
# core.add_predicate(:has_media) { |s| is_present?(s[:media_attachment_ids]) }
|
|
53
|
+
def add_predicate(name, &block)
|
|
54
|
+
raise InvalidPredicate, 'Predicate block is required' unless block_given?
|
|
55
|
+
|
|
56
|
+
@predicates[name.to_sym] = block
|
|
57
|
+
clear_cache! # Clear cache when predicates change
|
|
58
|
+
end
|
|
59
|
+
|
|
60
|
+
# Add section predicates for grouping related predicates
|
|
61
|
+
# @param section_name [Symbol, String] The section name
|
|
62
|
+
# @param block [Proc] Block containing section predicates
|
|
63
|
+
# @example
|
|
64
|
+
# core.add_section(:media) do |predicates|
|
|
65
|
+
# predicates[:has_media] = ->(s) { is_present?(s[:media_attachment_ids]) }
|
|
66
|
+
# predicates[:has_minimum_images] = ->(s) { s[:media_attachment_ids].length >= 1 }
|
|
67
|
+
# end
|
|
68
|
+
def add_section(section_name, &block)
|
|
69
|
+
raise InvalidPredicate, 'Section block is required' unless block_given?
|
|
70
|
+
|
|
71
|
+
@sections[section_name.to_sym] = block
|
|
72
|
+
end
|
|
73
|
+
|
|
74
|
+
# Call a predicate with state
|
|
75
|
+
# @param name [Symbol, String] The predicate name
|
|
76
|
+
# @param state [Hash] The state to evaluate against
|
|
77
|
+
# @return [Boolean] The predicate result
|
|
78
|
+
# @example
|
|
79
|
+
# result = core.call(:has_media, { media_attachment_ids: [1, 2] })
|
|
80
|
+
def call(name, state)
|
|
81
|
+
# Wrap entire operation in mutex if thread-safe mode enabled
|
|
82
|
+
if @thread_safe
|
|
83
|
+
@cache_mutex.synchronize { call_impl(name, state) }
|
|
84
|
+
else
|
|
85
|
+
call_impl(name, state)
|
|
86
|
+
end
|
|
87
|
+
end
|
|
88
|
+
|
|
89
|
+
# Internal implementation of call (extracted for mutex wrapping)
|
|
90
|
+
# @param name [Symbol, String] The predicate name
|
|
91
|
+
# @param state [Hash] The state to evaluate against
|
|
92
|
+
# @return [Boolean] The predicate result
|
|
93
|
+
def call_impl(name, state)
|
|
94
|
+
start_time = Predicate::Util.now
|
|
95
|
+
|
|
96
|
+
# Create optimized cache key from predicate name + state hash
|
|
97
|
+
cache_key = create_cache_key(name, state)
|
|
98
|
+
|
|
99
|
+
# Return cached result if available AND still valid (TTL check)
|
|
100
|
+
if @memoized_results.key?(cache_key) && cache_valid?(cache_key)
|
|
101
|
+
@cache_hits += 1
|
|
102
|
+
track_performance(name, 0.0)
|
|
103
|
+
Predicate::Performance.track_cache_hit(name) if defined?(Predicate::Performance)
|
|
104
|
+
return @memoized_results[cache_key]
|
|
105
|
+
end
|
|
106
|
+
|
|
107
|
+
@cache_misses += 1
|
|
108
|
+
Predicate::Performance.track_cache_miss(name) if defined?(Predicate::Performance)
|
|
109
|
+
|
|
110
|
+
# Find and execute predicate
|
|
111
|
+
predicate = find_predicate(name)
|
|
112
|
+
return false unless predicate
|
|
113
|
+
|
|
114
|
+
begin
|
|
115
|
+
result = predicate.call(state)
|
|
116
|
+
|
|
117
|
+
# Store result in cache with size management
|
|
118
|
+
store_in_cache(cache_key, result)
|
|
119
|
+
|
|
120
|
+
track_performance(name, Predicate::Util.now - start_time)
|
|
121
|
+
result
|
|
122
|
+
rescue StandardError => e
|
|
123
|
+
# Store false result for failed predicates to avoid re-execution
|
|
124
|
+
store_in_cache(cache_key, false)
|
|
125
|
+
track_performance(name, Predicate::Util.now - start_time)
|
|
126
|
+
|
|
127
|
+
# Log error but don't raise - predicates should be resilient
|
|
128
|
+
Rails.logger.error "Predicate #{name} failed: #{e.message}" if defined?(Rails) && Rails.respond_to?(:logger)
|
|
129
|
+
false
|
|
130
|
+
end
|
|
131
|
+
end
|
|
132
|
+
|
|
133
|
+
# Call a section predicate
|
|
134
|
+
# @param section_name [Symbol, String] The section name
|
|
135
|
+
# @param predicate_name [Symbol, String] The predicate name within the section
|
|
136
|
+
# @param state [Hash] The state to evaluate against
|
|
137
|
+
# @return [Boolean] The predicate result
|
|
138
|
+
# @example
|
|
139
|
+
# result = core.call_section(:media, :has_media, { media_attachment_ids: [1, 2] })
|
|
140
|
+
def call_section(section_name, predicate_name, state)
|
|
141
|
+
# Wrap entire operation in mutex if thread-safe mode enabled
|
|
142
|
+
if @thread_safe
|
|
143
|
+
@cache_mutex.synchronize { call_section_impl(section_name, predicate_name, state) }
|
|
144
|
+
else
|
|
145
|
+
call_section_impl(section_name, predicate_name, state)
|
|
146
|
+
end
|
|
147
|
+
end
|
|
148
|
+
|
|
149
|
+
# Internal implementation of call_section (extracted for mutex wrapping)
|
|
150
|
+
# @param section_name [Symbol, String] The section name
|
|
151
|
+
# @param predicate_name [Symbol, String] The predicate name within the section
|
|
152
|
+
# @param state [Hash] The state to evaluate against
|
|
153
|
+
# @return [Boolean] The predicate result
|
|
154
|
+
def call_section_impl(section_name, predicate_name, state)
|
|
155
|
+
start_time = Predicate::Util.now
|
|
156
|
+
|
|
157
|
+
# Use deterministic cache key (same as regular predicates)
|
|
158
|
+
combined_name = "#{section_name}_#{predicate_name}"
|
|
159
|
+
cache_key = create_cache_key(combined_name, state)
|
|
160
|
+
|
|
161
|
+
# Check cache with hit/miss tracking (same as regular predicates)
|
|
162
|
+
# Also check TTL validity
|
|
163
|
+
if @memoized_results.key?(cache_key) && cache_valid?(cache_key)
|
|
164
|
+
@cache_hits += 1 # Track cache hit
|
|
165
|
+
track_performance(combined_name.to_sym, 0.0)
|
|
166
|
+
return @memoized_results[cache_key]
|
|
167
|
+
end
|
|
168
|
+
|
|
169
|
+
@cache_misses += 1 # Track cache miss
|
|
170
|
+
|
|
171
|
+
# Execute section block to get predicates
|
|
172
|
+
section_predicates = {}
|
|
173
|
+
section = @sections[section_name.to_sym]
|
|
174
|
+
return false unless section
|
|
175
|
+
|
|
176
|
+
section.call(section_predicates)
|
|
177
|
+
|
|
178
|
+
predicate = section_predicates[predicate_name.to_sym]
|
|
179
|
+
return false unless predicate
|
|
180
|
+
|
|
181
|
+
begin
|
|
182
|
+
result = predicate.call(state)
|
|
183
|
+
|
|
184
|
+
# Use store_in_cache with all guardrails (size limit, LRU eviction)
|
|
185
|
+
store_in_cache(cache_key, result)
|
|
186
|
+
|
|
187
|
+
duration = Predicate::Util.now - start_time
|
|
188
|
+
track_performance(combined_name.to_sym, duration)
|
|
189
|
+
result
|
|
190
|
+
rescue StandardError => e
|
|
191
|
+
# Use store_in_cache for errors too
|
|
192
|
+
store_in_cache(cache_key, false)
|
|
193
|
+
|
|
194
|
+
duration = Predicate::Util.now - start_time
|
|
195
|
+
track_performance(combined_name.to_sym, duration)
|
|
196
|
+
|
|
197
|
+
# Log error but don't raise - predicates should be resilient
|
|
198
|
+
if defined?(Rails) && Rails.respond_to?(:logger)
|
|
199
|
+
Rails.logger.error "Section predicate #{combined_name} failed: #{e.message}"
|
|
200
|
+
end
|
|
201
|
+
false
|
|
202
|
+
end
|
|
203
|
+
end
|
|
204
|
+
|
|
205
|
+
# Check if a predicate exists
|
|
206
|
+
# @param name [Symbol, String] The predicate name
|
|
207
|
+
# @return [Boolean] True if predicate exists
|
|
208
|
+
def predicate?(name)
|
|
209
|
+
@predicates.key?(name.to_sym)
|
|
210
|
+
end
|
|
211
|
+
|
|
212
|
+
# Check if a section exists
|
|
213
|
+
# @param name [Symbol, String] The section name
|
|
214
|
+
# @return [Boolean] True if section exists
|
|
215
|
+
def has_section?(name)
|
|
216
|
+
@sections.key?(name.to_sym)
|
|
217
|
+
end
|
|
218
|
+
|
|
219
|
+
# Get all predicate names
|
|
220
|
+
# @return [Array<Symbol>] Array of predicate names
|
|
221
|
+
def predicate_names
|
|
222
|
+
@predicates.keys
|
|
223
|
+
end
|
|
224
|
+
|
|
225
|
+
# Get all section names
|
|
226
|
+
# @return [Array<Symbol>] Array of section names
|
|
227
|
+
def section_names
|
|
228
|
+
@sections.keys
|
|
229
|
+
end
|
|
230
|
+
|
|
231
|
+
# Clear the cache
|
|
232
|
+
def clear_cache!
|
|
233
|
+
if @thread_safe
|
|
234
|
+
@cache_mutex.synchronize do
|
|
235
|
+
@memoized_results.clear
|
|
236
|
+
@cache_timestamps.clear if @cache_ttl
|
|
237
|
+
end
|
|
238
|
+
else
|
|
239
|
+
@memoized_results.clear
|
|
240
|
+
@cache_timestamps.clear if @cache_ttl
|
|
241
|
+
end
|
|
242
|
+
end
|
|
243
|
+
|
|
244
|
+
# Get cache statistics
|
|
245
|
+
# @return [Hash] Cache statistics
|
|
246
|
+
def cache_stats
|
|
247
|
+
{
|
|
248
|
+
cached_results: @memoized_results.size,
|
|
249
|
+
predicates: @predicates.size,
|
|
250
|
+
sections: @sections.size,
|
|
251
|
+
cache_hits: @cache_hits,
|
|
252
|
+
cache_misses: @cache_misses,
|
|
253
|
+
cache_hit_ratio: calculate_cache_hit_ratio
|
|
254
|
+
}
|
|
255
|
+
end
|
|
256
|
+
|
|
257
|
+
# Get performance statistics
|
|
258
|
+
# @return [Hash] Performance statistics
|
|
259
|
+
def performance_stats
|
|
260
|
+
@performance_stats.dup
|
|
261
|
+
end
|
|
262
|
+
|
|
263
|
+
private
|
|
264
|
+
|
|
265
|
+
# Create an optimized cache key from predicate name and state
|
|
266
|
+
# @param name [Symbol, String] The predicate name
|
|
267
|
+
# @param state [Hash] The state hash
|
|
268
|
+
# @return [String] The cache key
|
|
269
|
+
def create_cache_key(name, state)
|
|
270
|
+
# Use deterministic JSON serialization + SHA256 for collision-free keys
|
|
271
|
+
# Sort keys for consistency regardless of hash order
|
|
272
|
+
|
|
273
|
+
require 'json'
|
|
274
|
+
require 'digest'
|
|
275
|
+
|
|
276
|
+
sorted_state = state.sort_by { |k, _v| k.to_s }.to_h
|
|
277
|
+
state_json = JSON.generate(sorted_state)
|
|
278
|
+
# Use first 16 chars of SHA256 hash for shorter keys
|
|
279
|
+
state_hash = Digest::SHA256.hexdigest(state_json)[0..15]
|
|
280
|
+
|
|
281
|
+
"#{name}_#{state_hash}"
|
|
282
|
+
rescue StandardError => e
|
|
283
|
+
# Fallback to original hash method if JSON fails (for non-serializable objects)
|
|
284
|
+
Rails.logger.warn "Cache key generation fallback: #{e.message}" if defined?(Rails) && Rails.respond_to?(:logger)
|
|
285
|
+
state_signature = state.sort_by { |k, _v| k.to_s }.hash
|
|
286
|
+
"#{name}_#{state_signature}"
|
|
287
|
+
end
|
|
288
|
+
|
|
289
|
+
# Store result in cache with size management
|
|
290
|
+
# @param cache_key [String] The cache key
|
|
291
|
+
# @param result [Boolean] The result to cache
|
|
292
|
+
def store_in_cache(cache_key, result)
|
|
293
|
+
# Implement LRU-style cache management
|
|
294
|
+
if @memoized_results.size >= @cache_size_limit
|
|
295
|
+
# Remove oldest 25% of entries when cache is full
|
|
296
|
+
entries_to_remove = @cache_size_limit / 4
|
|
297
|
+
@memoized_results.keys.first(entries_to_remove).each do |key|
|
|
298
|
+
@memoized_results.delete(key)
|
|
299
|
+
@cache_timestamps.delete(key) # Also remove timestamp
|
|
300
|
+
end
|
|
301
|
+
end
|
|
302
|
+
|
|
303
|
+
@memoized_results[cache_key] = result
|
|
304
|
+
# Track creation time if TTL enabled
|
|
305
|
+
@cache_timestamps[cache_key] = Predicate::Util.now if @cache_ttl
|
|
306
|
+
|
|
307
|
+
# Periodic cleanup of expired entries (every 100 writes)
|
|
308
|
+
@cache_writes += 1
|
|
309
|
+
clean_expired_cache! if @cache_ttl && (@cache_writes % 100).zero?
|
|
310
|
+
end
|
|
311
|
+
|
|
312
|
+
# Check if a cache entry is still valid (TTL check)
|
|
313
|
+
# @param cache_key [String] The cache key to check
|
|
314
|
+
# @return [Boolean] True if cache entry is valid (not expired)
|
|
315
|
+
def cache_valid?(cache_key)
|
|
316
|
+
# If no TTL configured, cache is always valid
|
|
317
|
+
return true unless @cache_ttl
|
|
318
|
+
|
|
319
|
+
# If no timestamp tracked, consider invalid (shouldn't happen, but defensive)
|
|
320
|
+
return false unless @cache_timestamps.key?(cache_key)
|
|
321
|
+
|
|
322
|
+
# Check if entry age is within TTL
|
|
323
|
+
entry_age = Predicate::Util.now - @cache_timestamps[cache_key]
|
|
324
|
+
entry_age <= @cache_ttl
|
|
325
|
+
end
|
|
326
|
+
|
|
327
|
+
# Clean up expired cache entries
|
|
328
|
+
# Called periodically (every 100 writes) when TTL is enabled
|
|
329
|
+
def clean_expired_cache!
|
|
330
|
+
return unless @cache_ttl
|
|
331
|
+
|
|
332
|
+
current_time = Predicate::Util.now
|
|
333
|
+
expired_keys = []
|
|
334
|
+
|
|
335
|
+
# Find all expired entries
|
|
336
|
+
@cache_timestamps.each do |key, timestamp|
|
|
337
|
+
entry_age = current_time - timestamp
|
|
338
|
+
expired_keys << key if entry_age > @cache_ttl
|
|
339
|
+
end
|
|
340
|
+
|
|
341
|
+
# Remove expired entries
|
|
342
|
+
expired_keys.each do |key|
|
|
343
|
+
@memoized_results.delete(key)
|
|
344
|
+
@cache_timestamps.delete(key)
|
|
345
|
+
end
|
|
346
|
+
end
|
|
347
|
+
|
|
348
|
+
# Calculate cache hit ratio
|
|
349
|
+
# @return [Float] Hit ratio between 0.0 and 1.0
|
|
350
|
+
def calculate_cache_hit_ratio
|
|
351
|
+
total = @cache_hits + @cache_misses
|
|
352
|
+
return 0.0 if total.zero?
|
|
353
|
+
|
|
354
|
+
(@cache_hits.to_f / total).round(3)
|
|
355
|
+
end
|
|
356
|
+
|
|
357
|
+
# Find a predicate by name (checks both direct predicates and sections)
|
|
358
|
+
# @param name [Symbol, String] The predicate name
|
|
359
|
+
# @return [Proc, nil] The predicate proc or nil if not found
|
|
360
|
+
def find_predicate(name)
|
|
361
|
+
# First check direct predicates
|
|
362
|
+
return @predicates[name.to_sym] if @predicates.key?(name.to_sym)
|
|
363
|
+
|
|
364
|
+
# Then check sections
|
|
365
|
+
@sections.each_value do |section_block|
|
|
366
|
+
section_predicates = {}
|
|
367
|
+
section_block.call(section_predicates)
|
|
368
|
+
return section_predicates[name.to_sym] if section_predicates.key?(name.to_sym)
|
|
369
|
+
end
|
|
370
|
+
|
|
371
|
+
nil
|
|
372
|
+
end
|
|
373
|
+
|
|
374
|
+
# Track performance metrics for a predicate
|
|
375
|
+
# @param predicate_name [Symbol, String] The predicate name
|
|
376
|
+
# @param duration [Float] Execution time in seconds
|
|
377
|
+
def track_performance(predicate_name, duration)
|
|
378
|
+
# Track stats unconditionally (not just when Rails is defined)
|
|
379
|
+
@performance_stats[predicate_name.to_sym] ||= {
|
|
380
|
+
calls: 0,
|
|
381
|
+
total_time: 0.0,
|
|
382
|
+
average_time: 0.0,
|
|
383
|
+
min_time: Float::INFINITY,
|
|
384
|
+
max_time: 0.0
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
stats = @performance_stats[predicate_name.to_sym]
|
|
388
|
+
stats[:calls] += 1
|
|
389
|
+
stats[:total_time] += duration
|
|
390
|
+
stats[:average_time] = stats[:total_time] / stats[:calls]
|
|
391
|
+
stats[:min_time] = [stats[:min_time], duration].min
|
|
392
|
+
stats[:max_time] = [stats[:max_time], duration].max
|
|
393
|
+
|
|
394
|
+
# Optional: Log to Rails if available
|
|
395
|
+
if defined?(Rails) && Rails.respond_to?(:logger)
|
|
396
|
+
Rails.logger.debug { "Predicate #{predicate_name} executed in #{duration}s" }
|
|
397
|
+
end
|
|
398
|
+
|
|
399
|
+
# Track globally if Performance module is available
|
|
400
|
+
Predicate::Performance.track(predicate_name, duration) if defined?(Predicate::Performance)
|
|
401
|
+
end
|
|
402
|
+
end
|
|
403
|
+
end
|