"""Eat This Much 离线克隆 —— FastAPI 组合根。 布局与判据: * ``frontend/pages`` 是每条范围内路由的本地化存档文档,``static/`` 是冻结的 静态资源。运行时不可达任何远端来源(CSP 把 connect/img/frame/script 全锁在本源)。 * 源站的 www 与 /app 都是 SvelteKit。www 走服务端渲染,正文在 HTML 里,可以直接 存档;``/app`` 是纯客户端渲染,页面外壳没有内容,全靠 ``/api/v1/*`` ——所以 ``/app`` 这一面必须把接口实现出来,让源站自己的 bundle 在本地跑起来。 * SvelteKit 按页面深度写相对资源前缀(``./_app/…``、``../../_app/…``)。克隆不改这些 标记,改的是路由:任意深度的 ``**/_app/immutable/**`` 都落到同一份冻结资源上。 * ``/calories/-``:数字是权威的,slug 是装饰性的。换个 slug 源站 301 回 规范地址,克隆照做——不比源站更严格,也不更宽松。 * ``/app`` 对未匹配路径答 **200 + 404 文案外壳**(源站如此)。克隆答真 404 会比 源站更严格,那是错的。 * 站外链接落到 ``/external/{host}`` 边界页,答 200:链接确实通向了某处,只是那个 某处在离线包里。 * 账号、邮件、支付全部走引擎自带的 ``websitebench.local_clone_auth`` 与 ``websitebench.site_backend``:口令 scrypt 存哈希、会话只存摘要、找回密码对 已知/未知邮箱给不可区分的公开响应、邮件默认 LOCAL_ONLY、支付只有本地沙箱。 * ``GET /healthz`` 恒返回 ``{"ok":true,"site_id":"eatthismuch"}``。 """ from __future__ import annotations import html import json import threading import os import pathlib import re import sys from typing import Any from urllib.parse import parse_qsl, quote, unquote, urlencode from fastapi import FastAPI, Request from fastapi.responses import ( FileResponse, HTMLResponse, JSONResponse, PlainTextResponse, RedirectResponse, Response, ) ROOT = pathlib.Path(__file__).resolve().parent if str(ROOT) not in sys.path: sys.path.insert(0, str(ROOT)) import sitepack # noqa: E402 from backend import content_store as store # noqa: E402 from backend import app_api from backend import macro_calculator # noqa: E402 from backend import g_api # noqa: E402 from backend.site_services import ( # noqa: E402 data_dir, DEMO_DISPLAY_NAME, DEMO_EMAIL, open_services, ) # 注册/找回密码要按引擎抛的异常分流:校验不过是字段错,其余归 __all__。 from websitebench.local_clone_auth import ( # noqa: E402 AuthError, RESET_PUBLIC_MESSAGE, ) SITE_ID = "eatthismuch" STATIC = ROOT / "static" # The frozen binary assets and the archived inline-API bodies are read out of # ``clone/_sitepack`` when compile.sh has packed them and straight off disk when # it has not; see sitepack.py for why the compiled tree may not carry fifteen # thousand files. STATIC_PACK = sitepack.SitePack.load(ROOT / "_sitepack" / "static.packindex.json") INLINE_PACK = sitepack.SitePack.load(ROOT / "_sitepack" / "inline-api.packindex.json") PAGES = ROOT / "frontend" / "pages" AUTH_PAGES = ROOT / "frontend" / "auth" def _load_static_map(name: str) -> dict[str, str]: """构建期从抓取日志带过来的静态资产索引。""" src = ROOT / "backend" / "content" / name if not src.is_file(): return {} try: data = json.loads(src.read_text(encoding="utf-8")) except Exception: return {} return {str(k): str(v) for k, v in data.items()} if isinstance(data, dict) else {} # 路径 → 实测 content-type STATIC_TYPES: dict[str, str] = _load_static_map("static-types.json") # "裸路径?归一化查询串" → 实际落盘的那个带哈希的路径 STATIC_QUERIES: dict[str, str] = _load_static_map("static-queries.json") # ---- 内联接口回放 --------------------------------------------------------- # # 源站把 load() 里 fetch 到的响应内联在页面里(`' if runtime not in body: body = body.replace(b"", runtime + b"", 1) return html_response(body, record.get("status", 200)) @app.get("/{full_path:path}") def catch_all(full_path: str, request: Request) -> Response: raw = "/" + full_path path = store.normalize(raw) # 先试 /app 那棵。两棵的文件名不会撞(哈希各自独立),所以取不到就回落 # 到前台那棵是安全的——回落只可能命中同名文件,而同名文件不存在。 app_immutable = _APP_IMMUTABLE.match(path) if app_immutable: response = _serve_static(f"app/_app/immutable/{app_immutable.group('rest')}") if response.status_code == 200: return response immutable = _IMMUTABLE.search(path) if immutable: rest = immutable.group("rest") response = _serve_static(f"_app/immutable/{rest}") if response.status_code == 200: return response return _serve_static(f"app/_app/immutable/{rest}") redirect = store.redirect_for(path) if redirect: return RedirectResponse(redirect["to"], status_code=redirect.get("status", 301)) # 尾斜杠的规范形态是**逐页**的,不是逐站的,所以照着构建期从抓取证据里 # 留下来的 record["canonical"] 走,而不是按前缀猜。实测四条: # # /about/ → 308 → /about (去斜杠) # /diet-plan/keto/ → 308 → /diet-plan/keto (去斜杠) # /sample-email → 301 → /sample-email/ (加斜杠) # /diet-plan/atkins-ketogenic → 301 → /diet-plan/atkins-ketogenic/(加斜杠) # # 加斜杠是 301(Django 的 APPEND_SLASH),去斜杠是 308,两个方向的状态码不同。 canonical = (store.page_record(path) or {}).get("canonical") if canonical: if raw != canonical: return RedirectResponse(canonical, status_code=301) elif raw != path and raw.endswith("/"): # 只对确实存在的目标发 308,否则一个不存在的路径会被 308 到另一个 # 不存在的路径,把 404 藏起来。 if store.page_record(path) or store.alias_target(path): return RedirectResponse(path, status_code=308) alias = store.alias_target(path) if alias: response = _stored_page(alias) if response is not None: return response response = _stored_page(path) if response is not None: return response # /calories/-:数字是权威的,slug 是装饰性的。 # # 但实测下来源站**不重定向**:/calories/zzz-banana-oatmeal-33511 直接答 200 # (74024B,规范地址是 74018B),/calories/33511 也答 200。 # 我原本按 goodreads 的经验假定它会 301 回规范地址——测下来是反的。 # 克隆照实测来:按 id 找到那一页,原样交出去,不发重定向。 if path.startswith("/calories/"): canonical = _canonical_food_path(path) if canonical: response = _stored_page(canonical) if response is not None: return response # 认得这条食物、但没有存档整页 —— 交客户端渲染的那张壳。 # # 这一支覆盖的量比看上去大:食物 2150 条,存档整页的只有 40 条。 # 剩下 2110 条在 SPA 里点进去都好好的(客户端路由自己跑 load), # 但**直接 goto 全是 404**——随机抽 30 条直接 GET,30 条全 404, # 交出去的是 "Server error - Eat This Much" 那张 404 壳。 # 冷启动、开新标签页、按刷新,这 2110 页全是死的。 # # 壳里是源站自己的 bundle 加两参启动(tools/build_clone.py: # install_food_shell 里记了为什么可以去掉水合负载),数据来自这边 # 已经实测出形状的 /api/v1/food// 那几条。所以这不是拿一张占位 # 页糊住 404:渲染出来的就是这条食物本身的页面。 # # 状态码 200 而不是 404:源站对这些地址答的就是 200。 shell = store.shell("food-shell") if shell is not None: return html_response(shell, 200) # 博客是源站自己的第二个第一方源,它的静态资源挂在 /blog/ 前缀下 if path.startswith("/blog/"): blog_asset = _serve_static( "blog-assets" + path[len("/blog"):], request.url.query ) if blog_asset.status_code == 200: return blog_asset # 博客列表的分页收边。 # # 源站的分页链接是真的:/blog/category/meal-planning/ 底部直接链到 page/2 3 4, # /blog/latest-articles/ 链到 page/2 3 7。前两页整页存档(范围内), # 第三页起收边——但**收边不等于 404**。答 404 就是在克隆里留死链, # 而这些链接在存档下来的标记里明明白白存在,点下去必须落到某处。 # 和 /food/browse 用同一套 _fence_document,边界只有一种表达方式。 m = _BLOG_PAGE.match(path) if m: base, page = f"/blog/{m.group(1)}", int(m.group(2)) if store.page_record(base) is not None and page > BLOG_PAGE_LIMIT: return html_response(_fence_document( f"Page {page} is past the edge of this clone", "This offline clone carries the first " f"{BLOG_PAGE_LIMIT} pages of every blog list in full, with every " "post on them reachable. Beyond that the archive stops here " "rather than pretending.", base + "/", "Back to this blog list", ), 200) # 页面里指向源站根路径的散装静态文件(favicon、static_files/… ) www_asset = _serve_static(f"www{path}", request.url.query) if www_asset.status_code == 200: return www_asset if path == "/app" or path.startswith("/app/"): # /app 是纯客户端渲染:实测 /app/login 与 /app/<不存在的路径> 拿到的 # 是**同一份 14586 字节的壳**,路由、登录判断、404 文案全在浏览器里跑。 # 所以克隆对 /app 下的每一条路径都交这一份壳、都答 200—— # 这不是「兜底」,这就是源站服务端的完整行为。 shell = store.shell("app-shell") or store.shell("app-not-found") if shell is not None: return html_response(shell, 200) not_found = store.shell("not-found") if not_found is not None: return html_response(not_found, 404) return _bare_404() # ------------------------------------------------------------------ 进程入口 def main() -> None: """引擎起候选站的第一顺位是直接执行本文件,端口从 ``PORT`` 读。""" import uvicorn uvicorn.run( app, host=os.environ.get("HOST", "127.0.0.1"), port=int(os.environ.get("PORT", "9060")), log_level=os.environ.get("LOG_LEVEL", "warning"), ) if __name__ == "__main__": main()