Class: Momento::CacheClient

Inherits:
Object
  • Object
show all
Defined in:
lib/momento/cache_client.rb

Overview

A simple client for Momento.

CacheClient does not use exceptions to report errors. Instead it returns an error response. Please see README.

Examples:

credential_provider = Momento::CredentialProvider.from_env_var('MOMENTO_API_KEY')
config = Momento::Cache::Configurations::Laptop.latest
client = Momento::CacheClient.new(
  configuration: config,
  credential_provider: credential_provider,
  # cached items will be deleted after 100 seconds
  default_ttl: 100
)

response = client.create_cache("my_cache")
if response.success?
  puts "my_cache was created"
elsif response.already_exists?
  puts "my_cache already exists"
elsif response.error?
  raise response.error
end

# set will only return success or error,
# we only need to check for error
response = client.set("my_cache", "key", "value")
raise response.error if response.error?

response = client.get("my_cache", "key")
if response.hit?
  puts "We got #{response.value_string}"
elsif response.miss?
  puts "It's not in the cache"
elsif response.error?
  raise response.error
end

See Also:

Constant Summary collapse

VERSION =

This gem’s version.

Momento::VERSION

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(configuration:, credential_provider:, default_ttl:) ⇒ CacheClient

credentials required to connect to Momento

Parameters:

Raises:

  • (ArgumentError)

    if the default_ttl or credential_provider is invalid



64
65
66
67
68
69
70
71
72
73
# File 'lib/momento/cache_client.rb', line 64

def initialize(configuration:, credential_provider:, default_ttl:)
  @default_ttl = Momento::Ttl.to_ttl(default_ttl)
  @api_key = credential_provider.api_key
  @control_endpoint = credential_provider.control_endpoint
  @cache_endpoint = credential_provider.cache_endpoint
  @configuration = configuration
  @next_cache_stub_index = 0
  @num_cache_stubs = @configuration.transport_strategy.grpc_configuration.num_grpc_channels
  @is_first_request = true
end

Instance Attribute Details

#default_ttlNumeric

Returns how long items should remain in the cache, in seconds.

Returns:

  • (Numeric)

    how long items should remain in the cache, in seconds.



57
58
59
# File 'lib/momento/cache_client.rb', line 57

def default_ttl
  @default_ttl
end

Instance Method Details

#create_cache(cache_name) ⇒ Momento::CreateCacheResponse

Create a new Momento cache.

Examples:

response = client.create_cache("my_cache")
if response.success?
  puts "my_cache was created"
elsif response.already_exists?
  puts "my_cache already exists"
elsif response.error?
  raise response.error
end

Parameters:

  • cache_name (String)

    the name of the cache to create.

Returns:

Raises:

  • (TypeError)

    when the cache_name is not a String

See Also:



179
180
181
182
183
184
185
186
187
188
189
# File 'lib/momento/cache_client.rb', line 179

def create_cache(cache_name)
  builder = CreateCacheResponseBuilder.new(
    context: { cache_name: cache_name }
  )

  builder.from_block do
    control_stub.create_cache(
      MomentoProtos::ControlClient::PB__CreateCacheRequest.new(cache_name: validate_cache_name(cache_name))
    )
  end
end

#delete(cache_name, key) ⇒ Momento::DeleteResponse

Delete a key in a cache.

If the key does not exist, delete will still succeed.

Examples:

response = client.delete("my_cache", "key")
raise response.error if response.error?

Parameters:

  • cache_name (String)
  • key (String)

    must only contain ASCII characters

Returns:

Raises:

  • (TypeError)

    when the cache_name or key is not a String

See Also:



151
152
153
154
155
156
157
158
159
160
161
162
# File 'lib/momento/cache_client.rb', line 151

def delete(cache_name, key)
  builder = DeleteResponseBuilder.new(
    context: { cache_name: cache_name, key: key }
  )

  builder.from_block do
    cache_stub.delete(
      MomentoProtos::CacheClient::PB__DeleteRequest.new(cache_key: to_bytes(key)),
      metadata: (cache_name)
    )
  end
end

#delete_cache(cache_name) ⇒ Momento::DeleteCacheResponse

Delete an existing Momento cache.

Examples:

response = client.delete_cache("my_cache")
raise response.error if response.error?

Parameters:

  • cache_name (String)

    the name of the cache to delete.

Returns:

Raises:

  • (TypeError)

    when the cache_name is not a String

See Also:



201
202
203
204
205
206
207
208
209
210
211
# File 'lib/momento/cache_client.rb', line 201

def delete_cache(cache_name)
  builder = DeleteCacheResponseBuilder.new(
    context: { cache_name: cache_name }
  )

  builder.from_block do
    control_stub.delete_cache(
      MomentoProtos::ControlClient::PB__DeleteCacheRequest.new(cache_name: validate_cache_name(cache_name))
    )
  end
end

#get(cache_name, key) ⇒ Momento::GetResponse

Get a value in a cache.

The value can be retrieved as either bytes or a string.

Examples:

response = client.get("my_cache", "key")
if response.hit?
  puts "We got #{response.value_string}"
elsif response.miss?
  puts "It's not in the cache"
elsif response.error?
  raise response.error
end

Parameters:

  • cache_name (String)
  • key (String)

    must only contain ASCII characters

Returns:

Raises:

  • (TypeError)

    when the cache_name or key is not a String

See Also:



93
94
95
96
97
98
99
100
101
102
103
104
# File 'lib/momento/cache_client.rb', line 93

def get(cache_name, key)
  builder = GetResponseBuilder.new(
    context: { cache_name: cache_name, key: key }
  )

  builder.from_block do
    cache_stub.get(
      MomentoProtos::CacheClient::PB__GetRequest.new(cache_key: to_bytes(key)),
      metadata: (cache_name)
    )
  end
end

#list_cachesMomento::ListCachesResponse

Lists your caches.



217
218
219
220
221
222
223
224
225
226
# File 'lib/momento/cache_client.rb', line 217

def list_caches
  builder = ListCachesResponseBuilder.new(
    context: {}
  )
  builder.from_block do
    control_stub.list_caches(
      MomentoProtos::ControlClient::PB__ListCachesRequest.new
    )
  end
end

#set(cache_name, key, value, ttl: default_ttl) ⇒ Momento::SetResponse

Set a value in a cache.

If ttl is not set, it will use the default_ttl.

Examples:

response = client.set("my_cache", "key", "value")
raise response.error if response.error?

Parameters:

  • cache_name (String)
  • key (String)

    must only contain ASCII characters

  • value (String)

    the value to cache

  • ttl (Numeric) (defaults to: default_ttl)

    time-to-live, in seconds.

Returns:

Raises:

  • (ArgumentError)

    if the ttl is invalid

  • (TypeError)

    when the cache_name, key, or value is not a String

See Also:



121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
# File 'lib/momento/cache_client.rb', line 121

def set(cache_name, key, value, ttl: default_ttl)
  ttl = Momento::Ttl.to_ttl(ttl)

  builder = SetResponseBuilder.new(
    context: { cache_name: cache_name, key: key, value: value, ttl: ttl }
  )

  builder.from_block do
    req = MomentoProtos::CacheClient::PB__SetRequest.new(
      cache_key: to_bytes(key),
      cache_body: to_bytes(value),
      ttl_milliseconds: ttl.milliseconds
    )

    cache_stub.set(req, metadata: (cache_name))
  end
end

#sorted_set_fetch_by_score(cache_name, sorted_set_name, min_score: nil, max_score: nil, sort_order: SortOrder::ASCENDING, offset: 0, count: -1)) ⇒ Momento::SortedSetFetchResponse

Fetch the elements a sorted set by score.

Examples:

response = client.sorted_set_fetch_by_score("my_cache", "sorted_set", min_score: 0.0, max_score: 1.0)
raise response.error if response.error?

Parameters:

  • cache_name (String)
  • sorted_set_name (String)
  • min_score (Float) (defaults to: nil)

    The minimum score (inclusive) of the elements to fetch. Defaults to negative infinity.

  • max_score (Float) (defaults to: nil)

    The maximum score (inclusive) of the elements to fetch. Defaults to positive infinity.

  • sort_order (SortOrder) (defaults to: SortOrder::ASCENDING)

    The order to fetch the elements in. Defaults to ascending.

  • offset (Integer) (defaults to: 0)

    The number of elements to skip before returning the first element. Defaults to 0.

  • count (Integer) (defaults to: -1))

    The maximum number of elements to return. Defaults to all elements.

Returns:

Raises:

  • (TypeError)

    when the cache_name, or sorted_set_name is not a String.

See Also:



319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
# File 'lib/momento/cache_client.rb', line 319

def sorted_set_fetch_by_score(cache_name, sorted_set_name, min_score: nil, max_score: nil,
                              sort_order: SortOrder::ASCENDING, offset: 0, count: -1)
  builder = SortedSetFetchResponseBuilder.new(
    context: { cache_name: cache_name, set_name: sorted_set_name, min_score: min_score, max_score: max_score,
               sort_order: sort_order, offset: offset, count: count }
  )

  builder.from_block do
    by_score = build_sorted_set_by_score(min_score, max_score, offset, count)

    req = MomentoProtos::CacheClient::PB__SortedSetFetchRequest.new(
      set_name: to_bytes(sorted_set_name),
      order: to_grpc_order(sort_order),
      with_scores: true,
      by_score: by_score
    )

    # noinspection RubyResolve
    cache_stub.sorted_set_fetch(req, metadata: (cache_name))
  end
end

#sorted_set_put_element(cache_name, sorted_set_name, value, score, collection_ttl: CollectionTtl.from_cache_ttl) ⇒ Momento::SortedSetPutElementResponse

Put an element in a sorted set

If collection_ttl is not set, it will use the default_ttl.

Examples:

response = client.sorted_set_put_element('my_cache', 'my_set', 'value', 1.0)
raise response.error if response.error?

Parameters:

  • cache_name (String)
  • sorted_set_name (String)
  • value (String)

    the value to add to the sorted set.

  • score (Float)

    the score of the value. Determines its place in the set.

  • collection_ttl (Momento::CollectionTtl) (defaults to: CollectionTtl.from_cache_ttl)

    time-to-live, in seconds.

Returns:

Raises:

  • (ArgumentError)

    if the ttl is invalid

  • (TypeError)

    when the cache_name, sorted_set_name, or value is not a String

See Also:



244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
# File 'lib/momento/cache_client.rb', line 244

def sorted_set_put_element(cache_name, sorted_set_name, value, score, collection_ttl: CollectionTtl.from_cache_ttl)
  collection_ttl = collection_ttl.with_ttl_if_absent(default_ttl.seconds)
  builder = SortedSetPutElementResponseBuilder.new(
    context: { cache_name: cache_name, set_name: sorted_set_name, value: value, score: score,
               collection_ttl: collection_ttl }
  )

  builder.from_block do
    req = MomentoProtos::CacheClient::PB__SortedSetPutRequest.new(
      set_name: to_bytes(sorted_set_name),
      elements: [{ value: to_bytes(value), score: score }],
      ttl_milliseconds: collection_ttl.ttl_milliseconds,
      refresh_ttl: collection_ttl.refresh_ttl
    )

    # noinspection RubyResolve
    cache_stub.sorted_set_put(req, metadata: (cache_name))
  end
end

#sorted_set_put_elements(cache_name, sorted_set_name, elements, collection_ttl = CollectionTtl.from_cache_ttl) ⇒ Momento::SortedSetPutElementsResponse

Put multiple elements in a sorted set

If collection_ttl is not set, it will use the default_ttl. an array of arrays [[“value”, 1.0]], or an array of hashes of value and score [“value”, score: 1.0]. an Array or Hash

Examples:

response = client.sorted_set_put_element('my_cache', 'my_set', [['value', 1.0]])
raise response.error if response.error?

Parameters:

  • cache_name (String)
  • sorted_set_name (String)
  • elements (Hash, Array)

    the elements to add. Must be a hash of String values to Float scores,

  • collection_ttl (Integer) (defaults to: CollectionTtl.from_cache_ttl)

    time-to-live, in seconds.

Returns:

Raises:

  • (ArgumentError)

    if the ttl is invalid

  • (TypeError)

    when the cache_name, or sorted_set_name is not a String, or if elements is not

See Also:



281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
# File 'lib/momento/cache_client.rb', line 281

def sorted_set_put_elements(cache_name, sorted_set_name, elements, collection_ttl = CollectionTtl.from_cache_ttl)
  collection_ttl = collection_ttl.with_ttl_if_absent(default_ttl.seconds)
  builder = SortedSetPutElementsResponseBuilder.new(
    context: { cache_name: cache_name, set_name: sorted_set_name, elements: elements,
               collection_ttl: collection_ttl }
  )

  builder.from_block do
    req = MomentoProtos::CacheClient::PB__SortedSetPutRequest.new(
      set_name: to_bytes(sorted_set_name),
      elements: to_sorted_set_elements(elements),
      ttl_milliseconds: collection_ttl.ttl_milliseconds,
      refresh_ttl: collection_ttl.refresh_ttl
    )

    # noinspection RubyResolve
    cache_stub.sorted_set_put(req, metadata: (cache_name))
  end
end