Media metadata cache
Cedar Media's playback team needs a bounded metadata cache. Supplied commands represent clip metadata reads and writes. Deliver a replayable function that supports replacement, eviction, read recency, deletion and reset, including capacity zero.
Cedar Media repeatedly loads metadata for recently viewed clips. Its cache needs predictable behavior when a clip is read again, overwritten, deleted or invalidated after an import. You build that behavior in six small steps.
The function boundary stays the same throughout the project. Each step starts with the previous implementation and adds a policy that changes an observable result. Keep the command parser separate from cache decisions so a new operation doesn't disturb existing reads. OrderedDict makes the order explicit without scanning every entry. Successful reads and replacement writes both refresh recency, so eviction removes the least recently used key. A miss returns null; a cached zero remains a value.
import json
def process_payload(payload: str) -> str:
data = json.loads(payload)
from collections import OrderedDict
cache, reads = OrderedDict(), []
for command in data['commands']:
parts = command.split(':')
op = parts[0]
if op == 'put':
key, value = parts[1], int(parts[2])
if key not in cache:
cache[key] = value
elif op == 'get':
key = parts[1]
reads.append(cache.get(key))
return json.dumps(reads,separators=(',',':'))
Every get produces one result; zero is a cached value and missing keys return null. Keep an OrderedDict so storage order records recency. Parse commands separately from policy updates. Dictionary reads and OrderedDict recency updates have average constant cost per command.