"""Offline Android capstone verifier for Ch 153: DrySister Part 3 (2-Level LruCache + DiskLruCache)."""
from collections import OrderedDict
import hashlib
import json
from pathlib import Path
import tempfile
VERSION = (
"CPython 3.12.14 offline Android system-service/sensor/capstone verifier "
"(Android SDK/emulator absent)"
)
class MemoryLruCache:
"""Byte-bounded strong-reference LruCache mirroring android.util.LruCache."""
def __init__(self, max_bytes: int) -> None:
self.max_bytes = max_bytes
self._store: OrderedDict[str, bytes] = OrderedDict()
self.current_bytes = 0
self.evictions: list[str] = []
def get(self, key: str) -> bytes | None:
val = self._store.get(key)
if val is not None:
self._store.move_to_end(key)
return val
def put(self, key: str, value: bytes) -> None:
if key in self._store:
self.current_bytes -= len(self._store.pop(key))
self._store[key] = value
self.current_bytes += len(value)
while self.current_bytes > self.max_bytes and self._store:
old_k, old_v = self._store.popitem(last=False)
self.current_bytes -= len(old_v)
self.evictions.append(old_k)
class DiskLruCacheDir:
"""Real filesystem DiskLruCache keyed by SHA-256 hex digest in a temporary directory."""
def __init__(self, cache_dir: Path, max_bytes: int) -> None:
self.cache_dir = cache_dir
self.max_bytes = max_bytes
self._order: OrderedDict[str, int] = OrderedDict()
self.current_bytes = 0
@staticmethod
def hash_key(url: str) -> str:
return hashlib.sha256(url.encode("utf-8")).hexdigest()
def put(self, url: str, data: bytes) -> str:
key = self.hash_key(url)
path = self.cache_dir / f"{key}.cache"
path.write_bytes(data)
if key in self._order:
self.current_bytes -= self._order.pop(key)
self._order[key] = len(data)
self.current_bytes += len(data)
while self.current_bytes > self.max_bytes and self._order:
old_k, old_sz = self._order.popitem(last=False)
self.current_bytes -= old_sz
(self.cache_dir / f"{old_k}.cache").unlink(missing_ok=True)
return key
def get(self, url: str) -> bytes | None:
key = self.hash_key(url)
path = self.cache_dir / f"{key}.cache"
if key in self._order and path.exists():
self._order.move_to_end(key)
return path.read_bytes()
return None
def calculate_in_sample_size(raw_w: int, raw_h: int, req_w: int, req_h: int) -> int:
"""Android official power-of-2 BitmapFactory.Options.inSampleSize algorithm."""
in_sample_size = 1
if raw_h > req_h or raw_w > req_w:
half_h = raw_h // 2
half_w = raw_w // 2
while (half_h // in_sample_size) >= req_h and (half_w // in_sample_size) >= req_w:
in_sample_size *= 2
return in_sample_size
def main() -> None:
# Case 1: Memory LruCache LRU ordering & eviction vs legacy SoftReference note
mem = MemoryLruCache(max_bytes=100)
mem.put("u1", b"a" * 40)
mem.put("u2", b"b" * 40)
assert mem.get("u1") is not None # promotes u1 so u2 becomes LRU
mem.put("u3", b"c" * 40) # total 120 > 100 -> evicts u2!
c1_actual = {
"evicted_keys": mem.evictions,
"remaining_keys": list(mem._store.keys()),
"current_bytes": mem.current_bytes,
"in_sample_size_1600x1200_to_400x400": calculate_in_sample_size(1600, 1200, 400, 400),
"in_sample_size_3200x2400_to_400x400": calculate_in_sample_size(3200, 2400, 400, 400),
}
c1_expected = {
"evicted_keys": ["u2"],
"remaining_keys": ["u1", "u3"],
"current_bytes": 80,
"in_sample_size_1600x1200_to_400x400": 2,
"in_sample_size_3200x2400_to_400x400": 4,
}
# Case 2: Full 2-level SisterLoader (L1 Memory -> L2 Temp-Dir DiskLruCache w/ SHA-256 -> Network)
network_fetches = []
origin_payloads = {
"https://example.invalid/sister_1.jpg": b"IMG1" * 15, # 60 bytes
"https://example.invalid/sister_2.jpg": b"IMG2" * 15, # 60 bytes
}
with tempfile.TemporaryDirectory() as tmp:
l1 = MemoryLruCache(max_bytes=80)
l2 = DiskLruCacheDir(Path(tmp), max_bytes=200)
def bind_bitmap(url: str, online: bool = True) -> tuple[str, int]:
key = l2.hash_key(url)
hit = l1.get(key)
if hit is not None:
return ("memory_l1", len(hit))
hit = l2.get(url)
if hit is not None:
l1.put(key, hit)
return ("disk_l2", len(hit))
if not online:
return ("miss_offline", 0)
network_fetches.append(url)
data = origin_payloads[url]
l2.put(url, data)
l1.put(key, data)
return ("network", len(data))
s1_first = bind_bitmap("https://example.invalid/sister_1.jpg", online=True)
s1_mem = bind_bitmap("https://example.invalid/sister_1.jpg", online=False)
# Load sister_2 (60B) -> evicts sister_1 from 80B L1 memory, but sister_1 stays on L2 disk!
s2_net = bind_bitmap("https://example.invalid/sister_2.jpg", online=True)
# Offline reload of sister_1 must hit L2 disk and repopulate L1!
s1_disk_offline = bind_bitmap("https://example.invalid/sister_1.jpg", online=False)
disk_files = sorted(p.name for p in Path(tmp).glob("*.cache"))
c2_actual = {
"steps": [s1_first, s1_mem, s2_net, s1_disk_offline],
"network_fetch_count": len(network_fetches),
"disk_cache_file_count": len(disk_files),
"sha256_key_len": len(DiskLruCacheDir.hash_key("https://example.invalid/sister_1.jpg")),
}
c2_expected = {
"steps": [
("network", 60),
("memory_l1", 60),
("network", 60),
("disk_l2", 60),
],
"network_fetch_count": 2,
"disk_cache_file_count": 2,
"sha256_key_len": 64,
}
cases = [
{
"name": "memory_lrucache_eviction_and_insamplesize",
"summary": "验证强引用 LruCache 的最近最少使用淘汰顺序与 Bitmap 2 的幂次采样率计算",
"expected": c1_expected,
"actual": c1_actual,
"passed": c1_actual == c1_expected,
},
{
"name": "two_level_memory_disk_sha256_cache",
"summary": "在真实临时目录中验证 SisterLoader 二级缓存(L1 内存 -> L2 SHA-256 磁盘 -> 网络)及断网回源命中",
"expected": c2_expected,
"actual": c2_actual,
"passed": c2_actual == c2_expected,
},
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
入口文件:projects/android-tutorial-exercise-3-lab/explore-tutorial-exercise-3.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-tutorial-exercise-3.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联156章) · 含当前章节或实例 · mbskycom202612a1829.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1881.zip