[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M731WAB2N2ATVQA9CNHZR89C":3,"skill-same:01M731WAB2N2ATVQA9CNHZR89C":48},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":25,"commitSha":26,"skillDirectory":27,"forksCount":28,"repositoryHtmlUrl":29,"repositoryHomepageUrl":6,"ownerHtmlUrl":30,"ownerBlogUrl":31,"ownerDescription":32,"updatedAt":33,"install":34,"resources":47},"01M731WAB2N2ATVQA9CNHZR89C","content-hash-cache-pattern",null,"使用SHA-256内容哈希缓存昂贵的文件处理结果——路径无关、自动失效、服务层分离。","SriramGandhiS\u002FSkills","SriramGandhiS","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F211849986?v=4","01M72WQCW12BYX71C6WN584TTA","Sriram S","01M72WQCWTJ2RD0ET1X31AF1RC",1,"MIT","https:\u002F\u002Fgithub.com\u002FSriramGandhiS\u002FSkills\u002Fblob\u002Fmaster\u002Fweb-assets\u002Fdocs\u002Fzh-CN\u002Fskills\u002Fcontent-hash-cache-pattern\u002FSKILL.md",[],[],"2026-11-11 15:11:14",false,"---\nname: content-hash-cache-pattern\ndescription: 使用SHA-256内容哈希缓存昂贵的文件处理结果——路径无关、自动失效、服务层分离。\norigin: ECC\n---\n\n# 内容哈希文件缓存模式\n\n使用 SHA-256 内容哈希作为缓存键，缓存昂贵的文件处理结果（PDF 解析、文本提取、图像分析）。与基于路径的缓存不同，此方法在文件移动\u002F重命名后仍然有效，并在内容更改时自动失效。\n\n## 何时激活\n\n* 构建文件处理管道时（PDF、图像、文本提取）\n* 处理成本高且同一文件被重复处理时\n* 需要一个 `--cache\u002F--no-cache` CLI 选项时\n* 希望在不修改现有纯函数的情况下为其添加缓存时\n\n## 核心模式\n\n### 1. 基于内容哈希的缓存键\n\n使用文件内容（而非路径）作为缓存键：\n\n```python\nimport hashlib\nfrom pathlib import Path\n\n_HASH_CHUNK_SIZE = 65536  # 64KB chunks for large files\n\ndef compute_file_hash(path: Path) -> str:\n    \"\"\"SHA-256 of file contents (chunked for large files).\"\"\"\n    if not path.is_file():\n        raise FileNotFoundError(f\"File not found: {path}\")\n    sha256 = hashlib.sha256()\n    with open(path, \"rb\") as f:\n        while True:\n            chunk = f.read(_HASH_CHUNK_SIZE)\n            if not chunk:\n                break\n            sha256.update(chunk)\n    return sha256.hexdigest()\n```\n\n**为什么使用内容哈希？** 文件重命名\u002F移动 = 缓存命中。内容更改 = 自动失效。无需索引文件。\n\n### 2. 用于缓存条目的冻结数据类\n\n```python\nfrom dataclasses import dataclass\n\n@dataclass(frozen=True, slots=True)\nclass CacheEntry:\n    file_hash: str\n    source_path: str\n    document: ExtractedDocument  # The cached result\n```\n\n### 3. 基于文件的缓存存储\n\n每个缓存条目都存储为 `{hash}.json` —— 通过哈希实现 O(1) 查找，无需索引文件。\n\n```python\nimport json\nfrom typing import Any\n\ndef write_cache(cache_dir: Path, entry: CacheEntry) -> None:\n    cache_dir.mkdir(parents=True, exist_ok=True)\n    cache_file = cache_dir \u002F f\"{entry.file_hash}.json\"\n    data = serialize_entry(entry)\n    cache_file.write_text(json.dumps(data, ensure_ascii=False), encoding=\"utf-8\")\n\ndef read_cache(cache_dir: Path, file_hash: str) -> CacheEntry | None:\n    cache_file = cache_dir \u002F f\"{file_hash}.json\"\n    if not cache_file.is_file():\n        return None\n    try:\n        raw = cache_file.read_text(encoding=\"utf-8\")\n        data = json.loads(raw)\n        return deserialize_entry(data)\n    except (json.JSONDecodeError, ValueError, KeyError):\n        return None  # Treat corruption as cache miss\n```\n\n### 4. 服务层包装器（单一职责原则）\n\n保持处理函数的纯净性。将缓存作为一个单独的服务层添加。\n\n```python\ndef extract_with_cache(\n    file_path: Path,\n    *,\n    cache_enabled: bool = True,\n    cache_dir: Path = Path(\".cache\"),\n) -> ExtractedDocument:\n    \"\"\"Service layer: cache check -> extraction -> cache write.\"\"\"\n    if not cache_enabled:\n        return extract_text(file_path)  # Pure function, no cache knowledge\n\n    file_hash = compute_file_hash(file_path)\n\n    # Check cache\n    cached = read_cache(cache_dir, file_hash)\n    if cached is not None:\n        logger.info(\"Cache hit: %s (hash=%s)\", file_path.name, file_hash[:12])\n        return cached.document\n\n    # Cache miss -> extract -> store\n    logger.info(\"Cache miss: %s (hash=%s)\", file_path.name, file_hash[:12])\n    doc = extract_text(file_path)\n    entry = CacheEntry(file_hash=file_hash, source_path=str(file_path), document=doc)\n    write_cache(cache_dir, entry)\n    return doc\n```\n\n## 关键设计决策\n\n| 决策 | 理由 |\n|----------|-----------|\n| SHA-256 内容哈希 | 与路径无关，内容更改时自动失效 |\n| `{hash}.json` 文件命名 | O(1) 查找，无需索引文件 |\n| 服务层包装器 | 单一职责原则：提取功能保持纯净，缓存是独立的关注点 |\n| 手动 JSON 序列化 | 完全控制冻结数据类的序列化 |\n| 损坏时返回 `None` | 优雅降级，在下次运行时重新处理 |\n| `cache_dir.mkdir(parents=True)` | 在首次写入时惰性创建目录 |\n\n## 最佳实践\n\n* **哈希内容，而非路径** —— 路径会变，内容标识不变\n* 对大文件进行哈希时**分块处理** —— 避免将整个文件加载到内存中\n* **保持处理函数的纯净性** —— 它们不应了解任何关于缓存的信息\n* **记录缓存命中\u002F未命中**，并使用截断的哈希值以便调试\n* **优雅地处理损坏** —— 将无效的缓存条目视为未命中，永不崩溃\n\n## 应避免的反模式\n\n```python\n## BAD: Path-based caching (breaks on file move\u002Frename)\ncache = {\"\u002Fpath\u002Fto\u002Ffile.pdf\": result}\n\n## BAD: Adding cache logic inside the processing function (SRP violation)\ndef extract_text(path, *, cache_enabled=False, cache_dir=None):\n    if cache_enabled:  # Now this function has two responsibilities\n        ...\n\n## BAD: Using dataclasses.asdict() with nested frozen dataclasses\n## (can cause issues with complex nested types)\ndata = dataclasses.asdict(entry)  # Use manual serialization instead\n```\n\n## 适用场景\n\n* 文件处理管道（PDF 解析、OCR、文本提取、图像分析）\n* 受益于 `--cache\u002F--no-cache` 选项的 CLI 工具\n* 跨多次运行出现相同文件的批处理\n* 在不修改现有纯函数的情况下为其添加缓存\n\n## 不适用场景\n\n* 必须始终保持最新的数据（实时数据流）\n* 缓存条目可能极其庞大的情况（应考虑使用流式处理）\n* 结果依赖于文件内容之外参数的情况（例如，不同的提取配置）\n","# 内容哈希文件缓存模式\n\n使用 SHA-256 内容哈希作为缓存键，缓存昂贵的文件处理结果（PDF 解析、文本提取、图像分析）。与基于路径的缓存不同，此方法在文件移动\u002F重命名后仍然有效，并在内容更改时自动失效。\n\n## 何时激活\n\n* 构建文件处理管道时（PDF、图像、文本提取）\n* 处理成本高且同一文件被重复处理时\n* 需要一个 `--cache\u002F--no-cache` CLI 选项时\n* 希望在不修改现有纯函数的情况下为其添加缓存时\n\n## 核心模式\n\n### 1. 基于内容哈希的缓存键\n\n使用文件内容（而非路径）作为缓存键：\n\n```python\nimport hashlib\nfrom pathlib import Path\n\n_HASH_CHUNK_SIZE = 65536  # 64KB chunks for large files\n\ndef compute_file_hash(path: Path) -> str:\n    \"\"\"SHA-256 of file contents (chunked for large files).\"\"\"\n    if not path.is_file():\n        raise FileNotFoundError(f\"File not found: {path}\")\n    sha256 = hashlib.sha256()\n    with open(path, \"rb\") as f:\n        while True:\n            chunk = f.read(_HASH_CHUNK_SIZE)\n            if not chunk:\n                break\n            sha256.update(chunk)\n    return sha256.hexdigest()\n```\n\n**为什么使用内容哈希？** 文件重命名\u002F移动 = 缓存命中。内容更改 = 自动失效。无需索引文件。\n\n### 2. 用于缓存条目的冻结数据类\n\n```python\nfrom dataclasses import dataclass\n\n@dataclass(frozen=True, slots=True)\nclass CacheEntry:\n    file_hash: str\n    source_path: str\n    document: ExtractedDocument  # The cached result\n```\n\n### 3. 基于文件的缓存存储\n\n每个缓存条目都存储为 `{hash}.json` —— 通过哈希实现 O(1) 查找，无需索引文件。\n\n```python\nimport json\nfrom typing import Any\n\ndef write_cache(cache_dir: Path, entry: CacheEntry) -> None:\n    cache_dir.mkdir(parents=True, exist_ok=True)\n    cache_file = cache_dir \u002F f\"{entry.file_hash}.json\"\n    data = serialize_entry(entry)\n    cache_file.write_text(json.dumps(data, ensure_ascii=False), encoding=\"utf-8\")\n\ndef read_cache(cache_dir: Path, file_hash: str) -> CacheEntry | None:\n    cache_file = cache_dir \u002F f\"{file_hash}.json\"\n    if not cache_file.is_file():\n        return None\n    try:\n        raw = cache_file.read_text(encoding=\"utf-8\")\n        data = json.loads(raw)\n        return deserialize_entry(data)\n    except (json.JSONDecodeError, ValueError, KeyError):\n        return None  # Treat corruption as cache miss\n```\n\n### 4. 服务层包装器（单一职责原则）\n\n保持处理函数的纯净性。将缓存作为一个单独的服务层添加。\n\n```python\ndef extract_with_cache(\n    file_path: Path,\n    *,\n    cache_enabled: bool = True,\n    cache_dir: Path = Path(\".cache\"),\n) -> ExtractedDocument:\n    \"\"\"Service layer: cache check -> extraction -> cache write.\"\"\"\n    if not cache_enabled:\n        return extract_text(file_path)  # Pure function, no cache knowledge\n\n    file_hash = compute_file_hash(file_path)\n\n    # Check cache\n    cached = read_cache(cache_dir, file_hash)\n    if cached is not None:\n        logger.info(\"Cache hit: %s (hash=%s)\", file_path.name, file_hash[:12])\n        return cached.document\n\n    # Cache miss -> extract -> store\n    logger.info(\"Cache miss: %s (hash=%s)\", file_path.name, file_hash[:12])\n    doc = extract_text(file_path)\n    entry = CacheEntry(file_hash=file_hash, source_path=str(file_path), document=doc)\n    write_cache(cache_dir, entry)\n    return doc\n```\n\n## 关键设计决策\n\n| 决策 | 理由 |\n|----------|-----------|\n| SHA-256 内容哈希 | 与路径无关，内容更改时自动失效 |\n| `{hash}.json` 文件命名 | O(1) 查找，无需索引文件 |\n| 服务层包装器 | 单一职责原则：提取功能保持纯净，缓存是独立的关注点 |\n| 手动 JSON 序列化 | 完全控制冻结数据类的序列化 |\n| 损坏时返回 `None` | 优雅降级，在下次运行时重新处理 |\n| `cache_dir.mkdir(parents=True)` | 在首次写入时惰性创建目录 |\n\n## 最佳实践\n\n* **哈希内容，而非路径** —— 路径会变，内容标识不变\n* 对大文件进行哈希时**分块处理** —— 避免将整个文件加载到内存中\n* **保持处理函数的纯净性** —— 它们不应了解任何关于缓存的信息\n* **记录缓存命中\u002F未命中**，并使用截断的哈希值以便调试\n* **优雅地处理损坏** —— 将无效的缓存条目视为未命中，永不崩溃\n\n## 应避免的反模式\n\n```python\n## BAD: Path-based caching (breaks on file move\u002Frename)\ncache = {\"\u002Fpath\u002Fto\u002Ffile.pdf\": result}\n\n## BAD: Adding cache logic inside the processing function (SRP violation)\ndef extract_text(path, *, cache_enabled=False, cache_dir=None):\n    if cache_enabled:  # Now this function has two responsibilities\n        ...\n\n## BAD: Using dataclasses.asdict() with nested frozen dataclasses\n## (can cause issues with complex nested types)\ndata = dataclasses.asdict(entry)  # Use manual serialization instead\n```\n\n## 适用场景\n\n* 文件处理管道（PDF 解析、OCR、文本提取、图像分析）\n* 受益于 `--cache\u002F--no-cache` 选项的 CLI 工具\n* 跨多次运行出现相同文件的批处理\n* 在不修改现有纯函数的情况下为其添加缓存\n\n## 不适用场景\n\n* 必须始终保持最新的数据（实时数据流）\n* 缓存条目可能极其庞大的情况（应考虑使用流式处理）\n* 结果依赖于文件内容之外参数的情况（例如，不同的提取配置）\n",{"name":5,"origin":24,"description":7},"ECC","master","d6ca01da0f24a3b0e26e4a8b7b66cbd25d429f5d","web-assets\u002Fdocs\u002Fzh-CN\u002Fskills\u002Fcontent-hash-cache-pattern",0,"https:\u002F\u002Fgithub.com\u002FSriramGandhiS\u002FSkills","https:\u002F\u002Fgithub.com\u002FSriramGandhiS","https:\u002F\u002Fsriram.website\u002F","Curious guy who keeps tinkering until something works","2026-05-20 16:21:34",{"source":8,"skillName":5,"commands":35,"prompt":45,"zipAvailable":46},[36,39,42],{"tool":37,"command":38},"npx","npx skills add SriramGandhiS\u002FSkills --skill content-hash-cache-pattern",{"tool":40,"command":41},"bunx","bunx skills add SriramGandhiS\u002FSkills --skill content-hash-cache-pattern",{"tool":43,"command":44},"pnpm","pnpm dlx skills add SriramGandhiS\u002FSkills --skill content-hash-cache-pattern","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FSriramGandhiS\u002FSkills\u002Fblob\u002Fmaster\u002Fweb-assets\u002Fdocs\u002Fzh-CN\u002Fskills\u002Fcontent-hash-cache-pattern\u002FSKILL.md",true,[],[49,56,61,67,74,81],{"skillNo":50,"name":51,"nameZh":6,"description":52,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":53,"categories":54,"keywords":55,"publishedAt":19},"01M732609EPJWV13PVTX3GT4TM","webgpu-threejs-tsl","Comprehensive guide for developing WebGPU-enabled Three.js applications using TSL (Three.js Shading Language). Covers WebGPU renderer setup, TSL syntax and node materials, compute shaders, post-processing effects, and WGSL integration. Use this skill when working with Three.js WebGPU, TSL shaders, node materials, or GPU compute in Three.js.","https:\u002F\u002Fgithub.com\u002FSriramGandhiS\u002FSkills\u002Fblob\u002Fmaster\u002Fwebgpu-threejs-tsl\u002Fskills\u002Fwebgpu-threejs-tsl\u002FSKILL.md",[],[],{"skillNo":57,"name":51,"nameZh":6,"description":52,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":58,"categories":59,"keywords":60,"publishedAt":19},"01M7325XM47AGWB6K6C4VXKE6B","https:\u002F\u002Fgithub.com\u002FSriramGandhiS\u002FSkills\u002Fblob\u002Fmaster\u002Fwebgpu-threejs-tsl\u002FSKILL.md",[],[],{"skillNo":62,"name":63,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":64,"categories":65,"keywords":66,"publishedAt":19},"01M7325WP6DES69JKC840VMFEP","verification-loop","https:\u002F\u002Fgithub.com\u002FSriramGandhiS\u002FSkills\u002Fblob\u002Fmaster\u002Fweb-assets\u002Fdocs\u002Fzh-TW\u002Fskills\u002Fverification-loop\u002FSKILL.md",[],[],{"skillNo":68,"name":69,"nameZh":6,"description":70,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":71,"categories":72,"keywords":73,"publishedAt":19},"01M7325TFQF1DZTQ6J3WGQQ1VR","tdd-workflow","Use this skill when writing new features, fixing bugs, or refactoring code. Enforces test-driven development with 80%+ coverage including unit, integration, and E2E tests.","https:\u002F\u002Fgithub.com\u002FSriramGandhiS\u002FSkills\u002Fblob\u002Fmaster\u002Fweb-assets\u002Fdocs\u002Fzh-TW\u002Fskills\u002Ftdd-workflow\u002FSKILL.md",[],[],{"skillNo":75,"name":76,"nameZh":6,"description":77,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":78,"categories":79,"keywords":80,"publishedAt":19},"01M7325RGV9AY9PK92D2V8KKPW","strategic-compact","Suggests manual context compaction at logical intervals to preserve context through task phases rather than arbitrary auto-compaction.","https:\u002F\u002Fgithub.com\u002FSriramGandhiS\u002FSkills\u002Fblob\u002Fmaster\u002Fweb-assets\u002Fdocs\u002Fzh-TW\u002Fskills\u002Fstrategic-compact\u002FSKILL.md",[],[],{"skillNo":82,"name":83,"nameZh":6,"description":84,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":85,"categories":86,"keywords":87,"publishedAt":19},"01M7325MZC28SE86E7NMCNEFS4","security-review","Use this skill when adding authentication, handling user input, working with secrets, creating API endpoints, or implementing payment\u002Fsensitive features. Provides comprehensive security checklist and patterns.","https:\u002F\u002Fgithub.com\u002FSriramGandhiS\u002FSkills\u002Fblob\u002Fmaster\u002Fweb-assets\u002Fdocs\u002Fzh-TW\u002Fskills\u002Fsecurity-review\u002FSKILL.md",[],[]]