TriChat / app /workspace.py
simonu5's picture
Upload 19 files
0299897 verified
Raw History Blame Contribute Delete
6.23 kB
"""專案工作區:每個專案一個資料夾,內容持久化在 Turso(project_files 表)。
- 開始對話時:把專案檔案從 Turso 還原到 WORKDIR/projects/<id>/(容器重啟後也能恢復)
- 每次工具改動檔案後:掃描資料夾,把新增/修改/刪除同步回 Turso
- 沒有專案的對話用 WORKDIR/scratch(不持久化)
"""
import asyncio
import base64
import contextvars
import hashlib
import io
import logging
import os
import zipfile
from pathlib import Path
from . import config
from . import db as store
log = logging.getLogger("workspace")
# 不同步的目錄(依賴、快取、虛擬環境):重裝即可,不值得存進資料庫
SKIP_DIRS = {"node_modules", ".git", "__pycache__", ".venv", "venv", ".mypy_cache", ".pytest_cache",
".next", ".cache", ".npm", ".ruff_cache"}
MAX_FILE = config.PROJECT_MAX_FILE_MB * 1024 * 1024
MAX_TOTAL = config.PROJECT_MAX_TOTAL_MB * 1024 * 1024
current_project: contextvars.ContextVar[str | None] = contextvars.ContextVar("current_project", default=None)
_snapshots: dict[str, dict[str, str]] = {} # project_id -> {path: sha1}
_locks: dict[str, asyncio.Lock] = {}
def project_dir(pid: str | None) -> Path:
d = Path(config.WORKDIR) / ("projects/" + pid if pid else "scratch")
d.mkdir(parents=True, exist_ok=True)
return d
def current_dir() -> Path:
return project_dir(current_project.get())
def safe_path(rel: str) -> Path:
"""把相對路徑解析到目前工作區內,防止跳出資料夾。"""
root = current_dir().resolve()
p = (root / (rel or ".").lstrip("/")).resolve()
if p != root and root not in p.parents:
raise ValueError(f"路徑超出專案資料夾:{rel}")
return p
def _scan(root: Path) -> dict[str, tuple[str, bytes]]:
out = {}
for dirpath, dirnames, filenames in os.walk(root):
dirnames[:] = [d for d in dirnames if d not in SKIP_DIRS]
for fn in filenames:
fp = Path(dirpath) / fn
try:
if fp.is_symlink() or fp.stat().st_size > MAX_FILE:
continue
data = fp.read_bytes()
except OSError:
continue
out[fp.relative_to(root).as_posix()] = (hashlib.sha1(data).hexdigest(), data)
return out
async def restore(pid: str):
"""從 Turso 還原專案檔案到磁碟(每個容器生命週期只做一次)。"""
if pid in _snapshots:
return
lock = _locks.setdefault(pid, asyncio.Lock())
async with lock:
if pid in _snapshots:
return
root = project_dir(pid)
snap = {}
for r in await store.list_project_files(pid, with_data=True):
fp = root / r["path"]
fp.parent.mkdir(parents=True, exist_ok=True)
data = base64.b64decode(r["data"] or "")
fp.write_bytes(data)
snap[r["path"]] = hashlib.sha1(data).hexdigest()
_snapshots[pid] = snap
async def sync(pid: str | None = None) -> dict:
"""把磁碟上的改動同步回 Turso,回傳 {changed, deleted}。"""
pid = pid or current_project.get()
if not pid:
return {"changed": [], "deleted": []}
await restore(pid)
async with _locks.setdefault(pid, asyncio.Lock()):
files = await asyncio.to_thread(_scan, project_dir(pid))
total = sum(len(d) for _, d in files.values())
if total > MAX_TOTAL:
log.warning("專案 %s 超過 %dMB,只同步較小的檔案", pid, config.PROJECT_MAX_TOTAL_MB)
old = _snapshots.get(pid, {})
changed = [p for p, (h, _) in files.items() if old.get(p) != h]
deleted = [p for p in old if p not in files]
budget = MAX_TOTAL
stmts = []
for p in sorted(files, key=lambda x: len(files[x][1])):
budget -= len(files[p][1])
if p in changed and budget >= 0:
stmts.append(store.upsert_file_stmt(pid, p, base64.b64encode(files[p][1]).decode(),
len(files[p][1])))
elif p in changed:
changed.remove(p)
stmts += [store.delete_file_stmt(pid, p) for p in deleted]
for i in range(0, len(stmts), 20):
await store.db.batch(stmts[i:i + 20])
new_snap = dict(old)
for p in changed:
new_snap[p] = files[p][0]
for p in deleted:
new_snap.pop(p, None)
_snapshots[pid] = new_snap
if stmts:
await store.touch_project(pid)
return {"changed": changed, "deleted": deleted}
def tree(pid: str | None, limit: int = 300) -> list[str]:
root = project_dir(pid)
out = []
for dirpath, dirnames, filenames in os.walk(root):
dirnames[:] = sorted(d for d in dirnames if d not in SKIP_DIRS)
for fn in sorted(filenames):
out.append((Path(dirpath) / fn).relative_to(root).as_posix())
if len(out) >= limit:
return out
return out
async def write_upload(pid: str, path: str, data: bytes):
await restore(pid)
token = current_project.set(pid)
try:
fp = safe_path(path)
fp.parent.mkdir(parents=True, exist_ok=True)
fp.write_bytes(data)
finally:
current_project.reset(token)
await sync(pid)
async def delete_path(pid: str, path: str):
await restore(pid)
token = current_project.set(pid)
try:
fp = safe_path(path)
if fp.is_file():
fp.unlink()
finally:
current_project.reset(token)
await sync(pid)
async def read_bytes(pid: str, path: str) -> bytes:
await restore(pid)
token = current_project.set(pid)
try:
return safe_path(path).read_bytes()
finally:
current_project.reset(token)
async def zip_project(pid: str) -> bytes:
await restore(pid)
root = project_dir(pid)
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as z:
for rel in tree(pid, limit=100000):
z.write(root / rel, rel)
return buf.getvalue()
def forget(pid: str):
import shutil
shutil.rmtree(project_dir(pid), ignore_errors=True)
_snapshots.pop(pid, None)