xrforge/manyfold/usr/src/app/config/initializers/xrforge.rb

45 lines
1.6 KiB
Ruby
Raw Normal View History

# this calls the xrforge unix file-hooks in /root/hook.d/experience_updated (but in a safe way)
# why: the database-write are sometimes chatty/duplicated.
# therefore it ratelimits and prevents processing unchanged files.
2025-10-29 15:05:18 +01:00
require 'pp'
require 'digest'
2025-10-29 15:05:18 +01:00
2025-10-29 10:47:55 +01:00
Rails.application.config.to_prepare do
Model # Zeitwerk autoload model
2025-10-29 15:05:18 +01:00
ModelFile
2025-10-29 10:47:55 +01:00
class ModelFile
2025-10-29 17:57:16 +01:00
# The macro is now run within the context of the existing Model class.
after_save :run_cli_hooks
2025-10-29 10:47:55 +01:00
2025-10-29 15:05:18 +01:00
def run_cli_hooks
file = "#{self.model.library.path}/#{self.path_within_library()}"
if File.exist?(file)
cache_key = "ttl:file:cli_hook:#{self.id}#{Digest::MD5.file(file).hexdigest}"
ttl = 60.0 # dont trigger hook twice for the same file within 60 seconds
now = Time.current
# 1. Read the last run time from the shared cache
last_run_time_str = Rails.cache.read(cache_key)
last_run_time = last_run_time_str ? Time.parse(last_run_time_str) : nil
if last_run_time.nil? || (now - last_run_time) > ttl
# 2. Write the new execution time to the shared cache
# Use `write` to set the new time. Caching a string representation is often safer/easier.
Rails.cache.write(cache_key, now.to_s, expires_in: ttl + 1.minute)
puts "[app/config/initializers/xrforge.rb] runnin hook\n"
command = "TS_SLOTS=5 ts /manyfold/cli/manyfold.sh hook experience_updated #{file} &"
2025-10-29 17:57:16 +01:00
system(command)
else
puts "[app/config/initializers/xrforge.rb] skipping hook\n"
2025-10-29 17:57:16 +01:00
end
end
2025-10-29 10:47:55 +01:00
end
end
end