summaryrefslogtreecommitdiff
path: root/lib/chef/node/immutable_collections.rb
blob: 3378bee2b5c2516562a405df0773dc143988b479 (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
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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
#--
# Copyright:: Copyright 2012-2017, Chef Software Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

require "chef/node/common_api"
require "chef/node/mixin/state_tracking"
require "chef/node/mixin/immutablize_array"
require "chef/node/mixin/immutablize_hash"

class Chef
  class Node
    module Immutablize
      # For elements like Fixnums, true, nil...
      def safe_dup(e)
        e.dup
      rescue TypeError
        e
      end

      def convert_value(value, path = nil)
        case value
        when Hash
          ImmutableMash.new({}, __root__, __node__, __precedence__, path)
        when Array
          ImmutableArray.new([], __root__, __node__, __precedence__, path)
        else
          safe_dup(value).freeze
        end
      end
    end

    # == ImmutableArray
    # ImmutableArray is used to implement Array collections when reading node
    # attributes.
    #
    # ImmutableArray acts like an ordinary Array, except:
    # * Methods that mutate the array are overridden to raise an error, making
    #   the collection more or less immutable.
    # * Since this class stores values computed from a parent
    #   Chef::Node::Attribute's values, it overrides all reader methods to
    #   detect staleness and raise an error if accessed when stale.
    class ImmutableArray < Array
      alias_method :internal_clear, :clear
      alias_method :internal_replace, :replace
      alias_method :internal_push, :<<
      alias_method :internal_to_a, :to_a
      alias_method :internal_each, :each
      private :internal_push, :internal_replace, :internal_clear, :internal_each
      protected :internal_to_a

      include Immutablize

      methods = Array.instance_methods - Object.instance_methods +
        [ :!, :!=, :<=>, :==, :===, :eql?, :to_s, :hash, :key, :has_key?, :inspect, :pretty_print, :pretty_print_inspect, :pretty_print_cycle, :pretty_print_instance_variables ]

      methods.each do |method|
        define_method method do |*args, &block|
          ensure_generated_cache!
          super(*args, &block)
        end
      end

      def each
        ensure_generated_cache!
        # aggressively pre generate the cache, works around ruby being too smart and fiddling with internals
        internal_each { |i| i.ensure_generated_cache! if i.respond_to?(:ensure_generated_cache!) }
        super
      end

      # because sometimes ruby gives us back Arrays or ImmutableArrays out of objects from things like #uniq or array slices
      def return_normal_array(array)
        if array.respond_to?(:internal_to_a, true)
          array.internal_to_a
        else
          puts array.class
          array.to_a
        end
      end

      def uniq
        ensure_generated_cache!
        return_normal_array(super)
      end

      def initialize(array_data = [])
        # Immutable collections no longer have initialized state
      end

      # For elements like Fixnums, true, nil...
      def safe_dup(e)
        e.dup
      rescue TypeError
        e
      end

      def dup
        Array.new(map { |e| safe_dup(e) })
      end

      def to_a
        Array.new(map do |v|
          case v
          when ImmutableArray
            v.to_a
          when ImmutableMash
            v.to_h
          else
            safe_dup(v)
          end
        end)
      end

      alias_method :to_array, :to_a

      def [](*args)
        ensure_generated_cache!
        args.length > 1 ? return_normal_array(super) : super # correctly handle array slices
      end

      def reset
        @generated_cache = false
        internal_clear # redundant?
      end

      # @api private
      def ensure_generated_cache!
        generate_cache unless @generated_cache
        @generated_cache = true
      end

      private

      def combined_components(components)
        combined_values = nil
        components.each do |component|
          values = __node__.attributes.instance_variable_get(component).read(*__path__)
          next unless values.is_a?(Array)
          combined_values ||= []
          combined_values += values
        end
        combined_values
      end

      def get_array(component)
        array = __node__.attributes.instance_variable_get(component).read(*__path__)
        if array.is_a?(Array)
          array
        end # else nil
      end

      def generate_cache
        internal_clear
        components = []
        components << combined_components(Attribute::DEFAULT_COMPONENTS)
        components << get_array(:@normal)
        components << combined_components(Attribute::OVERRIDE_COMPONENTS)
        components << get_array(:@automatic)
        highest = components.compact.last
        if highest.is_a?(Array)
          internal_replace( highest.each_with_index.map { |x, i| convert_value(x, __path__ + [ i ] ) } )
        end
      end

      # needed for __path__
      def convert_key(key)
        key
      end

      prepend Chef::Node::Mixin::StateTracking
      prepend Chef::Node::Mixin::ImmutablizeArray
    end

    # == ImmutableMash
    # ImmutableMash implements Hash/Dict behavior for reading values from node
    # attributes.
    #
    # ImmutableMash acts like a Mash (Hash that is indifferent to String or
    # Symbol keys), with some important exceptions:
    # * Methods that mutate state are overridden to raise an error instead.
    # * Methods that read from the collection are overriden so that they check
    #   if the Chef::Node::Attribute has been modified since an instance of
    #   this class was generated. An error is raised if the object detects that
    #   it is stale.
    # * Values can be accessed in attr_reader-like fashion via method_missing.
    class ImmutableMash < Mash
      alias_method :internal_clear, :clear
      alias_method :internal_key?, :key? # FIXME: could bypass convert_key in Mash for perf
      alias_method :internal_each, :each

      include Immutablize
      include CommonAPI

      methods = Hash.instance_methods - Object.instance_methods +
        [ :!, :!=, :<=>, :==, :===, :eql?, :to_s, :hash, :key, :has_key?, :inspect, :pretty_print, :pretty_print_inspect, :pretty_print_cycle, :pretty_print_instance_variables ]

      methods.each do |method|
        define_method method do |*args, &block|
          ensure_generated_cache!
          super(*args, &block)
        end
      end

      # this is for deep_merge usage, chef users must never touch this API
      # @api private
      def internal_set(key, value)
        regular_writer(key, convert_value(value, __path__ + [ key ]))
      end

      def initialize(mash_data = {})
        # Immutable collections no longer have initialized state
      end

      alias :attribute? :has_key?

      # NOTE: #default and #default= are likely to be pretty confusing. For a
      # regular ruby Hash, they control what value is returned for, e.g.,
      #   hash[:no_such_key] #=> hash.default
      # Of course, 'default' has a specific meaning in Chef-land

      def dup
        h = Mash.new
        each_pair do |k, v|
          h[k] = safe_dup(v)
        end
        h
      end

      def to_h
        h = Hash.new
        each_pair do |k, v|
          h[k] =
            case v
            when ImmutableMash
              v.to_h
            when ImmutableArray
              v.to_a
            else
              safe_dup(v)
            end
        end
        h
      end

      alias_method :to_hash, :to_h

      def [](key)
        ensure_generated_cache!
        super
      end

      alias_method :to_hash, :to_h

      def reset
        @generated_cache = false
        @short_circuit_attr_level = nil
        internal_clear # redundant?
      end

      # @api private
      def ensure_generated_cache!
        generate_cache unless @generated_cache
        @generated_cache = true
      end

      # @api private
      attr_accessor :short_circuit_attr_levels

      private

      def generate_cache
        internal_clear
        components = short_circuit_attr_levels ? short_circuit_attr_levels : Attribute::COMPONENTS.reverse
        # merged_components is not entirely accurate due to the short-circuit
        merged_components = []
        components.each do |component|
          subhash = __node__.attributes.instance_variable_get(component).read(*__path__)
          unless subhash.nil? # FIXME: nil is used for not present
            merged_components << component
            if subhash.kind_of?(Hash)
              subhash.keys.each do |key|
                next if internal_key?(key)
                internal_set(key, subhash[key])
              end
            else
              break
            end
          end
        end
        if merged_components.size == 1
          # merged_components is accurate enough to tell us if we're not really merging
          internal_each do |key, value|
            value.short_circuit_attr_levels = merged_components if value.respond_to?(:short_circuit_attr_levels)
          end
        end
      end

      prepend Chef::Node::Mixin::StateTracking
      prepend Chef::Node::Mixin::ImmutablizeHash
    end
  end
end