summaryrefslogtreecommitdiff
path: root/lib/dslkeywords/resource.rb
blob: c1c25543a061eb6b3982982eccf3e54dd1a214cc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
require 'set'

require_relative 'keyword'

module RCM
  # Concern that wraps side-effecting blocks so they are skipped (and
  # logged as dry-run) when the --dry option is active. Kept separate
  # from dependency tracking so each module has a single responsibility.
  module DryRun
    # Log the action and yield the block, unless --dry is active.
    # In dry-run mode only logs the message (with " - dry run!" appended)
    # and returns without executing the block.
    def do?(message)
      if option :dry
        info("#{message} - dry run!")
        return
      end
      info(message)
      yield
    end
  end

  # To track resource dependencies
  module ResourceDependencies
    def initialize(...)
      super(...)
      @requires = Set.new
      # Use the class-level registry (populated via Resource.inherited) rather
      # than scanning ObjectSpace — deterministic, load-order-safe, and O(1).
      @valid_resources = Resource.subclass_names
    end

    def method_missing(method_name, *args)
      super(method_name, *args) unless @valid_resources.include?(method_name)

      args.map { |arg| "#{method_name}('#{arg}')" }
    end

    def respond_to_missing? = true

    def requires(*others)
      return @requires if others.empty?

      others.flatten.each do |other|
        unless other.include?('(')
          # Convert "notify foo" to "notify('foo')"
          resource, rest = other.split(' ', 2)
          other = "#{resource}('#{rest}')"
        end

        info "Registered dependency on #{other}"
        @requires << other
      end
    end

    def requires?(*others) = others.flatten.none? { |other| !@requires&.include?(other) }
  end

  # To resolve dependencies
  module DependencyEvaluator
    attr_reader :evaluated

    class DependencyLoop < StandardError; end
    class UnresolvedDependency < StandardError; end

    def evaluate!
      return false if @evaluated

      info 'Evaluating...'
      raise DependencyLoop, "Dependency loop detected for #{id}" if @loop_detection

      @loop_detection = true

      # Try to evaluate all dependencies recursively.
      @requires.each.map { Resource.find(_1) }.each(&:evaluate!)

      # Raise an exception when there are still unresolved dependencies.
      unresolved = @requires.each.map { Resource.find(_1) }.reject(&:evaluated)
      raise UnresolvedDependency, "Unresolved dependencies: #{unresolved.map(&:id)}" if unresolved.count.positive?

      @loop_detection = false
      @evaluated = true
    end
  end

  # A resource is something concrete to be managed, e.g. a file, or a CRON job.
  class Resource < Keyword
    include DryRun
    include DependencyEvaluator
    include ResourceDependencies

    class NoSuchResourceObject < StandardError; end
    @@resource_find_cache = {}

    # Class-level registry: every subclass is registered here when it is
    # first loaded (via the inherited hook), so ResourceDependencies can
    # look up valid keyword names without scanning ObjectSpace.
    @@subclass_names = Set.new

    def self.inherited(subclass)
      super
      @@subclass_names << subclass.to_s.sub('RCM::', '').downcase.to_sym
    end

    # Return a frozen snapshot so callers cannot accidentally mutate the
    # shared registry through the @valid_resources instance variable.
    def self.subclass_names = @@subclass_names.freeze

    def self.find(id)
      return @@resource_find_cache[id] if @@resource_find_cache.key?(id)

      klass = Object.const_get("RCM::#{id.split(/[( ]/).first.capitalize}")
      resource = ObjectSpace.each_object(klass).find { _1.id == id }
      raise NoSuchResourceObject, "Unable to find resource #{id}" if resource.nil?

      @@resource_find_cache[id] = resource
    end
  end
end