feat: 使用 HF Dataset 做持久化(spaces-storage#dataset-storage)
Browse filesFiles changed (5)
- Dockerfile+11-4
- README.md+14-2
- scripts/entrypoint.shAdded+31
- scripts/restore_from_dataset.pyAdded+59
- scripts/save_to_dataset.pyAdded+41
5 unmodified lines678910111213141516173 unmodified lines21222324252610 unmodified lines3738394041425 unmodified lines# 避免交互式提示ENV DEBIAN_FRONTEND=noninteractive# 安装依赖:安装脚本需要 curl、tar(Linux 解压)RUN apt-get update && apt-get install -y --no-install-recommends \ca-certificates \curl \tar \git \&& rm -rf /var/lib/apt/lists/*# 不创建新用户(HF 构建环境可能已有 UID 1000),改为以 root 安装到 /home/user 再 chown3 unmodified lines# 必须让管道右侧的 bash 也继承 HOME,否则脚本会装到 /root/.opencode/binRUN bash -c 'export HOME=/home/user; curl -fsSL https://opencode.ai/install | bash -s -- --no-modify-path'# 将 /home/user 归属给 UID 1000(HF Spaces 运行时使用 UID 1000)RUN chown -R 1000:1000 /home/user10 unmodified lines# Hugging Face Spaces 默认暴露 7860EXPOSE 7860# 启动 headless HTTP server(使用默认数据目录 ~/.local/share/opencode,不指定 /data,避免发消息失败)# 文档与 API: /doc 为 OpenAPI 3.1 规范CMD ["/home/user/.opencode/bin/opencode", "serve", "--port", "7860", "--hostname", "0.0.0.0", "--cors", "https://tacits-candy-shop.vercel.app", "--cors", "https://opencode-web-pearl.vercel.app"]5 unmodified lines678910111213141516171819203 unmodified lines2425262728293031323310 unmodified lines4445464748495 unmodified lines# 避免交互式提示ENV DEBIAN_FRONTEND=noninteractive# 安装依赖:curl/tar/git 用于 opencode,python3/huggingface_hub 用于 Dataset 持久化RUN apt-get update && apt-get install -y --no-install-recommends \ca-certificates \curl \tar \git \python3 \python3-pip \&& pip3 install --break-system-packages huggingface_hub \&& rm -rf /var/lib/apt/lists/*# 不创建新用户(HF 构建环境可能已有 UID 1000),改为以 root 安装到 /home/user 再 chown3 unmodified lines# 必须让管道右侧的 bash 也继承 HOME,否则脚本会装到 /root/.opencode/binRUN bash -c 'export HOME=/home/user; curl -fsSL https://opencode.ai/install | bash -s -- --no-modify-path'# Dataset 持久化脚本(见 https://huggingface.co/docs/hub/spaces-storage#dataset-storage)COPY scripts/ /home/user/app/scripts/RUN chown -R 1000:1000 /home/user/app/scripts && chmod +x /home/user/app/scripts/entrypoint.sh# 将 /home/user 归属给 UID 1000(HF Spaces 运行时使用 UID 1000)RUN chown -R 1000:1000 /home/user10 unmodified lines# Hugging Face Spaces 默认暴露 7860EXPOSE 7860# 使用 entrypoint:若设置 HF_TOKEN + OPENCODE_DATASET_REPO 则从 Dataset 恢复并每 5 分钟保存# 否则直接启动 opencode serve(行为与原先一致)CMD ["/home/user/app/scripts/entrypoint.sh"]
26 unmodified lines27282930313233343526 unmodified lines- `OPENCODE_SERVER_PASSWORD`(必填时启用认证)- `OPENCODE_SERVER_USERNAME`(可选,默认 `opencode`)## 持久化存储当前 Space 使用容器默认数据目录,**重启后会话等数据会丢失**。请勿在 Settings → Variables 中设置 `XDG_DATA_HOME` / `XDG_CONFIG_HOME` 指向 `/data`,否则可能导致无法发送消息。若需长期保留数据,请使用外部存储或 Dataset 等方案。## 参考26 unmodified lines27282930313233343536373839404142434445464726 unmodified lines- `OPENCODE_SERVER_PASSWORD`(必填时启用认证)- `OPENCODE_SERVER_USERNAME`(可选,默认 `opencode`)## 持久化存储(Dataset,免费)采用 [HF 官方推荐的 Dataset 存储](https://huggingface.co/docs/hub/spaces-storage#dataset-storage):会话等数据写入你名下的 **Dataset 仓库**,用免费仓库存储额度,重启后可恢复。1. **新建一个 Dataset 仓库**在 [Hub](https://huggingface.co/new-dataset) 创建,例如 `tao-shen/opencode-data`(可先空着)。2. **在 Space 里配置**- **Settings → Repository secrets**:新增 `HF_TOKEN`,值为你的 [Access Token](https://huggingface.co/settings/tokens)(需 **Write** 权限)。- **Settings → Variables**:新增 `OPENCODE_DATASET_REPO`,值为 Dataset 的 `repo_id`,例如 `tao-shen/opencode-data`。3. **行为**- 启动时:从该 Dataset 拉取已有数据到 `~/.local/share/opencode`(若有)。- 运行中:每 5 分钟把当前数据上传回该 Dataset。- 未设置上述两个变量时,与之前一致:不恢复、不保存,重启后数据丢失。## 参考
12345678910111213141516171819202122232425262728293031#!/bin/sh# 若设置了 HF_TOKEN 与 OPENCODE_DATASET_REPO,则从 Dataset 恢复并定期保存到 Dataset;# 否则直接启动 opencode serve(与原先行为一致)。
set -eDATA_DIR="${HOME}/.local/share/opencode"OPENCODE_BIN="/home/user/.opencode/bin/opencode"SCRIPT_DIR="/home/user/app/scripts"SAVE_INTERVAL=300
if [ -n "$HF_TOKEN" ] && [ -n "$OPENCODE_DATASET_REPO" ]; then # 从 Dataset 恢复 python3 "$SCRIPT_DIR/restore_from_dataset.py" || true # 后台启动 opencode,并定期保存到 Dataset trap 'kill -TERM $OPENCODE_PID 2>/dev/null' TERM INT $OPENCODE_BIN serve --port 7860 --hostname 0.0.0.0 \ --cors https://tacits-candy-shop.vercel.app \ --cors https://opencode-web-pearl.vercel.app & OPENCODE_PID=$! while kill -0 $OPENCODE_PID 2>/dev/null; do sleep $SAVE_INTERVAL python3 "$SCRIPT_DIR/save_to_dataset.py" || true done wait $OPENCODE_PID exit $?fi
# 未配置 Dataset 时直接启动(与原先 CMD 一致)exec $OPENCODE_BIN serve --port 7860 --hostname 0.0.0.0 \ --cors https://tacits-candy-shop.vercel.app \ --cors https://opencode-web-pearl.vercel.app1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859#!/usr/bin/env python3"""从 Hugging Face Dataset 仓库恢复 OpenCode 数据到 ~/.local/share/opencode。需设置环境变量: HF_TOKEN, OPENCODE_DATASET_REPO。"""import osimport shutilimport sys
def main(): token = os.environ.get("HF_TOKEN") repo_id = os.environ.get("OPENCODE_DATASET_REPO") data_dir = os.path.expanduser("~/.local/share/opencode")
if not token or not repo_id: return 0
try: from huggingface_hub import HfApi, snapshot_download except ImportError: print("restore: huggingface_hub not installed, skip restore", file=sys.stderr) return 0
try: api = HfApi(token=token) files = api.list_repo_files(repo_id, repo_type="dataset") if not files or set(files) <= {".gitattributes"}: return 0 except Exception as e: print(f"restore: list repo failed ({e}), skip restore", file=sys.stderr) return 0
os.makedirs(data_dir, exist_ok=True) tmp_dir = data_dir + ".restore_tmp" try: snapshot_download( repo_id=repo_id, repo_type="dataset", local_dir=tmp_dir, token=token, ) for name in os.listdir(tmp_dir): if name == ".gitattributes": continue src = os.path.join(tmp_dir, name) dst = os.path.join(data_dir, name) if os.path.isdir(src): if os.path.exists(dst): shutil.rmtree(dst, ignore_errors=True) shutil.copytree(src, dst) else: shutil.copy2(src, dst) finally: if os.path.isdir(tmp_dir): shutil.rmtree(tmp_dir, ignore_errors=True) return 0
if __name__ == "__main__": sys.exit(main())1234567891011121314151617181920212223242526272829303132333435363738394041#!/usr/bin/env python3"""将 ~/.local/share/opencode 上传到 Hugging Face Dataset 仓库。需设置环境变量: HF_TOKEN, OPENCODE_DATASET_REPO。"""import osimport sys
def main(): token = os.environ.get("HF_TOKEN") repo_id = os.environ.get("OPENCODE_DATASET_REPO") data_dir = os.path.expanduser("~/.local/share/opencode")
if not token or not repo_id: return 0
if not os.path.isdir(data_dir): return 0
try: from huggingface_hub import HfApi except ImportError: print("save: huggingface_hub not installed, skip save", file=sys.stderr) return 0
try: api = HfApi() api.upload_folder( folder_path=data_dir, path_in_repo=".", repo_id=repo_id, repo_type="dataset", token=token, ) except Exception as e: print(f"save: upload failed ({e})", file=sys.stderr) return 1 return 0
if __name__ == "__main__": sys.exit(main())Dockerfile+11-4
README.md+14-2
scripts/entrypoint.shAdded+31
scripts/restore_from_dataset.pyAdded+59
scripts/save_to_dataset.pyAdded+41