File size: 6,232 Bytes
4d5692f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0299897
4d5692f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
"""專案工作區:每個專案一個資料夾,內容持久化在 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)