Class: Parse::Middleware::Caching

Inherits:
Faraday::Middleware
  • Object
show all
Includes:
Protocol
Defined in:
lib/parse/client/caching.rb

Overview

This is a caching middleware for Parse queries using Moneta. The caching middleware will cache all GET requests made to the Parse REST API as long as the API responds with a successful non-empty result payload.

Whenever an object is created or updated, the corresponding entry in the cache when fetching the particular record (using the specific non-Query based API) will be cleared.

Constant Summary collapse

CACHEABLE_HTTP_CODES =

List of status codes that can be cached:

  • 200 - 'OK'
  • 203 - 'Non-Authoritative Information'
  • 300 - 'Multiple Choices'
  • 301 - 'Moved Permanently'
  • 302 - 'Found'
  • 404 - 'Not Found' - removed
  • 410 - 'Gone' - removed
[200, 203, 300, 301, 302].freeze
CACHE_CONTROL =

Cache control header

"Cache-Control"
CONTENT_LENGTH_KEY =

Request env key for the content length

"content-length"
CACHE_RESPONSE_HEADER =

Header in response that is sent if this is a cached result

"X-Cache-Response"
CACHE_EXPIRES_DURATION =

Header in request to set caching information for the middleware.

"X-Parse-Stack-Cache-Expires"
CACHE_WRITE_ONLY =

Header in request to enable write-only cache mode (skip read, still write)

"X-Parse-Stack-Cache-Write-Only"
UNCACHEABLE_PATH_RE =

Paths whose responses are never cached. users/me and sessions/me answer "who owns this token", so a cached copy keeps a logged-out or revoked token resolving to its user until the entry expires. The credential endpoints carry a password and must never be stored.

%r{/(?:users/me|sessions/me|login|verifyPassword|logout)/?\z}.freeze
LEGACY_VERSION_PREFIX =

Prefix of the per-resource version keys. See #version_keys.

"rv"
CLASS_VERSION_PREFIX =

Prefix of the per-class version keys folded into collection reads (queries, aggregates). See #version_keys.

"cv"
METHOD_OVERRIDE =

Request header BodyBuilder sets when it re-sends a long GET as a POST.

"X-Http-Method-Override"
CLASS_PATH_RE =

Paths that name a Parse class, optionally followed by an object id.

%r{(?:\A|/)(?:classes|aggregate|purge|schemas)/([^/]+)(?:/([^/]+))?/?\z}.freeze
SYSTEM_CLASS_PATH_RE =

Built-in class endpoints, optionally followed by an object id.

%r{(?:\A|/)(users|roles|installations|sessions)(?:/([^/]+))?/?\z}.freeze
SYSTEM_CLASSES =

Class names for the built-in class endpoints.

{
  "users" => "_User", "roles" => "_Role",
  "installations" => "_Installation", "sessions" => "_Session",
}.freeze
BATCH_PATH_RE =

Path of the batch endpoint, whose body names the resources it writes.

%r{(?:\A|/)batch/?\z}.freeze

Constants included from Protocol

Protocol::API_KEY, Protocol::APP_ID, Protocol::CLOUD_CONTEXT, Protocol::CONTENT_TYPE, Protocol::CONTENT_TYPE_FORMAT, Protocol::EMAIL, Protocol::INSTALLATION_ID, Protocol::MASTER_KEY, Protocol::PASSWORD, Protocol::READ_PREFERENCE, Protocol::READ_PREFERENCES, Protocol::REVOCABLE_SESSION, Protocol::SERVER_URL, Protocol::SESSION_TOKEN

Class Attribute Summary collapse

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(adapter, store, opts = {}) ⇒ Caching

Creates a new caching middleware.

Parameters:

  • adapter (Faraday::Adapter) —

    An instance of the Faraday adapter used for the connection. Defaults Faraday::Adapter::NetHttp.

  • store (Moneta) —

    An instance of the Moneta cache store to use.

  • opts (Hash) (defaults to: {}) —

    additional options.

Options Hash (opts):

  • :expires (Integer) —

    the default expiration for a cache entry.

Raises:

  • ArgumentError, if store is not a Moneta::Transformer or Moneta::Expires instance.



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
# File 'lib/parse/client/caching.rb', line 129

def initialize(adapter, store, opts = {})
  super(adapter)
  @store = store
  @opts = { expires: 0 }
  @opts.merge!(opts) if opts.is_a?(Hash)
  @expires = @opts[:expires]
  # Per-middleware override of {.cache_session_requests}; nil defers to
  # the class-level default.
  @cache_session_requests =
    @opts.key?(:cache_session_requests) ? (@opts[:cache_session_requests] == true) : nil
  # Optional cache key namespace so two Parse apps sharing one Redis don't
  # collide (e.g. `mk:/classes/Song/abc` is the same path for both apps).
  # When set, keys become `<namespace>:<existing-prefix>:<url>`. Empty
  # string is treated as nil. Trailing `:` is stripped once so users can
  # pass either `"app_x"` or `"app_x:"`.
  ns = @opts[:namespace].to_s
  ns = ns.chomp(":")
  @namespace = ns.empty? ? nil : ns

  # The keyspace owns physical key layout and the patterns that clear it,
  # so key generation and eviction cannot drift apart. Previously this
  # middleware composed keys from its own `@namespace` while
  # `Parse::Cache::Redis` held a separate one, and `clear_cache!` used
  # only the latter: a client namespaced here but not there would clear
  # every SDK key on the database instead of its own.
  #
  # When no keyspace is supplied the middleware keeps writing legacy
  # un-prefixed keys, so an upgrade that does not opt in behaves exactly
  # as before.
  @keyspace = @opts[:keyspace]
  # During the transition, also delete the pre-keyspace form of a key on
  # invalidation. Without this, a rolling deploy has new workers writing
  # keyspaced keys while old workers still read legacy ones, so a write
  # served by a new worker never invalidates what an old worker serves.
  @delete_legacy_variants = @opts.fetch(:delete_legacy_variants, true)

  unless [:key?, :[], :delete, :store].all? { |method| @store.respond_to?(method) }
    raise ArgumentError, "Caching store object must a Moneta key/value store."
  end
end

Class Attribute Details

.cache_session_requests ⇒ Boolean

Whether reads made with a session token are cached. Off by default.

A cached session read is answered without contacting Parse Server, so it cannot notice that the session was revoked (logout, Session#destroy, logout_all!, a password change) or that the user lost a role or row access through a change the SDK did not make. With this off, every session read reaches Parse Server, which checks the token and the current ACLs and CLPs each time. Master-key and anonymous reads are cached as before. Turning this on trades that guarantee for speed: a revoked or narrowed session keeps reading its cached responses until they expire.

Only true enables it; any other value (including the String "true" read from an environment variable) leaves session reads uncached. A client can override this default with Parse.setup(cache_session_requests: true) (the middleware option of the same name).

Returns:

  • (Boolean)


95
# File 'lib/parse/client/caching.rb', line 95

attr_writer :cache_session_requests

.enabled ⇒ Boolean

Returns whether the caching middleware should be enabled.

Returns:

  • (Boolean) —

    whether the caching middleware should be enabled.



70
# File 'lib/parse/client/caching.rb', line 70

attr_writer :enabled

.logging ⇒ Boolean

Returns whether the logging should be enabled.

Returns:

  • (Boolean) —

    whether the logging should be enabled.



74
75
76
# File 'lib/parse/client/caching.rb', line 74

def logging
  @logging
end

Instance Attribute Details

#expires ⇒ Integer

The expiration time in seconds for this particular request.

Returns:

  • (Integer)


120
121
122
# File 'lib/parse/client/caching.rb', line 120

def expires
  @expires
end

#store ⇒ Moneta::Transformer, Moneta::Expires

The internal moneta cache store instance.

Returns:

  • (Moneta::Transformer, Moneta::Expires)


115
116
117
# File 'lib/parse/client/caching.rb', line 115

def store
  @store
end

Class Method Details

.caching? ⇒ Boolean

Returns whether caching is enabled.

Returns:

  • (Boolean) —

    whether caching is enabled.



107
108
109
# File 'lib/parse/client/caching.rb', line 107

def caching?
  @enabled
end