Skip to content

Hyku API: Caching

Paul Danelli edited this page Mar 18, 2022 · 2 revisions

Caching can be enabled or disabled per tenant with the FlipFlop feature cache_api. Every time we switch into a tenant account, if the tenant has enabled caching, we tell ActionController to enable it and use the tenants Redis endpoint as the cache store. If it is not enabled, we tell Rails to use the Filesystem in case it needs to store something. ​ All this happens in HykuAddons::AccountBehavior.switch!. The method calls setup_tenant_cache which does all the configuration previously mentioned. Once the cache is set, we need to add cache tags to all of the views we want to be cached. The trickiest part of Rails caching is generating keys which are unique enough and will be invalidated when any of the data, that we need to represent, changes. ​ Let's take a look at how the API uses the cache to render work metadata: ​

# app/views/hyku/api/v1/work/_work.json.jbuilder
json.cache! [@account, :works, work.id, work.solr_document[:_version_], work.member_of_collection_ids & collection_docs.pluck('id')] do
  json.uuid work.id
  json.abstract work.try(:solr_document)&.dig('abstract_tesim')&.first
  # ...
end

​ The cache key is generated based on the params sent to json.cache!, and in this case, it would be something like: "account-1-works-123abc-10-xyz456" ​ First, we want the cache entry to be specific to this account and work (that's why we add the account and work ids in the cache key). We also want the Solr document version to be part of the cache keys in order to detect changes in the work metadata ,which trigger a reindex of the documents and therefore a new Solr document version. ​ Finally, we use the last cache key to check what collections of the work this user has permissions to browse, because the user can get his permissions changed and the work metadata remain as it is.

Clearing the Cache

From time to time you will need to clear the cache manually on the server. To do this, you must first access Bash on the correct cluster.

You can then run the following to clear the cache - please note, this will have an affect on the speed of the cluster.

bundle exec rails hyku:cache:expire