Class: Parse::Authorization::MemoryCache

Inherits:
Object
  • Object
show all
Defined in:
lib/parse/authorization.rb

Overview

Default cache: a process-local hash with per-entry TTL, guarded by a Mutex. Fine for a single process. Multi-process deployments (Puma workers, Sidekiq processes) get one of these per process and should install a shared plane instead, which is what Parse::Cache::Redis#scoped(...).identity / .roles return.

Instance Method Summary collapse

Constructor Details

#initialize ⇒ MemoryCache

Returns a new instance of MemoryCache.



65
66
67
68
# File 'lib/parse/authorization.rb', line 65

def initialize
  @data = {}
  @mutex = Mutex.new
end

Instance Method Details

#clear ⇒ Object

Drop every entry.



114
115
116
# File 'lib/parse/authorization.rb', line 114

def clear
  @mutex.synchronize { @data.clear }
end

#get(key) ⇒ Object?

Returns the cached value, or nil when the key is missing or its TTL has elapsed. Expired entries are evicted lazily on read.

Parameters:

Returns:

  • (Object, nil) —

    the cached value, or nil when the key is missing or its TTL has elapsed. Expired entries are evicted lazily on read.



74
75
76
77
78
79
80
81
82
83
84
# File 'lib/parse/authorization.rb', line 74

def get(key)
  @mutex.synchronize do
    entry = @data[key]
    return nil if entry.nil?
    if entry[:expires_at] < Time.now
      @data.delete(key)
      return nil
    end
    entry[:value]
  end
end

#invalidate(key) ⇒ Object

Parameters:

  • key (String) —

    cache key to forget.



96
97
98
# File 'lib/parse/authorization.rb', line 96

def invalidate(key)
  @mutex.synchronize { @data.delete(key) }
end

#invalidate_value(value) ⇒ Integer

Drop every entry whose value equals value. Lets the identity plane forget every token of one user after a revocation, since it is keyed by token and holds the user id as the value.

Parameters:

Returns:

  • (Integer) —

    number of entries removed.



105
106
107
108
109
110
111
# File 'lib/parse/authorization.rb', line 105

def invalidate_value(value)
  @mutex.synchronize do
    before = @data.size
    @data.delete_if { |_key, entry| entry[:value] == value }
    before - @data.size
  end
end

#set(key, value, ttl:) ⇒ Object

Parameters:

  • key (String)
  • value (Object)
  • ttl (Numeric) —

    seconds until the entry expires.



89
90
91
92
93
# File 'lib/parse/authorization.rb', line 89

def set(key, value, ttl:)
  @mutex.synchronize do
    @data[key] = { value: value, expires_at: Time.now + ttl }
  end
end