From b66ce61aea2da05727afd0264077afaf3cef2f76 Mon Sep 17 00:00:00 2001 From: William B <7444334+whabanks@users.noreply.github.com> Date: Mon, 22 Jul 2024 15:08:08 -0400 Subject: [PATCH] Update service template cache keys when a template category is updated (#1899) * Update service template cache keys when a template category is updated * Rever unneeded changes --- app/notify_client/cache.py | 40 +++++++++++++++++++++++++ app/notify_client/service_api_client.py | 2 +- 2 files changed, 41 insertions(+), 1 deletion(-) diff --git a/app/notify_client/cache.py b/app/notify_client/cache.py index 2243ca0c0a..e9095ab0ee 100644 --- a/app/notify_client/cache.py +++ b/app/notify_client/cache.py @@ -32,6 +32,46 @@ def _make_key(key_format, client_method, args, kwargs): ) +def set_service_template(key_format): + def _set(client_method): + @wraps(client_method) + def new_client_method(client_instance, *args, **kwargs): + """ + This decorator is functionaly the same as the `set` decorator. The only difference is that it checks if the + category of the service template is dirty and updates it if it is. When a category is updated via the admin + UI, the category is updated in the cache. However, the service template is not updated in the cache. This + decorator checks the category on the template against the cached category and updates the template if it is + dirty + """ + redis_key = _make_key(key_format, client_method, args, kwargs) + cached_template = redis_client.get(redis_key) + + if cached_template: + template_category = json.loads(cached_template.decode("utf-8")).get("template_category") + cached_category = redis_client.get(f"template_category-{template_category['id']}") if template_category else None + + if cached_category: + category = json.loads(cached_category.decode("utf-8")) + + if not category == template_category: + redis_client.set(redis_key, json.dumps(cached_category), ex=TTL) + + return json.loads(cached_template.decode("utf-8")) + + api_response = client_method(client_instance, *args, **kwargs) + + redis_client.set( + redis_key, + json.dumps(api_response), + ex=TTL, + ) + return api_response + + return new_client_method + + return _set + + def set(key_format): def _set(client_method): @wraps(client_method) diff --git a/app/notify_client/service_api_client.py b/app/notify_client/service_api_client.py index 1bbc491edd..94f130d823 100644 --- a/app/notify_client/service_api_client.py +++ b/app/notify_client/service_api_client.py @@ -268,7 +268,7 @@ def update_service_template_postage(self, service_id, template_id, postage): _attach_current_user({"postage": postage}), ) - @cache.set("template-{template_id}-version-{version}") + @cache.set_service_template("template-{template_id}-version-{version}") def get_service_template(self, service_id, template_id, version=None): """ Retrieve a service template.