diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..c6164e9 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,11 @@ +.git +node_modules +.next +dist +data +.env +.env.* +!.env.example +*.log +*.tsbuildinfo +next-env.d.ts diff --git a/.env.example b/.env.example index f5d7200..03c692c 100644 --- a/.env.example +++ b/.env.example @@ -7,6 +7,9 @@ DATABASE_URL=file:/data/app.db MAX_CONCURRENT_DOWNLOADS=1 # 0 disables the periodic update check UPDATE_CHECK_INTERVAL_HOURS=12 +# 1 (default): hf downloads over plain HTTP, so progress can be measured from bytes on disk. +# 0: use Xet (chunk-level dedup on updates), but progress only advances in large jumps. +HF_HUB_DISABLE_XET=1 # Auth.js: generate with `npx auth secret` or `openssl rand -base64 33` AUTH_SECRET= diff --git a/.gitignore b/.gitignore index fe0b91a..e7a161f 100644 --- a/.gitignore +++ b/.gitignore @@ -43,3 +43,4 @@ next-env.d.ts # local runtime data (SQLite, downloaded models) /data/ +dist/ diff --git a/CHANGELOG.md b/CHANGELOG.md index dbfab8d..daa3534 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,45 @@ step 1 (Hugging Face downloader) is released as a minor version. ## [Unreleased] +## [0.3.0] - 2026-10-05 + +Milestone (c): worker and downloads with live progress. + +### Added + +- Worker download queue: claims queued jobs (oldest first, one job per model, + `MAX_CONCURRENT_DOWNLOADS` in parallel) and runs + `hf download --revision --local-dir // --include …` + with exact, glob-escaped paths. `HF_TOKEN` is passed via the environment only; the child gets a + minimal environment (no web/OIDC secrets). +- Progress from bytes on disk (final files + `.incomplete` files matched by etag), sampled every + second: per job and per file bytes, %, speed (10 s window) and ETA. +- stdout/stderr captured as the job log (ANSI stripped, token-like strings masked), viewable live + and downloadable as text. +- After `hf` exits 0, every file is checked (size + `.metadata` etag) before the job is + `completed` and the model `ready`; otherwise the job fails with the list of missing files. +- Failed jobs show the exit code and the last stderr lines. +- Cancel (SIGTERM, SIGKILL after 10 s); graceful worker shutdown marks running jobs `interrupted`. +- Leftover partial files are deleted before a run and after a cancelled/failed run (hf can't resume + them). +- Free-space check before starting a download. +- Single-worker lease in the DB; a second worker waits instead of running the same jobs. +- Live UI over SSE (`/api/stream`): progress in the library, download card and job history on the + model page, job page with per-file progress and live log. "Add & download" queues the download + right away. +- Docker image (Node 24 + Python with pinned `huggingface_hub[hf_xet]==2.1.1`) and `compose.yaml` + with `web` and `worker` services, `data` and `models` volumes, worker healthcheck. +- `HF_HUB_DISABLE_XET` setting (default on, see README for why). + +### Changed + +- Dates are rendered in the browser's timezone (the server may run in UTC). + +### Notes + +- The spec assumed `hf download` resumes partial files. huggingface_hub 2.1.1 doesn't: re-running + skips completed files but restarts unfinished ones. Documented in the README. + ## [0.2.0] - 2026-10-05 Milestone (b): repo lookup and file selection. diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..6a810fd --- /dev/null +++ b/Dockerfile @@ -0,0 +1,50 @@ +# One image for both services: `web` (next start) and `worker` (node dist/worker.mjs). + +FROM node:24-trixie-slim AS node + +# --- build ------------------------------------------------------------------- +FROM node AS build +ENV NEXT_TELEMETRY_DISABLED=1 +WORKDIR /app +COPY package.json package-lock.json ./ +RUN npm ci +COPY . . +RUN npm run build \ + && npm run build:worker \ + && npm prune --omit=dev + +# --- runtime ----------------------------------------------------------------- +# Python base (provides the official `hf` CLI) plus the Node binary. The Python image already +# has CA certificates and libstdc++, so no apt is needed. +FROM python:3.13-slim-trixie AS runtime +COPY --from=node /usr/local/bin/node /usr/local/bin/node + +# Pinned: the worker relies on the CLI's on-disk layout (see src/worker/hf-layout.ts); +# re-verify that before bumping. +ARG HF_HUB_VERSION=2.1.1 +RUN python -m venv /opt/hf \ + && /opt/hf/bin/pip install --no-cache-dir "huggingface_hub[hf_xet]==${HF_HUB_VERSION}" \ + && rm -rf /root/.cache \ + && useradd --uid 1000 --create-home --shell /usr/sbin/nologin app \ + && mkdir -p /data /models \ + && chown app:app /data /models + +ENV PATH=/opt/hf/bin:$PATH \ + NODE_ENV=production \ + NEXT_TELEMETRY_DISABLED=1 \ + PORT=3000 \ + HOSTNAME=0.0.0.0 \ + DATABASE_URL=file:/data/app.db \ + MODELS_DIR=/models \ + HF_HOME=/data/hf-home + +WORKDIR /app +COPY --from=build --chown=app:app /app/package.json /app/next.config.ts ./ +COPY --from=build --chown=app:app /app/node_modules ./node_modules +COPY --from=build --chown=app:app /app/.next ./.next +COPY --from=build --chown=app:app /app/dist ./dist +COPY --from=build --chown=app:app /app/drizzle ./drizzle + +USER app +EXPOSE 3000 +CMD ["node_modules/.bin/next", "start"] diff --git a/README.md b/README.md index 8720b7d..c12d246 100644 --- a/README.md +++ b/README.md @@ -5,28 +5,55 @@ Downloads are done by the official `hf` CLI; the Hub API is used for metadata. ## Architecture -- **web** (`next dev` / `next start`): Next.js App Router UI + API routes, OIDC login via Auth.js. -- **worker** (`src/worker`): owns the job queue, spawns `hf download`, tracks progress, runs update checks. - Applies DB migrations at startup. -- They talk only through the SQLite database (`DATABASE_URL`). +- **web** (`next start`): Next.js App Router UI + API routes, OIDC login via Auth.js. +- **worker** (`src/worker`): owns the job queue, spawns `hf download`, tracks progress from bytes on + disk, applies DB migrations at startup. Only one worker runs at a time (DB lease). +- They talk only through the SQLite database (`DATABASE_URL`); the UI gets live updates via SSE + (`/api/stream`). + +## Run with Docker (recommended) + +```bash +cp .env.example .env # fill in HF_TOKEN, AUTH_SECRET, OIDC_*; AUTH_URL = URL you open in the browser +docker compose up --build +``` + +Open `AUTH_URL` (e.g. http://localhost:3000). `WEB_PORT=3100 docker compose up` changes the host port. +Volumes: `data` (SQLite + hf home, keep on local disk) and `models` (downloaded models). + +OIDC redirect URI for the client in Pocket ID: `/api/auth/callback/pocket-id`. ## Local development ```bash -cp .env.example .env # then fill in OIDC_* and AUTH_SECRET; use local paths, e.g. - # DATABASE_URL=file:./data/app.db, MODELS_DIR=./data/models, AUTH_URL=http://localhost:3000 npm install -npm run dev # starts web (http://localhost:3000) and worker together +npm run dev # web (http://localhost:3000) + worker ``` -OIDC redirect URI for the client in Pocket ID: `/api/auth/callback/pocket-id`. - -Other scripts: +Use local paths in `.env` (`DATABASE_URL=file:./data/app.db`, `MODELS_DIR=./data/models`). +The worker needs the `hf` CLI on `PATH` (`pip install "huggingface_hub[hf_xet]==2.1.1"`); without it +everything but downloading works. Don't point a Windows-native web app and a containerized worker at +the same SQLite file: SQLite locking doesn't work across that boundary. | Script | What it does | | --- | --- | | `npm run dev:web` / `npm run dev:worker` | run one side only | | `npm run db:generate` | create a migration after changing `src/lib/db/schema.ts` | | `npm run db:migrate` | apply migrations without starting the worker | +| `npm run build:worker` | bundle the worker to `dist/worker.mjs` (used in the image) | | `npm test` | unit tests (Node test runner via tsx) | | `npm run typecheck`, `npm run lint` | checks | + +## How `hf download` behaves (huggingface_hub 2.1.1) + +Verified in a container; the image pins this version. Re-check before bumping it. + +- With `--local-dir`, partial files live in `/.cache/huggingface/download/` as + `...incomplete` and are moved into place when complete. +- **Partial files are not resumed.** A re-run skips completed files but restarts unfinished ones + from zero (new random name). The worker deletes leftover partials. +- With Xet enabled the partial file only grows in large bursts, so the worker sets + `HF_HUB_DISABLE_XET=1` by default for accurate progress (configurable in `.env`). +- SIGTERM stops a download (exit 143); SIGINT does not stop a Xet download. +- Exit code 0 doesn't guarantee the files are there (e.g. a pattern that matched nothing), so the + worker checks every expected file's size and metadata afterwards. diff --git a/compose.yaml b/compose.yaml new file mode 100644 index 0000000..8b4131f --- /dev/null +++ b/compose.yaml @@ -0,0 +1,44 @@ +name: kaname + +x-app: &app + image: kaname:local + build: . + env_file: .env + # Container paths override whatever local-dev paths are in .env. + environment: + DATABASE_URL: file:/data/app.db + MODELS_DIR: /models + HF_HOME: /data/hf-home + restart: unless-stopped + init: true # reaps child processes (hf) and forwards signals + +services: + worker: + <<: *app + command: ["node", "dist/worker.mjs"] + volumes: + - data:/data + - models:/models + # Give running downloads time to stop cleanly (they are marked "interrupted"). + stop_grace_period: 20s + healthcheck: + test: ["CMD-SHELL", "find /tmp/kaname-worker-alive -mmin -1 | grep -q ."] + interval: 10s + timeout: 5s + start_period: 30s + retries: 3 + + web: + <<: *app + command: ["node_modules/.bin/next", "start"] + ports: + - "${WEB_PORT:-3000}:3000" + volumes: + - data:/data + depends_on: + worker: + condition: service_healthy # worker applies DB migrations on startup + +volumes: + data: # SQLite + hf home; keep on local disk (SQLite and NFS don't mix) + models: # downloaded models; will become an NFS mount from TrueNAS diff --git a/drizzle/0002_worker_lease.sql b/drizzle/0002_worker_lease.sql new file mode 100644 index 0000000..64c288d --- /dev/null +++ b/drizzle/0002_worker_lease.sql @@ -0,0 +1 @@ +ALTER TABLE `worker_state` ADD `instance_id` text; \ No newline at end of file diff --git a/drizzle/meta/0002_snapshot.json b/drizzle/meta/0002_snapshot.json new file mode 100644 index 0000000..2500fdb --- /dev/null +++ b/drizzle/meta/0002_snapshot.json @@ -0,0 +1,732 @@ +{ + "version": "6", + "dialect": "sqlite", + "id": "ccc02033-9cf0-4202-af94-36f060837602", + "prevId": "4e7ad000-61ee-41cc-94ab-ce600f479a95", + "tables": { + "job_files": { + "name": "job_files", + "columns": { + "job_id": { + "name": "job_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "model_file_id": { + "name": "model_file_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "path": { + "name": "path", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "expected_bytes": { + "name": "expected_bytes", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "done_bytes": { + "name": "done_bytes", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "state": { + "name": "state", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'pending'" + } + }, + "indexes": {}, + "foreignKeys": { + "job_files_job_id_jobs_id_fk": { + "name": "job_files_job_id_jobs_id_fk", + "tableFrom": "job_files", + "tableTo": "jobs", + "columnsFrom": [ + "job_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "job_files_model_file_id_model_files_id_fk": { + "name": "job_files_model_file_id_model_files_id_fk", + "tableFrom": "job_files", + "tableTo": "model_files", + "columnsFrom": [ + "model_file_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "job_files_job_id_model_file_id_pk": { + "columns": [ + "job_id", + "model_file_id" + ], + "name": "job_files_job_id_model_file_id_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "job_logs": { + "name": "job_logs", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "job_id": { + "name": "job_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "ts": { + "name": "ts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "stream": { + "name": "stream", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "line": { + "name": "line", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "job_logs_job_idx": { + "name": "job_logs_job_idx", + "columns": [ + "job_id", + "id" + ], + "isUnique": false + } + }, + "foreignKeys": { + "job_logs_job_id_jobs_id_fk": { + "name": "job_logs_job_id_jobs_id_fk", + "tableFrom": "job_logs", + "tableTo": "jobs", + "columnsFrom": [ + "job_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "jobs": { + "name": "jobs", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "model_id": { + "name": "model_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "purpose": { + "name": "purpose", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "target_sha": { + "name": "target_sha", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "state": { + "name": "state", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'queued'" + }, + "attempt": { + "name": "attempt", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "total_bytes": { + "name": "total_bytes", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "done_bytes": { + "name": "done_bytes", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "speed_bps": { + "name": "speed_bps", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "eta_seconds": { + "name": "eta_seconds", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "exit_code": { + "name": "exit_code", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "error_code": { + "name": "error_code", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "error_message": { + "name": "error_message", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "cancel_requested_at": { + "name": "cancel_requested_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "started_at": { + "name": "started_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "finished_at": { + "name": "finished_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "jobs_state_idx": { + "name": "jobs_state_idx", + "columns": [ + "state" + ], + "isUnique": false + }, + "jobs_model_idx": { + "name": "jobs_model_idx", + "columns": [ + "model_id" + ], + "isUnique": false + } + }, + "foreignKeys": { + "jobs_model_id_models_id_fk": { + "name": "jobs_model_id_models_id_fk", + "tableFrom": "jobs", + "tableTo": "models", + "columnsFrom": [ + "model_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "model_files": { + "name": "model_files", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "model_id": { + "name": "model_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "path": { + "name": "path", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "size": { + "name": "size", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "blob_oid": { + "name": "blob_oid", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "lfs_sha256": { + "name": "lfs_sha256", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "selected": { + "name": "selected", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "state": { + "name": "state", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'pending'" + }, + "checked_at": { + "name": "checked_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "model_files_model_path_uq": { + "name": "model_files_model_path_uq", + "columns": [ + "model_id", + "path" + ], + "isUnique": true + } + }, + "foreignKeys": { + "model_files_model_id_models_id_fk": { + "name": "model_files_model_id_models_id_fk", + "tableFrom": "model_files", + "tableTo": "models", + "columnsFrom": [ + "model_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "model_revisions": { + "name": "model_revisions", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "model_id": { + "name": "model_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "sha": { + "name": "sha", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "pinned_at": { + "name": "pinned_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "superseded_at": { + "name": "superseded_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "model_revisions_model_idx": { + "name": "model_revisions_model_idx", + "columns": [ + "model_id" + ], + "isUnique": false + } + }, + "foreignKeys": { + "model_revisions_model_id_models_id_fk": { + "name": "model_revisions_model_id_models_id_fk", + "tableFrom": "model_revisions", + "tableTo": "models", + "columnsFrom": [ + "model_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "models": { + "name": "models", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "repo_type": { + "name": "repo_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'model'" + }, + "repo_id": { + "name": "repo_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "tracked_revision": { + "name": "tracked_revision", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'main'" + }, + "pinned_sha": { + "name": "pinned_sha", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "local_path": { + "name": "local_path", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "include_patterns": { + "name": "include_patterns", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'[]'" + }, + "exclude_patterns": { + "name": "exclude_patterns", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'[]'" + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'pending'" + }, + "remote_sha": { + "name": "remote_sha", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_checked_at": { + "name": "last_checked_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_check_error": { + "name": "last_check_error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_verified_at": { + "name": "last_verified_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "downloaded_at": { + "name": "downloaded_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "models_repo_uq": { + "name": "models_repo_uq", + "columns": [ + "repo_type", + "repo_id" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "worker_state": { + "name": "worker_state", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "instance_id": { + "name": "instance_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "pid": { + "name": "pid", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "hf_version": { + "name": "hf_version", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "models_dir_free_bytes": { + "name": "models_dir_free_bytes", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "models_dir_total_bytes": { + "name": "models_dir_total_bytes", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "started_at": { + "name": "started_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "heartbeat_at": { + "name": "heartbeat_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + } + }, + "views": {}, + "enums": {}, + "_meta": { + "schemas": {}, + "tables": {}, + "columns": {} + }, + "internal": { + "indexes": {} + } +} \ No newline at end of file diff --git a/drizzle/meta/_journal.json b/drizzle/meta/_journal.json index d25addd..2f2783e 100644 --- a/drizzle/meta/_journal.json +++ b/drizzle/meta/_journal.json @@ -15,6 +15,13 @@ "when": 1791207195702, "tag": "0001_worker_disk_space", "breakpoints": true + }, + { + "idx": 2, + "version": "6", + "when": 1791210991713, + "tag": "0002_worker_lease", + "breakpoints": true } ] } \ No newline at end of file diff --git a/eslint.config.mjs b/eslint.config.mjs index 05e726d..912c67d 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -12,6 +12,8 @@ const eslintConfig = defineConfig([ "out/**", "build/**", "next-env.d.ts", + // Bundled worker output + "dist/**", ]), ]); diff --git a/package-lock.json b/package-lock.json index 10306d0..fa88c0a 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "kaname", - "version": "0.2.0", + "version": "0.3.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "kaname", - "version": "0.2.0", + "version": "0.3.0", "dependencies": { "@base-ui/react": "^1.8.0", "@libsql/client": "^0.18.0", @@ -34,6 +34,7 @@ "concurrently": "^10.0.5", "dotenv-cli": "^11.0.0", "drizzle-kit": "^0.31.11", + "esbuild": "^0.25.12", "eslint": "^9", "eslint-config-next": "16.3.8", "tailwindcss": "^4", diff --git a/package.json b/package.json index 25593b0..8e745d0 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "kaname", - "version": "0.2.0", + "version": "0.3.0", "private": true, "scripts": { "dev": "concurrently -k -n web,worker -c blue,magenta \"npm:dev:web\" \"npm:dev:worker\"", @@ -13,7 +13,8 @@ "typecheck": "next typegen && tsc --noEmit", "db:generate": "drizzle-kit generate", "db:migrate": "dotenv -e .env -- tsx src/lib/db/migrate-cli.ts", - "test": "tsx --test \"src/**/*.test.ts\"" + "test": "tsx --test \"src/**/*.test.ts\"", + "build:worker": "esbuild src/worker/index.ts --bundle --platform=node --target=node24 --format=esm --packages=external --outfile=dist/worker.mjs" }, "dependencies": { "@base-ui/react": "^1.8.0", @@ -42,6 +43,7 @@ "concurrently": "^10.0.5", "dotenv-cli": "^11.0.0", "drizzle-kit": "^0.31.11", + "esbuild": "^0.25.12", "eslint": "^9", "eslint-config-next": "16.3.8", "tailwindcss": "^4", diff --git a/src/app/(app)/jobs/[id]/job-live.tsx b/src/app/(app)/jobs/[id]/job-live.tsx new file mode 100644 index 0000000..46f6cb0 --- /dev/null +++ b/src/app/(app)/jobs/[id]/job-live.tsx @@ -0,0 +1,148 @@ +"use client"; + +import Link from "next/link"; +import { useEffect, useRef, useState } from "react"; +import { cancelJob } from "@/components/job-actions"; +import { JobFilesTable } from "@/components/job-files-table"; +import { JobProgress } from "@/components/job-progress"; +import { Button } from "@/components/ui/button"; +import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; +import { useLive } from "@/hooks/use-live"; +import { formatDuration } from "@/lib/format"; +import { LocalTime } from "@/components/local-time"; +import type { JobSnapshot } from "@/lib/jobs"; + +const OPEN = ["queued", "downloading", "verifying"]; + +export function JobLive({ initial }: { initial: JobSnapshot }) { + const { snapshot, logs } = useLive({ job: initial.id }, true); + const job = snapshot?.jobs[0] ?? initial; + const files = snapshot?.files ?? []; + const open = OPEN.includes(job.state); + const [busy, setBusy] = useState(false); + + const logRef = useRef(null); + const [follow, setFollow] = useState(true); + useEffect(() => { + if (follow && logRef.current) logRef.current.scrollTop = logRef.current.scrollHeight; + }, [logs, follow]); + + // Tick once per second while running so the duration keeps counting. + const [now, setNow] = useState(() => Date.now()); + useEffect(() => { + if (job.finishedAt != null) return; + const t = setInterval(() => setNow(Date.now()), 1000); + return () => clearInterval(t); + }, [job.finishedAt]); + const duration = job.startedAt != null ? ((job.finishedAt ?? now) - job.startedAt) / 1000 : null; + + return ( +
+
+

+ {job.kind === "download" ? "Download" : job.kind} ·{" "} + + {job.repoId} + +

+ {open && ( + + )} +
+ + + + +
+
Created
+
+
Started
+
+ + {job.attempt > 1 ? ` (attempt ${job.attempt})` : ""} +
+
Finished
+
+
Duration
+
{formatDuration(duration)}
+ {job.exitCode != null && ( + <> +
Exit code
+
{job.exitCode}
+ + )} +
+ {job.errorMessage && ( +
+              {job.errorMessage}
+            
+ )} +
+
+ + {files.length > 0 && ( + + + Files + + + + )} + + + + Log +
+ + + Download full log + +
+
+ +
+ {logs.length === 0 ? ( + No output yet. + ) : ( + logs.map((l) => ( +
+ + {new Date(l.ts).toLocaleTimeString("en-GB")}{" "} + + {l.line} +
+ )) + )} +
+
+
+
+ ); +} diff --git a/src/app/(app)/jobs/[id]/page.tsx b/src/app/(app)/jobs/[id]/page.tsx new file mode 100644 index 0000000..1710330 --- /dev/null +++ b/src/app/(app)/jobs/[id]/page.tsx @@ -0,0 +1,12 @@ +import { notFound } from "next/navigation"; +import { getJob } from "@/lib/jobs"; +import { JobLive } from "./job-live"; + +export const dynamic = "force-dynamic"; + +export default async function JobPage({ params }: PageProps<"/jobs/[id]">) { + const { id } = await params; + const job = await getJob(id); + if (!job) notFound(); + return ; +} diff --git a/src/app/(app)/library-table.tsx b/src/app/(app)/library-table.tsx new file mode 100644 index 0000000..f658c77 --- /dev/null +++ b/src/app/(app)/library-table.tsx @@ -0,0 +1,75 @@ +"use client"; + +import Link from "next/link"; +import { JobProgress, JobStateBadge } from "@/components/job-progress"; +import { ModelStatusBadge } from "@/components/model-status-badge"; +import { Card } from "@/components/ui/card"; +import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"; +import { useLive } from "@/hooks/use-live"; +import { formatBytes, shortSha } from "@/lib/format"; +import { LocalTime } from "@/components/local-time"; +import type { JobSnapshot } from "@/lib/jobs"; +import type { LibraryRow } from "@/lib/library"; + +const OPEN = ["queued", "downloading", "verifying"]; + +export function LibraryTable({ rows }: { rows: LibraryRow[] }) { + const { snapshot } = useLive(); + const openJobs = new Map(); + for (const j of snapshot?.jobs ?? []) { + if (OPEN.includes(j.state) && !openJobs.has(j.modelId)) openJobs.set(j.modelId, j); + } + + return ( + + + + + Repository + Selection + Size + Pinned + Downloaded + Status + + + + {rows.map((r) => { + const job = openJobs.get(r.id); + return ( + + + + {r.repoId} + + + + {r.quants.length > 0 ? r.quants.join(", ") : `${r.fileCount} files`} + + {formatBytes(r.totalBytes)} + + + {r.trackedRevision}@{shortSha(r.pinnedSha)} + + + + + + + {job ? ( + + + {job.state !== "queued" && } + + ) : ( + + )} + + + ); + })} + +
+
+ ); +} diff --git a/src/app/(app)/models/[id]/model-live.tsx b/src/app/(app)/models/[id]/model-live.tsx new file mode 100644 index 0000000..cf83e25 --- /dev/null +++ b/src/app/(app)/models/[id]/model-live.tsx @@ -0,0 +1,136 @@ +"use client"; + +import Link from "next/link"; +import { useState } from "react"; +import { cancelJob, startDownload } from "@/components/job-actions"; +import { JobFilesTable } from "@/components/job-files-table"; +import { JobProgress, JobStateBadge } from "@/components/job-progress"; +import { Button } from "@/components/ui/button"; +import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"; +import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"; +import { useLive } from "@/hooks/use-live"; +import type { ModelStatus } from "@/lib/db/schema"; +import { formatBytes } from "@/lib/format"; +import { LocalTime } from "@/components/local-time"; +import type { JobSnapshot } from "@/lib/jobs"; + +const OPEN = ["queued", "downloading", "verifying"]; + +export function ModelLive({ modelId, status }: { modelId: string; status: ModelStatus }) { + const { snapshot } = useLive({ model: modelId }); + const [busy, setBusy] = useState(false); + const jobs = snapshot?.jobs ?? []; + const latest = jobs[0] as JobSnapshot | undefined; + const open = latest && OPEN.includes(latest.state) ? latest : undefined; + const workerOffline = snapshot && !snapshot.worker.online; + + async function run(fn: () => Promise) { + setBusy(true); + try { + await fn(); + } finally { + setBusy(false); + } + } + + return ( + <> + + + + Download + {latest && } + + + {open + ? open.state === "queued" + ? workerOffline + ? "Queued, but the worker is offline." + : "Queued, waiting for a free download slot." + : "Running in the background; you can close this page." + : status === "ready" + ? "All selected files are present." + : "Downloads the selected files at the pinned SHA."} + + + + {latest && !(latest.state === "completed" && status === "ready") && } + {latest?.errorMessage && latest.state === "failed" && ( +
+              {latest.errorMessage}
+            
+ )} +
+ {open ? ( + + ) : ( + status !== "ready" && + snapshot && ( + + ) + )} + {latest && ( + + View log + + )} +
+
+ {open && snapshot && snapshot.files.length > 0 && } +
+ + {jobs.length > 0 && ( + + + Jobs + + + + + Started + Kind + State + Size + Finished + + + + {jobs.map((j) => ( + + + + + + + + {j.kind} + {j.purpose && j.purpose !== "initial" ? ` (${j.purpose})` : ""} + + + + + {formatBytes(j.totalBytes)} + + + + + ))} + +
+
+ )} + + ); +} diff --git a/src/app/(app)/models/[id]/page.tsx b/src/app/(app)/models/[id]/page.tsx index c1bdb89..4bdd1a2 100644 --- a/src/app/(app)/models/[id]/page.tsx +++ b/src/app/(app)/models/[id]/page.tsx @@ -2,8 +2,10 @@ import { notFound } from "next/navigation"; import { ModelStatusBadge } from "@/components/model-status-badge"; import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"; import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"; -import { formatBytes, formatDate } from "@/lib/format"; +import { formatBytes } from "@/lib/format"; +import { LocalTime } from "@/components/local-time"; import { getModel } from "@/lib/library"; +import { ModelLive } from "./model-live"; import { RemoveModelButton } from "./remove-model-button"; export const dynamic = "force-dynamic"; @@ -27,7 +29,6 @@ export default async function ModelPage({ params }: PageProps<"/models/[id]">) { Details - Downloading starts in the next milestone.
@@ -53,11 +54,13 @@ export default async function ModelPage({ params }: PageProps<"/models/[id]">) {
Exclude
{model.excludePatterns.join(", ") || "–"}
Added
-
{formatDate(model.createdAt)}
+
+ + diff --git a/src/app/(app)/models/new/add-model-form.tsx b/src/app/(app)/models/new/add-model-form.tsx index 1df538b..4a8df5f 100644 --- a/src/app/(app)/models/new/add-model-form.tsx +++ b/src/app/(app)/models/new/add-model-form.tsx @@ -126,7 +126,7 @@ export function AddModelForm({ freeBytes }: { freeBytes: number | null }) { include: [...includePatterns, ...[...checked].sort().map(escapeGlob)], exclude: excludePatterns, }); - toast.success(`${result.repoId} added to the library`); + toast.success(`${result.repoId} added, download queued`); router.push(`/models/${id}`); } catch (err) { toast.error(err instanceof Error ? err.message : String(err)); @@ -331,7 +331,7 @@ export function AddModelForm({ freeBytes }: { freeBytes: number | null }) { onClick={addToLibrary} disabled={selected.length === 0 || submitting || !!result.existingModelId} > - {submitting ? "Adding…" : "Add to library"} + {submitting ? "Adding…" : "Add & download"} diff --git a/src/app/(app)/page.tsx b/src/app/(app)/page.tsx index 198781d..9b710d2 100644 --- a/src/app/(app)/page.tsx +++ b/src/app/(app)/page.tsx @@ -1,10 +1,8 @@ import Link from "next/link"; -import { ModelStatusBadge } from "@/components/model-status-badge"; import { buttonVariants } from "@/components/ui/button"; import { Card, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"; -import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"; -import { formatBytes, formatDate, shortSha } from "@/lib/format"; import { listLibrary } from "@/lib/library"; +import { LibraryTable } from "./library-table"; export const dynamic = "force-dynamic"; @@ -28,46 +26,7 @@ export default async function LibraryPage() { ) : ( - - - - - Repository - Selection - Size - Pinned - Downloaded - Status - - - - {rows.map((r) => ( - - - - {r.repoId} - - - - {r.quants.length > 0 ? r.quants.join(", ") : `${r.fileCount} files`} - - {formatBytes(r.totalBytes)} - - - {r.trackedRevision}@{shortSha(r.pinnedSha)} - - - - {formatDate(r.downloadedAt)} - - - - - - ))} - -
-
+ )} ); diff --git a/src/app/api/jobs/[id]/cancel/route.ts b/src/app/api/jobs/[id]/cancel/route.ts new file mode 100644 index 0000000..acc209d --- /dev/null +++ b/src/app/api/jobs/[id]/cancel/route.ts @@ -0,0 +1,15 @@ +import { NextResponse } from "next/server"; +import { withAuth } from "@/lib/api-auth"; +import { apiError } from "@/lib/api-errors"; +import { JobError, requestCancel } from "@/lib/jobs"; + +export const POST = withAuth>(async (_req, { params }) => { + const { id } = await params; + try { + await requestCancel(id); + return NextResponse.json({ ok: true }, { status: 202 }); + } catch (err) { + if (err instanceof JobError) return apiError(err.status, err.code, err.message); + throw err; + } +}); diff --git a/src/app/api/jobs/[id]/log/route.ts b/src/app/api/jobs/[id]/log/route.ts new file mode 100644 index 0000000..0ca9ad8 --- /dev/null +++ b/src/app/api/jobs/[id]/log/route.ts @@ -0,0 +1,16 @@ +import { withAuth } from "@/lib/api-auth"; +import { apiError } from "@/lib/api-errors"; +import { fullJobLog, getJob } from "@/lib/jobs"; + +/** Full job log as a plain-text download. */ +export const GET = withAuth>(async (_req, { params }) => { + const { id } = await params; + const job = await getJob(id); + if (!job) return apiError(404, "not_found", "Job not found."); + return new Response(await fullJobLog(id), { + headers: { + "Content-Type": "text/plain; charset=utf-8", + "Content-Disposition": `attachment; filename="job-${id}.log"`, + }, + }); +}); diff --git a/src/app/api/models/[id]/download/route.ts b/src/app/api/models/[id]/download/route.ts new file mode 100644 index 0000000..30f4bf2 --- /dev/null +++ b/src/app/api/models/[id]/download/route.ts @@ -0,0 +1,15 @@ +import { NextResponse } from "next/server"; +import { withAuth } from "@/lib/api-auth"; +import { apiError } from "@/lib/api-errors"; +import { JobError, queueDownload } from "@/lib/jobs"; + +/** Queue a download of the model's selected files at its pinned SHA. */ +export const POST = withAuth>(async (_req, { params }) => { + const { id } = await params; + try { + return NextResponse.json(await queueDownload(id), { status: 201 }); + } catch (err) { + if (err instanceof JobError) return apiError(err.status, err.code, err.message); + throw err; + } +}); diff --git a/src/app/api/models/route.ts b/src/app/api/models/route.ts index 0d9ce70..bf5aa35 100644 --- a/src/app/api/models/route.ts +++ b/src/app/api/models/route.ts @@ -3,6 +3,7 @@ import { z } from "zod"; import { withAuth } from "@/lib/api-auth"; import { apiError, handleApiError } from "@/lib/api-errors"; import { REPO_ID_RE, SHA_RE } from "@/lib/hub/client"; +import { queueDownload } from "@/lib/jobs"; import { addModel, ModelError } from "@/lib/models"; const Body = z.object({ @@ -11,9 +12,10 @@ const Body = z.object({ sha: z.string().regex(SHA_RE, "must be a full 40-character commit SHA"), include: z.array(z.string().min(1).max(1024)).max(10_000), exclude: z.array(z.string().min(1).max(1024)).max(1_000), + download: z.boolean().default(true), }); -/** Add a model to the library, pinned to the SHA the user reviewed. */ +/** Add a model to the library, pinned to the SHA the user reviewed, and queue its download. */ export const POST = withAuth(async (req) => { try { const body = Body.parse(await req.json()); @@ -23,7 +25,8 @@ export const POST = withAuth(async (req) => { sha: body.sha, rule: { include: body.include, exclude: body.exclude }, }); - return NextResponse.json({ id }, { status: 201 }); + const job = body.download ? await queueDownload(id) : null; + return NextResponse.json({ id, jobId: job?.jobId ?? null }, { status: 201 }); } catch (err) { if (err instanceof ModelError) return apiError(err.status, err.code, err.message); return handleApiError(err); diff --git a/src/app/api/stream/route.ts b/src/app/api/stream/route.ts new file mode 100644 index 0000000..7fe7e55 --- /dev/null +++ b/src/app/api/stream/route.ts @@ -0,0 +1,97 @@ +import { withAuth } from "@/lib/api-auth"; +import { getJob, listJobFiles, listJobLogs, listLiveJobs, listModelJobs } from "@/lib/jobs"; +import { getWorkerStatus } from "@/lib/worker-status"; + +export const dynamic = "force-dynamic"; + +const INTERVAL_MS = 1_000; +const KEEPALIVE_MS = 15_000; + +/** + * Server-Sent Events with live job state, polled from the DB once per second. + * ?model= jobs of one model (+ files of its newest job) + * ?job= one job with per-file progress and incremental log lines + * (none) open and recently finished jobs (library view) + * Events: "snapshot" (only when something changed) and "logs" (new lines). + */ +export const GET = withAuth(async (req) => { + const url = new URL(req.url); + const modelId = url.searchParams.get("model"); + const jobId = url.searchParams.get("job"); + let logCursor = Number(url.searchParams.get("logAfter") ?? 0) || 0; + + const encoder = new TextEncoder(); + const signal = req.signal; + + const stream = new ReadableStream({ + async start(controller) { + let last = ""; + let lastWrite = Date.now(); + const write = (chunk: string) => { + controller.enqueue(encoder.encode(chunk)); + lastWrite = Date.now(); + }; + const send = (event: string, data: unknown) => write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`); + + try { + write("retry: 3000\n\n"); + while (!signal.aborted) { + const snapshot = await buildSnapshot(modelId, jobId); + const serialized = JSON.stringify(snapshot); + if (serialized !== last) { + send("snapshot", snapshot); + last = serialized; + } + if (jobId) { + const lines = await listJobLogs(jobId, logCursor); + if (lines.length > 0) { + logCursor = lines[lines.length - 1].id; + send("logs", lines); + } + } + if (Date.now() - lastWrite > KEEPALIVE_MS) write(": keepalive\n\n"); + await sleep(INTERVAL_MS, signal); + } + } catch { + // client went away or the stream was closed + } finally { + try { + controller.close(); + } catch {} + } + }, + }); + + return new Response(stream, { + headers: { + "Content-Type": "text/event-stream; charset=utf-8", + "Cache-Control": "no-cache, no-transform", + Connection: "keep-alive", + "X-Accel-Buffering": "no", + }, + }); +}); + +async function buildSnapshot(modelId: string | null, jobId: string | null) { + const worker = await getWorkerStatus(); + if (jobId) { + const job = await getJob(jobId); + return { worker, jobs: job ? [job] : [], files: job ? await listJobFiles(jobId) : [] }; + } + if (modelId) { + const jobs = await listModelJobs(modelId); + const files = jobs[0] ? await listJobFiles(jobs[0].id) : []; + return { worker, jobs, files }; + } + return { worker, jobs: await listLiveJobs(), files: [] }; +} + +function sleep(ms: number, signal: AbortSignal) { + return new Promise((resolve) => { + const t = setTimeout(resolve, ms); + signal.addEventListener("abort", () => { + clearTimeout(t); + resolve(); + }); + }); +} diff --git a/src/components/job-actions.ts b/src/components/job-actions.ts new file mode 100644 index 0000000..f6d54eb --- /dev/null +++ b/src/components/job-actions.ts @@ -0,0 +1,19 @@ +"use client"; + +import { toast } from "sonner"; + +async function post(url: string): Promise { + const res = await fetch(url, { method: "POST" }); + if (res.ok) return true; + const body = await res.json().catch(() => ({})); + toast.error(body.error?.message ?? `Request failed (${res.status})`); + return false; +} + +export async function startDownload(modelId: string) { + if (await post(`/api/models/${modelId}/download`)) toast.success("Download queued"); +} + +export async function cancelJob(jobId: string) { + if (await post(`/api/jobs/${jobId}/cancel`)) toast.info("Cancelling…"); +} diff --git a/src/components/job-files-table.tsx b/src/components/job-files-table.tsx new file mode 100644 index 0000000..b93751b --- /dev/null +++ b/src/components/job-files-table.tsx @@ -0,0 +1,41 @@ +import { Progress } from "@/components/ui/progress"; +import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"; +import { formatBytes, percent } from "@/lib/format"; +import type { JobFileSnapshot } from "@/lib/jobs"; + +/** Per-file progress of one job. */ +export function JobFilesTable({ files }: { files: JobFileSnapshot[] }) { + return ( + + + + File + Progress + Size + + + + {files.map((f) => { + const pct = percent(f.doneBytes, f.expectedBytes); + return ( + + {f.path} + +
+ + + {f.state === "failed" ? "missing" : `${pct.toFixed(0)}%`} + +
+
+ + {f.doneBytes < f.expectedBytes && f.doneBytes > 0 ? `${formatBytes(f.doneBytes)} / ` : ""} + {formatBytes(f.expectedBytes)} + +
+ ); + })} +
+
+ ); +} diff --git a/src/components/job-progress.tsx b/src/components/job-progress.tsx new file mode 100644 index 0000000..a9ad896 --- /dev/null +++ b/src/components/job-progress.tsx @@ -0,0 +1,42 @@ +import { Badge } from "@/components/ui/badge"; +import { Progress } from "@/components/ui/progress"; +import { formatBytes, formatDuration, formatSpeed, percent } from "@/lib/format"; +import type { JobSnapshot } from "@/lib/jobs"; + +const STATE_VARIANT: Record = { + queued: "outline", + downloading: "secondary", + verifying: "secondary", + completed: "default", + failed: "destructive", + cancelled: "outline", + interrupted: "destructive", +}; + +export function JobStateBadge({ job }: { job: Pick }) { + const label = job.cancelRequested && !["cancelled", "completed", "failed"].includes(job.state) ? "cancelling" : job.state; + return {label}; +} + +/** Overall progress line for a job: bar, bytes, %, speed, ETA. */ +export function JobProgress({ job, compact = false }: { job: JobSnapshot; compact?: boolean }) { + const pct = percent(job.doneBytes, job.totalBytes); + const running = job.state === "downloading" || job.state === "verifying"; + return ( +
+ +
+ {!compact && } + + {formatBytes(job.doneBytes)} / {formatBytes(job.totalBytes)} · {pct.toFixed(1)}% + + {running && ( + <> + {formatSpeed(job.speedBps)} + ETA {formatDuration(job.etaSeconds)} + + )} +
+
+ ); +} diff --git a/src/components/local-time.tsx b/src/components/local-time.tsx new file mode 100644 index 0000000..53c6222 --- /dev/null +++ b/src/components/local-time.tsx @@ -0,0 +1,25 @@ +"use client"; + +import { useSyncExternalStore } from "react"; +import { formatDate } from "@/lib/format"; + +const subscribe = () => () => {}; + +/** + * Date/time in the browser's timezone. Renders empty during SSR (the server, e.g. a UTC container, + * would format in its own timezone) and fills in on the client. + */ +export function LocalTime({ value }: { value: Date | string | number | null | undefined }) { + const isClient = useSyncExternalStore( + subscribe, + () => true, + () => false, + ); + if (value == null) return <>–; + const d = new Date(value); + return ( + + ); +} diff --git a/src/components/ui/progress.tsx b/src/components/ui/progress.tsx new file mode 100644 index 0000000..7f3ee7d --- /dev/null +++ b/src/components/ui/progress.tsx @@ -0,0 +1,82 @@ +"use client" + +import { Progress as ProgressPrimitive } from "@base-ui/react/progress" +import { cn } from "cn" + +function Progress({ + className, + children, + value, + ...props +}: ProgressPrimitive.Root.Props) { + return ( + + {children} + + + + + ) +} + +function ProgressTrack({ className, ...props }: ProgressPrimitive.Track.Props) { + return ( + + ) +} + +function ProgressIndicator({ + className, + ...props +}: ProgressPrimitive.Indicator.Props) { + return ( + + ) +} + +function ProgressLabel({ className, ...props }: ProgressPrimitive.Label.Props) { + return ( + + ) +} + +function ProgressValue({ className, ...props }: ProgressPrimitive.Value.Props) { + return ( + + ) +} + +export { + Progress, + ProgressTrack, + ProgressIndicator, + ProgressLabel, + ProgressValue, +} diff --git a/src/hooks/use-live.ts b/src/hooks/use-live.ts new file mode 100644 index 0000000..a714ee9 --- /dev/null +++ b/src/hooks/use-live.ts @@ -0,0 +1,58 @@ +"use client"; + +import { useRouter } from "next/navigation"; +import { useEffect, useRef, useState } from "react"; +import type { JobFileSnapshot, JobSnapshot, LogLine } from "@/lib/jobs"; +import type { WorkerStatus } from "@/lib/worker-status"; + +export type LiveSnapshot = { worker: WorkerStatus; jobs: JobSnapshot[]; files: JobFileSnapshot[] }; + +export const TERMINAL_STATES = ["completed", "failed", "cancelled", "interrupted"]; +const MAX_LOG_LINES = 5000; + +/** + * Subscribe to /api/stream. Re-renders on every snapshot; refreshes server components + * (model status, library) when a job reaches a terminal state. + */ +export function useLive(query: { model?: string; job?: string } = {}, withLogs = false) { + const router = useRouter(); + const [snapshot, setSnapshot] = useState(null); + const [logs, setLogs] = useState([]); + const [connected, setConnected] = useState(false); + const states = useRef(new Map()); + + const params = new URLSearchParams(); + if (query.model) params.set("model", query.model); + if (query.job) params.set("job", query.job); + const url = `/api/stream${params.size ? `?${params}` : ""}`; + + useEffect(() => { + const es = new EventSource(url); + es.onopen = () => setConnected(true); + es.onerror = () => setConnected(false); + es.addEventListener("snapshot", (e) => { + const snap = JSON.parse((e as MessageEvent).data) as LiveSnapshot; + let finished = false; + for (const j of snap.jobs) { + const prev = states.current.get(j.id); + if (prev && prev !== j.state && TERMINAL_STATES.includes(j.state)) finished = true; + states.current.set(j.id, j.state); + } + setSnapshot(snap); + if (finished) router.refresh(); + }); + if (withLogs) { + es.addEventListener("logs", (e) => { + const lines = JSON.parse((e as MessageEvent).data) as LogLine[]; + setLogs((prev) => { + const seen = prev.length ? prev[prev.length - 1].id : 0; + const merged = prev.concat(lines.filter((l) => l.id > seen)); + return merged.length > MAX_LOG_LINES ? merged.slice(-MAX_LOG_LINES) : merged; + }); + }); + } + return () => es.close(); + }, [url, withLogs, router]); + + return { snapshot, logs, connected }; +} diff --git a/src/lib/db/schema.ts b/src/lib/db/schema.ts index c2ab499..a5e9c3f 100644 --- a/src/lib/db/schema.ts +++ b/src/lib/db/schema.ts @@ -239,6 +239,8 @@ export const jobLogs = sqliteTable( export const workerState = sqliteTable("worker_state", { id: text("id").primaryKey(), // "worker" + /** Random per process; the row acts as a lease so only one worker runs at a time. */ + instanceId: text("instance_id"), pid: integer("pid"), hfVersion: text("hf_version"), /** Free/total bytes on the filesystem holding MODELS_DIR (the web app has no access to it). */ diff --git a/src/lib/env.ts b/src/lib/env.ts index 2564a18..9379781 100644 --- a/src/lib/env.ts +++ b/src/lib/env.ts @@ -12,6 +12,16 @@ const coreSchema = z.object({ DATABASE_URL: z.preprocess(emptyToUndefined, z.string().default("file:/data/app.db")), MAX_CONCURRENT_DOWNLOADS: z.preprocess(emptyToUndefined, z.coerce.number().int().min(1).default(1)), UPDATE_CHECK_INTERVAL_HOURS: z.preprocess(emptyToUndefined, z.coerce.number().min(0).default(12)), + /** + * Passed to the hf CLI. Default on: with Xet the partial file only grows in large bursts, so + * progress from bytes on disk is useless; plain HTTP writes steadily. Set to 0 to use Xet. + */ + HF_HUB_DISABLE_XET: z.preprocess( + (v) => (v === undefined || v === "" ? true : !["0", "false", "no", "off"].includes(String(v).toLowerCase())), + z.boolean(), + ), + /** hf CLI home (token cache, Xet logs/cache). Not the model storage. */ + HF_HOME: z.preprocess(emptyToUndefined, z.string().optional()), }); const authSchema = z.object({ diff --git a/src/lib/format.ts b/src/lib/format.ts index ea05c5d..1fe7667 100644 --- a/src/lib/format.ts +++ b/src/lib/format.ts @@ -13,6 +13,25 @@ export function formatBytes(bytes: number | null | undefined): string { return `${v >= 100 ? v.toFixed(0) : v >= 10 ? v.toFixed(1) : v.toFixed(2)} ${UNITS[i]}`; } +export function formatSpeed(bps: number | null | undefined): string { + return bps == null ? "–" : `${formatBytes(Math.round(bps))}/s`; +} + +/** 3725 -> "1h 2m", 95 -> "1m 35s". */ +export function formatDuration(seconds: number | null | undefined): string { + if (seconds == null || !Number.isFinite(seconds)) return "–"; + const s = Math.max(0, Math.round(seconds)); + const h = Math.floor(s / 3600); + const m = Math.floor((s % 3600) / 60); + if (h > 0) return `${h}h ${m}m`; + if (m > 0) return `${m}m ${s % 60}s`; + return `${s}s`; +} + +export function percent(done: number, total: number): number { + return total > 0 ? Math.min(100, (done / total) * 100) : 0; +} + export function shortSha(sha: string | null | undefined): string { return sha ? sha.slice(0, 7) : "–"; } diff --git a/src/lib/jobs.ts b/src/lib/jobs.ts new file mode 100644 index 0000000..af0a704 --- /dev/null +++ b/src/lib/jobs.ts @@ -0,0 +1,219 @@ +import "server-only"; +import { and, asc, desc, eq, gt, gte, inArray, isNull, or } from "drizzle-orm"; +import { ulid } from "ulid"; +import { db } from "@/lib/db/client"; +import { + ACTIVE_JOB_STATES, + type JobPurpose, + jobFiles, + jobLogs, + jobs, + modelFiles, + models, +} from "@/lib/db/schema"; + +export class JobError extends Error { + constructor( + public code: "not_found" | "busy" | "nothing_selected" | "not_cancellable", + message: string, + public status: number, + ) { + super(message); + } +} + +const OPEN_STATES = ["queued", ...ACTIVE_JOB_STATES] as const; +const INSERT_CHUNK = 500; + +/** Queue a download of all selected files of a model at its pinned SHA. */ +export async function queueDownload(modelId: string, purpose: JobPurpose = "initial"): Promise<{ jobId: string }> { + const d = db(); + const model = await d.query.models.findFirst({ where: eq(models.id, modelId) }); + if (!model) throw new JobError("not_found", "Model not found.", 404); + + const open = await d.query.jobs.findFirst({ + columns: { id: true }, + where: and(eq(jobs.modelId, modelId), inArray(jobs.state, [...OPEN_STATES])), + }); + if (open) throw new JobError("busy", "This model already has a queued or running job.", 409); + + const files = await d + .select({ id: modelFiles.id, path: modelFiles.path, size: modelFiles.size }) + .from(modelFiles) + .where(and(eq(modelFiles.modelId, modelId), eq(modelFiles.selected, true))) + .orderBy(asc(modelFiles.path)); + if (files.length === 0) throw new JobError("nothing_selected", "No files selected for this model.", 400); + + const jobId = ulid(); + const rows = files.map((f) => ({ jobId, modelFileId: f.id, path: f.path, expectedBytes: f.size })); + await d.batch([ + d.insert(jobs).values({ + id: jobId, + modelId, + kind: "download", + purpose, + targetSha: model.pinnedSha, + totalBytes: files.reduce((s, f) => s + f.size, 0), + }), + ...chunk(rows, INSERT_CHUNK).map((c) => d.insert(jobFiles).values(c)), + d.update(models).set({ status: "downloading" }).where(eq(models.id, modelId)), + ]); + return { jobId }; +} + +/** Ask the worker to stop a job. Queued jobs are cancelled by the worker on its next tick. */ +export async function requestCancel(jobId: string): Promise { + const res = await db() + .update(jobs) + .set({ cancelRequestedAt: new Date() }) + .where(and(eq(jobs.id, jobId), inArray(jobs.state, [...OPEN_STATES]), isNull(jobs.cancelRequestedAt))) + .returning({ id: jobs.id }); + if (res.length === 0) { + const job = await db().query.jobs.findFirst({ columns: { id: true }, where: eq(jobs.id, jobId) }); + if (!job) throw new JobError("not_found", "Job not found.", 404); + throw new JobError("not_cancellable", "This job is not running anymore.", 409); + } +} + +// --------------------------------------------------------------------------- +// Read models for the UI +// --------------------------------------------------------------------------- + +export type JobSnapshot = { + id: string; + modelId: string; + repoId: string; + kind: string; + purpose: string | null; + state: string; + attempt: number; + totalBytes: number; + doneBytes: number; + speedBps: number | null; + etaSeconds: number | null; + exitCode: number | null; + errorCode: string | null; + errorMessage: string | null; + cancelRequested: boolean; + createdAt: number; + startedAt: number | null; + finishedAt: number | null; +}; + +export type JobFileSnapshot = { + modelFileId: string; + path: string; + expectedBytes: number; + doneBytes: number; + state: string; +}; + +export type LogLine = { id: number; ts: number; stream: string; line: string }; + +const jobColumns = { + id: jobs.id, + modelId: jobs.modelId, + repoId: models.repoId, + kind: jobs.kind, + purpose: jobs.purpose, + state: jobs.state, + attempt: jobs.attempt, + totalBytes: jobs.totalBytes, + doneBytes: jobs.doneBytes, + speedBps: jobs.speedBps, + etaSeconds: jobs.etaSeconds, + exitCode: jobs.exitCode, + errorCode: jobs.errorCode, + errorMessage: jobs.errorMessage, + cancelRequestedAt: jobs.cancelRequestedAt, + createdAt: jobs.createdAt, + startedAt: jobs.startedAt, + finishedAt: jobs.finishedAt, +}; + +type JobRow = Omit & { repoId: string }; + +function toSnapshot(r: JobRow): JobSnapshot { + const { cancelRequestedAt, createdAt, startedAt, finishedAt, ...rest } = r; + return { + ...rest, + cancelRequested: cancelRequestedAt != null, + createdAt: createdAt.getTime(), + startedAt: startedAt?.getTime() ?? null, + finishedAt: finishedAt?.getTime() ?? null, + }; +} + +/** Open jobs plus jobs that finished in the last few minutes (so the UI sees the final state). */ +export async function listLiveJobs(): Promise { + const recent = new Date(Date.now() - 5 * 60_000); + const rows = await db() + .select(jobColumns) + .from(jobs) + .innerJoin(models, eq(models.id, jobs.modelId)) + .where(or(inArray(jobs.state, [...OPEN_STATES]), gte(jobs.finishedAt, recent))) + .orderBy(desc(jobs.createdAt)); + return rows.map(toSnapshot); +} + +export async function listModelJobs(modelId: string, limit = 10): Promise { + const rows = await db() + .select(jobColumns) + .from(jobs) + .innerJoin(models, eq(models.id, jobs.modelId)) + .where(eq(jobs.modelId, modelId)) + .orderBy(desc(jobs.createdAt)) + .limit(limit); + return rows.map(toSnapshot); +} + +export async function getJob(jobId: string): Promise { + const [row] = await db() + .select(jobColumns) + .from(jobs) + .innerJoin(models, eq(models.id, jobs.modelId)) + .where(eq(jobs.id, jobId)); + return row ? toSnapshot(row) : null; +} + +export async function listJobFiles(jobId: string): Promise { + return db() + .select({ + modelFileId: jobFiles.modelFileId, + path: jobFiles.path, + expectedBytes: jobFiles.expectedBytes, + doneBytes: jobFiles.doneBytes, + state: jobFiles.state, + }) + .from(jobFiles) + .where(eq(jobFiles.jobId, jobId)) + .orderBy(asc(jobFiles.path)); +} + +/** Log lines after `afterId`; on first load (afterId 0) only the last `tail` lines. */ +export async function listJobLogs(jobId: string, afterId: number, tail = 1000): Promise { + const d = db(); + const rows = + afterId > 0 + ? await d + .select() + .from(jobLogs) + .where(and(eq(jobLogs.jobId, jobId), gt(jobLogs.id, afterId))) + .orderBy(asc(jobLogs.id)) + .limit(5000) + : ( + await d.select().from(jobLogs).where(eq(jobLogs.jobId, jobId)).orderBy(desc(jobLogs.id)).limit(tail) + ).reverse(); + return rows.map((r) => ({ id: r.id, ts: r.ts.getTime(), stream: r.stream, line: r.line })); +} + +export async function fullJobLog(jobId: string): Promise { + const rows = await db().select().from(jobLogs).where(eq(jobLogs.jobId, jobId)).orderBy(asc(jobLogs.id)); + return rows.map((r) => `${r.ts.toISOString()} [${r.stream}] ${r.line}`).join("\n") + "\n"; +} + +function chunk(items: T[], size: number): T[][] { + const out: T[][] = []; + for (let i = 0; i < items.length; i += size) out.push(items.slice(i, i + size)); + return out; +} diff --git a/src/worker/download.ts b/src/worker/download.ts new file mode 100644 index 0000000..bcb2583 --- /dev/null +++ b/src/worker/download.ts @@ -0,0 +1,402 @@ +import { type ChildProcess, spawn } from "node:child_process"; +import { mkdir, statfs } from "node:fs/promises"; +import { and, eq, inArray } from "drizzle-orm"; +import { db } from "@/lib/db/client"; +import { + type JobErrorCode, + type JobState, + jobFiles, + jobs, + modelFiles, + models, +} from "@/lib/db/schema"; +import { coreEnv } from "@/lib/env"; +import { formatBytes } from "@/lib/format"; +import { escapeGlob } from "@/lib/selection"; +import { + bytesOnDisk, + type ExpectedFile, + listIncomplete, + modelDir, + removeStaleIncomplete, +} from "./hf-layout"; +import { JobLog } from "./job-log"; +import { log } from "./log"; +import { settleModelStatus } from "./model-status"; +import { SpeedMeter } from "./speed"; + +const SAMPLE_MS = 1_000; +const KILL_GRACE_MS = 10_000; + +/** Environment variables passed through to hf (everything else, e.g. AUTH_SECRET, is withheld). */ +const PASSTHROUGH_ENV = [ + "PATH", "HOME", "USER", "LANG", "LC_ALL", "TZ", "TMPDIR", + "SYSTEMROOT", "USERPROFILE", "APPDATA", "LOCALAPPDATA", "TEMP", "TMP", "PATHEXT", "COMSPEC", + "HTTP_PROXY", "HTTPS_PROXY", "NO_PROXY", "http_proxy", "https_proxy", "no_proxy", + "SSL_CERT_FILE", "REQUESTS_CA_BUNDLE", "HF_ENDPOINT", +]; + +type Job = typeof jobs.$inferSelect; +type Model = typeof models.$inferSelect; +type FileRow = { + modelFileId: string; + path: string; + expectedBytes: number; + doneBytes: number; + lfsSha256: string | null; + blobOid: string | null; +}; + +type Outcome = + | { state: "completed" } + | { state: "cancelled" | "interrupted"; message: string } + | { state: "failed"; code: JobErrorCode; message: string; exitCode?: number | null }; + +export class DownloadRunner { + private child?: ChildProcess; + private stopReason?: "cancelled" | "interrupted"; + private killTimer?: NodeJS.Timeout; + private jobLog: JobLog; + + constructor( + private job: Job, + private model: Model, + private files: FileRow[], + ) { + this.jobLog = new JobLog(job.id, [coreEnv().HF_TOKEN ?? ""]); + } + + get jobId() { + return this.job.id; + } + + get modelId() { + return this.model.id; + } + + /** User cancel: stop hf, keep completed files. */ + cancel() { + this.stop("cancelled"); + } + + /** Worker shutdown: stop hf, job can be resumed later. */ + interrupt() { + this.stop("interrupted"); + } + + private stop(reason: "cancelled" | "interrupted") { + if (this.stopReason) return; + this.stopReason = reason; + this.jobLog.system(reason === "cancelled" ? "Cancel requested, stopping hf…" : "Worker shutting down, stopping hf…"); + if (!this.child || this.child.exitCode !== null) return; + killTree(this.child, "SIGTERM"); + this.killTimer = setTimeout(() => { + if (this.child && this.child.exitCode === null) killTree(this.child, "SIGKILL"); + }, KILL_GRACE_MS); + } + + async run(): Promise { + const outcome = await this.execute().catch( + (err): Outcome => ({ + state: "failed", + code: "unknown", + message: `Internal worker error: ${err instanceof Error ? err.message : String(err)}`, + }), + ); + clearTimeout(this.killTimer); + if (outcome.state !== "completed") await this.removePartials(); + await this.finish(outcome); + } + + /** hf can't resume partial files, so free their space as soon as hf has exited. */ + private async removePartials() { + if (this.child && this.child.exitCode === null && this.child.signalCode === null) return; // still running + try { + const dir = modelDir(coreEnv().MODELS_DIR, this.model.localPath); + const removed = await removeStaleIncomplete(dir); + if (removed.count > 0) { + this.jobLog.system( + `Removed ${removed.count} partial file(s) (${formatBytes(removed.bytes)}); hf restarts unfinished files from the beginning.`, + ); + } + } catch (err) { + log.error(`could not remove partial files for job ${this.job.id}`, err); + } + } + + private async execute(): Promise { + const env = coreEnv(); + const dir = modelDir(env.MODELS_DIR, this.model.localPath); + const expected: ExpectedFile[] = this.files.map((f) => ({ + path: f.path, + size: f.expectedBytes, + etags: [f.lfsSha256, f.blobOid].filter((x): x is string => !!x), + })); + + await mkdir(dir, { recursive: true }); + this.jobLog.system( + `Attempt ${this.job.attempt}: ${this.model.repoId} @ ${this.job.targetSha}, ${this.files.length} file(s), ${formatBytes(this.job.totalBytes)}`, + ); + + // hf never resumes a partial file; leftovers from earlier runs only waste space. + const stale = await removeStaleIncomplete(dir); + if (stale.count > 0) { + this.jobLog.system(`Removed ${stale.count} partial file(s) from an earlier run (${formatBytes(stale.bytes)}).`); + } + + const initial = await this.sample(dir, expected); + const remaining = expected.reduce((s, f, i) => s + (initial[i].complete ? 0 : f.size), 0); + const doneCount = initial.filter((p) => p.complete).length; + if (doneCount > 0) this.jobLog.system(`${doneCount} file(s) already complete, hf will skip them.`); + + const free = await freeBytes(dir); + if (free != null && remaining > free) { + return { + state: "failed", + code: "disk_full", + message: `Not enough disk space: ${formatBytes(remaining)} still needed, ${formatBytes(free)} free on the models volume.`, + }; + } + if (this.stopReason) return { state: this.stopReason, message: "Stopped before hf started." }; + + const exit = await this.spawnHf(dir, expected); + if (this.stopReason) { + return { + state: this.stopReason, + message: this.stopReason === "cancelled" ? "Cancelled by user." : "Interrupted by worker shutdown.", + }; + } + if (exit.error) { + return { state: "failed", code: "unknown", message: exit.error, exitCode: exit.code }; + } + if (exit.code !== 0) { + const tail = this.jobLog.stderrTail.slice(-8).join("\n"); + return { + state: "failed", + code: "unknown", + exitCode: exit.code, + message: `hf exited with code ${exit.code}${exit.signal ? ` (${exit.signal})` : ""}.${tail ? `\n${tail}` : ""}`, + }; + } + + // hf exits 0 even if e.g. a pattern matched nothing, so check every expected file. + await this.setState("verifying"); + const final = await this.sample(dir, expected); + await this.markFiles(final.map((p, i) => ({ id: this.files[i].modelFileId, complete: p.complete }))); + const bad = expected.filter((_, i) => !final[i].complete); + if (bad.length > 0) { + return { + state: "failed", + code: "size_mismatch", + exitCode: 0, + message: `hf finished, but ${bad.length} file(s) are missing or have the wrong size: ${bad + .slice(0, 5) + .map((f) => f.path) + .join(", ")}${bad.length > 5 ? ", …" : ""}`, + }; + } + return { state: "completed" }; + } + + private spawnHf( + dir: string, + expected: ExpectedFile[], + ): Promise<{ code: number | null; signal: NodeJS.Signals | null; error?: string }> { + const env = coreEnv(); + const args = [ + "download", + this.model.repoId, + "--revision", + this.job.targetSha, + "--local-dir", + dir, + ...expected.flatMap((f) => ["--include", escapeGlob(f.path)]), + ]; + + const childEnv: Record = {}; + for (const k of PASSTHROUGH_ENV) { + const v = process.env[k]; + if (v !== undefined) childEnv[k] = v; + } + Object.assign(childEnv, { + HF_HUB_DISABLE_XET: env.HF_HUB_DISABLE_XET ? "1" : "0", + HF_HUB_DISABLE_PROGRESS_BARS: "1", + HF_HUB_DISABLE_TELEMETRY: "1", + NO_COLOR: "1", + PYTHONUNBUFFERED: "1", + }); + if (env.HF_HOME) childEnv.HF_HOME = env.HF_HOME; + if (env.HF_TOKEN) childEnv.HF_TOKEN = env.HF_TOKEN; // via env, never argv + + this.jobLog.system( + `$ hf download ${this.model.repoId} --revision ${this.job.targetSha} --local-dir ${dir} ` + + `(${expected.length} --include pattern(s); xet ${env.HF_HUB_DISABLE_XET ? "off" : "on"}; token ${env.HF_TOKEN ? "set" : "not set"})`, + ); + + return new Promise((resolve) => { + let settled = false; + const done = (r: { code: number | null; signal: NodeJS.Signals | null; error?: string }) => { + if (settled) return; + settled = true; + clearInterval(timer); + this.jobLog.end(); + resolve(r); + }; + + const child = spawn("hf", args, { env: childEnv as NodeJS.ProcessEnv, stdio: ["ignore", "pipe", "pipe"], windowsHide: true }); + this.child = child; + child.stdout.on("data", (d) => this.jobLog.chunk("stdout", d)); + child.stderr.on("data", (d) => this.jobLog.chunk("stderr", d)); + child.on("error", (err: NodeJS.ErrnoException) => + done({ + code: null, + signal: null, + error: + err.code === "ENOENT" + ? "The hf CLI was not found on PATH. Install huggingface_hub[hf_xet] in the worker environment." + : `Could not start hf: ${err.message}`, + }), + ); + child.on("close", (code, signal) => done({ code, signal })); + + // Progress from bytes on disk, written to the DB once per second. + const speed = new SpeedMeter(); + let busy = false; + const timer = setInterval(async () => { + if (busy) return; + busy = true; + try { + const progress = await this.sample(dir, expected); + const doneBytes = progress.reduce((s, p) => s + p.done, 0); + speed.add(Date.now(), doneBytes); + await this.writeProgress(progress, doneBytes, speed); + await this.jobLog.flush(); + } catch (err) { + log.error(`progress sample failed for job ${this.job.id}`, err); + } finally { + busy = false; + } + }, SAMPLE_MS); + }); + } + + private async sample(dir: string, expected: ExpectedFile[]) { + const incomplete = await listIncomplete(dir); + return Promise.all(expected.map((f) => bytesOnDisk(dir, f, incomplete))); + } + + private async writeProgress( + progress: { done: number; complete: boolean }[], + doneBytes: number, + speed: SpeedMeter, + ) { + const d = db(); + const fileUpdates = []; + for (let i = 0; i < this.files.length; i++) { + const f = this.files[i]; + if (f.doneBytes === progress[i].done) continue; + f.doneBytes = progress[i].done; + fileUpdates.push( + d + .update(jobFiles) + .set({ doneBytes: f.doneBytes, state: progress[i].complete ? "done" : "downloading" }) + .where(and(eq(jobFiles.jobId, this.job.id), eq(jobFiles.modelFileId, f.modelFileId))), + ); + } + const bps = speed.bytesPerSecond(); + await d.batch([ + d + .update(jobs) + .set({ + doneBytes, + speedBps: bps == null ? null : Math.round(bps), + etaSeconds: speed.eta(this.job.totalBytes - doneBytes), + }) + .where(eq(jobs.id, this.job.id)), + ...fileUpdates, + ]); + } + + private async markFiles(results: { id: string; complete: boolean }[]) { + const d = db(); + const now = new Date(); + const statements = []; + for (const [ids, fileState, jobFileState] of [ + [results.filter((r) => r.complete).map((r) => r.id), "present", "done"], + [results.filter((r) => !r.complete).map((r) => r.id), "missing", "failed"], + ] as const) { + if (ids.length === 0) continue; + statements.push( + d.update(modelFiles).set({ state: fileState, checkedAt: now }).where(inArray(modelFiles.id, ids)), + d + .update(jobFiles) + .set({ state: jobFileState }) + .where(and(eq(jobFiles.jobId, this.job.id), inArray(jobFiles.modelFileId, ids))), + ); + } + if (statements.length > 0) await d.batch(statements as [(typeof statements)[number], ...typeof statements]); + } + + private async setState(state: JobState) { + await db().update(jobs).set({ state }).where(eq(jobs.id, this.job.id)); + } + + private async finish(outcome: Outcome) { + const now = new Date(); + const d = db(); + switch (outcome.state) { + case "completed": + this.jobLog.system("Download complete, all files verified (size)."); + await d.batch([ + d + .update(jobs) + .set({ state: "completed", finishedAt: now, speedBps: null, etaSeconds: 0, doneBytes: this.job.totalBytes }) + .where(eq(jobs.id, this.job.id)), + d.update(models).set({ downloadedAt: now }).where(eq(models.id, this.model.id)), + ]); + break; + case "failed": + this.jobLog.system(`Failed: ${outcome.message}`); + await d + .update(jobs) + .set({ + state: "failed", + finishedAt: now, + speedBps: null, + etaSeconds: null, + errorCode: outcome.code, + errorMessage: outcome.message, + exitCode: outcome.exitCode ?? null, + }) + .where(eq(jobs.id, this.job.id)); + break; + default: + this.jobLog.system(outcome.message); + await d + .update(jobs) + .set({ state: outcome.state, finishedAt: now, speedBps: null, etaSeconds: null }) + .where(eq(jobs.id, this.job.id)); + } + await this.jobLog.close(); + await settleModelStatus(this.model.id, outcome.state === "failed" ? "failed" : undefined); + log.info(`job ${this.job.id} (${this.model.repoId}) ${outcome.state}`); + } +} + +async function freeBytes(dir: string): Promise { + try { + const s = await statfs(dir); + return s.bavail * s.bsize; + } catch { + return null; + } +} + +function killTree(child: ChildProcess, signal: NodeJS.Signals) { + if (process.platform === "win32" && child.pid) { + // hf.exe is a launcher for python; kill the whole tree. + spawn("taskkill", ["/PID", String(child.pid), "/T", "/F"], { stdio: "ignore", windowsHide: true }); + return; + } + child.kill(signal); +} diff --git a/src/worker/hf-layout.ts b/src/worker/hf-layout.ts new file mode 100644 index 0000000..fca03b3 --- /dev/null +++ b/src/worker/hf-layout.ts @@ -0,0 +1,111 @@ +// What `hf download --local-dir ` writes to disk (verified against huggingface_hub 2.1.1): +// +// / final file (moved in place when complete) +// /.cache/huggingface/download/.metadata "\n\n\n" +// /.cache/huggingface/download/.lock lock file, left behind +// /.cache/huggingface/download/**/...incomplete partial download +// /.cache/huggingface/trees/.json cached file tree +// +// The etag is the LFS sha256 for LFS/Xet files and the git blob SHA-1 for small files. +// Partial files are NOT resumed: every run writes a new name, and a killed run leaves +// its .incomplete file behind. We delete those before each run. + +import { readdir, readFile, rm, stat } from "node:fs/promises"; +import { join, resolve, sep } from "node:path"; + +export const HF_CACHE_DIR = join(".cache", "huggingface"); +const DOWNLOAD_DIR = join(HF_CACHE_DIR, "download"); + +/** Absolute local dir for a model; refuses paths that would escape MODELS_DIR. */ +export function modelDir(modelsDir: string, localPath: string): string { + const root = resolve(modelsDir); + const dir = resolve(root, localPath); + if (dir === root || !dir.startsWith(root + sep)) { + throw new Error(`Refusing model path outside MODELS_DIR: ${localPath}`); + } + return dir; +} + +export type FileMetadata = { commit: string; etag: string }; + +export async function readMetadata(dir: string, path: string): Promise { + try { + const text = await readFile(join(dir, DOWNLOAD_DIR, `${path}.metadata`), "utf8"); + const [commit, etag] = text.split("\n"); + return commit && etag ? { commit: commit.trim(), etag: etag.trim() } : null; + } catch { + return null; + } +} + +/** Size of a file, or null if it doesn't exist. */ +export async function fileSize(path: string): Promise { + try { + const s = await stat(path); + return s.isFile() ? s.size : null; + } catch { + return null; + } +} + +/** Extract the etag (40 or 64 hex chars) from an .incomplete file name. */ +export function etagFromIncompleteName(name: string): string | null { + if (!name.endsWith(".incomplete")) return null; + for (const part of name.split(".")) { + if (/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(part)) return part; + } + return null; +} + +export type IncompleteFile = { path: string; etag: string | null; size: number }; + +/** All partial files under the local dir's download cache. */ +export async function listIncomplete(dir: string): Promise { + const root = join(dir, DOWNLOAD_DIR); + let entries; + try { + entries = await readdir(root, { recursive: true, withFileTypes: true }); + } catch { + return []; + } + const out: IncompleteFile[] = []; + for (const e of entries) { + if (!e.isFile() || !e.name.endsWith(".incomplete")) continue; + const full = join(e.parentPath, e.name); + const size = await fileSize(full); + if (size == null) continue; // finished and moved between readdir and stat + out.push({ path: full, etag: etagFromIncompleteName(e.name), size }); + } + return out; +} + +/** Delete leftover partial files from earlier runs. Only call while no hf process uses the dir. */ +export async function removeStaleIncomplete(dir: string): Promise<{ count: number; bytes: number }> { + const files = await listIncomplete(dir); + for (const f of files) await rm(f.path, { force: true }); + return { count: files.length, bytes: files.reduce((s, f) => s + f.size, 0) }; +} + +export type ExpectedFile = { path: string; size: number; etags: string[] }; + +/** + * Bytes present for one expected file: + * - final file with the expected size and matching (or missing) metadata etag → complete + * - otherwise the size of its in-progress .incomplete file (matched by etag), else 0 + */ +export async function bytesOnDisk( + dir: string, + file: ExpectedFile, + incomplete: IncompleteFile[], +): Promise<{ done: number; complete: boolean }> { + const size = await fileSize(join(dir, file.path)); + if (size === file.size) { + const meta = await readMetadata(dir, file.path); + if (!meta || file.etags.includes(meta.etag)) return { done: file.size, complete: true }; + } + let partial = 0; + for (const inc of incomplete) { + if (inc.etag && file.etags.includes(inc.etag)) partial = Math.max(partial, inc.size); + } + return { done: Math.min(partial, file.size), complete: false }; +} diff --git a/src/worker/index.ts b/src/worker/index.ts index d138328..dc32dd4 100644 --- a/src/worker/index.ts +++ b/src/worker/index.ts @@ -1,44 +1,45 @@ import { execFile } from "node:child_process"; -import { mkdir, statfs } from "node:fs/promises"; +import { randomUUID } from "node:crypto"; +import { mkdir, statfs, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; import { promisify } from "node:util"; -import { inArray } from "drizzle-orm"; +import { and, asc, eq, inArray, isNotNull, isNull, lt, or, sql } from "drizzle-orm"; import { db } from "@/lib/db/client"; import { runMigrations } from "@/lib/db/migrate"; -import { ACTIVE_JOB_STATES, jobLogs, jobs, workerState } from "@/lib/db/schema"; +import { ACTIVE_JOB_STATES, jobFiles, jobLogs, jobs, modelFiles, models, workerState } from "@/lib/db/schema"; import { coreEnv } from "@/lib/env"; +import { DownloadRunner } from "./download"; import { log } from "./log"; +import { settleModelStatus } from "./model-status"; const HEARTBEAT_MS = 5_000; +const TICK_MS = 1_000; +/** A lease older than this is considered abandoned (worker crashed without releasing it). */ +const LEASE_STALE_MS = 20_000; +const SHUTDOWN_GRACE_MS = 8_000; +/** Touched on every heartbeat; the Docker healthcheck checks its age. */ +const HEALTH_FILE = join(tmpdir(), "kaname-worker-alive"); + +const instanceId = randomUUID(); +const startedAt = new Date(); +const runners = new Map(); +let hfVersion: string | null = null; +let stopping = false; async function detectHfVersion(): Promise { try { - const { stdout } = await promisify(execFile)("hf", ["version"], { timeout: 30_000 }); - return stdout.trim() || null; + const { stdout } = await promisify(execFile)("hf", ["version"], { + timeout: 30_000, + env: { ...process.env, NO_COLOR: "1" }, + }); + const m = stdout.match(/version:\s*(\S+)/); + return m ? `huggingface_hub ${m[1]}` : stdout.trim() || null; } catch { return null; } } -/** Jobs that were running when the worker last stopped can't still be running: mark them interrupted. */ -async function recoverInterruptedJobs() { - const stale = await db() - .update(jobs) - .set({ state: "interrupted", finishedAt: new Date(), speedBps: null, etaSeconds: null }) - .where(inArray(jobs.state, [...ACTIVE_JOB_STATES])) - .returning({ id: jobs.id }); - if (stale.length === 0) return; - await db() - .insert(jobLogs) - .values( - stale.map((j) => ({ - jobId: j.id, - stream: "system" as const, - line: "Worker restarted while this job was running. Marked as interrupted; resume to continue.", - })), - ); - log.warn(`marked ${stale.length} job(s) as interrupted`); -} - async function diskSpace(dir: string) { try { const s = await statfs(dir); @@ -48,48 +49,234 @@ async function diskSpace(dir: string) { } } -async function heartbeat(startedAt: Date, hfVersion: string | null) { +// --------------------------------------------------------------------------- +// Lease: only one worker may run, otherwise two processes would run the same jobs. +// --------------------------------------------------------------------------- + +async function tryAcquireLease(): Promise { const now = new Date(); + await db() + .insert(workerState) + .values({ id: "worker", startedAt: now, heartbeatAt: new Date(0) }) + .onConflictDoNothing(); + const won = await db() + .update(workerState) + .set({ instanceId, pid: process.pid, startedAt, heartbeatAt: now }) + .where( + and( + eq(workerState.id, "worker"), + or( + isNull(workerState.instanceId), + eq(workerState.instanceId, instanceId), + lt(workerState.heartbeatAt, new Date(now.getTime() - LEASE_STALE_MS)), + ), + ), + ) + .returning({ id: workerState.id }); + return won.length > 0; +} + +async function acquireLease() { + let warned = false; + while (!(await tryAcquireLease())) { + if (!warned) { + const other = await db().query.workerState.findFirst({ where: eq(workerState.id, "worker") }); + log.warn(`another worker (pid ${other?.pid ?? "?"}) holds the lease; waiting until it stops or goes stale`); + warned = true; + } + await sleep(5_000); + } +} + +async function heartbeat() { const values = { pid: process.pid, hfVersion, - startedAt, - heartbeatAt: now, + heartbeatAt: new Date(), ...(await diskSpace(coreEnv().MODELS_DIR)), }; + const kept = await db() + .update(workerState) + .set(values) + .where(and(eq(workerState.id, "worker"), eq(workerState.instanceId, instanceId))) + .returning({ id: workerState.id }); + if (kept.length === 0) { + log.error("lost the worker lease to another process; exiting"); + await shutdown("lease lost", 1); + return; + } + await writeFile(HEALTH_FILE, String(Date.now())).catch(() => {}); +} + +async function releaseLease() { await db() - .insert(workerState) - .values({ id: "worker", ...values }) - .onConflictDoUpdate({ target: workerState.id, set: values }); + .update(workerState) + .set({ heartbeatAt: new Date(0) }) + .where(and(eq(workerState.id, "worker"), eq(workerState.instanceId, instanceId))); +} + +// --------------------------------------------------------------------------- +// Jobs +// --------------------------------------------------------------------------- + +/** Jobs that were running when the previous worker stopped can't still be running. */ +async function recoverInterruptedJobs() { + const stale = await db() + .update(jobs) + .set({ state: "interrupted", finishedAt: new Date(), speedBps: null, etaSeconds: null }) + .where(inArray(jobs.state, [...ACTIVE_JOB_STATES])) + .returning({ id: jobs.id, modelId: jobs.modelId }); + if (stale.length === 0) return; + await db() + .insert(jobLogs) + .values( + stale.map((j) => ({ + jobId: j.id, + stream: "system" as const, + line: "Worker restarted while this job was running. Marked as interrupted; resume to continue.", + })), + ); + for (const j of stale) await settleModelStatus(j.modelId); + log.warn(`marked ${stale.length} job(s) as interrupted`); +} + +async function handleCancelRequests() { + const requested = await db() + .select({ id: jobs.id, state: jobs.state, modelId: jobs.modelId }) + .from(jobs) + .where(and(isNotNull(jobs.cancelRequestedAt), inArray(jobs.state, ["queued", ...ACTIVE_JOB_STATES]))); + for (const j of requested) { + const runner = runners.get(j.id); + if (runner) { + runner.cancel(); + } else if (j.state === "queued") { + await db() + .update(jobs) + .set({ state: "cancelled", finishedAt: new Date() }) + .where(and(eq(jobs.id, j.id), eq(jobs.state, "queued"))); + await settleModelStatus(j.modelId); + } + } +} + +/** Claim the oldest queued download whose model has no running job. */ +async function claimNextJob() { + const busyModels = [...runners.values()].map((r) => r.modelId); + const candidates = await db() + .select({ id: jobs.id, modelId: jobs.modelId }) + .from(jobs) + .where(and(eq(jobs.state, "queued"), eq(jobs.kind, "download"), isNull(jobs.cancelRequestedAt))) + .orderBy(asc(jobs.createdAt)) + .limit(20); + const next = candidates.find((c) => !busyModels.includes(c.modelId)); + if (!next) return null; + + const [job] = await db() + .update(jobs) + .set({ state: "downloading", startedAt: new Date(), finishedAt: null, attempt: sql`${jobs.attempt} + 1` }) + .where(and(eq(jobs.id, next.id), eq(jobs.state, "queued"))) + .returning(); + return job ?? null; +} + +async function startJob(job: typeof jobs.$inferSelect) { + const model = await db().query.models.findFirst({ where: eq(models.id, job.modelId) }); + if (!model) { + await db() + .update(jobs) + .set({ state: "failed", errorCode: "unknown", errorMessage: "Model no longer exists.", finishedAt: new Date() }) + .where(eq(jobs.id, job.id)); + return; + } + const files = await db() + .select({ + modelFileId: jobFiles.modelFileId, + path: jobFiles.path, + expectedBytes: jobFiles.expectedBytes, + doneBytes: jobFiles.doneBytes, + lfsSha256: modelFiles.lfsSha256, + blobOid: modelFiles.blobOid, + }) + .from(jobFiles) + .innerJoin(modelFiles, eq(modelFiles.id, jobFiles.modelFileId)) + .where(eq(jobFiles.jobId, job.id)); + + await db().update(models).set({ status: "downloading" }).where(eq(models.id, model.id)); + const runner = new DownloadRunner(job, model, files); + runners.set(job.id, runner); + log.info(`job ${job.id}: downloading ${model.repoId} (${files.length} files, attempt ${job.attempt})`); + runner + .run() + .catch((err) => log.error(`job ${job.id} crashed`, err)) + .finally(() => runners.delete(job.id)); +} + +let ticking = false; +async function tick() { + if (ticking || stopping) return; + ticking = true; + try { + await handleCancelRequests(); + const max = coreEnv().MAX_CONCURRENT_DOWNLOADS; + while (runners.size < max && !stopping) { + const job = await claimNextJob(); + if (!job) break; + await startJob(job); + } + } catch (err) { + log.error("tick failed", err); + } finally { + ticking = false; + } +} + +// --------------------------------------------------------------------------- +// Lifecycle +// --------------------------------------------------------------------------- + +const timers: NodeJS.Timeout[] = []; + +async function shutdown(reason: string, code = 0) { + if (stopping) return; + stopping = true; + log.info(`shutting down (${reason})`); + timers.forEach(clearInterval); + if (runners.size > 0) { + for (const r of runners.values()) r.interrupt(); + const deadline = Date.now() + SHUTDOWN_GRACE_MS; + while (runners.size > 0 && Date.now() < deadline) await sleep(200); + } + await releaseLease().catch(() => {}); + process.exit(code); } async function main() { const env = coreEnv(); - log.info(`starting (pid ${process.pid}), models dir: ${env.MODELS_DIR}`); + log.info(`starting (pid ${process.pid}), models dir: ${env.MODELS_DIR}, max concurrent: ${env.MAX_CONCURRENT_DOWNLOADS}`); await mkdir(env.MODELS_DIR, { recursive: true }); await runMigrations(); log.info("database migrated"); + process.on("SIGINT", () => void shutdown("SIGINT")); + process.on("SIGTERM", () => void shutdown("SIGTERM")); + + await acquireLease(); + log.info("acquired worker lease"); await recoverInterruptedJobs(); - const hfVersion = await detectHfVersion(); - if (hfVersion) log.info(`hf CLI: ${hfVersion}`); + hfVersion = await detectHfVersion(); + if (hfVersion) log.info(`hf CLI: ${hfVersion}, xet ${env.HF_HUB_DISABLE_XET ? "disabled" : "enabled"}`); else log.warn("hf CLI not found on PATH; downloads will fail until it is installed"); - const startedAt = new Date(); - await heartbeat(startedAt, hfVersion); - const timer = setInterval(() => { - heartbeat(startedAt, hfVersion).catch((err) => log.error("heartbeat failed", err)); - }, HEARTBEAT_MS); + await heartbeat(); + timers.push(setInterval(() => heartbeat().catch((err) => log.error("heartbeat failed", err)), HEARTBEAT_MS)); + timers.push(setInterval(() => void tick(), TICK_MS)); + void tick(); +} - const shutdown = (signal: string) => { - log.info(`received ${signal}, shutting down`); - clearInterval(timer); - process.exit(0); - }; - process.on("SIGINT", () => shutdown("SIGINT")); - process.on("SIGTERM", () => shutdown("SIGTERM")); +function sleep(ms: number) { + return new Promise((r) => setTimeout(r, ms)); } main().catch((err) => { diff --git a/src/worker/job-log.ts b/src/worker/job-log.ts new file mode 100644 index 0000000..946007a --- /dev/null +++ b/src/worker/job-log.ts @@ -0,0 +1,86 @@ +import { db } from "@/lib/db/client"; +import { jobLogs, type LogStream } from "@/lib/db/schema"; + +const MAX_LINE = 4_000; +const MAX_LINES_PER_JOB = 20_000; + +const ANSI = /\x1b\[[0-9;?]*[ -/]*[@-~]/g; +const HF_TOKEN_RE = /hf_[A-Za-z0-9]{20,}/g; + +/** Remove ANSI color codes and anything that looks like an HF token. */ +export function sanitizeLine(line: string, secrets: string[] = []): string { + let out = line.replace(ANSI, "").replace(HF_TOKEN_RE, "hf_***"); + for (const s of secrets) if (s) out = out.split(s).join("***"); + return out.length > MAX_LINE ? out.slice(0, MAX_LINE) + " …[truncated]" : out; +} + +/** + * Buffers a job's stdout/stderr and writes it to job_logs in batches. + * Splits on \n and \r (progress bars), drops empty lines, keeps the last stderr lines for errors. + */ +export class JobLog { + private buffer: { stream: LogStream; line: string; ts: Date }[] = []; + private partial: Record<"stdout" | "stderr", string> = { stdout: "", stderr: "" }; + private written = 0; + private dropped = 0; + readonly stderrTail: string[] = []; + + constructor( + private jobId: string, + private secrets: string[] = [], + ) {} + + system(line: string) { + this.push("system", line); + } + + chunk(stream: "stdout" | "stderr", data: Buffer | string) { + const text = this.partial[stream] + data.toString(); + const lines = text.split(/\r\n|\r|\n/); + this.partial[stream] = lines.pop() ?? ""; + for (const l of lines) this.push(stream, l); + } + + /** Flush incomplete trailing lines (call when the process exits). */ + end() { + for (const stream of ["stdout", "stderr"] as const) { + if (this.partial[stream]) this.push(stream, this.partial[stream]); + this.partial[stream] = ""; + } + } + + private push(stream: LogStream, raw: string) { + const line = sanitizeLine(raw, this.secrets); + if (!line.trim()) return; + if (stream === "stderr") { + this.stderrTail.push(line); + if (this.stderrTail.length > 30) this.stderrTail.shift(); + } + if (this.written + this.buffer.length >= MAX_LINES_PER_JOB) { + this.dropped++; + return; + } + this.buffer.push({ stream, line, ts: new Date() }); + } + + async flush() { + if (this.buffer.length === 0) return; + const rows = this.buffer.splice(0, this.buffer.length); + await db() + .insert(jobLogs) + .values(rows.map((r) => ({ jobId: this.jobId, stream: r.stream, line: r.line, ts: r.ts }))); + this.written += rows.length; + } + + async close() { + this.end(); + if (this.dropped > 0) { + this.buffer.push({ + stream: "system", + line: `${this.dropped} further log lines were dropped (limit ${MAX_LINES_PER_JOB}).`, + ts: new Date(), + }); + } + await this.flush(); + } +} diff --git a/src/worker/model-status.ts b/src/worker/model-status.ts new file mode 100644 index 0000000..1bde0da --- /dev/null +++ b/src/worker/model-status.ts @@ -0,0 +1,36 @@ +import { and, eq, inArray, sql } from "drizzle-orm"; +import { db } from "@/lib/db/client"; +import { ACTIVE_JOB_STATES, jobs, type ModelStatus, modelFiles, models } from "@/lib/db/schema"; + +/** + * Recompute a model's status from its jobs and files: + * - an active job → downloading + * - all selected files present → ready + * - `failure` given (last job failed) → failed + * - some files present → incomplete, none → pending + */ +export async function settleModelStatus(modelId: string, failure?: "failed"): Promise { + const d = db(); + const active = await d + .select({ n: sql`count(*)` }) + .from(jobs) + .where(and(eq(jobs.modelId, modelId), inArray(jobs.state, ["queued", ...ACTIVE_JOB_STATES]))); + let status: ModelStatus; + if (active[0].n > 0) { + status = "downloading"; + } else { + const [counts] = await d + .select({ + total: sql`count(*)`, + present: sql`sum(case when ${modelFiles.state} in ('present', 'verified') then 1 else 0 end)`, + }) + .from(modelFiles) + .where(and(eq(modelFiles.modelId, modelId), eq(modelFiles.selected, true))); + const present = counts.present ?? 0; + if (counts.total > 0 && present === counts.total) status = "ready"; + else if (failure) status = "failed"; + else status = present > 0 ? "incomplete" : "pending"; + } + await d.update(models).set({ status }).where(eq(models.id, modelId)); + return status; +} diff --git a/src/worker/speed.ts b/src/worker/speed.ts new file mode 100644 index 0000000..7cb6425 --- /dev/null +++ b/src/worker/speed.ts @@ -0,0 +1,32 @@ +/** + * Download speed over a sliding time window, from periodic (time, totalBytes) samples. + * Using deltas means bytes that were already on disk before the job started never count as speed. + */ +export class SpeedMeter { + private samples: { t: number; bytes: number }[] = []; + + constructor(private windowMs = 10_000) {} + + add(t: number, bytes: number) { + this.samples.push({ t, bytes }); + while (this.samples.length > 2 && t - this.samples[1].t >= this.windowMs) this.samples.shift(); + } + + /** Bytes per second, or null until there are two samples at least 1s apart. */ + bytesPerSecond(): number | null { + if (this.samples.length < 2) return null; + const a = this.samples[0]; + const b = this.samples[this.samples.length - 1]; + const dt = (b.t - a.t) / 1000; + if (dt < 1) return null; + return Math.max(0, (b.bytes - a.bytes) / dt); + } + + /** Seconds remaining, or null if unknown or stalled. */ + eta(remainingBytes: number): number | null { + const bps = this.bytesPerSecond(); + if (remainingBytes <= 0) return 0; + if (!bps || bps < 1) return null; + return Math.round(remainingBytes / bps); + } +} diff --git a/src/worker/worker.test.ts b/src/worker/worker.test.ts new file mode 100644 index 0000000..86c48f3 --- /dev/null +++ b/src/worker/worker.test.ts @@ -0,0 +1,94 @@ +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { after, describe, it } from "node:test"; +import { + bytesOnDisk, + etagFromIncompleteName, + listIncomplete, + modelDir, + removeStaleIncomplete, +} from "./hf-layout"; +import { sanitizeLine } from "./job-log"; +import { SpeedMeter } from "./speed"; + +const SHA256 = "e150ed544dfe6016930c026a93913a5e3184181ebfe6ab2223ae01dd0491784c"; +const SHA1 = "de077778adaa4aa6e706209cd95a2a0d6049bc59"; + +describe("hf-layout", () => { + const dirs: string[] = []; + after(async () => { + for (const d of dirs) await rm(d, { recursive: true, force: true }); + }); + + async function fixture() { + const dir = await mkdtemp(join(tmpdir(), "kaname-test-")); + dirs.push(dir); + const dl = join(dir, ".cache", "huggingface", "download"); + await mkdir(join(dl, "Q4_K_M"), { recursive: true }); + return { dir, dl }; + } + + it("parses the etag from real .incomplete names", () => { + assert.equal(etagFromIncompleteName(`3nJsnUdcCmdBOp4dLn_dEgZ50vw=.${SHA256}.cd150ce3.incomplete`), SHA256); + assert.equal(etagFromIncompleteName(`abc=.${SHA1}.0fa2cc3c.incomplete`), SHA1); + assert.equal(etagFromIncompleteName("model.gguf.metadata"), null); + }); + + it("modelDir refuses paths outside MODELS_DIR", () => { + assert.ok(modelDir("/models", "org/name").endsWith(join("org", "name"))); + assert.throws(() => modelDir("/models", "../etc")); + assert.throws(() => modelDir("/models", ".")); + }); + + it("counts partial bytes by etag, complete files by size + metadata", async () => { + const { dir, dl } = await fixture(); + await writeFile(join(dl, `x=.${SHA256}.aaaa1111.incomplete`), Buffer.alloc(300)); + await writeFile(join(dl, "Q4_K_M", `y=.${SHA1}.bbbb2222.incomplete`), Buffer.alloc(10)); + const incomplete = await listIncomplete(dir); + assert.equal(incomplete.length, 2); + + const big = { path: "big.gguf", size: 1000, etags: [SHA256] }; + assert.deepEqual(await bytesOnDisk(dir, big, incomplete), { done: 300, complete: false }); + + // Final file present with matching metadata → complete + await writeFile(join(dir, "big.gguf"), Buffer.alloc(1000)); + await writeFile(join(dl, "big.gguf.metadata"), `abc\n${SHA256}\n123.4\n`); + assert.deepEqual(await bytesOnDisk(dir, big, []), { done: 1000, complete: true }); + + // Same size but metadata from a different file version → not complete + await writeFile(join(dl, "big.gguf.metadata"), `abc\n${"0".repeat(64)}\n123.4\n`); + assert.equal((await bytesOnDisk(dir, big, [])).complete, false); + }); + + it("removes stale partial files", async () => { + const { dir, dl } = await fixture(); + await writeFile(join(dl, `x=.${SHA256}.aaaa1111.incomplete`), Buffer.alloc(50)); + await writeFile(join(dl, "keep.metadata"), "x"); + assert.deepEqual(await removeStaleIncomplete(dir), { count: 1, bytes: 50 }); + assert.equal((await listIncomplete(dir)).length, 0); + }); +}); + +describe("SpeedMeter", () => { + it("measures deltas over the window and estimates ETA", () => { + const m = new SpeedMeter(10_000); + m.add(0, 5_000_000); // bytes already on disk at start don't count + assert.equal(m.bytesPerSecond(), null); + m.add(2_000, 7_000_000); + assert.equal(m.bytesPerSecond(), 1_000_000); + assert.equal(m.eta(10_000_000), 10); + m.add(30_000, 7_000_000); // stalled + assert.equal(m.bytesPerSecond(), 0); + assert.equal(m.eta(10_000_000), null); + }); +}); + +describe("sanitizeLine", () => { + it("strips ANSI codes and hides tokens", () => { + assert.equal(sanitizeLine("\x1b[1m\x1b[31mError: boom\x1b[0m"), "Error: boom"); + assert.equal(sanitizeLine("token hf_abcdefghijklmnopqrstuvwxyz123 used"), "token hf_*** used"); + assert.equal(sanitizeLine("secret=s3cr3t-value", ["s3cr3t-value"]), "secret=***"); + }); +});