Sha256: c42ed5c315a5b6b58f7c65e53c89deb39119b9ba77d4bf9a9e292edd4250edb2

Contents?: true

Size: 1.73 KB

Versions: 4

Compression:

Stored size: 1.73 KB

Contents

# We cache the clients globally to avoid re-instantiating them again after the initial Lambda cold start.
#
# Based on: https://hashrocket.com/blog/posts/implementing-a-macro-in-ruby-for-memoization
# Except we use a global variable for the cache. So we'll use the same client across
# all instances as well as across Lambda executions after the cold-start. Example:
#
#   class Foo
#     def s3
#       Aws::S3::Client.new
#     end
#     global_memoize :s3
#   end
#
#   foo1 = Foo.new
#   foo2 = Foo.new
#   foo1.s3
#   foo2.s3 # same client as foo1
#
# A prewarmed request after a cold-start will still use the same s3 client instance since it uses the
# global variable $__memo_methods as the cache.
#
module Jets::AwsServices
  module GlobalMemoist
    def reset_cache!
      $__memo_methods = {}
    end
    extend self

    def self.included(klass)
      klass.extend(Macros)
    end

    module Macros
      def global_memoize(*methods)
        const_defined?(:"GlobalMemoist#{object_id}") ?
          const_get(:"GlobalMemoist#{object_id}") : const_set(:"GlobalMemoist#{object_id}", Module.new)
        mod = const_get(:"GlobalMemoist#{object_id}")

        mod.class_eval do
          methods.each do |method|
            define_method(method) do |skip_cache = false|
              $__memo_methods ||= {}
              if $__memo_methods.include?(method) && !skip_cache
                $__memo_methods[method]
              else
                $__memo_methods[method] = super()
              end
            end
          end
        end
        prepend mod
      end

      def global_memoize_class_method(*methods)
        singleton_class.class_eval do
          include GlobalMemoist
          global_memoize(*methods)
        end
      end
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
jets-6.0.5 lib/jets/aws_services/global_memoist.rb
jets-6.0.4 lib/jets/aws_services/global_memoist.rb
jets-6.0.3 lib/jets/aws_services/global_memoist.rb
jets-6.0.2 lib/jets/aws_services/global_memoist.rb