Skip to content

Commit

Permalink
minor refactor for readability and bypass when no content hash is sent
Browse files Browse the repository at this point in the history
  • Loading branch information
DGaffney committed Jun 18, 2024
1 parent a6dc857 commit bb6080e
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 12 deletions.
13 changes: 7 additions & 6 deletions lib/cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,12 +29,13 @@ def get_cached_result(content_hash: str, reset_ttl: bool = True, ttl: int = DEFA
Returns:
Optional[Any]: The cached result, or None if the key does not exist.
"""
client = Cache.get_client()
cached_result = client.get(content_hash)
if cached_result is not None:
if reset_ttl:
client.expire(content_hash, ttl)
return json.loads(cached_result)
if content_hash:
client = Cache.get_client()
cached_result = client.get(content_hash)
if cached_result is not None:
if reset_ttl:
client.expire(content_hash, ttl)
return json.loads(cached_result)
return None

@staticmethod
Expand Down
17 changes: 11 additions & 6 deletions lib/model/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,19 +40,24 @@ def get_tempfile(self) -> Any:
def process(self, messages: Union[List[schemas.Message], schemas.Message]) -> List[schemas.Message]:
return []

def get_response(self, message: schemas.Message) -> schemas.GenericItem:
"""
Perform a lookup on the cache for a message, and if found, return that cached value.
"""
result = Cache.get_cached_result(message.body.content_hash)
if not result:
result = self.process(message)
Cache.set_cached_result(message.body.content_hash, message.body.result)
return result

def respond(self, messages: Union[List[schemas.Message], schemas.Message]) -> List[schemas.Message]:
"""
Force messages as list of messages in case we get a singular item. Then, run fingerprint routine.
"""
if not isinstance(messages, list):
messages = [messages]
for message in messages:
existing = Cache.get_cached_result(message.body.content_hash)
if existing:
message.body.result = existing
else:
message.body.result = self.process(message)
Cache.set_cached_result(message.body.content_hash, message.body.result)
message.body.result = self.get_response(message)
return messages

@classmethod
Expand Down

0 comments on commit bb6080e

Please sign in to comment.