mirror of
https://github.com/ShayManor/github-readme-stats.git
synced 2026-12-02 11:53:48 +05:30
Compare commits
30
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
181668a3b3 | ||
|
|
83c4227d5f | ||
|
|
814bbf7d8d | ||
|
|
74047b28fc | ||
|
|
a2e7a52169 | ||
|
|
2ff5d21b1c | ||
|
|
3e0b69cacd | ||
|
|
917ad098f7 | ||
|
|
f93c39d022 | ||
|
|
4edc66d1bb | ||
|
|
5ba5ec4f4b | ||
|
|
a3c17a15da | ||
|
|
c0401a8a28 | ||
|
|
c50393467e | ||
|
|
d448825bed | ||
|
|
961a3330e1 | ||
|
|
07221a1329 | ||
|
|
97ad1c2b39 | ||
|
|
540d172011 | ||
|
|
a0c5e8a86e | ||
|
|
361c938985 | ||
|
|
3525144aeb | ||
|
|
cb3ace8dcd | ||
|
|
d77dea20bc | ||
|
|
1a3caff269 | ||
|
|
15ad9c81aa | ||
|
|
832f94c1b9 | ||
|
|
f0e6d9439e | ||
|
|
7aa5f9d5a0 | ||
|
|
9feae9ff35 |
@@ -0,0 +1,29 @@
|
|||||||
|
name: docker
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [main]
|
||||||
|
pull_request:
|
||||||
|
branches: [main]
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build:
|
||||||
|
name: ${{ matrix.service }}
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
strategy:
|
||||||
|
fail-fast: false
|
||||||
|
matrix:
|
||||||
|
service: [fetcher, generator, edge]
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- uses: docker/setup-buildx-action@v3
|
||||||
|
|
||||||
|
- name: Build ${{ matrix.service }} image
|
||||||
|
uses: docker/build-push-action@v6
|
||||||
|
with:
|
||||||
|
context: ./${{ matrix.service }}
|
||||||
|
push: false
|
||||||
|
tags: ghstats-${{ matrix.service }}:ci
|
||||||
|
cache-from: type=gha,scope=${{ matrix.service }}
|
||||||
|
cache-to: type=gha,mode=max,scope=${{ matrix.service }}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
name: tests
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [main]
|
||||||
|
pull_request:
|
||||||
|
branches: [main]
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
pytest:
|
||||||
|
name: ${{ matrix.service }}
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
strategy:
|
||||||
|
fail-fast: false
|
||||||
|
matrix:
|
||||||
|
service: [fetcher, generator, edge]
|
||||||
|
defaults:
|
||||||
|
run:
|
||||||
|
working-directory: ${{ matrix.service }}
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- uses: actions/setup-python@v5
|
||||||
|
with:
|
||||||
|
python-version: "3.11"
|
||||||
|
cache: pip
|
||||||
|
cache-dependency-path: ${{ matrix.service }}/requirements.txt
|
||||||
|
|
||||||
|
- name: Install dependencies
|
||||||
|
run: pip install -r requirements.txt
|
||||||
|
|
||||||
|
- name: Run pytest
|
||||||
|
run: pytest -v
|
||||||
+31
-2
@@ -14,8 +14,8 @@ dist/
|
|||||||
downloads/
|
downloads/
|
||||||
eggs/
|
eggs/
|
||||||
.eggs/
|
.eggs/
|
||||||
lib/
|
/lib/
|
||||||
lib64/
|
/lib64/
|
||||||
parts/
|
parts/
|
||||||
sdist/
|
sdist/
|
||||||
var/
|
var/
|
||||||
@@ -205,3 +205,32 @@ cython_debug/
|
|||||||
marimo/_static/
|
marimo/_static/
|
||||||
marimo/_lsp/
|
marimo/_lsp/
|
||||||
__marimo__/
|
__marimo__/
|
||||||
|
|
||||||
|
# Per-service SQLite databases (runtime data)
|
||||||
|
fetcher/data/*.db
|
||||||
|
fetcher/data/*.db-wal
|
||||||
|
fetcher/data/*.db-shm
|
||||||
|
generator/data/*.db
|
||||||
|
generator/data/*.db-wal
|
||||||
|
generator/data/*.db-shm
|
||||||
|
|
||||||
|
# Built frontend bundle
|
||||||
|
generator/src/static/
|
||||||
|
generator/frontend/dist/
|
||||||
|
generator/frontend/node_modules/
|
||||||
|
|
||||||
|
# Python build artifacts
|
||||||
|
**/__pycache__/
|
||||||
|
**/*.pyc
|
||||||
|
.pytest_cache/
|
||||||
|
|
||||||
|
# Widget build artifacts at repo root (retired)
|
||||||
|
/widget_*.svg
|
||||||
|
/data/ghstats.db
|
||||||
|
|
||||||
|
# Editor / tooling caches
|
||||||
|
.idea/
|
||||||
|
.claude/
|
||||||
|
.superpowers/
|
||||||
|
.playwright-mcp/
|
||||||
|
screenshots/
|
||||||
|
|||||||
@@ -0,0 +1,63 @@
|
|||||||
|
# CLAUDE.md
|
||||||
|
|
||||||
|
Guidance for Claude Code working in this repository.
|
||||||
|
|
||||||
|
## Layout
|
||||||
|
|
||||||
|
This is a monorepo of three independent Python services plus a Vite+React
|
||||||
|
frontend. Each service has its own `requirements.txt`, `pytest.ini`,
|
||||||
|
`Dockerfile`, and README:
|
||||||
|
|
||||||
|
- `fetcher/` — port 5001. Owns the GitHub PAT and `fetcher.db`. Refresh
|
||||||
|
cron polls GitHub, upserts raw payloads, serves `/data/<u>` to internal
|
||||||
|
callers only.
|
||||||
|
- `generator/` — port 5002. Owns settings + widgets SQLite DBs. Build
|
||||||
|
worker renders SVGs from fetcher data. Serves the React SPA from
|
||||||
|
`src/static/` and all `/api/*` routes. Frontend sources live in
|
||||||
|
`generator/frontend/` and get built into `src/static/` by the
|
||||||
|
multi-stage Dockerfile.
|
||||||
|
- `edge/` — port 5003. Cache-first SVG proxy in front of the generator;
|
||||||
|
Flask-Caching + Flask-Compress, optional Redis.
|
||||||
|
|
||||||
|
Per-service READMEs cover run/test/Docker commands. The design and
|
||||||
|
implementation plan live in `docs/superpowers/`.
|
||||||
|
|
||||||
|
## Working on a single service
|
||||||
|
|
||||||
|
Each service is self-contained. `cd <service> && pytest` is the test
|
||||||
|
entry point; `cd <service> && pip install -r requirements.txt` is the
|
||||||
|
dependency install. Don't cross-import across services — they talk
|
||||||
|
over HTTP (generator → fetcher via `generator/src/fetcher_client.py`;
|
||||||
|
edge → generator via `edge/src/api.py::_fetch_origin`).
|
||||||
|
|
||||||
|
## Configuration
|
||||||
|
|
||||||
|
All runtime tuning is in each service's `src/config.py` and is
|
||||||
|
overridable via env vars:
|
||||||
|
|
||||||
|
- `fetcher/src/config.py` — `GITHUB_PAT`, `FETCHER_INTERNAL_TOKEN`,
|
||||||
|
`COLLABORATOR_*`, `COMMIT_*`, `API_TIMEOUT`, refresh cadence.
|
||||||
|
- `generator/src/config.py` — `FETCHER_URL`, `FETCHER_INTERNAL_TOKEN`,
|
||||||
|
`ENROLLMENT_DAILY_CAP`, `WIDGET_LRU_PER_USER`, `POLL_INTERVAL_MINUTES`,
|
||||||
|
`TAG_MAX_COUNT`, `TAG_LANGUAGE_MAP`, `TAG_TOPIC_MAP`,
|
||||||
|
`ENABLED_WIDGETS`, `WIDGET_ORDER`, `HIDDEN_LANGUAGES`.
|
||||||
|
- `edge/src/config.py` — `GENERATOR_URL`, `CACHE_TYPE`,
|
||||||
|
`CACHE_REDIS_URL`, `CACHE_DEFAULT_TIMEOUT`, `CACHE_THRESHOLD`,
|
||||||
|
`UPSTREAM_TIMEOUT`.
|
||||||
|
|
||||||
|
## Conventions
|
||||||
|
|
||||||
|
- Widget renderers return SVG strings; only `generator/src/worker.py`
|
||||||
|
persists them (via `db.put_widgets`).
|
||||||
|
- The `X-Widget-Status` header (`ready | building | rate_limited |
|
||||||
|
not_found`) is the contract between generator and edge for what to
|
||||||
|
cache.
|
||||||
|
- Generator ↔ fetcher traffic uses the shared secret
|
||||||
|
`FETCHER_INTERNAL_TOKEN` (HTTP header `X-Internal-Token`). Public
|
||||||
|
routes on the generator don't require auth in v1.
|
||||||
|
- Adding a widget still means: new `generator/src/widgets/<name>.py`,
|
||||||
|
export from `generator/src/widgets/__init__.py`, wire into
|
||||||
|
`generator/src/processor.py::generate_widgets_from_github`, add the
|
||||||
|
key to `WIDGET_ORDER` / `ENABLED_WIDGETS` in
|
||||||
|
`generator/src/config.py`.
|
||||||
|
- Adding a theme: entry in `generator/src/themes/themes.py`.
|
||||||
@@ -1,90 +1,43 @@
|
|||||||
# GitHub README Stats
|
# github-readme-stats
|
||||||
|
|
||||||
Generate polished SVG profile cards from your GitHub data. Fetches your repos, contributions, languages, and collaborators, then renders them into composable widgets you can drop into your profile README.
|
[](https://github.com/ShayManor/github-readme-stats/actions/workflows/tests.yml)
|
||||||
|
[](https://github.com/ShayManor/github-readme-stats/actions/workflows/docker.yml)
|
||||||
|
|
||||||
<p align="center">
|
A monorepo of three independent Python services plus a React frontend,
|
||||||
<img src="widget_shaymanor.svg" width="420" alt="Example composite widget" />
|
each self-contained. See each service's README for details.
|
||||||
</p>
|
|
||||||
|
|
||||||
## Widgets
|
## Services
|
||||||
|
|
||||||
| Widget | What it shows |
|
| Folder | Port | Responsibility |
|
||||||
|--------|--------------|
|
|---|---|---|
|
||||||
| **Grade** | Letter grade (S through F) with score breakdown, stats, and inferred role tags |
|
| [`fetcher/`](./fetcher/README.md) | 5001 | Owns GitHub PAT + `fetcher.db`; cron-refreshes data |
|
||||||
| **Impact** | Contribution timeline over the last 6 months |
|
| [`generator/`](./generator/README.md) | 5002 | Settings + widgets DBs, build worker, serves React SPA + `/api/*` |
|
||||||
| **Collaborators** | Top people you've committed alongside, ranked by shared commits |
|
| [`edge/`](./edge/README.md) | 5003 | Cache-first SVG proxy; deploy globally |
|
||||||
| **Focus** | Where your recent work falls (Backend, Frontend, ML, DevOps, etc.) |
|
|
||||||
| **Languages** | Donut chart of your most-used languages by LOC |
|
|
||||||
| **Achievements** | Custom badges you define (hackathons, awards, milestones) |
|
|
||||||
|
|
||||||
Each widget is also saved individually as `widget_<name>.svg`.
|
## Design Docs
|
||||||
|
|
||||||
## Quick Start
|
- Spec: [`docs/superpowers/specs/2026-04-17-production-pipeline-design.md`](docs/superpowers/specs/2026-04-17-production-pipeline-design.md)
|
||||||
|
- Plan: [`docs/superpowers/plans/2026-04-17-production-pipeline.md`](docs/superpowers/plans/2026-04-17-production-pipeline.md)
|
||||||
|
|
||||||
```bash
|
## Quick start (local dev, no Docker)
|
||||||
# Basic (public data only)
|
|
||||||
python run.py <username>
|
|
||||||
|
|
||||||
# With a GitHub token for full commit/contribution data
|
# 1) fetcher
|
||||||
GITHUB_PAT=<your-token> python run.py <username>
|
(cd fetcher && pip install -r requirements.txt &&
|
||||||
|
FETCHER_INTERNAL_TOKEN=dev GITHUB_PAT=<your-pat> python -m src.api) &
|
||||||
|
|
||||||
# Choose a theme
|
# 2) generator API, worker, cron (three processes)
|
||||||
python run.py <username> nord
|
cd generator && pip install -r requirements.txt
|
||||||
```
|
FETCHER_URL=http://localhost:5001 FETCHER_INTERNAL_TOKEN=dev python -m src.api &
|
||||||
|
FETCHER_URL=http://localhost:5001 FETCHER_INTERNAL_TOKEN=dev python -m src.worker &
|
||||||
|
FETCHER_URL=http://localhost:5001 FETCHER_INTERNAL_TOKEN=dev python -m src.cron &
|
||||||
|
|
||||||
Output lands in the repo root as `widget_<username>.svg`.
|
# 3) edge
|
||||||
|
(cd ../edge && pip install -r requirements.txt &&
|
||||||
|
GENERATOR_URL=http://localhost:5002 python -m src.api) &
|
||||||
|
|
||||||
## Themes
|
# 4) frontend (dev server)
|
||||||
|
cd ../generator/frontend && npm install && npm run dev
|
||||||
|
|
||||||
Five built-in themes:
|
Test everything:
|
||||||
|
|
||||||
| Theme | Style |
|
(cd fetcher && pytest) && (cd generator && pytest) && (cd edge && pytest)
|
||||||
|-------|-------|
|
|
||||||
| `midnight` / `dark` | Dark blue-gray (default) |
|
|
||||||
| `onyx` | High-contrast on near-black |
|
|
||||||
| `nord` | Muted pastels on slate |
|
|
||||||
| `clean` / `light` | White background |
|
|
||||||
| `paper` | Warm off-white, sepia accents |
|
|
||||||
|
|
||||||
## Web UI
|
|
||||||
|
|
||||||
A React frontend lets you customize widgets interactively with live preview and per-widget advanced settings (colors, counts, etc.).
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Terminal 1 — start the generator API
|
|
||||||
python -m src.generator_api # :5002
|
|
||||||
|
|
||||||
# Terminal 2 — start the frontend
|
|
||||||
cd frontend && npm install && npm run dev # :3000
|
|
||||||
```
|
|
||||||
|
|
||||||
Open `http://localhost:3000`, enter a GitHub username, tweak settings, and hit Generate.
|
|
||||||
|
|
||||||
## Configuration
|
|
||||||
|
|
||||||
All tuning lives in `src/config.py` and can be overridden with environment variables. Key knobs:
|
|
||||||
|
|
||||||
| Variable | Default | What it does |
|
|
||||||
|----------|---------|-------------|
|
|
||||||
| `GITHUB_PAT` | — | GitHub personal access token |
|
|
||||||
| `COMMIT_MAX_REPOS` | 10 | Max repos to scan for commits |
|
|
||||||
| `COMMIT_PER_REPO` | 30 | Max commits per repo |
|
|
||||||
| `COLLABORATOR_MIN_COMMITS` | 3 | Minimum shared commits to show a collaborator |
|
|
||||||
| `API_TIMEOUT` | 5 | Per-request timeout in seconds |
|
|
||||||
|
|
||||||
See [CONFIGURATION.md](CONFIGURATION.md) for the full list.
|
|
||||||
|
|
||||||
## Project Structure
|
|
||||||
|
|
||||||
```
|
|
||||||
src/
|
|
||||||
data/ # GitHub API fetching + data processing
|
|
||||||
widgets/ # One SVG renderer per widget
|
|
||||||
themes/ # Color palettes
|
|
||||||
models/ # Typed data structures
|
|
||||||
utils/ # SVG helpers
|
|
||||||
config.py # All tunables
|
|
||||||
generate.py # CLI entry point
|
|
||||||
generator_api.py # Flask API for the web UI
|
|
||||||
frontend/ # React + TypeScript + Vite
|
|
||||||
```
|
|
||||||
|
|||||||
Binary file not shown.
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,531 @@
|
|||||||
|
# Production Pipeline Design — github-readme-stats
|
||||||
|
|
||||||
|
**Date:** 2026-04-17
|
||||||
|
**Status:** Approved for planning
|
||||||
|
**Scope:** Restructure the repo into three independent Python services (fetcher, generator, edge), each with its own Docker image, tests, README, and API. The existing React/Vite frontend folds into the generator service (built and served by it, but kept as a decoupled React app with its own sources). Redis is designed for but not stood up in v1; the edge uses in-process Flask-Caching + Flask-Compress as free wins. Hosting/orchestration is explicitly out of scope.
|
||||||
|
|
||||||
|
## Goals
|
||||||
|
|
||||||
|
- A public, unauthenticated URL `GET /<github-username>` returns an SVG profile card suitable for embedding in a GitHub README.
|
||||||
|
- If the username is unknown at request time, return a clean "we're building your widget" placeholder immediately; fetch and build in the background.
|
||||||
|
- GitHub API calls are tightly rate-limited and live behind a single internal service (the fetcher) that holds the only GitHub PAT.
|
||||||
|
- The serving path is always a precomputed SVG lookup — never a render on the hot path.
|
||||||
|
- The three services must be genuinely independent so the generator can later be split into a build worker + a serverless edge serving layer without reshuffling the other services.
|
||||||
|
|
||||||
|
## Non-Goals (v1)
|
||||||
|
|
||||||
|
- No GitHub OAuth, no login, no per-user auth on the settings API. An auth stub is included so auth can be added later without touching call sites.
|
||||||
|
- No hosting, CI, cloud config, or docker-compose.
|
||||||
|
- No analytics, no metrics dashboard, no admin UI.
|
||||||
|
- No Postgres / remote DB. SQLite with WAL is sufficient for the v1 workload (one writer per DB, small volumes, mostly reads). All DB access lives behind one `db.py` per service so a swap to Postgres is a localized change.
|
||||||
|
- **No Redis deployment in v1.** Redis is designed in this spec so the integration points are correct, but v1 ships without Redis standing up. Edge uses in-process Flask-Caching; generator/fetcher skip the cache layer and talk directly over HTTP. Enabling Redis later is a config toggle — see the Redis section.
|
||||||
|
|
||||||
|
## Architecture
|
||||||
|
|
||||||
|
```
|
||||||
|
GitHub README embed Browser (user visits app)
|
||||||
|
│ │
|
||||||
|
▼ ▼
|
||||||
|
┌───────────────┐ ┌─────────────────────────────┐
|
||||||
|
│ Edge service │ │ Generator service │
|
||||||
|
│ (many nodes) │──── HTTP ─────►│ / + /assets/* → React SPA │
|
||||||
|
│ Flask- │ origin fetch │ /api/<u> → widget │
|
||||||
|
│ Caching + │ on miss │ /api/enroll → enroll │
|
||||||
|
│ Compress │ │ /api/<u>/... → settings │
|
||||||
|
│ - /<u> │ │ + build worker container │
|
||||||
|
│ - /<u>/<w> │ │ + poll cron container │
|
||||||
|
└───────────────┘ └──────┬──────────┬───────────┘
|
||||||
|
│ │
|
||||||
|
settings.db widgets.db
|
||||||
|
▲
|
||||||
|
│
|
||||||
|
HTTP (internal,
|
||||||
|
X-Internal-Token)
|
||||||
|
│
|
||||||
|
┌─────────────────▼───────┐
|
||||||
|
│ Fetcher service │
|
||||||
|
│ - /data/<u> (auto- │
|
||||||
|
│ fetches on miss) │
|
||||||
|
│ - /fetch (force) │
|
||||||
|
│ - /avatar │
|
||||||
|
│ + cron container │
|
||||||
|
└──────┬──────────────────┘
|
||||||
|
▼
|
||||||
|
fetcher.db
|
||||||
|
│
|
||||||
|
▼
|
||||||
|
GitHub API
|
||||||
|
|
||||||
|
(v2) Redis slots between edge↔generator and generator↔fetcher.
|
||||||
|
cache.py is a no-op wrapper until REDIS_URL is set.
|
||||||
|
```
|
||||||
|
|
||||||
|
The edge has no DB of its own and no origin DB access — it's a cache-first proxy. The generator serves both the React SPA (static files at `/`) and the API (`/api/*`). Deploy as many edge instances around the world as you like.
|
||||||
|
|
||||||
|
## Redis (designed, not deployed in v1)
|
||||||
|
|
||||||
|
Specified here so the code knows the integration shape. v1 behavior: every `REDIS_URL` env var is unset → the cache wrapper short-circuits to a no-op, and every caller falls through to the underlying service. No code changes required to enable later — set `REDIS_URL` and it starts caching.
|
||||||
|
|
||||||
|
One Redis instance, accessible from fetcher, generator, and edge. Two key namespaces:
|
||||||
|
|
||||||
|
| Key | Value | TTL | Written by | Read by |
|
||||||
|
|---|---|---|---|---|
|
||||||
|
| `fetcher:data:<u>` | JSON payload from fetcher | 1h | fetcher (on miss-fill), generator cron on invalidation | generator API + worker |
|
||||||
|
| `fetcher:hash:<u>` | Current `payload_hash` | 1h | fetcher | generator cron (cheap change detection) |
|
||||||
|
| `widget:composite:<u>` | SVG string | 24h | edge (on miss-fill), generator (on rebuild invalidation) | edge |
|
||||||
|
| `widget:<name>:<u>` | SVG string per widget | 24h | same as composite | edge |
|
||||||
|
| `enroll:day:<YYYY-MM-DD>` | Counter | 48h | generator API | generator API (rate limit check) |
|
||||||
|
|
||||||
|
Rules:
|
||||||
|
|
||||||
|
- **Redis is a cache, never a source of truth.** Every key has a TTL. Losing Redis is a latency event, not a correctness event.
|
||||||
|
- **Invalidation on write, not just TTL.** When the build worker writes new widget rows, it immediately `DEL`s the matching `widget:*:<u>` keys so the next edge read re-populates. Same for fetcher on re-fetch.
|
||||||
|
- **Single Redis instance in v1.** If edge latency to a single Redis becomes a problem, swap to an edge-native KV (Cloudflare KV, Upstash) — only `edge/src/api.py` changes.
|
||||||
|
|
||||||
|
## Services
|
||||||
|
|
||||||
|
### 1. Fetcher
|
||||||
|
|
||||||
|
**Purpose:** Own every GitHub API interaction. Hold the PAT. Expose cached payloads to the generator.
|
||||||
|
|
||||||
|
**Endpoints** (all internal; not exposed to the public internet):
|
||||||
|
|
||||||
|
- `GET /data/<username>` — return stored payload JSON. If not stored, fetch from GitHub, store, return. This is the first-enrollment path. 502 on GitHub failure; 404 if GitHub says the user doesn't exist (fetcher stores a `{error: "not_found"}` marker so repeat calls are cheap).
|
||||||
|
- `POST /fetch {username}` — force re-fetch, ignoring any existing cache. Used by the fetcher's own cron and by manual admin action. Returns `{stored, payload_hash, changed}`.
|
||||||
|
- `GET /avatar/<username>` — return avatar bytes. GitHub's `https://github.com/<u>.png` is public and requires no PAT, so this is cheap. Used by the generator's placeholder renderer.
|
||||||
|
- `GET /health`
|
||||||
|
|
||||||
|
**Auth:** every request requires `X-Internal-Token: <shared-secret>` header. The generator holds the matching secret. The fetcher never listens on a public interface.
|
||||||
|
|
||||||
|
**Storage:** `fetcher.db` (SQLite), single table:
|
||||||
|
|
||||||
|
```sql
|
||||||
|
CREATE TABLE users (
|
||||||
|
username TEXT PRIMARY KEY,
|
||||||
|
data_json TEXT NOT NULL, -- full GitHub payload OR {"error":"not_found"}
|
||||||
|
payload_hash TEXT NOT NULL, -- sha256 of data_json
|
||||||
|
fetched_at TEXT NOT NULL, -- UTC ISO 8601
|
||||||
|
last_requested_at TEXT NOT NULL -- updated on every GET /data; drives GC
|
||||||
|
);
|
||||||
|
```
|
||||||
|
|
||||||
|
**Cron (`fetcher/src/cron.py`):** runs every hour. Each tick:
|
||||||
|
|
||||||
|
1. Select users with `fetched_at < now - 24h` AND `last_requested_at > now - 7d`. Stagger calls across the hour so we don't burst GitHub.
|
||||||
|
2. For each, call `POST /fetch` internally (or the equivalent function). Update `payload_hash`.
|
||||||
|
3. Delete rows where `last_requested_at < now - 7d` (trial GC — unused enrollments drop out automatically). `last_requested_at` is updated on every `GET /data/<u>`, so actively-embedded users are never dropped.
|
||||||
|
|
||||||
|
**Env vars:**
|
||||||
|
|
||||||
|
- `FETCHER_PORT` (default `5001`)
|
||||||
|
- `FETCHER_DB_PATH` (default `./data/fetcher.db` inside container)
|
||||||
|
- `GITHUB_PAT` (required)
|
||||||
|
- `FETCHER_INTERNAL_TOKEN` (required; the shared secret)
|
||||||
|
- `FETCHER_REFRESH_INTERVAL_HOURS` (default `24`)
|
||||||
|
- `FETCHER_TRIAL_GC_DAYS` (default `7`)
|
||||||
|
- `REDIS_URL` (optional; if set, writes to cache on fetch)
|
||||||
|
|
||||||
|
**DB pragmas:** on connection open, run `PRAGMA journal_mode=WAL; PRAGMA synchronous=NORMAL; PRAGMA foreign_keys=ON; PRAGMA busy_timeout=5000;`.
|
||||||
|
|
||||||
|
### 2. Generator
|
||||||
|
|
||||||
|
**Purpose:** Serve precomputed SVGs to the public internet. Hold user settings. Build widgets in the background. Never call GitHub directly; only talk to the fetcher over HTTP.
|
||||||
|
|
||||||
|
All API endpoints are under the `/api/` prefix. Root `/` and `/assets/*` serve the React SPA built into `src/static/`.
|
||||||
|
|
||||||
|
**Public API endpoints:**
|
||||||
|
|
||||||
|
- `GET /api/<username>` — return composite SVG from `widgets.db`. Placeholder on miss. Sets `X-Widget-Status` header.
|
||||||
|
- `GET /api/<username>/<widget>.svg` — individual widget. Same behavior.
|
||||||
|
- `POST /api/enroll {username}` — explicit enrollment (SPA uses this). Also auto-invoked when `GET /api/<unknown>` arrives. Enforces daily rate limit. Returns `{enrolled, job_id}` or `{error: "rate_limited"}`.
|
||||||
|
- `GET /api/health`
|
||||||
|
|
||||||
|
**Auth-gated API endpoints** (auth stub in v1 — passes everything through; real auth later):
|
||||||
|
|
||||||
|
- `GET /api/<username>/settings` — current settings.
|
||||||
|
- `PATCH /api/<username>/settings` — update settings; enqueues a rebuild. Unlimited. Does NOT re-fetch GitHub.
|
||||||
|
- `POST /api/<username>/refresh` — one-shot manual re-fetch + rebuild. Calls fetcher's `POST /fetch`, then enqueues a rebuild. Gated by `manual_refresh_used` flag (allowed once per user, ever). Returns 409 `already_used` after the first call.
|
||||||
|
|
||||||
|
**Storage:**
|
||||||
|
|
||||||
|
**`settings.db`** (SQLite):
|
||||||
|
|
||||||
|
```sql
|
||||||
|
CREATE TABLE users (
|
||||||
|
username TEXT PRIMARY KEY,
|
||||||
|
settings_json TEXT NOT NULL, -- theme, enabled widgets, order, custom_tags, achievements, widget_settings
|
||||||
|
settings_hash TEXT NOT NULL, -- sha256 of canonicalized settings_json
|
||||||
|
enrolled_at TEXT NOT NULL,
|
||||||
|
last_fetcher_payload_hash TEXT, -- last hash we rebuilt from; cron compares
|
||||||
|
manual_refresh_used INTEGER DEFAULT 0, -- enforces one-shot user-triggered re-fetch
|
||||||
|
last_requested_at TEXT NOT NULL -- updated on every GET /<u>; drives trial GC
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE enrollments_daily (
|
||||||
|
day TEXT PRIMARY KEY, -- YYYY-MM-DD, UTC
|
||||||
|
count INTEGER NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE jobs (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
kind TEXT NOT NULL, -- "build"
|
||||||
|
username TEXT NOT NULL,
|
||||||
|
status TEXT NOT NULL, -- "pending" | "running" | "done" | "failed"
|
||||||
|
attempts INTEGER DEFAULT 0,
|
||||||
|
last_error TEXT,
|
||||||
|
created_at TEXT NOT NULL,
|
||||||
|
updated_at TEXT NOT NULL
|
||||||
|
);
|
||||||
|
CREATE INDEX idx_jobs_pending ON jobs(status, created_at);
|
||||||
|
```
|
||||||
|
|
||||||
|
**`widgets.db`** (SQLite in v1; designed for swap to remote backend later):
|
||||||
|
|
||||||
|
```sql
|
||||||
|
CREATE TABLE widgets (
|
||||||
|
username TEXT NOT NULL,
|
||||||
|
settings_hash TEXT NOT NULL,
|
||||||
|
widget_name TEXT NOT NULL, -- "composite" | "grade" | "focus" | ...
|
||||||
|
svg TEXT NOT NULL,
|
||||||
|
built_at TEXT NOT NULL,
|
||||||
|
PRIMARY KEY (username, settings_hash, widget_name)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE current_widget (
|
||||||
|
username TEXT PRIMARY KEY,
|
||||||
|
settings_hash TEXT NOT NULL, -- pointer to the "live" set
|
||||||
|
updated_at TEXT NOT NULL
|
||||||
|
);
|
||||||
|
CREATE INDEX idx_widgets_username ON widgets(username);
|
||||||
|
```
|
||||||
|
|
||||||
|
The `widgets_repo.py` module wraps all access. Future swap to Postgres / Turso / D1 / S3 changes only that one file.
|
||||||
|
|
||||||
|
**Build worker (`generator/src/build_worker.py`):**
|
||||||
|
|
||||||
|
- In-process thread polling `jobs` table every 500ms.
|
||||||
|
- For each pending job: mark `running`, load settings, `GET {fetcher}/data/<u>` (fetcher auto-fetches on miss), compute `settings_hash`, render all enabled widgets + composite, upsert into `widgets.db`, flip `current_widget` pointer atomically, LRU-trim to 10 rows per user, mark `done`.
|
||||||
|
- Failure: increment `attempts`, exponential backoff (1min, 5min, 15min); after 3 attempts mark `failed` and leave the existing widget (if any) in place. Placeholder continues to serve for un-built users.
|
||||||
|
- Extractable to a standalone process later (same DB, same code, separate entrypoint).
|
||||||
|
|
||||||
|
**Generator cron (`generator/src/cron.py`):** runs every 15 minutes.
|
||||||
|
|
||||||
|
1. For each enrolled user, `GET {fetcher}/data/<u>` (response includes `payload_hash`).
|
||||||
|
2. If `payload_hash != last_fetcher_payload_hash`, enqueue a build job and update `last_fetcher_payload_hash`.
|
||||||
|
3. LRU-trim widgets per user.
|
||||||
|
|
||||||
|
**Enrollment rate limit:** global cap of 50 new enrollments per UTC day (`ENROLLMENT_DAILY_CAP`). Over cap → `POST /enroll` returns `rate_limited`; `GET /<unknown>` returns a "try again tomorrow" placeholder. Enrollment counter increments only on *new* users, not on re-requests.
|
||||||
|
|
||||||
|
**Placeholder renderer (`generator/src/placeholder.py`):** produces SVGs matching the card wrapper and theme of real widgets. Three variants:
|
||||||
|
|
||||||
|
- **building**: "Building @username's widget... This usually takes under a minute." Shows avatar if fetched (generator calls `GET {fetcher}/avatar/<u>`). Serves when user is enrolled but widgets not yet built.
|
||||||
|
- **rate_limited**: "Too many new users today — try again tomorrow." Shown when enrollment cap is hit.
|
||||||
|
- **not_found**: "GitHub user @username doesn't exist." Shown when fetcher stored a `not_found` marker.
|
||||||
|
|
||||||
|
Placeholders are rendered on the fly (no DB lookup needed) and served with `Cache-Control: no-store`.
|
||||||
|
|
||||||
|
**Env vars:**
|
||||||
|
|
||||||
|
- `GENERATOR_PORT` (default `5002`)
|
||||||
|
- `GENERATOR_SETTINGS_DB_PATH` (default `./data/settings.db`)
|
||||||
|
- `GENERATOR_WIDGETS_DB_PATH` (default `./data/widgets.db`)
|
||||||
|
- `FETCHER_URL` (required, e.g. `http://mini-pc:5001`)
|
||||||
|
- `FETCHER_INTERNAL_TOKEN` (required, matches fetcher's)
|
||||||
|
- `REDIS_URL` (optional; if set, read-through to fetcher cache and invalidation on rebuild)
|
||||||
|
- `ENROLLMENT_DAILY_CAP` (default `50`)
|
||||||
|
- `WIDGET_LRU_PER_USER` (default `10`)
|
||||||
|
- `GENERATOR_POLL_INTERVAL_MINUTES` (default `15`)
|
||||||
|
|
||||||
|
**DB pragmas:** same as fetcher (WAL + NORMAL sync + 5s busy_timeout).
|
||||||
|
|
||||||
|
### 3. Edge
|
||||||
|
|
||||||
|
**Purpose:** Serve widget SVGs cache-first, with the generator as origin. Deploy many instances around the world (Cloud Run, Fly, Lambda container, etc.). No DB of its own.
|
||||||
|
|
||||||
|
**Endpoints:**
|
||||||
|
|
||||||
|
- `GET /<username>` — check cache; hit → return; miss → fetch generator `GET /api/<u>`, cache, return.
|
||||||
|
- `GET /<username>/<widget>.svg` — same pattern.
|
||||||
|
- `GET /health` — reports cache type + origin reachability.
|
||||||
|
|
||||||
|
**Caching (v1):** [Flask-Caching](https://flask-caching.readthedocs.io/) with `CACHE_TYPE=SimpleCache` — in-process LRU, per-instance, no external dependency. Wrapped by a thin `cache.py` so `CACHE_TYPE=RedisCache` + `CACHE_REDIS_URL` swaps in Redis later with no call-site changes. TTL: 24h. Max entries per instance: 10000.
|
||||||
|
|
||||||
|
**Compression:** [Flask-Compress](https://github.com/colour-science/flask-compress) on, default settings. SVG is text — gzip typically 70-80%% savings.
|
||||||
|
|
||||||
|
**HTTP cache headers on hits:**
|
||||||
|
- `Cache-Control: public, max-age=3600, s-maxage=86400, stale-while-revalidate=86400`
|
||||||
|
|
||||||
|
**Placeholder handling:** generator sets `X-Widget-Status: ready | building | rate_limited | not_found`. Edge only caches `ready` responses. Others are passed through with `Cache-Control: no-store` so a CDN in front doesn't memorize them.
|
||||||
|
|
||||||
|
**Implementation:** single `edge/src/api.py` Flask file (~100 lines) + `edge/src/cache.py` (~30 lines).
|
||||||
|
|
||||||
|
**Env vars:**
|
||||||
|
- `EDGE_PORT` (default `5003`)
|
||||||
|
- `GENERATOR_URL` (required — origin)
|
||||||
|
- `CACHE_TYPE` (default `SimpleCache`; later `RedisCache`)
|
||||||
|
- `CACHE_REDIS_URL` (optional)
|
||||||
|
- `CACHE_DEFAULT_TIMEOUT` (default `86400`)
|
||||||
|
|
||||||
|
### Frontend (served by the generator)
|
||||||
|
|
||||||
|
**Not a separate service.** The existing React/Vite frontend moves into `generator/frontend/` (source code) and is built by the generator's Dockerfile. The Flask app in `generator/src/api.py` serves the built static bundle from `/` (and `/assets/*`). The architecture stays decoupled — React sources live in their own folder, are built by their own toolchain, and only the static output is served by Flask.
|
||||||
|
|
||||||
|
**URL split on the generator:**
|
||||||
|
|
||||||
|
| Path | Served | Notes |
|
||||||
|
|---|---|---|
|
||||||
|
| `/` | `generator/frontend/dist/index.html` | React SPA entry |
|
||||||
|
| `/assets/*` | `generator/frontend/dist/assets/*` | JS/CSS bundles |
|
||||||
|
| `/api/<u>` | Flask route | widget origin (called by edge) |
|
||||||
|
| `/api/<u>/<w>.svg` | Flask route | individual widget origin |
|
||||||
|
| `/api/enroll` | Flask route | enrollment |
|
||||||
|
| `/api/<u>/settings` | Flask route | settings CRUD |
|
||||||
|
| `/api/<u>/refresh` | Flask route | one-shot re-fetch |
|
||||||
|
| `/api/health` | Flask route | health |
|
||||||
|
|
||||||
|
**Why `/api/` prefix:** keeps the frontend `/` clean for the SPA and keeps widget origin paths from colliding with React routes. The edge rewrites `GET /<u>` → `GET /api/<u>` when calling origin.
|
||||||
|
|
||||||
|
**Dockerfile (one, multi-stage):**
|
||||||
|
|
||||||
|
1. **Stage `frontend-build`** — `node:20-alpine`, `npm ci && npm run build` inside `/app/frontend`, produces `/app/frontend/dist`.
|
||||||
|
2. **Stage `runtime`** — `python:3.11-slim`, install `requirements.txt`, copy `src/` and the built `frontend/dist` from stage 1 into `src/static/`. Flask serves from there.
|
||||||
|
|
||||||
|
**Flow (v1, no auth):**
|
||||||
|
|
||||||
|
1. User opens `https://generator.example.com/` → React SPA loads.
|
||||||
|
2. User enters their GitHub username → calls `POST /api/enroll`.
|
||||||
|
3. UI polls `GET {EDGE_URL}/<username>` preview (placeholder until build completes).
|
||||||
|
4. Settings form edits go to `PATCH /api/<username>/settings`.
|
||||||
|
5. "Refresh from GitHub" button calls `POST /api/<username>/refresh`. Disabled after one use (server enforces 409).
|
||||||
|
6. UI displays the embeddable edge URL for pasting into their README.
|
||||||
|
|
||||||
|
**Vite env vars:** `VITE_GENERATOR_URL`, `VITE_EDGE_URL` (baked at build time by the Dockerfile).
|
||||||
|
|
||||||
|
## File Layout
|
||||||
|
|
||||||
|
Simplified — each Python service is ~4-6 files plus its rendering assets.
|
||||||
|
|
||||||
|
```
|
||||||
|
github-readme-stats/
|
||||||
|
├── fetcher/
|
||||||
|
│ ├── src/
|
||||||
|
│ │ ├── __init__.py
|
||||||
|
│ │ ├── api.py # Flask app + all routes + auth header check
|
||||||
|
│ │ ├── github.py # GitHub GraphQL/REST client (from src/data/fetcher.py)
|
||||||
|
│ │ ├── db.py # SQLite repo, WAL setup, schema migrations
|
||||||
|
│ │ ├── cron.py # scheduled refresh + GC; run as separate container
|
||||||
|
│ │ └── config.py
|
||||||
|
│ ├── tests/
|
||||||
|
│ │ ├── test_api.py
|
||||||
|
│ │ ├── test_github.py
|
||||||
|
│ │ ├── test_db.py
|
||||||
|
│ │ └── test_cron.py
|
||||||
|
│ ├── data/ # gitignored
|
||||||
|
│ ├── Dockerfile
|
||||||
|
│ ├── requirements.txt
|
||||||
|
│ ├── pytest.ini
|
||||||
|
│ └── README.md
|
||||||
|
│
|
||||||
|
├── generator/
|
||||||
|
│ ├── frontend/ # React+Vite sources (moved from top-level frontend/)
|
||||||
|
│ │ ├── src/
|
||||||
|
│ │ ├── package.json
|
||||||
|
│ │ ├── vite.config.ts
|
||||||
|
│ │ └── tsconfig.json
|
||||||
|
│ ├── src/
|
||||||
|
│ │ ├── __init__.py
|
||||||
|
│ │ ├── api.py # Flask app + all /api/* routes + SPA static serve + fetcher HTTP client inline + auth stub inline
|
||||||
|
│ │ ├── worker.py # build worker loop; run as separate container
|
||||||
|
│ │ ├── cron.py # polls fetcher, enqueues rebuilds; run as separate container
|
||||||
|
│ │ ├── db.py # settings_repo + widgets_repo together
|
||||||
|
│ │ ├── cache.py # no-op in v1 (REDIS_URL unset); real wrapper otherwise
|
||||||
|
│ │ ├── placeholder.py # three SVG variants
|
||||||
|
│ │ ├── processor.py # widget rendering pipeline (from src/data/processor.py)
|
||||||
|
│ │ ├── config.py
|
||||||
|
│ │ ├── static/ # populated at Docker build time from frontend/dist
|
||||||
|
│ │ ├── widgets/ # (from src/widgets/)
|
||||||
|
│ │ ├── themes/ # (from src/themes/)
|
||||||
|
│ │ ├── models/ # (from src/models/)
|
||||||
|
│ │ └── utils/ # (from src/utils/)
|
||||||
|
│ ├── tests/
|
||||||
|
│ │ ├── test_api.py
|
||||||
|
│ │ ├── test_worker.py
|
||||||
|
│ │ ├── test_cron.py
|
||||||
|
│ │ ├── test_db.py
|
||||||
|
│ │ ├── test_placeholder.py
|
||||||
|
│ │ ├── test_processor.py
|
||||||
|
│ │ └── integration/
|
||||||
|
│ │ └── test_end_to_end.py
|
||||||
|
│ ├── data/ # gitignored
|
||||||
|
│ ├── Dockerfile # multi-stage: node build → python runtime (api+worker+cron share image)
|
||||||
|
│ ├── requirements.txt
|
||||||
|
│ ├── pytest.ini
|
||||||
|
│ └── README.md
|
||||||
|
│
|
||||||
|
├── edge/
|
||||||
|
│ ├── src/
|
||||||
|
│ │ ├── __init__.py
|
||||||
|
│ │ ├── api.py # Flask app + Flask-Caching + Flask-Compress + origin fetch
|
||||||
|
│ │ ├── cache.py # Flask-Caching config (SimpleCache now, RedisCache later)
|
||||||
|
│ │ └── config.py
|
||||||
|
│ ├── tests/
|
||||||
|
│ │ └── test_api.py
|
||||||
|
│ ├── Dockerfile
|
||||||
|
│ ├── requirements.txt
|
||||||
|
│ ├── pytest.ini
|
||||||
|
│ └── README.md
|
||||||
|
│
|
||||||
|
├── docs/superpowers/specs/2026-04-17-production-pipeline-design.md
|
||||||
|
├── .gitignore # **/data/*.db, built artifacts
|
||||||
|
└── README.md # points to each service's README
|
||||||
|
```
|
||||||
|
|
||||||
|
**Independence rules:**
|
||||||
|
|
||||||
|
- No Python imports cross service folders. Communication only via HTTP + Redis.
|
||||||
|
- No shared package. Duplicate any trivial util (e.g., `payload_hash`) per service.
|
||||||
|
- Each service has its own `requirements.txt`, `pytest.ini`, `Dockerfile`, `README.md`.
|
||||||
|
- `docker build ./fetcher` etc. succeeds with no repo-root build context.
|
||||||
|
- Generator ships one Docker image; three containers run from it with different `CMD`s: `python -m src.api`, `python -m src.worker`, `python -m src.cron`.
|
||||||
|
|
||||||
|
## Code to Delete
|
||||||
|
|
||||||
|
The current `src/` layout is retired wholesale. Specifically:
|
||||||
|
|
||||||
|
- `run.py` — CLI entry point replaced by frontend + API.
|
||||||
|
- `src/generate.py` — replaced by the generator service.
|
||||||
|
- `src/fetcher_api.py`, `src/generator_api.py` — replaced by `fetcher/src/api.py` and `generator/src/api.py`.
|
||||||
|
- `src/db/` — schema moves to fetcher's `repository.py`; dummy user pattern replaced by placeholders.
|
||||||
|
- `src/data/ARCHITECTURE.md` — superseded by this spec.
|
||||||
|
- `widget_*.svg` at repo root — build artifacts, no longer produced.
|
||||||
|
- `data/ghstats.db` at repo root — replaced by per-service `data/*.db`.
|
||||||
|
- `REPORT.md`, `CHANGELOG.md` — stale; drop unless user wants them kept.
|
||||||
|
- `src/README.md` — superseded by per-service READMEs.
|
||||||
|
|
||||||
|
`CLAUDE.md` is updated to reflect the new layout (sections on commands, architecture, configuration). `CONFIGURATION.md` and `TAG_CUSTOMIZATION.md` move into the generator's `README.md` (or its own `docs/` under `generator/`).
|
||||||
|
|
||||||
|
Existing widget/theme/model code under `src/widgets/`, `src/themes/`, `src/models/`, `src/utils/`, and most of `src/data/processor.py` move into `generator/src/` and are kept. `src/data/fetcher.py` moves into `fetcher/src/github.py`. The top-level `frontend/` folder moves wholesale into `generator/frontend/`.
|
||||||
|
|
||||||
|
## Data Flow
|
||||||
|
|
||||||
|
### First-time `GET /shaymanor` (from a README embed, hitting the edge)
|
||||||
|
|
||||||
|
1. Edge: Flask-Caching lookup for `/shaymanor` → miss.
|
||||||
|
2. Edge: HTTP `GET {generator}/api/shaymanor` → origin.
|
||||||
|
3. Generator: `widgets_repo.get_current(shaymanor)` → miss.
|
||||||
|
4. Generator: `settings_repo.get(shaymanor)` → miss → user unenrolled.
|
||||||
|
5. Enrollment path:
|
||||||
|
a. Check today's counter in `enrollments_daily`. If `>= 50`, return `rate_limited` placeholder with `X-Widget-Status: rate_limited` and `Cache-Control: no-store`.
|
||||||
|
b. Insert default settings row. Increment counter.
|
||||||
|
c. Insert `build` job.
|
||||||
|
6. Generator returns `building` placeholder with `X-Widget-Status: building`, `Cache-Control: no-store`.
|
||||||
|
7. Edge sees non-`ready` status header, returns SVG to the reader without caching.
|
||||||
|
|
||||||
|
### Build worker processing a job
|
||||||
|
|
||||||
|
1. Mark job `running`.
|
||||||
|
2. `cache.get("fetcher:data:<u>")` via the wrapper (v1 = no-op, always miss). Miss → `GET {fetcher}/data/<u>` with internal token (fetcher auto-fetches from GitHub on miss). Hit → use cached payload.
|
||||||
|
3. If payload is the `not_found` marker: upsert a `not_found` placeholder into widgets; flip `current_widget`; mark job `done`. No retries on this user.
|
||||||
|
4. Otherwise: load settings, compute `settings_hash`, render all enabled widgets + composite via the existing `processor.py` pipeline.
|
||||||
|
5. Transaction: insert widget rows, flip `current_widget`, update `settings.last_fetcher_payload_hash`.
|
||||||
|
6. `cache.delete("widget:composite:<u>")` and per-widget keys (v1 no-op; real invalidation once Redis is enabled).
|
||||||
|
7. LRU-trim widgets for this user to 10 hashes.
|
||||||
|
8. Mark job `done`.
|
||||||
|
|
||||||
|
The edge clears its own Flask-Caching entry via TTL expiry (24h) in v1. Users who want instant invalidation on rebuild can call the edge's `POST /admin/purge/<u>` (added in v2 when Redis comes online — not in v1).
|
||||||
|
|
||||||
|
### Cron-driven refresh
|
||||||
|
|
||||||
|
1. Fetcher cron (hourly) re-fetches due users; updates `payload_hash` on change.
|
||||||
|
2. Generator cron (15 min) calls fetcher `GET /data/<u>` per enrolled user (response includes `payload_hash`). Compares with `last_fetcher_payload_hash`. On mismatch, enqueues `build` job. (When Redis comes online in v2, this reads `fetcher:hash:<u>` from Redis — HTTP becomes the fallback.)
|
||||||
|
3. Trial users not requested in 7 days are GC'd by fetcher cron.
|
||||||
|
|
||||||
|
### Settings change from frontend
|
||||||
|
|
||||||
|
1. `PATCH /shaymanor/settings` (auth stub passes through).
|
||||||
|
2. Generator computes new `settings_hash`, updates `settings_json`.
|
||||||
|
3. Enqueue `build` job.
|
||||||
|
4. Old `(username, old_hash)` rows remain in `widgets` until LRU-trimmed. `current_widget` flips once the build completes — no user-visible flicker.
|
||||||
|
|
||||||
|
### Manual refresh (one-shot, user-triggered)
|
||||||
|
|
||||||
|
1. `POST /shaymanor/refresh`.
|
||||||
|
2. If `manual_refresh_used = 1`, return 409 `already_used`.
|
||||||
|
3. Otherwise: set `manual_refresh_used = 1`, call fetcher `POST /fetch {username: shaymanor}` (this burns one GitHub-quota hit), enqueue `build` job. The rebuild will pick up the freshly-fetched data on the next poll.
|
||||||
|
|
||||||
|
After this one-shot is spent, the user's data only changes via fetcher cron (every 24h). Settings edits continue to trigger unlimited rebuilds but never re-fetch.
|
||||||
|
|
||||||
|
## Error Handling
|
||||||
|
|
||||||
|
| Failure mode | Behavior |
|
||||||
|
|---|---|
|
||||||
|
| Fetcher unreachable from generator | Build job retries with backoff; placeholder continues to serve; `/health` reports degraded. |
|
||||||
|
| GitHub returns 5xx | Fetcher returns 502 to generator; build job retries. |
|
||||||
|
| GitHub returns 404 | Fetcher stores `{error: "not_found"}`; generator builds a `not_found` placeholder once, stops retrying. |
|
||||||
|
| GitHub rate-limit | Fetcher returns 429 to generator; build job retries with longer backoff. |
|
||||||
|
| Enrollment cap exceeded | `POST /enroll` → `rate_limited`. `GET /<unknown>` → `rate_limited` placeholder. Next day resets. |
|
||||||
|
| Settings DB or widgets DB corrupt | Generator serves 503. Intentional — this is a server bug, not a missing-user condition. |
|
||||||
|
| Build worker dies mid-job | On next start, any `running` job older than 10 minutes is reclaimed to `pending`. |
|
||||||
|
| Manual refresh reused | 409 `already_used`. |
|
||||||
|
|
||||||
|
## Testing
|
||||||
|
|
||||||
|
Each service has its own `tests/` and runs with `cd <service> && pytest`.
|
||||||
|
|
||||||
|
**Fetcher:**
|
||||||
|
- `test_repository.py`: upsert, payload_hash stability, last_requested_at update on read.
|
||||||
|
- `test_github_client.py`: mocked HTTP with the `responses` library; covers GraphQL + REST paths, 404, 429, 502.
|
||||||
|
- `test_api.py`: auth-header enforcement, auto-fetch on miss, 404 handling.
|
||||||
|
- `test_cron.py`: staggered refresh, GC of stale trial users.
|
||||||
|
|
||||||
|
**Generator:**
|
||||||
|
- `test_db.py`: settings + widgets CRUD, settings_hash canonicalization, LRU trimming, `current_widget` pointer atomicity, WAL pragma applied.
|
||||||
|
- `test_placeholder.py`: each of the three placeholder variants renders valid SVG and matches theme.
|
||||||
|
- `test_worker.py`: picks jobs, retries on fetcher failures, handles `not_found` marker, invalidates Redis on success.
|
||||||
|
- `test_api.py`: full surface — auth stub, rate limit, enrollment auto-trigger on `GET /api/<unknown>`, serves precomputed on hit, placeholder on miss, `X-Widget-Status` header correct per case, SPA served at `/`.
|
||||||
|
- `test_cron.py`: polls fetcher via HTTP, enqueues only on hash change.
|
||||||
|
- `test_processor.py`: carry-over tests for widget rendering (from existing code).
|
||||||
|
|
||||||
|
**Edge (`edge/tests/`):**
|
||||||
|
- `test_api.py`: SimpleCache hit returns cached SVG; miss fetches origin, caches, returns; `X-Widget-Status: ready` is cached, others pass through uncached; gzip content-encoding applied to responses > threshold.
|
||||||
|
|
||||||
|
**Integration (`generator/tests/integration/`):** spin up generator API + worker + cron + edge + a fake fetcher (responses/respx mock) in-process, drive `GET /<newuser>` end to end via the edge. Assert placeholder → build → real SVG transition and that the edge serves from cache on second request.
|
||||||
|
|
||||||
|
**Frontend:** Vitest smoke tests: form submit, preview fetch, settings save. No E2E required in v1.
|
||||||
|
|
||||||
|
## Security
|
||||||
|
|
||||||
|
- Fetcher's `X-Internal-Token` is required on every endpoint except `/health`. Constant-time comparison. 401 on mismatch.
|
||||||
|
- No endpoint on the fetcher is exposed to the public internet. Deployment guidance in the fetcher README: bind to `127.0.0.1` or a private interface.
|
||||||
|
- Generator does not echo stored data anywhere except via the widget SVG — no `/data/<u>` mirror. Prevents the generator from leaking raw GitHub payloads.
|
||||||
|
- Frontend talks to generator over HTTPS in production (user's responsibility).
|
||||||
|
- No secrets logged. No `GITHUB_PAT` in generator env at all.
|
||||||
|
|
||||||
|
## Observability
|
||||||
|
|
||||||
|
- Each service logs to stdout in a line-oriented format: `ts level service event key=val ...`.
|
||||||
|
- `/health` on each service returns `{status, service, db_ok, upstream_ok?}`.
|
||||||
|
- No metrics backend in v1.
|
||||||
|
|
||||||
|
## Migration Plan (executed by the implementation phase)
|
||||||
|
|
||||||
|
1. Create new folder scaffolding and move code wholesale. Do not keep the old `src/` in parallel — cut over in one branch.
|
||||||
|
2. Split `src/db/repository.py` into fetcher's `repository.py`.
|
||||||
|
3. Define new settings_repo and widgets_repo in `generator/src/`.
|
||||||
|
4. Write placeholder renderer using the existing card wrapper util (moved into `generator/src/utils/`).
|
||||||
|
5. Wire build worker + cron.
|
||||||
|
6. Update `.gitignore`; delete retired files and build artifacts.
|
||||||
|
7. Update the top-level `README.md` to point to the three service READMEs.
|
||||||
|
8. Update `CLAUDE.md` to reflect the new layout.
|
||||||
|
|
||||||
|
## Open Questions
|
||||||
|
|
||||||
|
None at time of writing. All design choices confirmed in brainstorming.
|
||||||
|
|
||||||
|
## Future Work (out of scope for this spec)
|
||||||
|
|
||||||
|
- GitHub OAuth on settings endpoints.
|
||||||
|
- Postgres migration (swap `db.py` per service; all call sites unchanged).
|
||||||
|
- Edge-native KV store (Cloudflare KV / Upstash) if single-Redis latency is a problem from far regions.
|
||||||
|
- Admin endpoints for cron pause / manual re-fetch / user purge.
|
||||||
|
- Metrics + alerting.
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
FROM python:3.11-slim
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
COPY requirements.txt ./
|
||||||
|
RUN pip install --no-cache-dir -r requirements.txt
|
||||||
|
COPY src ./src
|
||||||
|
|
||||||
|
EXPOSE 5003
|
||||||
|
CMD ["gunicorn", "-b", "0.0.0.0:5003", "-w", "2", "src.api:app"]
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
# Edge Service
|
||||||
|
|
||||||
|
Cache-first SVG proxy in front of the generator. Deploy many instances
|
||||||
|
around the world. No DB of its own; optional Redis for shared cache.
|
||||||
|
|
||||||
|
## Run locally
|
||||||
|
|
||||||
|
cd edge
|
||||||
|
pip install -r requirements.txt
|
||||||
|
GENERATOR_URL=http://localhost:5002 python -m src.api
|
||||||
|
|
||||||
|
## Test
|
||||||
|
|
||||||
|
cd edge && pytest
|
||||||
|
|
||||||
|
## Docker
|
||||||
|
|
||||||
|
docker build -t ghstats-edge .
|
||||||
|
docker run --rm -e GENERATOR_URL=http://host.docker.internal:5002 -p 5003:5003 ghstats-edge
|
||||||
|
|
||||||
|
## Endpoints
|
||||||
|
|
||||||
|
| Method | Path | Description |
|
||||||
|
|---|---|---|
|
||||||
|
| GET | /health | cache type + upstream reachability |
|
||||||
|
| GET | /<u> | composite SVG (cached on X-Widget-Status: ready) |
|
||||||
|
| GET | /<u>/<w>.svg | individual widget SVG |
|
||||||
|
|
||||||
|
## Env
|
||||||
|
|
||||||
|
- `GENERATOR_URL` — origin (required)
|
||||||
|
- `CACHE_TYPE` — `SimpleCache` (default) or `RedisCache`
|
||||||
|
- `CACHE_REDIS_URL` — if using RedisCache
|
||||||
|
- `CACHE_DEFAULT_TIMEOUT` — seconds, default 86400
|
||||||
|
- `CACHE_THRESHOLD` — max entries (SimpleCache only), default 10000
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
[pytest]
|
||||||
|
testpaths = tests
|
||||||
|
python_files = test_*.py
|
||||||
|
pythonpath = .
|
||||||
|
addopts = -ra --strict-markers
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
flask==3.0.3
|
||||||
|
flask-caching==2.3.0
|
||||||
|
flask-compress==1.15
|
||||||
|
requests==2.32.3
|
||||||
|
pytest==8.3.3
|
||||||
|
responses==0.25.3
|
||||||
|
gunicorn==23.0.0
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
"""Edge service — cache-first SVG proxy in front of the generator."""
|
||||||
|
import logging
|
||||||
|
import requests
|
||||||
|
from flask import Flask, Response, jsonify
|
||||||
|
from flask_compress import Compress
|
||||||
|
|
||||||
|
from . import cache as cache_mod, config
|
||||||
|
|
||||||
|
app = Flask(__name__)
|
||||||
|
Compress(app)
|
||||||
|
cache_ext = cache_mod.build_cache(app)
|
||||||
|
log = logging.getLogger("edge")
|
||||||
|
|
||||||
|
|
||||||
|
def _cache_key(path: str) -> str:
|
||||||
|
return f"edge:{path}"
|
||||||
|
|
||||||
|
|
||||||
|
def _fetch_origin(path: str) -> requests.Response:
|
||||||
|
url = f"{config.GENERATOR_URL}/api/{path}"
|
||||||
|
return requests.get(url, timeout=config.UPSTREAM_TIMEOUT)
|
||||||
|
|
||||||
|
|
||||||
|
@app.route("/health", methods=["GET"])
|
||||||
|
def health():
|
||||||
|
ok = True
|
||||||
|
try:
|
||||||
|
r = requests.get(f"{config.GENERATOR_URL}/api/health", timeout=config.UPSTREAM_TIMEOUT)
|
||||||
|
ok = r.status_code == 200
|
||||||
|
except Exception:
|
||||||
|
ok = False
|
||||||
|
return jsonify({"service": "edge", "cache_type": config.CACHE_TYPE, "upstream_ok": ok})
|
||||||
|
|
||||||
|
|
||||||
|
@app.route("/<username>", methods=["GET"])
|
||||||
|
def serve(username: str):
|
||||||
|
return _serve(username, path=username)
|
||||||
|
|
||||||
|
|
||||||
|
@app.route("/<username>/<widget>.svg", methods=["GET"])
|
||||||
|
def serve_widget(username: str, widget: str):
|
||||||
|
return _serve(f"{username}/{widget}", path=f"{username}/{widget}.svg")
|
||||||
|
|
||||||
|
|
||||||
|
def _serve(key_suffix: str, path: str) -> Response:
|
||||||
|
ck = _cache_key(key_suffix)
|
||||||
|
cached = cache_ext.get(ck)
|
||||||
|
if cached is not None:
|
||||||
|
body, content_type = cached
|
||||||
|
return Response(body, mimetype=content_type, headers={
|
||||||
|
"X-Widget-Status": "ready",
|
||||||
|
"X-Cache": "HIT",
|
||||||
|
"Cache-Control": "public, max-age=3600, s-maxage=86400, stale-while-revalidate=86400",
|
||||||
|
})
|
||||||
|
|
||||||
|
try:
|
||||||
|
r = _fetch_origin(path)
|
||||||
|
except Exception as e:
|
||||||
|
log.warning("origin unreachable for %s: %s", path, e)
|
||||||
|
return jsonify({"error": "origin unreachable"}), 503
|
||||||
|
|
||||||
|
if r.status_code >= 500:
|
||||||
|
return jsonify({"error": "origin error"}), 503
|
||||||
|
|
||||||
|
status = r.headers.get("X-Widget-Status", "ready")
|
||||||
|
content_type = r.headers.get("Content-Type", "image/svg+xml")
|
||||||
|
if status == "ready" and r.status_code == 200:
|
||||||
|
cache_ext.set(ck, (r.content, content_type), timeout=config.CACHE_DEFAULT_TIMEOUT)
|
||||||
|
cc = "public, max-age=3600, s-maxage=86400, stale-while-revalidate=86400"
|
||||||
|
else:
|
||||||
|
cc = "no-store"
|
||||||
|
|
||||||
|
return Response(r.content, status=r.status_code, mimetype=content_type, headers={
|
||||||
|
"X-Widget-Status": status,
|
||||||
|
"X-Cache": "MISS",
|
||||||
|
"Cache-Control": cc,
|
||||||
|
})
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
app.run(host="0.0.0.0", port=config.PORT)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
"""Flask-Caching config. v1 = SimpleCache (in-process). Swap to RedisCache via env."""
|
||||||
|
from flask_caching import Cache
|
||||||
|
from . import config
|
||||||
|
|
||||||
|
|
||||||
|
def build_cache(app) -> Cache:
|
||||||
|
cfg = {
|
||||||
|
"CACHE_TYPE": config.CACHE_TYPE,
|
||||||
|
"CACHE_DEFAULT_TIMEOUT": config.CACHE_DEFAULT_TIMEOUT,
|
||||||
|
"CACHE_THRESHOLD": config.CACHE_THRESHOLD,
|
||||||
|
}
|
||||||
|
if config.CACHE_TYPE == "RedisCache" and config.CACHE_REDIS_URL:
|
||||||
|
cfg["CACHE_REDIS_URL"] = config.CACHE_REDIS_URL
|
||||||
|
c = Cache(config=cfg)
|
||||||
|
c.init_app(app)
|
||||||
|
return c
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
import os
|
||||||
|
|
||||||
|
PORT = int(os.getenv("EDGE_PORT", "5003"))
|
||||||
|
GENERATOR_URL = os.getenv("GENERATOR_URL", "http://localhost:5002")
|
||||||
|
CACHE_TYPE = os.getenv("CACHE_TYPE", "SimpleCache")
|
||||||
|
CACHE_REDIS_URL = os.getenv("CACHE_REDIS_URL", "")
|
||||||
|
CACHE_DEFAULT_TIMEOUT = int(os.getenv("CACHE_DEFAULT_TIMEOUT", "86400"))
|
||||||
|
CACHE_THRESHOLD = int(os.getenv("CACHE_THRESHOLD", "10000"))
|
||||||
|
UPSTREAM_TIMEOUT = int(os.getenv("EDGE_UPSTREAM_TIMEOUT", "10"))
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
import pytest
|
||||||
|
import responses
|
||||||
|
from src import api as apimod
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def client(monkeypatch):
|
||||||
|
monkeypatch.setattr(apimod.config, "GENERATOR_URL", "http://gen:5002")
|
||||||
|
apimod.cache_ext.clear()
|
||||||
|
apimod.app.config["TESTING"] = True
|
||||||
|
with apimod.app.test_client() as c:
|
||||||
|
yield c
|
||||||
|
|
||||||
|
|
||||||
|
@responses.activate
|
||||||
|
def test_miss_then_hit_serves_from_cache(client):
|
||||||
|
responses.add(responses.GET, "http://gen:5002/api/alice",
|
||||||
|
body=b"<svg>ready</svg>", status=200,
|
||||||
|
headers={"X-Widget-Status": "ready", "Content-Type": "image/svg+xml"})
|
||||||
|
r1 = client.get("/alice")
|
||||||
|
assert r1.status_code == 200
|
||||||
|
assert r1.data == b"<svg>ready</svg>"
|
||||||
|
responses.reset()
|
||||||
|
r2 = client.get("/alice")
|
||||||
|
assert r2.status_code == 200
|
||||||
|
assert r2.data == b"<svg>ready</svg>"
|
||||||
|
|
||||||
|
|
||||||
|
@responses.activate
|
||||||
|
def test_placeholder_not_cached(client):
|
||||||
|
responses.add(responses.GET, "http://gen:5002/api/alice",
|
||||||
|
body=b"<svg>building</svg>", status=200,
|
||||||
|
headers={"X-Widget-Status": "building", "Content-Type": "image/svg+xml"})
|
||||||
|
r1 = client.get("/alice")
|
||||||
|
assert r1.status_code == 200
|
||||||
|
r2 = client.get("/alice")
|
||||||
|
assert len(responses.calls) == 2
|
||||||
|
|
||||||
|
|
||||||
|
@responses.activate
|
||||||
|
def test_origin_error_returns_503(client):
|
||||||
|
responses.add(responses.GET, "http://gen:5002/api/alice", status=500)
|
||||||
|
r = client.get("/alice")
|
||||||
|
assert r.status_code == 503
|
||||||
|
|
||||||
|
|
||||||
|
def test_health(client):
|
||||||
|
r = client.get("/health")
|
||||||
|
assert r.status_code == 200
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
FROM python:3.11-slim
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
COPY requirements.txt ./
|
||||||
|
RUN pip install --no-cache-dir -r requirements.txt
|
||||||
|
|
||||||
|
COPY src ./src
|
||||||
|
RUN mkdir -p /app/data
|
||||||
|
|
||||||
|
EXPOSE 5001
|
||||||
|
ENV FETCHER_DB_PATH=/app/data/fetcher.db
|
||||||
|
|
||||||
|
# Default is the API. Override CMD for cron: ["python", "-m", "src.cron"]
|
||||||
|
CMD ["gunicorn", "-b", "0.0.0.0:5001", "-w", "2", "src.api:app"]
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
# Fetcher Service
|
||||||
|
|
||||||
|
Owns every GitHub API interaction. Holds the PAT. Exposes cached payloads
|
||||||
|
over an internal-only HTTP API protected by a shared secret.
|
||||||
|
|
||||||
|
## Run locally
|
||||||
|
|
||||||
|
cd fetcher
|
||||||
|
pip install -r requirements.txt
|
||||||
|
FETCHER_INTERNAL_TOKEN=dev GITHUB_PAT=ghp_xxx python -m src.api
|
||||||
|
|
||||||
|
Cron (separate process):
|
||||||
|
|
||||||
|
FETCHER_INTERNAL_TOKEN=dev GITHUB_PAT=ghp_xxx python -m src.cron
|
||||||
|
|
||||||
|
## Test
|
||||||
|
|
||||||
|
cd fetcher && pytest
|
||||||
|
|
||||||
|
## Docker
|
||||||
|
|
||||||
|
docker build -t ghstats-fetcher .
|
||||||
|
docker run -e GITHUB_PAT=ghp_xxx -e FETCHER_INTERNAL_TOKEN=dev -p 5001:5001 -v $(pwd)/data:/app/data ghstats-fetcher
|
||||||
|
# cron: override CMD to ["python","-m","src.cron"]
|
||||||
|
|
||||||
|
## Endpoints
|
||||||
|
|
||||||
|
| Method | Path | Auth | Description |
|
||||||
|
|---|---|---|---|
|
||||||
|
| GET | /health | none | health check |
|
||||||
|
| GET | /data/<u> | X-Internal-Token | return stored payload; auto-fetches on miss |
|
||||||
|
| POST | /fetch | X-Internal-Token | force re-fetch (body: {username}) |
|
||||||
|
| GET | /avatar/<u> | X-Internal-Token | proxied avatar bytes |
|
||||||
|
|
||||||
|
## Env
|
||||||
|
|
||||||
|
See `src/config.py`.
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
[pytest]
|
||||||
|
testpaths = tests
|
||||||
|
python_files = test_*.py
|
||||||
|
pythonpath = .
|
||||||
|
addopts = -ra --strict-markers
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
flask==3.0.3
|
||||||
|
requests==2.32.3
|
||||||
|
pytest==8.3.3
|
||||||
|
responses==0.25.3
|
||||||
|
gunicorn==23.0.0
|
||||||
@@ -0,0 +1,89 @@
|
|||||||
|
"""Flask app for the fetcher service. All endpoints require X-Internal-Token."""
|
||||||
|
import hmac
|
||||||
|
import requests
|
||||||
|
from flask import Flask, jsonify, request, Response
|
||||||
|
from functools import wraps
|
||||||
|
|
||||||
|
from . import config, db, github
|
||||||
|
|
||||||
|
app = Flask(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
def require_internal_token(fn):
|
||||||
|
@wraps(fn)
|
||||||
|
def wrapper(*args, **kwargs):
|
||||||
|
token = request.headers.get("X-Internal-Token", "")
|
||||||
|
if not config.INTERNAL_TOKEN or not hmac.compare_digest(token, config.INTERNAL_TOKEN):
|
||||||
|
return jsonify({"error": "unauthorized"}), 401
|
||||||
|
return fn(*args, **kwargs)
|
||||||
|
return wrapper
|
||||||
|
|
||||||
|
|
||||||
|
@app.route("/health", methods=["GET"])
|
||||||
|
def health():
|
||||||
|
return jsonify({"status": "ok", "service": "fetcher", "users": len(db.list_usernames())})
|
||||||
|
|
||||||
|
|
||||||
|
@app.route("/data/<username>", methods=["GET"])
|
||||||
|
@require_internal_token
|
||||||
|
def get_data(username: str):
|
||||||
|
row = db.get_user(username)
|
||||||
|
if row is None:
|
||||||
|
# Auto-fetch path
|
||||||
|
data = github.fetch_github_data(username, token=config.GITHUB_PAT)
|
||||||
|
if _is_github_not_found(data):
|
||||||
|
data = {"error": "not_found"}
|
||||||
|
h = db.upsert_user(username, data)
|
||||||
|
return jsonify({"data": data, "payload_hash": h, "fetched": True})
|
||||||
|
return jsonify({
|
||||||
|
"data": row["data"],
|
||||||
|
"payload_hash": row["payload_hash"],
|
||||||
|
"fetched_at": row["fetched_at"],
|
||||||
|
"fetched": False,
|
||||||
|
})
|
||||||
|
|
||||||
|
|
||||||
|
@app.route("/fetch", methods=["POST"])
|
||||||
|
@require_internal_token
|
||||||
|
def force_fetch():
|
||||||
|
body = request.get_json(silent=True) or {}
|
||||||
|
username = body.get("username")
|
||||||
|
if not username:
|
||||||
|
return jsonify({"error": "username required"}), 400
|
||||||
|
try:
|
||||||
|
data = github.fetch_github_data(username, token=config.GITHUB_PAT)
|
||||||
|
except Exception as e:
|
||||||
|
return jsonify({"error": f"fetch failed: {e}"}), 502
|
||||||
|
if _is_github_not_found(data):
|
||||||
|
data = {"error": "not_found"}
|
||||||
|
old = db.get_user(username)
|
||||||
|
old_hash = old["payload_hash"] if old else None
|
||||||
|
new_hash = db.upsert_user(username, data)
|
||||||
|
return jsonify({"stored": True, "payload_hash": new_hash, "changed": old_hash != new_hash})
|
||||||
|
|
||||||
|
|
||||||
|
@app.route("/avatar/<username>", methods=["GET"])
|
||||||
|
@require_internal_token
|
||||||
|
def avatar(username: str):
|
||||||
|
r = requests.get(f"https://github.com/{username}.png", timeout=config.API_TIMEOUT, allow_redirects=True)
|
||||||
|
if r.status_code != 200:
|
||||||
|
return jsonify({"error": "avatar unavailable"}), 404
|
||||||
|
return Response(r.content, mimetype=r.headers.get("Content-Type", "image/png"))
|
||||||
|
|
||||||
|
|
||||||
|
def _is_github_not_found(data: dict) -> bool:
|
||||||
|
user = data.get("user")
|
||||||
|
if user is None:
|
||||||
|
return True
|
||||||
|
if isinstance(user, dict) and user.get("message") == "Not Found":
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
db.init_db()
|
||||||
|
app.run(host="0.0.0.0", port=config.PORT)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
"""Fetcher service configuration, overridable via env vars."""
|
||||||
|
import os
|
||||||
|
|
||||||
|
PORT = int(os.getenv("FETCHER_PORT", "5001"))
|
||||||
|
DB_PATH = os.getenv("FETCHER_DB_PATH", "./data/fetcher.db")
|
||||||
|
GITHUB_PAT = os.getenv("GITHUB_PAT", "")
|
||||||
|
INTERNAL_TOKEN = os.getenv("FETCHER_INTERNAL_TOKEN", "")
|
||||||
|
REFRESH_INTERVAL_HOURS = int(os.getenv("FETCHER_REFRESH_INTERVAL_HOURS", "24"))
|
||||||
|
TRIAL_GC_DAYS = int(os.getenv("FETCHER_TRIAL_GC_DAYS", "7"))
|
||||||
|
API_TIMEOUT = int(os.getenv("API_TIMEOUT", "15"))
|
||||||
|
|
||||||
|
# Collaborator-detection tuning
|
||||||
|
COLLABORATOR_MAX_REPO_SIZE = int(os.getenv("COLLABORATOR_MAX_REPO_SIZE", "150"))
|
||||||
|
COLLABORATOR_TOP_REPOS = int(os.getenv("COLLABORATOR_TOP_REPOS", "30"))
|
||||||
|
SMALL_OWNED_REPO_SIZE = int(os.getenv("SMALL_OWNED_REPO_SIZE", "10"))
|
||||||
|
COLLABORATOR_LOOKBACK_DAYS = int(os.getenv("COLLABORATOR_LOOKBACK_DAYS", "365"))
|
||||||
|
MEANINGFUL_MIN_COMMITS = int(os.getenv("MEANINGFUL_MIN_COMMITS", "3"))
|
||||||
|
FORK_MIN_COMMITS = int(os.getenv("FORK_MIN_COMMITS", "10"))
|
||||||
|
OWNER_BOOST = float(os.getenv("OWNER_BOOST", "1.5"))
|
||||||
|
MIN_SHARED_REPOS = int(os.getenv("MIN_SHARED_REPOS", "2"))
|
||||||
|
DEEP_COLLAB_THRESHOLD = int(os.getenv("DEEP_COLLAB_THRESHOLD", "25"))
|
||||||
|
|
||||||
|
# Commit-fetching caps
|
||||||
|
COMMIT_MAX_REPOS = int(os.getenv("COMMIT_MAX_REPOS", "10"))
|
||||||
|
COMMIT_PER_REPO = int(os.getenv("COMMIT_PER_REPO", "30"))
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
"""Scheduled refresh + GC loop. Run as its own container (CMD override)."""
|
||||||
|
import logging
|
||||||
|
import time
|
||||||
|
|
||||||
|
from . import config, db, github
|
||||||
|
|
||||||
|
log = logging.getLogger("fetcher.cron")
|
||||||
|
|
||||||
|
|
||||||
|
def tick(hours: int, active_within_days: int, gc_days: int) -> dict:
|
||||||
|
"""Refresh due users, then GC abandoned ones. Returns counts."""
|
||||||
|
refreshed = 0
|
||||||
|
failed = 0
|
||||||
|
due = db.users_due_for_refresh(hours=hours, active_within_days=active_within_days)
|
||||||
|
for username in due:
|
||||||
|
try:
|
||||||
|
data = github.fetch_github_data(username, token=config.GITHUB_PAT)
|
||||||
|
user = data.get("user")
|
||||||
|
if user is None or (isinstance(user, dict) and user.get("message") == "Not Found"):
|
||||||
|
data = {"error": "not_found"}
|
||||||
|
db.upsert_user(username, data)
|
||||||
|
refreshed += 1
|
||||||
|
except Exception as e:
|
||||||
|
log.warning("refresh failed for %s: %s", username, e)
|
||||||
|
failed += 1
|
||||||
|
gc_removed = db.delete_stale(days=gc_days)
|
||||||
|
return {"refreshed": refreshed, "failed": failed, "gc_removed": gc_removed}
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s %(message)s")
|
||||||
|
db.init_db()
|
||||||
|
interval = 3600 # 1h between ticks
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
stats = tick(
|
||||||
|
hours=config.REFRESH_INTERVAL_HOURS,
|
||||||
|
active_within_days=config.TRIAL_GC_DAYS,
|
||||||
|
gc_days=config.TRIAL_GC_DAYS,
|
||||||
|
)
|
||||||
|
log.info("tick complete: %s", stats)
|
||||||
|
except Exception:
|
||||||
|
log.exception("tick failed")
|
||||||
|
time.sleep(interval)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,121 @@
|
|||||||
|
"""SQLite repository for the fetcher service.
|
||||||
|
|
||||||
|
Single table: users (raw GitHub payloads keyed by username).
|
||||||
|
Uses WAL mode so concurrent readers don't block the writer.
|
||||||
|
"""
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import sqlite3
|
||||||
|
from contextlib import contextmanager
|
||||||
|
from datetime import datetime, timedelta
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
from . import config
|
||||||
|
|
||||||
|
DB_PATH = config.DB_PATH
|
||||||
|
|
||||||
|
SCHEMA_SQL = """
|
||||||
|
CREATE TABLE IF NOT EXISTS users (
|
||||||
|
username TEXT PRIMARY KEY,
|
||||||
|
data_json TEXT NOT NULL,
|
||||||
|
payload_hash TEXT NOT NULL,
|
||||||
|
fetched_at TEXT NOT NULL,
|
||||||
|
last_requested_at TEXT NOT NULL
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_users_fetched_at ON users(fetched_at);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_users_last_requested_at ON users(last_requested_at);
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
def _now() -> str:
|
||||||
|
return datetime.utcnow().isoformat(timespec="seconds") + "Z"
|
||||||
|
|
||||||
|
|
||||||
|
@contextmanager
|
||||||
|
def _connect():
|
||||||
|
os.makedirs(os.path.dirname(DB_PATH) or ".", exist_ok=True)
|
||||||
|
conn = sqlite3.connect(DB_PATH, timeout=10)
|
||||||
|
conn.row_factory = sqlite3.Row
|
||||||
|
conn.execute("PRAGMA journal_mode=WAL")
|
||||||
|
conn.execute("PRAGMA synchronous=NORMAL")
|
||||||
|
conn.execute("PRAGMA foreign_keys=ON")
|
||||||
|
conn.execute("PRAGMA busy_timeout=5000")
|
||||||
|
try:
|
||||||
|
yield conn
|
||||||
|
conn.commit()
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def init_db() -> None:
|
||||||
|
with _connect() as c:
|
||||||
|
c.executescript(SCHEMA_SQL)
|
||||||
|
c.commit()
|
||||||
|
|
||||||
|
|
||||||
|
def payload_hash(data: dict) -> str:
|
||||||
|
canonical = json.dumps(data, sort_keys=True, separators=(",", ":"))
|
||||||
|
return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
|
||||||
|
|
||||||
|
|
||||||
|
def upsert_user(username: str, data: dict) -> str:
|
||||||
|
h = payload_hash(data)
|
||||||
|
now = _now()
|
||||||
|
with _connect() as c:
|
||||||
|
c.execute(
|
||||||
|
"""INSERT INTO users(username, data_json, payload_hash, fetched_at, last_requested_at)
|
||||||
|
VALUES (?, ?, ?, ?, ?)
|
||||||
|
ON CONFLICT(username) DO UPDATE SET
|
||||||
|
data_json = excluded.data_json,
|
||||||
|
payload_hash = excluded.payload_hash,
|
||||||
|
fetched_at = excluded.fetched_at""",
|
||||||
|
(username, json.dumps(data), h, now, now),
|
||||||
|
)
|
||||||
|
c.commit()
|
||||||
|
return h
|
||||||
|
|
||||||
|
|
||||||
|
def get_user(username: str) -> Optional[dict]:
|
||||||
|
"""Returns {data, payload_hash, fetched_at, last_requested_at} or None. Updates last_requested_at."""
|
||||||
|
now = _now()
|
||||||
|
with _connect() as c:
|
||||||
|
row = c.execute(
|
||||||
|
"SELECT data_json, payload_hash, fetched_at, last_requested_at FROM users WHERE username=?",
|
||||||
|
(username,),
|
||||||
|
).fetchone()
|
||||||
|
if row is None:
|
||||||
|
return None
|
||||||
|
c.execute("UPDATE users SET last_requested_at=? WHERE username=?", (now, username))
|
||||||
|
c.commit()
|
||||||
|
return {
|
||||||
|
"data": json.loads(row["data_json"]),
|
||||||
|
"payload_hash": row["payload_hash"],
|
||||||
|
"fetched_at": row["fetched_at"],
|
||||||
|
"last_requested_at": now,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def delete_stale(days: int) -> int:
|
||||||
|
cutoff = (datetime.utcnow() - timedelta(days=days)).isoformat(timespec="seconds") + "Z"
|
||||||
|
with _connect() as c:
|
||||||
|
cur = c.execute("DELETE FROM users WHERE last_requested_at < ?", (cutoff,))
|
||||||
|
c.commit()
|
||||||
|
return cur.rowcount
|
||||||
|
|
||||||
|
|
||||||
|
def users_due_for_refresh(hours: int, active_within_days: int) -> list[str]:
|
||||||
|
"""Return usernames with fetched_at older than `hours` and last_requested_at within `active_within_days`."""
|
||||||
|
stale_before = (datetime.utcnow() - timedelta(hours=hours)).isoformat(timespec="seconds") + "Z"
|
||||||
|
active_after = (datetime.utcnow() - timedelta(days=active_within_days)).isoformat(timespec="seconds") + "Z"
|
||||||
|
with _connect() as c:
|
||||||
|
rows = c.execute(
|
||||||
|
"SELECT username FROM users WHERE fetched_at < ? AND last_requested_at > ?",
|
||||||
|
(stale_before, active_after),
|
||||||
|
).fetchall()
|
||||||
|
return [r["username"] for r in rows]
|
||||||
|
|
||||||
|
|
||||||
|
def list_usernames() -> list[str]:
|
||||||
|
with _connect() as c:
|
||||||
|
return [r["username"] for r in c.execute("SELECT username FROM users ORDER BY username").fetchall()]
|
||||||
@@ -4,20 +4,7 @@ import requests
|
|||||||
import base64
|
import base64
|
||||||
from typing import Optional, Protocol
|
from typing import Optional, Protocol
|
||||||
|
|
||||||
from ..config import (
|
from . import config
|
||||||
COLLABORATOR_MAX_REPO_SIZE,
|
|
||||||
COLLABORATOR_TOP_REPOS,
|
|
||||||
COLLABORATOR_LOOKBACK_DAYS,
|
|
||||||
MEANINGFUL_MIN_COMMITS,
|
|
||||||
FORK_MIN_COMMITS,
|
|
||||||
OWNER_BOOST,
|
|
||||||
MIN_SHARED_REPOS,
|
|
||||||
DEEP_COLLAB_THRESHOLD,
|
|
||||||
SMALL_OWNED_REPO_SIZE,
|
|
||||||
COMMIT_MAX_REPOS,
|
|
||||||
COMMIT_PER_REPO,
|
|
||||||
API_TIMEOUT,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
class GitHubDataSource(Protocol):
|
class GitHubDataSource(Protocol):
|
||||||
@@ -91,7 +78,7 @@ class DirectAPISource:
|
|||||||
"https://api.github.com/graphql",
|
"https://api.github.com/graphql",
|
||||||
json=payload,
|
json=payload,
|
||||||
headers=headers,
|
headers=headers,
|
||||||
timeout=API_TIMEOUT,
|
timeout=config.API_TIMEOUT,
|
||||||
)
|
)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f" GraphQL request failed: {e}")
|
print(f" GraphQL request failed: {e}")
|
||||||
@@ -203,7 +190,7 @@ class DirectAPISource:
|
|||||||
'https://api.github.com/graphql',
|
'https://api.github.com/graphql',
|
||||||
json={'query': query},
|
json={'query': query},
|
||||||
headers=headers,
|
headers=headers,
|
||||||
timeout=API_TIMEOUT
|
timeout=config.API_TIMEOUT
|
||||||
)
|
)
|
||||||
|
|
||||||
if not resp.ok:
|
if not resp.ok:
|
||||||
@@ -287,7 +274,7 @@ class DirectAPISource:
|
|||||||
'https://api.github.com/graphql',
|
'https://api.github.com/graphql',
|
||||||
json={'query': query, 'variables': {'username': username}},
|
json={'query': query, 'variables': {'username': username}},
|
||||||
headers=headers,
|
headers=headers,
|
||||||
timeout=API_TIMEOUT
|
timeout=config.API_TIMEOUT
|
||||||
)
|
)
|
||||||
|
|
||||||
if not resp.ok or 'data' not in resp.json():
|
if not resp.ok or 'data' not in resp.json():
|
||||||
@@ -322,7 +309,7 @@ class DirectAPISource:
|
|||||||
'https://api.github.com/graphql',
|
'https://api.github.com/graphql',
|
||||||
json={'query': year_query},
|
json={'query': year_query},
|
||||||
headers=headers,
|
headers=headers,
|
||||||
timeout=API_TIMEOUT
|
timeout=config.API_TIMEOUT
|
||||||
)
|
)
|
||||||
|
|
||||||
if year_resp.ok:
|
if year_resp.ok:
|
||||||
@@ -371,7 +358,7 @@ class DirectAPISource:
|
|||||||
'https://api.github.com/graphql',
|
'https://api.github.com/graphql',
|
||||||
json={'query': query},
|
json={'query': query},
|
||||||
headers=headers,
|
headers=headers,
|
||||||
timeout=API_TIMEOUT
|
timeout=config.API_TIMEOUT
|
||||||
)
|
)
|
||||||
|
|
||||||
if resp.ok:
|
if resp.ok:
|
||||||
@@ -401,7 +388,7 @@ class DirectAPISource:
|
|||||||
f"{self.base}/search/issues",
|
f"{self.base}/search/issues",
|
||||||
headers=self.headers,
|
headers=self.headers,
|
||||||
params={"q": query, "per_page": 1},
|
params={"q": query, "per_page": 1},
|
||||||
timeout=API_TIMEOUT
|
timeout=config.API_TIMEOUT
|
||||||
)
|
)
|
||||||
|
|
||||||
if resp.ok:
|
if resp.ok:
|
||||||
@@ -428,7 +415,7 @@ class DirectAPISource:
|
|||||||
f"{self.base}/repos/{repo_name}/contributors",
|
f"{self.base}/repos/{repo_name}/contributors",
|
||||||
headers=self.headers,
|
headers=self.headers,
|
||||||
params={"per_page": 100},
|
params={"per_page": 100},
|
||||||
timeout=API_TIMEOUT
|
timeout=config.API_TIMEOUT
|
||||||
)
|
)
|
||||||
|
|
||||||
if resp.ok:
|
if resp.ok:
|
||||||
@@ -508,7 +495,7 @@ class DirectAPISource:
|
|||||||
def fetch_avatar(self, avatar_url: str) -> str:
|
def fetch_avatar(self, avatar_url: str) -> str:
|
||||||
"""Fetch and encode avatar as base64."""
|
"""Fetch and encode avatar as base64."""
|
||||||
try:
|
try:
|
||||||
resp = requests.get(avatar_url + "&s=64", timeout=API_TIMEOUT)
|
resp = requests.get(avatar_url + "&s=64", timeout=config.API_TIMEOUT)
|
||||||
if resp.ok:
|
if resp.ok:
|
||||||
return base64.b64encode(resp.content).decode("ascii")
|
return base64.b64encode(resp.content).decode("ascii")
|
||||||
except Exception:
|
except Exception:
|
||||||
@@ -627,7 +614,7 @@ def _fetch_collaborators_data(
|
|||||||
low = login.lower()
|
low = login.lower()
|
||||||
return low in BOT_LOGINS or low.endswith("[bot]") or low.endswith("-bot")
|
return low in BOT_LOGINS or low.endswith("[bot]") or low.endswith("-bot")
|
||||||
|
|
||||||
since = (datetime.now() - timedelta(days=COLLABORATOR_LOOKBACK_DAYS)).strftime("%Y-%m-%d")
|
since = (datetime.now() - timedelta(days=config.COLLABORATOR_LOOKBACK_DAYS)).strftime("%Y-%m-%d")
|
||||||
commit_repos = source.fetch_user_commit_repos(username, since)
|
commit_repos = source.fetch_user_commit_repos(username, since)
|
||||||
if not commit_repos:
|
if not commit_repos:
|
||||||
return []
|
return []
|
||||||
@@ -636,15 +623,15 @@ def _fetch_collaborators_data(
|
|||||||
qualifying = []
|
qualifying = []
|
||||||
for r in commit_repos:
|
for r in commit_repos:
|
||||||
user_commits = r.get("user_commits", 0)
|
user_commits = r.get("user_commits", 0)
|
||||||
if user_commits < MEANINGFUL_MIN_COMMITS:
|
if user_commits < config.MEANINGFUL_MIN_COMMITS:
|
||||||
continue
|
continue
|
||||||
if r.get("is_fork") and user_commits < FORK_MIN_COMMITS:
|
if r.get("is_fork") and user_commits < config.FORK_MIN_COMMITS:
|
||||||
continue
|
continue
|
||||||
qualifying.append(r)
|
qualifying.append(r)
|
||||||
|
|
||||||
# Rank user's repos by their own commit count, scan top N
|
# Rank user's repos by their own commit count, scan top N
|
||||||
qualifying.sort(key=lambda r: -r.get("user_commits", 0))
|
qualifying.sort(key=lambda r: -r.get("user_commits", 0))
|
||||||
qualifying = qualifying[:COLLABORATOR_TOP_REPOS]
|
qualifying = qualifying[:config.COLLABORATOR_TOP_REPOS]
|
||||||
print(f" Scoring collaborators across {len(qualifying)} qualifying repos")
|
print(f" Scoring collaborators across {len(qualifying)} qualifying repos")
|
||||||
|
|
||||||
# Step 3+4: fetch contributors and score
|
# Step 3+4: fetch contributors and score
|
||||||
@@ -652,17 +639,17 @@ def _fetch_collaborators_data(
|
|||||||
for r in qualifying:
|
for r in qualifying:
|
||||||
full_name = r["full_name"]
|
full_name = r["full_name"]
|
||||||
user_commits = r["user_commits"]
|
user_commits = r["user_commits"]
|
||||||
boost = OWNER_BOOST if r["is_owner"] else 1.0
|
boost = config.OWNER_BOOST if r["is_owner"] else 1.0
|
||||||
|
|
||||||
contributors = source.fetch_repo_contributors(full_name, min_commits=1)
|
contributors = source.fetch_repo_contributors(full_name, min_commits=1)
|
||||||
# Drop huge OSS projects
|
# Drop huge OSS projects
|
||||||
if len(contributors) >= COLLABORATOR_MAX_REPO_SIZE:
|
if len(contributors) >= config.COLLABORATOR_MAX_REPO_SIZE:
|
||||||
print(f" skipping {full_name}: too many contributors ({len(contributors)})")
|
print(f" skipping {full_name}: too many contributors ({len(contributors)})")
|
||||||
continue
|
continue
|
||||||
|
|
||||||
# A "tight" repo: one the user owns with few contributors — hackathon
|
# A "tight" repo: one the user owns with few contributors — hackathon
|
||||||
# and side-project partners qualify from a single such repo.
|
# and side-project partners qualify from a single such repo.
|
||||||
is_tight_owned = r["is_owner"] and len(contributors) <= SMALL_OWNED_REPO_SIZE
|
is_tight_owned = r["is_owner"] and len(contributors) <= config.SMALL_OWNED_REPO_SIZE
|
||||||
|
|
||||||
for c in contributors:
|
for c in contributors:
|
||||||
login = c.get("login", "")
|
login = c.get("login", "")
|
||||||
@@ -705,8 +692,8 @@ def _fetch_collaborators_data(
|
|||||||
# or a partner in a tight user-owned project (hackathon/side-project).
|
# or a partner in a tight user-owned project (hackathon/side-project).
|
||||||
filtered = [
|
filtered = [
|
||||||
s for s in scored
|
s for s in scored
|
||||||
if s["shared_repos"] >= MIN_SHARED_REPOS
|
if s["shared_repos"] >= config.MIN_SHARED_REPOS
|
||||||
or s["raw_score"] >= DEEP_COLLAB_THRESHOLD
|
or s["raw_score"] >= config.DEEP_COLLAB_THRESHOLD
|
||||||
or s["tight_owned_partner"]
|
or s["tight_owned_partner"]
|
||||||
]
|
]
|
||||||
|
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
import os
|
||||||
|
import tempfile
|
||||||
|
import pytest
|
||||||
|
import responses as resp_lib
|
||||||
|
from src import db as dbmod
|
||||||
|
from src import api as apimod
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def client(monkeypatch):
|
||||||
|
with tempfile.TemporaryDirectory() as d:
|
||||||
|
monkeypatch.setattr(dbmod, "DB_PATH", os.path.join(d, "t.db"))
|
||||||
|
monkeypatch.setattr(apimod.config, "INTERNAL_TOKEN", "secret")
|
||||||
|
monkeypatch.setattr(apimod.config, "GITHUB_PAT", "ghp_test")
|
||||||
|
dbmod.init_db()
|
||||||
|
app = apimod.app
|
||||||
|
app.config["TESTING"] = True
|
||||||
|
with app.test_client() as c:
|
||||||
|
yield c
|
||||||
|
|
||||||
|
|
||||||
|
def test_health_no_auth_required(client):
|
||||||
|
r = client.get("/health")
|
||||||
|
assert r.status_code == 200
|
||||||
|
assert r.get_json()["service"] == "fetcher"
|
||||||
|
|
||||||
|
|
||||||
|
def test_endpoints_require_internal_token(client):
|
||||||
|
r = client.get("/data/alice")
|
||||||
|
assert r.status_code == 401
|
||||||
|
|
||||||
|
|
||||||
|
@resp_lib.activate
|
||||||
|
def test_data_auto_fetches_on_miss(client, monkeypatch):
|
||||||
|
# fetch_commits: contributionCalendar/weeks
|
||||||
|
resp_lib.add(resp_lib.POST, "https://api.github.com/graphql",
|
||||||
|
json={"data": {"user": {"contributionsCollection": {"contributionCalendar": {"weeks": []}}}}}, status=200)
|
||||||
|
# fetch_commit_count (alltime) — first call: get createdAt
|
||||||
|
resp_lib.add(resp_lib.POST, "https://api.github.com/graphql",
|
||||||
|
json={"data": {"user": {"createdAt": "2020-01-01T00:00:00Z"}}}, status=200)
|
||||||
|
# fetch_commit_count (alltime) — per-year contribution totals (2020–2026, 7 years)
|
||||||
|
for _ in range(7):
|
||||||
|
resp_lib.add(resp_lib.POST, "https://api.github.com/graphql",
|
||||||
|
json={"data": {"user": {"contributionsCollection": {"contributionCalendar": {"totalContributions": 10}}}}},
|
||||||
|
status=200)
|
||||||
|
# fetch_commit_count (recent, last 6 months)
|
||||||
|
resp_lib.add(resp_lib.POST, "https://api.github.com/graphql",
|
||||||
|
json={"data": {"user": {"contributionsCollection": {"contributionCalendar": {"totalContributions": 5}}}}},
|
||||||
|
status=200)
|
||||||
|
# fetch_user_commit_repos (for collaborators)
|
||||||
|
resp_lib.add(resp_lib.POST, "https://api.github.com/graphql",
|
||||||
|
json={"data": {"user": {"contributionsCollection": {"commitContributionsByRepository": []}}}},
|
||||||
|
status=200)
|
||||||
|
# PR count search
|
||||||
|
resp_lib.add(resp_lib.GET, "https://api.github.com/search/issues",
|
||||||
|
json={"total_count": 0, "items": []}, status=200)
|
||||||
|
resp_lib.add(resp_lib.GET, "https://api.github.com/users/alice",
|
||||||
|
json={"login": "alice", "public_repos": 1, "followers": 0, "avatar_url": "https://avatars.example/a"}, status=200)
|
||||||
|
# fetch_repos: two calls (owner + all)
|
||||||
|
resp_lib.add(resp_lib.GET, "https://api.github.com/users/alice/repos", json=[], status=200)
|
||||||
|
resp_lib.add(resp_lib.GET, "https://api.github.com/users/alice/repos", json=[], status=200)
|
||||||
|
resp_lib.add(resp_lib.GET, "https://api.github.com/users/alice/events", json=[], status=200)
|
||||||
|
|
||||||
|
r = client.get("/data/alice", headers={"X-Internal-Token": "secret"})
|
||||||
|
assert r.status_code == 200
|
||||||
|
body = r.get_json()
|
||||||
|
assert body["payload_hash"]
|
||||||
|
assert body["data"]["user"]["login"] == "alice"
|
||||||
|
|
||||||
|
|
||||||
|
def test_force_fetch_requires_auth(client):
|
||||||
|
r = client.post("/fetch", json={"username": "alice"})
|
||||||
|
assert r.status_code == 401
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
import os
|
||||||
|
import tempfile
|
||||||
|
import pytest
|
||||||
|
from unittest.mock import patch
|
||||||
|
from src import db as dbmod
|
||||||
|
from src import cron as cronmod
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def tmp_db(monkeypatch):
|
||||||
|
with tempfile.TemporaryDirectory() as d:
|
||||||
|
monkeypatch.setattr(dbmod, "DB_PATH", os.path.join(d, "t.db"))
|
||||||
|
dbmod.init_db()
|
||||||
|
yield
|
||||||
|
|
||||||
|
|
||||||
|
def test_refresh_tick_calls_github_for_due_users(tmp_db):
|
||||||
|
dbmod.upsert_user("alice", {"user": {"login": "alice"}})
|
||||||
|
# Backdate
|
||||||
|
with dbmod._connect() as c:
|
||||||
|
c.execute("UPDATE users SET fetched_at='2020-01-01T00:00:00Z', last_requested_at=? WHERE username='alice'",
|
||||||
|
(dbmod._now(),))
|
||||||
|
with patch("src.cron.github.fetch_github_data", return_value={"user": {"login": "alice", "updated": True}}) as gh:
|
||||||
|
stats = cronmod.tick(hours=24, active_within_days=7, gc_days=7)
|
||||||
|
assert gh.called
|
||||||
|
assert stats["refreshed"] == 1
|
||||||
|
|
||||||
|
|
||||||
|
def test_tick_runs_gc_for_abandoned_trial_users(tmp_db):
|
||||||
|
dbmod.upsert_user("ghost", {"user": {"login": "ghost"}})
|
||||||
|
with dbmod._connect() as c:
|
||||||
|
c.execute("UPDATE users SET last_requested_at='2020-01-01T00:00:00Z' WHERE username='ghost'")
|
||||||
|
stats = cronmod.tick(hours=24, active_within_days=7, gc_days=7)
|
||||||
|
assert stats["gc_removed"] == 1
|
||||||
|
assert dbmod.get_user("ghost") is None
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
import os
|
||||||
|
import tempfile
|
||||||
|
import pytest
|
||||||
|
from src import db as dbmod
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def tmp_db(monkeypatch):
|
||||||
|
with tempfile.TemporaryDirectory() as d:
|
||||||
|
path = os.path.join(d, "t.db")
|
||||||
|
monkeypatch.setattr(dbmod, "DB_PATH", path)
|
||||||
|
dbmod.init_db()
|
||||||
|
yield path
|
||||||
|
|
||||||
|
|
||||||
|
def test_init_creates_schema_with_wal(tmp_db):
|
||||||
|
with dbmod._connect() as c:
|
||||||
|
mode = c.execute("PRAGMA journal_mode").fetchone()[0]
|
||||||
|
assert mode.lower() == "wal"
|
||||||
|
cols = [r[1] for r in c.execute("PRAGMA table_info(users)").fetchall()]
|
||||||
|
assert set(cols) == {"username", "data_json", "payload_hash",
|
||||||
|
"fetched_at", "last_requested_at"}
|
||||||
|
|
||||||
|
|
||||||
|
def test_upsert_and_get_round_trip(tmp_db):
|
||||||
|
dbmod.upsert_user("alice", {"user": {"login": "alice"}, "repos": []})
|
||||||
|
row = dbmod.get_user("alice")
|
||||||
|
assert row["data"]["user"]["login"] == "alice"
|
||||||
|
assert row["payload_hash"]
|
||||||
|
assert row["fetched_at"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_payload_hash_is_deterministic_and_changes_on_diff():
|
||||||
|
h1 = dbmod.payload_hash({"a": 1, "b": 2})
|
||||||
|
h2 = dbmod.payload_hash({"b": 2, "a": 1})
|
||||||
|
h3 = dbmod.payload_hash({"a": 1, "b": 3})
|
||||||
|
assert h1 == h2
|
||||||
|
assert h1 != h3
|
||||||
|
|
||||||
|
|
||||||
|
def test_get_updates_last_requested_at(tmp_db):
|
||||||
|
dbmod.upsert_user("alice", {"user": {"login": "alice"}})
|
||||||
|
first = dbmod.get_user("alice")["last_requested_at"]
|
||||||
|
import time; time.sleep(1.1)
|
||||||
|
second = dbmod.get_user("alice")["last_requested_at"]
|
||||||
|
assert second > first
|
||||||
|
|
||||||
|
|
||||||
|
def test_delete_stale_removes_old_rows(tmp_db):
|
||||||
|
dbmod.upsert_user("ghost", {"user": {"login": "ghost"}})
|
||||||
|
# Manually backdate last_requested_at
|
||||||
|
with dbmod._connect() as c:
|
||||||
|
c.execute("UPDATE users SET last_requested_at='2020-01-01T00:00:00Z' WHERE username='ghost'")
|
||||||
|
removed = dbmod.delete_stale(days=7)
|
||||||
|
assert removed == 1
|
||||||
|
assert dbmod.get_user("ghost") is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_users_due_for_refresh(tmp_db):
|
||||||
|
dbmod.upsert_user("alice", {"user": {"login": "alice"}})
|
||||||
|
# Backdate fetched_at so alice is due
|
||||||
|
with dbmod._connect() as c:
|
||||||
|
c.execute("UPDATE users SET fetched_at='2020-01-01T00:00:00Z' WHERE username='alice'")
|
||||||
|
due = dbmod.users_due_for_refresh(hours=24, active_within_days=7)
|
||||||
|
assert "alice" in due
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
import responses
|
||||||
|
import pytest
|
||||||
|
from src import github
|
||||||
|
|
||||||
|
|
||||||
|
@responses.activate
|
||||||
|
def test_fetch_user_data_returns_user_payload():
|
||||||
|
# fetch_commits: contributionCalendar/weeks
|
||||||
|
responses.add(
|
||||||
|
responses.POST, "https://api.github.com/graphql",
|
||||||
|
json={"data": {"user": {"contributionsCollection": {"contributionCalendar": {"weeks": []}}}}},
|
||||||
|
status=200,
|
||||||
|
)
|
||||||
|
# fetch_commit_count (alltime) — first call: get createdAt
|
||||||
|
responses.add(
|
||||||
|
responses.POST, "https://api.github.com/graphql",
|
||||||
|
json={"data": {"user": {"createdAt": "2020-01-01T00:00:00Z"}}},
|
||||||
|
status=200,
|
||||||
|
)
|
||||||
|
# fetch_commit_count (alltime) — per-year contribution totals (2020–2026)
|
||||||
|
for _ in range(7):
|
||||||
|
responses.add(
|
||||||
|
responses.POST, "https://api.github.com/graphql",
|
||||||
|
json={"data": {"user": {"contributionsCollection": {"contributionCalendar": {"totalContributions": 10}}}}},
|
||||||
|
status=200,
|
||||||
|
)
|
||||||
|
# fetch_commit_count (recent, last 6 months)
|
||||||
|
responses.add(
|
||||||
|
responses.POST, "https://api.github.com/graphql",
|
||||||
|
json={"data": {"user": {"contributionsCollection": {"contributionCalendar": {"totalContributions": 5}}}}},
|
||||||
|
status=200,
|
||||||
|
)
|
||||||
|
# fetch_user_commit_repos (for collaborators)
|
||||||
|
responses.add(
|
||||||
|
responses.POST, "https://api.github.com/graphql",
|
||||||
|
json={"data": {"user": {"contributionsCollection": {"commitContributionsByRepository": []}}}},
|
||||||
|
status=200,
|
||||||
|
)
|
||||||
|
# PR count search
|
||||||
|
responses.add(
|
||||||
|
responses.GET, "https://api.github.com/search/issues",
|
||||||
|
json={"total_count": 0, "items": []},
|
||||||
|
status=200,
|
||||||
|
)
|
||||||
|
responses.add(
|
||||||
|
responses.GET, "https://api.github.com/users/alice",
|
||||||
|
json={"login": "alice", "public_repos": 3, "followers": 5, "avatar_url": "https://avatars.example/1"},
|
||||||
|
status=200,
|
||||||
|
)
|
||||||
|
# fetch_repos: two calls (owner + all)
|
||||||
|
responses.add(
|
||||||
|
responses.GET, "https://api.github.com/users/alice/repos",
|
||||||
|
json=[], status=200,
|
||||||
|
)
|
||||||
|
responses.add(
|
||||||
|
responses.GET, "https://api.github.com/users/alice/repos",
|
||||||
|
json=[], status=200,
|
||||||
|
)
|
||||||
|
responses.add(
|
||||||
|
responses.GET, "https://api.github.com/users/alice/events",
|
||||||
|
json=[], status=200,
|
||||||
|
)
|
||||||
|
data = github.fetch_github_data("alice", token="t")
|
||||||
|
assert data["user"]["login"] == "alice"
|
||||||
|
assert "repos" in data
|
||||||
|
assert "events" in data
|
||||||
|
|
||||||
|
|
||||||
|
@responses.activate
|
||||||
|
def test_fetch_handles_404():
|
||||||
|
responses.add(
|
||||||
|
responses.GET, "https://api.github.com/users/nope",
|
||||||
|
json={"message": "Not Found"}, status=404,
|
||||||
|
)
|
||||||
|
responses.add(
|
||||||
|
responses.POST, "https://api.github.com/graphql",
|
||||||
|
json={"data": {"user": None}}, status=200,
|
||||||
|
)
|
||||||
|
responses.add(
|
||||||
|
responses.GET, "https://api.github.com/users/nope/repos",
|
||||||
|
json={"message": "Not Found"}, status=404,
|
||||||
|
)
|
||||||
|
responses.add(
|
||||||
|
responses.GET, "https://api.github.com/users/nope/events",
|
||||||
|
json={"message": "Not Found"}, status=404,
|
||||||
|
)
|
||||||
|
data = github.fetch_github_data("nope", token="t")
|
||||||
|
assert data["user"].get("message") == "Not Found" or data["user"] is None
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
# --- stage 1: build the React SPA ---
|
||||||
|
FROM node:20-alpine AS frontend-build
|
||||||
|
WORKDIR /app/frontend
|
||||||
|
COPY frontend/package.json frontend/package-lock.json ./
|
||||||
|
RUN npm ci
|
||||||
|
COPY frontend/ ./
|
||||||
|
ARG VITE_GENERATOR_URL=""
|
||||||
|
ARG VITE_EDGE_URL=""
|
||||||
|
ENV VITE_GENERATOR_URL=$VITE_GENERATOR_URL
|
||||||
|
ENV VITE_EDGE_URL=$VITE_EDGE_URL
|
||||||
|
RUN npm run build
|
||||||
|
|
||||||
|
# --- stage 2: python runtime ---
|
||||||
|
FROM python:3.11-slim AS runtime
|
||||||
|
WORKDIR /app
|
||||||
|
COPY requirements.txt ./
|
||||||
|
RUN pip install --no-cache-dir -r requirements.txt
|
||||||
|
|
||||||
|
COPY src ./src
|
||||||
|
RUN mkdir -p /app/src/static /app/data
|
||||||
|
COPY --from=frontend-build /app/frontend/dist/ /app/src/static/
|
||||||
|
|
||||||
|
EXPOSE 5002
|
||||||
|
ENV GENERATOR_SETTINGS_DB_PATH=/app/data/settings.db
|
||||||
|
ENV GENERATOR_WIDGETS_DB_PATH=/app/data/widgets.db
|
||||||
|
|
||||||
|
CMD ["gunicorn", "-b", "0.0.0.0:5002", "-w", "2", "src.api:app"]
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
# Generator Service
|
||||||
|
|
||||||
|
Serves precomputed SVGs to the public internet. Holds user settings and
|
||||||
|
the widgets cache. Runs a build worker + cron in the background. Also
|
||||||
|
serves the React SPA (frontend sources live under `frontend/`).
|
||||||
|
|
||||||
|
## Run locally (3 processes)
|
||||||
|
|
||||||
|
cd generator
|
||||||
|
pip install -r requirements.txt
|
||||||
|
|
||||||
|
# API
|
||||||
|
FETCHER_URL=http://localhost:5001 FETCHER_INTERNAL_TOKEN=dev python -m src.api
|
||||||
|
# Build worker
|
||||||
|
FETCHER_URL=http://localhost:5001 FETCHER_INTERNAL_TOKEN=dev python -m src.worker
|
||||||
|
# Poll cron
|
||||||
|
FETCHER_URL=http://localhost:5001 FETCHER_INTERNAL_TOKEN=dev python -m src.cron
|
||||||
|
|
||||||
|
## Frontend (dev)
|
||||||
|
|
||||||
|
cd generator/frontend && npm install && npm run dev
|
||||||
|
# Vite dev server proxies /api to the Flask app.
|
||||||
|
|
||||||
|
## Test
|
||||||
|
|
||||||
|
cd generator && pytest
|
||||||
|
|
||||||
|
## Docker
|
||||||
|
|
||||||
|
Multi-stage (builds the frontend with node, serves everything from Python):
|
||||||
|
|
||||||
|
docker build -t ghstats-generator .
|
||||||
|
docker run --rm -e FETCHER_URL=http://fetcher:5001 -e FETCHER_INTERNAL_TOKEN=dev \
|
||||||
|
-p 5002:5002 -v $(pwd)/data:/app/data ghstats-generator
|
||||||
|
# Worker: override CMD to ["python","-m","src.worker"]
|
||||||
|
# Cron: override CMD to ["python","-m","src.cron"]
|
||||||
|
|
||||||
|
## Endpoints
|
||||||
|
|
||||||
|
All API endpoints are under `/api/`. The root and `/assets/*` serve the SPA.
|
||||||
|
|
||||||
|
| Method | Path | Auth | Description |
|
||||||
|
|---|---|---|---|
|
||||||
|
| GET | /api/health | none | health |
|
||||||
|
| GET | /api/<u> | none | composite SVG; auto-enrolls unknown users |
|
||||||
|
| GET | /api/<u>/<w>.svg | none | individual widget SVG |
|
||||||
|
| POST | /api/enroll | none | explicit enroll (body: {username}) |
|
||||||
|
| GET | /api/<u>/settings | stub | current settings |
|
||||||
|
| PATCH | /api/<u>/settings | stub | update settings (enqueues rebuild) |
|
||||||
|
| POST | /api/<u>/refresh | stub | one-shot re-fetch + rebuild |
|
||||||
|
|
||||||
|
Responses carry `X-Widget-Status: ready | building | rate_limited | not_found`.
|
||||||
|
|
||||||
|
## Env
|
||||||
|
|
||||||
|
See `src/config.py`.
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
VITE_GENERATOR_URL=http://localhost:5002
|
||||||
|
VITE_EDGE_URL=http://localhost:5003
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
# Logs
|
||||||
|
logs
|
||||||
|
*.log
|
||||||
|
npm-debug.log*
|
||||||
|
yarn-debug.log*
|
||||||
|
yarn-error.log*
|
||||||
|
pnpm-debug.log*
|
||||||
|
lerna-debug.log*
|
||||||
|
|
||||||
|
node_modules
|
||||||
|
dist
|
||||||
|
dist-ssr
|
||||||
|
*.local
|
||||||
|
|
||||||
|
# Editor directories and files
|
||||||
|
.vscode/*
|
||||||
|
!.vscode/extensions.json
|
||||||
|
.idea
|
||||||
|
.DS_Store
|
||||||
|
*.suo
|
||||||
|
*.ntvs*
|
||||||
|
*.njsproj
|
||||||
|
*.sln
|
||||||
|
*.sw?
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
# Frontend (Vite + React)
|
||||||
|
|
||||||
|
Part of the generator service. Sources live here; the production build
|
||||||
|
is served as static files by the generator's Flask app (at `/`) and
|
||||||
|
produced by the generator's Dockerfile.
|
||||||
|
|
||||||
|
## Dev
|
||||||
|
|
||||||
|
npm install
|
||||||
|
VITE_GENERATOR_URL=http://localhost:5002 VITE_EDGE_URL=http://localhost:5003 npm run dev
|
||||||
|
|
||||||
|
Vite proxies `/api/*` to the Flask app at :5002.
|
||||||
|
|
||||||
|
## Build
|
||||||
|
|
||||||
|
npm run build
|
||||||
|
# produces dist/ which is copied into generator/src/static/ by the Docker build
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
import js from '@eslint/js'
|
||||||
|
import globals from 'globals'
|
||||||
|
import reactHooks from 'eslint-plugin-react-hooks'
|
||||||
|
import reactRefresh from 'eslint-plugin-react-refresh'
|
||||||
|
import tseslint from 'typescript-eslint'
|
||||||
|
import { defineConfig, globalIgnores } from 'eslint/config'
|
||||||
|
|
||||||
|
export default defineConfig([
|
||||||
|
globalIgnores(['dist']),
|
||||||
|
{
|
||||||
|
files: ['**/*.{ts,tsx}'],
|
||||||
|
extends: [
|
||||||
|
js.configs.recommended,
|
||||||
|
tseslint.configs.recommended,
|
||||||
|
reactHooks.configs.flat.recommended,
|
||||||
|
reactRefresh.configs.vite,
|
||||||
|
],
|
||||||
|
languageOptions: {
|
||||||
|
ecmaVersion: 2020,
|
||||||
|
globals: globals.browser,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
])
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8" />
|
||||||
|
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
|
<title>frontend</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div id="root"></div>
|
||||||
|
<script type="module" src="/src/main.tsx"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
Generated
+3333
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,34 @@
|
|||||||
|
{
|
||||||
|
"name": "frontend",
|
||||||
|
"private": true,
|
||||||
|
"version": "0.0.0",
|
||||||
|
"type": "module",
|
||||||
|
"scripts": {
|
||||||
|
"dev": "vite",
|
||||||
|
"build": "tsc -b && vite build",
|
||||||
|
"lint": "eslint .",
|
||||||
|
"preview": "vite preview"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"dompurify": "^3.4.0",
|
||||||
|
"react": "^19.2.4",
|
||||||
|
"react-dom": "^19.2.4"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@eslint/js": "^9.39.4",
|
||||||
|
"@tailwindcss/vite": "^4.2.2",
|
||||||
|
"@types/dompurify": "^3.0.5",
|
||||||
|
"@types/node": "^24.12.2",
|
||||||
|
"@types/react": "^19.2.14",
|
||||||
|
"@types/react-dom": "^19.2.3",
|
||||||
|
"@vitejs/plugin-react": "^6.0.1",
|
||||||
|
"eslint": "^9.39.4",
|
||||||
|
"eslint-plugin-react-hooks": "^7.0.1",
|
||||||
|
"eslint-plugin-react-refresh": "^0.5.2",
|
||||||
|
"globals": "^17.4.0",
|
||||||
|
"tailwindcss": "^4.2.2",
|
||||||
|
"typescript": "~6.0.2",
|
||||||
|
"typescript-eslint": "^8.58.0",
|
||||||
|
"vite": "^8.0.4"
|
||||||
|
}
|
||||||
|
}
|
||||||
File diff suppressed because one or more lines are too long
|
After Width: | Height: | Size: 9.3 KiB |
@@ -0,0 +1,24 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg">
|
||||||
|
<symbol id="bluesky-icon" viewBox="0 0 16 17">
|
||||||
|
<g clip-path="url(#bluesky-clip)"><path fill="#08060d" d="M7.75 7.735c-.693-1.348-2.58-3.86-4.334-5.097-1.68-1.187-2.32-.981-2.74-.79C.188 2.065.1 2.812.1 3.251s.241 3.602.398 4.13c.52 1.744 2.367 2.333 4.07 2.145-2.495.37-4.71 1.278-1.805 4.512 3.196 3.309 4.38-.71 4.987-2.746.608 2.036 1.307 5.91 4.93 2.746 2.72-2.746.747-4.143-1.747-4.512 1.702.189 3.55-.4 4.07-2.145.156-.528.397-3.691.397-4.13s-.088-1.186-.575-1.406c-.42-.19-1.06-.395-2.741.79-1.755 1.24-3.64 3.752-4.334 5.099"/></g>
|
||||||
|
<defs><clipPath id="bluesky-clip"><path fill="#fff" d="M.1.85h15.3v15.3H.1z"/></clipPath></defs>
|
||||||
|
</symbol>
|
||||||
|
<symbol id="discord-icon" viewBox="0 0 20 19">
|
||||||
|
<path fill="#08060d" d="M16.224 3.768a14.5 14.5 0 0 0-3.67-1.153c-.158.286-.343.67-.47.976a13.5 13.5 0 0 0-4.067 0c-.128-.306-.317-.69-.476-.976A14.4 14.4 0 0 0 3.868 3.77C1.546 7.28.916 10.703 1.231 14.077a14.7 14.7 0 0 0 4.5 2.306q.545-.748.965-1.587a9.5 9.5 0 0 1-1.518-.74q.191-.14.372-.293c2.927 1.369 6.107 1.369 8.999 0q.183.152.372.294-.723.437-1.52.74.418.838.963 1.588a14.6 14.6 0 0 0 4.504-2.308c.37-3.911-.63-7.302-2.644-10.309m-9.13 8.234c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.894 0 1.614.82 1.599 1.82.001 1-.705 1.82-1.6 1.82m5.91 0c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.893 0 1.614.82 1.599 1.82 0 1-.706 1.82-1.6 1.82"/>
|
||||||
|
</symbol>
|
||||||
|
<symbol id="documentation-icon" viewBox="0 0 21 20">
|
||||||
|
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="m15.5 13.333 1.533 1.322c.645.555.967.833.967 1.178s-.322.623-.967 1.179L15.5 18.333m-3.333-5-1.534 1.322c-.644.555-.966.833-.966 1.178s.322.623.966 1.179l1.534 1.321"/>
|
||||||
|
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M17.167 10.836v-4.32c0-1.41 0-2.117-.224-2.68-.359-.906-1.118-1.621-2.08-1.96-.599-.21-1.349-.21-2.848-.21-2.623 0-3.935 0-4.983.369-1.684.591-3.013 1.842-3.641 3.428C3 6.449 3 7.684 3 10.154v2.122c0 2.558 0 3.838.706 4.726q.306.383.713.671c.76.536 1.79.64 3.581.66"/>
|
||||||
|
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M3 10a2.78 2.78 0 0 1 2.778-2.778c.555 0 1.209.097 1.748-.047.48-.129.854-.503.982-.982.145-.54.048-1.194.048-1.749a2.78 2.78 0 0 1 2.777-2.777"/>
|
||||||
|
</symbol>
|
||||||
|
<symbol id="github-icon" viewBox="0 0 19 19">
|
||||||
|
<path fill="#08060d" fill-rule="evenodd" d="M9.356 1.85C5.05 1.85 1.57 5.356 1.57 9.694a7.84 7.84 0 0 0 5.324 7.44c.387.079.528-.168.528-.376 0-.182-.013-.805-.013-1.454-2.165.467-2.616-.935-2.616-.935-.349-.91-.864-1.143-.864-1.143-.71-.48.051-.48.051-.48.787.051 1.2.805 1.2.805.695 1.194 1.817.857 2.268.649.064-.507.27-.857.49-1.052-1.728-.182-3.545-.857-3.545-3.87 0-.857.31-1.558.8-2.104-.078-.195-.349-1 .077-2.078 0 0 .657-.208 2.14.805a7.5 7.5 0 0 1 1.946-.26c.657 0 1.328.092 1.946.26 1.483-1.013 2.14-.805 2.14-.805.426 1.078.155 1.883.078 2.078.502.546.799 1.247.799 2.104 0 3.013-1.818 3.675-3.558 3.87.284.247.528.714.528 1.454 0 1.052-.012 1.896-.012 2.156 0 .208.142.455.528.377a7.84 7.84 0 0 0 5.324-7.441c.013-4.338-3.48-7.844-7.773-7.844" clip-rule="evenodd"/>
|
||||||
|
</symbol>
|
||||||
|
<symbol id="social-icon" viewBox="0 0 20 20">
|
||||||
|
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M12.5 6.667a4.167 4.167 0 1 0-8.334 0 4.167 4.167 0 0 0 8.334 0"/>
|
||||||
|
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M2.5 16.667a5.833 5.833 0 0 1 8.75-5.053m3.837.474.513 1.035c.07.144.257.282.414.309l.93.155c.596.1.736.536.307.965l-.723.73a.64.64 0 0 0-.152.531l.207.903c.164.715-.213.991-.84.618l-.872-.52a.63.63 0 0 0-.577 0l-.872.52c-.624.373-1.003.094-.84-.618l.207-.903a.64.64 0 0 0-.152-.532l-.723-.729c-.426-.43-.289-.864.306-.964l.93-.156a.64.64 0 0 0 .412-.31l.513-1.034c.28-.562.735-.562 1.012 0"/>
|
||||||
|
</symbol>
|
||||||
|
<symbol id="x-icon" viewBox="0 0 19 19">
|
||||||
|
<path fill="#08060d" fill-rule="evenodd" d="M1.893 1.98c.052.072 1.245 1.769 2.653 3.77l2.892 4.114c.183.261.333.48.333.486s-.068.089-.152.183l-.522.593-.765.867-3.597 4.087c-.375.426-.734.834-.798.905a1 1 0 0 0-.118.148c0 .01.236.017.664.017h.663l.729-.83c.4-.457.796-.906.879-.999a692 692 0 0 0 1.794-2.038c.034-.037.301-.34.594-.675l.551-.624.345-.392a7 7 0 0 1 .34-.374c.006 0 .93 1.306 2.052 2.903l2.084 2.965.045.063h2.275c1.87 0 2.273-.003 2.266-.021-.008-.02-1.098-1.572-3.894-5.547-2.013-2.862-2.28-3.246-2.273-3.266.008-.019.282-.332 2.085-2.38l2-2.274 1.567-1.782c.022-.028-.016-.03-.65-.03h-.674l-.3.342a871 871 0 0 1-1.782 2.025c-.067.075-.405.458-.75.852a100 100 0 0 1-.803.91c-.148.172-.299.344-.99 1.127-.304.343-.32.358-.345.327-.015-.019-.904-1.282-1.976-2.808L6.365 1.85H1.8zm1.782.91 8.078 11.294c.772 1.08 1.413 1.973 1.425 1.984.016.017.241.02 1.05.017l1.03-.004-2.694-3.766L7.796 5.75 5.722 2.852l-1.039-.004-1.039-.004z" clip-rule="evenodd"/>
|
||||||
|
</symbol>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 4.9 KiB |
@@ -0,0 +1 @@
|
|||||||
|
/* Intentionally empty — all styles use Tailwind */
|
||||||
@@ -0,0 +1,124 @@
|
|||||||
|
import { useState, useRef, useCallback } from 'react'
|
||||||
|
import './index.css'
|
||||||
|
import { SearchScreen } from './screens/SearchScreen'
|
||||||
|
import { WorkshopScreen } from './screens/WorkshopScreen'
|
||||||
|
import { ResultScreen } from './screens/ResultScreen'
|
||||||
|
|
||||||
|
export type Achievement = {
|
||||||
|
title: string
|
||||||
|
subtitle: string
|
||||||
|
event_date: string
|
||||||
|
icon: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export type PerWidgetSettings = {
|
||||||
|
grade?: { max_tags?: number }
|
||||||
|
impact?: { line_color?: string }
|
||||||
|
collaborators?: { max_count?: number; bar_color?: string }
|
||||||
|
focus?: { max_categories?: number }
|
||||||
|
languages?: { max_languages?: number }
|
||||||
|
achievements?: { max_items?: number }
|
||||||
|
}
|
||||||
|
|
||||||
|
export type WidgetSettings = {
|
||||||
|
theme: string
|
||||||
|
widgets: string[]
|
||||||
|
impactPeriod: string
|
||||||
|
customTags: string[]
|
||||||
|
hiddenLanguages: string[]
|
||||||
|
achievements: Achievement[]
|
||||||
|
widgetSettings: PerWidgetSettings
|
||||||
|
}
|
||||||
|
|
||||||
|
const DEFAULT_SETTINGS: WidgetSettings = {
|
||||||
|
theme: 'midnight',
|
||||||
|
widgets: ['grade', 'impact', 'collaborators', 'focus', 'languages'],
|
||||||
|
impactPeriod: '6mo',
|
||||||
|
customTags: [],
|
||||||
|
hiddenLanguages: [],
|
||||||
|
achievements: [],
|
||||||
|
widgetSettings: {},
|
||||||
|
}
|
||||||
|
|
||||||
|
type Step = 'search' | 'workshop' | 'result'
|
||||||
|
|
||||||
|
export default function App() {
|
||||||
|
const [step, setStep] = useState<Step>('search')
|
||||||
|
const [username, setUsername] = useState('')
|
||||||
|
const [settings, setSettings] = useState<WidgetSettings>({ ...DEFAULT_SETTINGS })
|
||||||
|
const [fetchDone, setFetchDone] = useState(false)
|
||||||
|
const [fetchError, setFetchError] = useState<string | null>(null)
|
||||||
|
const fetchRef = useRef<AbortController | null>(null)
|
||||||
|
|
||||||
|
const startFetch = useCallback((user: string) => {
|
||||||
|
if (fetchRef.current) fetchRef.current.abort()
|
||||||
|
const ctrl = new AbortController()
|
||||||
|
fetchRef.current = ctrl
|
||||||
|
setFetchDone(false)
|
||||||
|
setFetchError(null)
|
||||||
|
|
||||||
|
fetch('/api/fetch', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ username: user }),
|
||||||
|
signal: ctrl.signal,
|
||||||
|
})
|
||||||
|
.then(r => {
|
||||||
|
if (!r.ok) throw new Error(`Fetch failed (${r.status})`)
|
||||||
|
return r.json()
|
||||||
|
})
|
||||||
|
.then(() => setFetchDone(true))
|
||||||
|
.catch(e => {
|
||||||
|
if (e.name !== 'AbortError') {
|
||||||
|
console.warn('Fetch error:', e)
|
||||||
|
setFetchError(e.message)
|
||||||
|
setFetchDone(true)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
const handleSearch = (user: string) => {
|
||||||
|
setUsername(user)
|
||||||
|
startFetch(user)
|
||||||
|
setStep('workshop')
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleGenerate = () => {
|
||||||
|
setStep('result')
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleBack = () => {
|
||||||
|
if (step === 'result') setStep('workshop')
|
||||||
|
else if (step === 'workshop') {
|
||||||
|
if (fetchRef.current) fetchRef.current.abort()
|
||||||
|
setStep('search')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen bg-gray-50">
|
||||||
|
{step === 'search' && (
|
||||||
|
<SearchScreen onSearch={handleSearch} />
|
||||||
|
)}
|
||||||
|
{step === 'workshop' && (
|
||||||
|
<WorkshopScreen
|
||||||
|
username={username}
|
||||||
|
settings={settings}
|
||||||
|
onSettingsChange={setSettings}
|
||||||
|
onGenerate={handleGenerate}
|
||||||
|
onBack={handleBack}
|
||||||
|
fetchDone={fetchDone}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
{step === 'result' && (
|
||||||
|
<ResultScreen
|
||||||
|
username={username}
|
||||||
|
settings={settings}
|
||||||
|
fetchDone={fetchDone}
|
||||||
|
fetchError={fetchError}
|
||||||
|
onBack={handleBack}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
Binary file not shown.
|
After Width: | Height: | Size: 44 KiB |
@@ -0,0 +1 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>
|
||||||
|
After Width: | Height: | Size: 4.0 KiB |
File diff suppressed because one or more lines are too long
|
After Width: | Height: | Size: 8.5 KiB |
@@ -0,0 +1,36 @@
|
|||||||
|
@import url('https://fonts.googleapis.com/css2?family=DM+Sans:ital,opsz,wght@0,9..40,100..1000;1,9..40,100..1000&family=Instrument+Serif:ital@0;1&family=JetBrains+Mono:wght@400;500;600&display=swap');
|
||||||
|
|
||||||
|
@import "tailwindcss";
|
||||||
|
|
||||||
|
@theme {
|
||||||
|
--font-sans: 'DM Sans', system-ui, sans-serif;
|
||||||
|
--font-serif: 'Instrument Serif', Georgia, serif;
|
||||||
|
--font-mono: 'JetBrains Mono', monospace;
|
||||||
|
}
|
||||||
|
|
||||||
|
::-webkit-scrollbar { display: none; }
|
||||||
|
* { -ms-overflow-style: none; scrollbar-width: none; }
|
||||||
|
|
||||||
|
body {
|
||||||
|
margin: 0;
|
||||||
|
font-family: 'DM Sans', system-ui, sans-serif;
|
||||||
|
-webkit-font-smoothing: antialiased;
|
||||||
|
-moz-osx-font-smoothing: grayscale;
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes fade-in-up {
|
||||||
|
from { opacity: 0; transform: translateY(16px); }
|
||||||
|
to { opacity: 1; transform: translateY(0); }
|
||||||
|
}
|
||||||
|
|
||||||
|
.animate-fade-in-up {
|
||||||
|
animation: fade-in-up 0.5s ease-out both;
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes spin-slow {
|
||||||
|
to { transform: rotate(360deg); }
|
||||||
|
}
|
||||||
|
|
||||||
|
.animate-spin-slow {
|
||||||
|
animation: spin-slow 1s linear infinite;
|
||||||
|
}
|
||||||
@@ -0,0 +1,333 @@
|
|||||||
|
import { THEMES, TAG_COLORS, GRADE_COLORS, FOCUS_COLORS, LANG_COLORS, type Theme } from './themes'
|
||||||
|
|
||||||
|
// --- Types matching the API `format=data` response ---
|
||||||
|
|
||||||
|
export type GradeData = {
|
||||||
|
grade: string; score: number
|
||||||
|
stats: Record<string, number>
|
||||||
|
tags: { tag: string; source: string; confidence: number }[]
|
||||||
|
breakdown: Record<string, number>
|
||||||
|
}
|
||||||
|
export type ImpactWeek = { week_start: string; commits: number }
|
||||||
|
export type CollaboratorData = { username: string; shared_repos: number; shared_commits: number }
|
||||||
|
export type FocusCategory = { category: string; percentage: number; commit_count: number }
|
||||||
|
export type LanguageData = { language: string; percentage: number; loc: number }
|
||||||
|
export type AchievementInput = { title: string; subtitle: string; event_date: string; icon: string }
|
||||||
|
|
||||||
|
export type WidgetData = {
|
||||||
|
grade?: GradeData
|
||||||
|
impact?: ImpactWeek[]
|
||||||
|
collaborators?: CollaboratorData[]
|
||||||
|
focus?: FocusCategory[]
|
||||||
|
languages?: LanguageData[]
|
||||||
|
}
|
||||||
|
|
||||||
|
export type PerWidgetSettings = {
|
||||||
|
grade?: { max_tags?: number }
|
||||||
|
impact?: { line_color?: string }
|
||||||
|
collaborators?: { max_count?: number; bar_color?: string }
|
||||||
|
focus?: { max_categories?: number }
|
||||||
|
languages?: { max_languages?: number }
|
||||||
|
achievements?: { max_items?: number }
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Helpers ---
|
||||||
|
|
||||||
|
const esc = (s: string) => s.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').replace(/"/g,'"')
|
||||||
|
const font = '-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif'
|
||||||
|
|
||||||
|
function cardWrapper(inner: string, w: number, h: number, t: Theme, title: string, prefix = '') {
|
||||||
|
const sid = `${prefix}shadow`
|
||||||
|
return `<svg xmlns="http://www.w3.org/2000/svg" width="${w}" height="${h}" viewBox="0 0 ${w} ${h}" fill="none">
|
||||||
|
<defs><filter id="${sid}" x="-2%" y="-2%" width="104%" height="104%"><feDropShadow dx="0" dy="1" stdDeviation="2" flood-color="#000" flood-opacity="0.15"/></filter></defs>
|
||||||
|
<rect x="1" y="1" width="${w-2}" height="${h-2}" rx="10" ry="10" fill="${t.card_bg}" stroke="${t.card_border}" stroke-width="1" filter="url(#${sid})"/>
|
||||||
|
${title ? `<text x="20" y="30" font-family="${font}" font-size="11" font-weight="600" fill="${t.text_secondary}" letter-spacing="0.8" opacity="0.7">${esc(title.toUpperCase())}</text>` : ''}
|
||||||
|
<g transform="translate(0, ${title ? 36 : 0})">${inner}</g>
|
||||||
|
</svg>`
|
||||||
|
}
|
||||||
|
|
||||||
|
function iconSvg(kind: string, color: string): string {
|
||||||
|
const icons: Record<string, string> = {
|
||||||
|
commits: `<circle cx="7" cy="7" r="3" fill="none" stroke="${color}" stroke-width="1.4"/><circle cx="7" cy="7" r="1" fill="${color}"/><line x1="7" y1="10" x2="7" y2="14" stroke="${color}" stroke-width="1.4"/><line x1="7" y1="0" x2="7" y2="4" stroke="${color}" stroke-width="1.4"/>`,
|
||||||
|
prs: `<circle cx="4" cy="4" r="2" fill="none" stroke="${color}" stroke-width="1.2"/><circle cx="10" cy="10" r="2" fill="none" stroke="${color}" stroke-width="1.2"/><path d="M4 6v4c0 1.1.9 2 2 2h2" fill="none" stroke="${color}" stroke-width="1.2"/>`,
|
||||||
|
stars: `<path d="M7 1l1.8 3.6 4 .6-2.9 2.8.7 4L7 10.2 3.4 12l.7-4L1.2 5.2l4-.6z" fill="${color}" opacity="0.85"/>`,
|
||||||
|
repos: `<rect x="2" y="1" width="10" height="12" rx="1.5" fill="none" stroke="${color}" stroke-width="1.2"/><line x1="5" y1="4" x2="9" y2="4" stroke="${color}" stroke-width="1"/><line x1="5" y1="6.5" x2="9" y2="6.5" stroke="${color}" stroke-width="1"/><line x1="5" y1="9" x2="7" y2="9" stroke="${color}" stroke-width="1"/>`,
|
||||||
|
followers: `<circle cx="5" cy="4" r="2.5" fill="none" stroke="${color}" stroke-width="1.2"/><path d="M0.5 12c0-2.5 2-4 4.5-4s4.5 1.5 4.5 4" fill="none" stroke="${color}" stroke-width="1.2"/><circle cx="11" cy="3.5" r="1.8" fill="none" stroke="${color}" stroke-width="1"/><path d="M10 7.5c1.5 0 3.5 1 3.5 3" fill="none" stroke="${color}" stroke-width="1"/>`,
|
||||||
|
}
|
||||||
|
return `<g>${icons[kind] ?? ''}</g>`
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Widget renderers ---
|
||||||
|
|
||||||
|
function renderGrade(data: GradeData, t: Theme, s?: { max_tags?: number }): string {
|
||||||
|
const tags = s?.max_tags ? data.tags.slice(0, s.max_tags) : data.tags
|
||||||
|
const base = data.grade[0]
|
||||||
|
const color = GRADE_COLORS[base] ?? t.accent
|
||||||
|
const radius = 36
|
||||||
|
const circ = 2 * Math.PI * radius
|
||||||
|
const offset = circ * (1 - data.score / 100)
|
||||||
|
const gf = data.grade.length <= 2 ? 30 : 22
|
||||||
|
|
||||||
|
const statLabels: Record<string, string> = { commits:'Commits', prs:'PRs', stars:'Stars', repos:'Repos', followers:'Followers' }
|
||||||
|
const statKeys = ['commits','prs','stars','repos','followers'].filter(k => k in data.stats)
|
||||||
|
const sw = 340 / Math.max(statKeys.length, 1)
|
||||||
|
let statsSvg = ''
|
||||||
|
for (let i = 0; i < statKeys.length; i++) {
|
||||||
|
const k = statKeys[i], v = data.stats[k]
|
||||||
|
const sx = i * sw + sw / 2
|
||||||
|
const vs = v < 100000 ? v.toLocaleString() : `${Math.round(v/1000)}k`
|
||||||
|
statsSvg += `<g transform="translate(${sx}, 0)"><g transform="translate(-7, 0)">${iconSvg(k, t.text_secondary)}</g><text x="0" y="28" text-anchor="middle" font-family="${font}" font-size="14" font-weight="700" fill="${t.text}">${vs}</text><text x="0" y="41" text-anchor="middle" font-family="${font}" font-size="9" fill="${t.text_secondary}">${statLabels[k]??k}</text></g>`
|
||||||
|
}
|
||||||
|
|
||||||
|
let tagsSvg = '', tx = 0, ty = 0
|
||||||
|
for (const tag of tags) {
|
||||||
|
const tc = TAG_COLORS[tag.tag] ?? t.accent
|
||||||
|
const label = tag.tag.replace(/-/g,' ').replace(/\b\w/g, c => c.toUpperCase())
|
||||||
|
const tw = Math.round(label.length * 6.6 + 18)
|
||||||
|
const po = tag.source === 'earned' ? 0.9 : 0.55
|
||||||
|
if (tx + tw > 340) { tx = 0; ty += 30 }
|
||||||
|
tagsSvg += `<g transform="translate(${tx}, ${ty})" opacity="${po}"><rect width="${tw}" height="24" rx="12" fill="${tc}" opacity="0.12"/><rect width="${tw}" height="24" rx="12" fill="none" stroke="${tc}" stroke-width="1" opacity="0.3"/><text x="${Math.round(tw/2)}" y="16" text-anchor="middle" font-family="${font}" font-size="10" font-weight="500" fill="${tc}">${esc(label)}</text></g>`
|
||||||
|
tx += tw + 6
|
||||||
|
}
|
||||||
|
|
||||||
|
const tagsH = tags.length ? ty + 24 : 0
|
||||||
|
const statsY = 100, tagsY = statsY + 54
|
||||||
|
const tagPad = tagsH > 24 ? 18 : 14
|
||||||
|
const cardH = tags.length ? tagsY + tagsH + tagPad : statsY + 54
|
||||||
|
|
||||||
|
let inner = `<g transform="translate(52, 48)"><circle cx="0" cy="0" r="${radius}" fill="none" stroke="${t.grid}" stroke-width="5"/><circle cx="0" cy="0" r="${radius}" fill="none" stroke="${color}" stroke-width="5" stroke-dasharray="${circ.toFixed(1)}" stroke-dashoffset="${offset.toFixed(1)}" stroke-linecap="round" transform="rotate(-90)"/><text x="0" y="-4" text-anchor="middle" dominant-baseline="middle" font-family="${font}" font-size="${gf}" font-weight="800" fill="${color}">${esc(data.grade)}</text><text x="0" y="18" text-anchor="middle" font-family="${font}" font-size="11" fill="${t.text_secondary}">${data.score.toFixed(0)} / 100</text></g>
|
||||||
|
<line x1="100" y1="16" x2="100" y2="80" stroke="${t.grid}" stroke-width="1"/>
|
||||||
|
<g transform="translate(114, 26)"><text x="0" y="10" font-family="${font}" font-size="16" font-weight="700" fill="${t.text}">Developer Profile</text><text x="0" y="28" font-family="${font}" font-size="11" fill="${t.text_secondary}">Grade <tspan fill="${color}" font-weight="700">${esc(data.grade)}</tspan> · ${data.score.toFixed(0)}/100</text></g>
|
||||||
|
<line x1="20" y1="${statsY-4}" x2="360" y2="${statsY-4}" stroke="${t.grid}" stroke-width="0.5"/>
|
||||||
|
<g transform="translate(20, ${statsY})">${statsSvg}</g>`
|
||||||
|
|
||||||
|
if (tags.length) {
|
||||||
|
inner += `<line x1="20" y1="${tagsY-6}" x2="360" y2="${tagsY-6}" stroke="${t.grid}" stroke-width="0.5"/><g transform="translate(20, ${tagsY})">${tagsSvg}</g>`
|
||||||
|
}
|
||||||
|
|
||||||
|
return cardWrapper(inner, 380, cardH, t, '')
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderImpact(weeks: ImpactWeek[], t: Theme, s?: { line_color?: string }): string {
|
||||||
|
const w = 380, h = 200, cx = 40, cy = 8, cw = 316, ch = 82
|
||||||
|
const lineColor = s?.line_color ?? t.accent
|
||||||
|
|
||||||
|
if (!weeks.length) {
|
||||||
|
const inner = `<line x1="${cx}" y1="${cy+ch}" x2="${cx+cw}" y2="${cy+ch}" stroke="${t.grid}" stroke-width="0.5"/>
|
||||||
|
<text x="${cx+cw/2}" y="${cy+ch/2+4}" text-anchor="middle" font-family="${font}" font-size="11" fill="${t.text_secondary}">No contribution data yet</text>
|
||||||
|
<g transform="translate(20, ${cy+ch+46})"><text x="0" y="0" font-family="${font}" font-size="13" font-weight="700" fill="${t.text}">0</text><text x="0" y="14" font-family="${font}" font-size="9" fill="${t.text_secondary}">commits over 6mo</text></g>`
|
||||||
|
return cardWrapper(inner, w, h, t, 'Impact Timeline')
|
||||||
|
}
|
||||||
|
|
||||||
|
const maxC = Math.max(...weeks.map(w => w.commits), 1)
|
||||||
|
const n = weeks.length
|
||||||
|
const pts = weeks.map((wk, i) => ({
|
||||||
|
x: cx + (i / Math.max(n-1, 1)) * cw,
|
||||||
|
y: cy + ch - (wk.commits / maxC) * ch,
|
||||||
|
}))
|
||||||
|
|
||||||
|
let pathD = `M ${pts[0].x.toFixed(1)} ${pts[0].y.toFixed(1)}`
|
||||||
|
for (let i = 1; i < pts.length; i++) {
|
||||||
|
const mx = (pts[i-1].x + pts[i].x) / 2
|
||||||
|
pathD += ` C ${mx.toFixed(1)} ${pts[i-1].y.toFixed(1)}, ${mx.toFixed(1)} ${pts[i].y.toFixed(1)}, ${pts[i].x.toFixed(1)} ${pts[i].y.toFixed(1)}`
|
||||||
|
}
|
||||||
|
const areaD = pathD + ` L ${pts[n-1].x.toFixed(1)} ${cy+ch} L ${pts[0].x.toFixed(1)} ${cy+ch} Z`
|
||||||
|
|
||||||
|
let yLabels = ''
|
||||||
|
for (let i = 0; i < 3; i++) {
|
||||||
|
const v = Math.round(maxC * (1 - i/2))
|
||||||
|
const yy = cy + (i/2) * ch
|
||||||
|
yLabels += `<text x="${cx-6}" y="${yy+4}" text-anchor="end" font-family="${font}" font-size="9" fill="${t.text_secondary}">${v}</text><line x1="${cx}" y1="${yy}" x2="${cx+cw}" y2="${yy}" stroke="${t.grid}" stroke-width="0.5" stroke-dasharray="3,3"/>`
|
||||||
|
}
|
||||||
|
|
||||||
|
let xLabels = ''
|
||||||
|
const li = n > 2 ? [0, Math.floor(n/2), n-1] : Array.from({length: n}, (_, i) => i)
|
||||||
|
for (const idx of li) {
|
||||||
|
if (idx < weeks.length) {
|
||||||
|
const px = cx + (idx / Math.max(n-1,1)) * cw
|
||||||
|
xLabels += `<text x="${px.toFixed(1)}" y="${cy+ch+14}" text-anchor="middle" font-family="${font}" font-size="9" fill="${t.text_secondary}">${weeks[idx].week_start.slice(0,7)}</text>`
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const total = weeks.reduce((a, w) => a + w.commits, 0)
|
||||||
|
const sy = cy + ch + 46
|
||||||
|
const inner = `<defs><linearGradient id="areaGrad" x1="0" y1="${cy}" x2="0" y2="${cy+ch}" gradientUnits="userSpaceOnUse"><stop offset="0%" stop-color="${lineColor}" stop-opacity="0.35"/><stop offset="100%" stop-color="${lineColor}" stop-opacity="0.02"/></linearGradient></defs>
|
||||||
|
${yLabels}${xLabels}
|
||||||
|
<path d="${areaD}" fill="url(#areaGrad)"/>
|
||||||
|
<path d="${pathD}" fill="none" stroke="${lineColor}" stroke-width="2" stroke-linecap="round"/>
|
||||||
|
<g transform="translate(20, ${sy})"><text x="0" y="0" font-family="${font}" font-size="13" font-weight="700" fill="${t.text}">${total.toLocaleString()}</text><text x="0" y="14" font-family="${font}" font-size="9" fill="${t.text_secondary}">commits over 6mo</text></g>`
|
||||||
|
|
||||||
|
return cardWrapper(inner, w, h, t, 'Impact Timeline')
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderCollaborators(collabs: CollaboratorData[], t: Theme, s?: { max_count?: number; bar_color?: string }): string {
|
||||||
|
const maxCount = Math.min(Math.max(s?.max_count ?? 5, 1), 10)
|
||||||
|
const barColor = s?.bar_color ?? t.purple
|
||||||
|
const shown = collabs.slice(0, maxCount)
|
||||||
|
const barMax = Math.max(...shown.map(c => c.shared_commits), 1)
|
||||||
|
let items = ''
|
||||||
|
|
||||||
|
for (let i = 0; i < shown.length; i++) {
|
||||||
|
const c = shown[i], y = i * 50
|
||||||
|
const hue = [...c.username].reduce((h, ch) => h + ch.charCodeAt(0), 0) % 360
|
||||||
|
const avatar = `<circle cx="0" cy="0" r="18" fill="hsl(${hue}, 50%, 40%)"/><text x="0" y="1" text-anchor="middle" dominant-baseline="middle" font-family="${font}" font-size="14" font-weight="600" fill="white">${esc(c.username[0].toUpperCase())}</text>`
|
||||||
|
const bw = (c.shared_commits / barMax * 120).toFixed(1)
|
||||||
|
items += `<g transform="translate(36, ${y+20})">${avatar}<text x="28" y="-2" font-family="${font}" font-size="13" font-weight="600" fill="${t.text}">${esc(c.username)}</text><text x="28" y="14" font-family="${font}" font-size="10" fill="${t.text_secondary}">${c.shared_repos} repos · ${c.shared_commits} commits</text><rect x="200" y="-6" width="130" height="8" rx="4" fill="${t.grid}"/><rect x="200" y="-6" width="${bw}" height="8" rx="4" fill="${barColor}" opacity="0.8"/></g>`
|
||||||
|
}
|
||||||
|
|
||||||
|
return cardWrapper(items, 380, shown.length * 50 + 48, t, 'Top Collaborators')
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderFocus(cats: FocusCategory[], t: Theme, s?: { max_categories?: number }): string {
|
||||||
|
const maxCats = Math.min(Math.max(s?.max_categories ?? 6, 1), 10)
|
||||||
|
const sorted = [...cats].sort((a, b) => b.percentage - a.percentage).slice(0, maxCats)
|
||||||
|
if (!sorted.length) return ''
|
||||||
|
|
||||||
|
const maxPct = Math.max(sorted[0].percentage, 1)
|
||||||
|
const barMaxW = 210
|
||||||
|
let items = ''
|
||||||
|
|
||||||
|
for (let i = 0; i < sorted.length; i++) {
|
||||||
|
const cat = sorted[i], y = i * 36
|
||||||
|
const color = FOCUS_COLORS[i % FOCUS_COLORS.length]
|
||||||
|
const bw = (cat.percentage / maxPct * barMaxW).toFixed(1)
|
||||||
|
items += `<g transform="translate(16, ${y})"><text x="0" y="14" font-family="${font}" font-size="12" font-weight="600" fill="${t.text}">${esc(cat.category)}</text><rect x="90" y="4" width="${barMaxW}" height="14" rx="7" fill="${t.grid}"/><rect x="90" y="4" width="${bw}" height="14" rx="7" fill="${color}" opacity="0.8"/><text x="90" y="32" font-family="${font}" font-size="9" fill="${t.text_secondary}">${cat.commit_count} commits</text><text x="${90+barMaxW+8}" y="15" font-family="${font}" font-size="12" font-weight="700" fill="${color}">${Math.round(cat.percentage)}%</text></g>`
|
||||||
|
}
|
||||||
|
|
||||||
|
const subY = sorted.length * 36 + 8
|
||||||
|
items += `<text x="16" y="${subY}" font-family="${font}" font-size="9" fill="${t.text_secondary}" opacity="0.7">Recent activity · last year</text>`
|
||||||
|
|
||||||
|
return cardWrapper(items, 380, sorted.length * 36 + 54, t, 'Recent Focus')
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderLanguages(languages: LanguageData[], t: Theme, s?: { max_languages?: number }): string {
|
||||||
|
const maxLangs = Math.min(Math.max(s?.max_languages ?? 5, 1), 10)
|
||||||
|
const topLangs = [...languages].sort((a, b) => b.percentage - a.percentage).slice(0, maxLangs)
|
||||||
|
if (!topLangs.length) return ''
|
||||||
|
|
||||||
|
const totalPct = topLangs.reduce((a, l) => a + l.percentage, 0)
|
||||||
|
const langs = [...topLangs]
|
||||||
|
|
||||||
|
if (totalPct < 99.9 && languages.length > maxLangs) {
|
||||||
|
langs.push({ language: 'Other', percentage: Math.round((100 - totalPct) * 10) / 10, loc: 0 })
|
||||||
|
} else if (totalPct < 99.9 && totalPct > 0) {
|
||||||
|
const f = 100 / totalPct
|
||||||
|
for (const l of langs) l.percentage = Math.round(l.percentage * f * 10) / 10
|
||||||
|
}
|
||||||
|
|
||||||
|
const legendStart = 20, legendH = langs.length * 22
|
||||||
|
const ccy = legendStart + legendH / 2, ccx = 60, r = 44, innerR = 28
|
||||||
|
const circ = 2 * Math.PI * r
|
||||||
|
|
||||||
|
let arcs = '', legend = '', offset = 0
|
||||||
|
for (let i = 0; i < langs.length; i++) {
|
||||||
|
const lang = langs[i]
|
||||||
|
const color = lang.language === 'Other' ? t.text_secondary : (LANG_COLORS[lang.language] ?? FOCUS_COLORS[i % FOCUS_COLORS.length])
|
||||||
|
const dash = circ * lang.percentage / 100
|
||||||
|
const gap = circ - dash
|
||||||
|
arcs += `<circle cx="${ccx}" cy="${ccy}" r="${r}" fill="none" stroke="${color}" stroke-width="16" stroke-dasharray="${dash.toFixed(1)} ${gap.toFixed(1)}" stroke-dashoffset="${(-offset).toFixed(1)}" transform="rotate(-90 ${ccx} ${ccy})" opacity="0.85"/>`
|
||||||
|
offset += dash
|
||||||
|
|
||||||
|
const ly = i * 22
|
||||||
|
legend += `<g transform="translate(140, ${ly + legendStart})"><rect width="10" height="10" rx="2" fill="${color}"/><text x="16" y="9" font-family="${font}" font-size="12" fill="${t.text}">${esc(lang.language)}</text><text x="210" y="9" text-anchor="end" font-family="${font}" font-size="11" font-weight="600" fill="${t.text_secondary}">${Math.round(lang.percentage)}%</text></g>`
|
||||||
|
}
|
||||||
|
|
||||||
|
const center = `<circle cx="${ccx}" cy="${ccy}" r="${innerR}" fill="${t.card_bg}"/><text x="${ccx}" y="${ccy+1}" text-anchor="middle" dominant-baseline="middle" font-family="${font}" font-size="11" font-weight="700" fill="${t.text}">${esc(langs[0].language)}</text>`
|
||||||
|
const inner = `<g transform="translate(16, 0)">${arcs}${center}${legend}</g>`
|
||||||
|
const rowsH = Math.max(langs.length * 22 + 40, 120)
|
||||||
|
return cardWrapper(inner, 380, rowsH + 36, t, 'Languages')
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderAchievements(achievements: AchievementInput[], t: Theme, s?: { max_items?: number }): string {
|
||||||
|
const maxItems = Math.min(Math.max(s?.max_items ?? 5, 1), 10)
|
||||||
|
const shown = achievements.filter(a => a.title.trim()).slice(0, maxItems)
|
||||||
|
if (!shown.length) return ''
|
||||||
|
|
||||||
|
const accentColors = [t.orange, t.green, t.accent, t.purple, t.pink]
|
||||||
|
let items = ''
|
||||||
|
|
||||||
|
for (let i = 0; i < shown.length; i++) {
|
||||||
|
const ach = shown[i], y = i * 56
|
||||||
|
const color = accentColors[i % accentColors.length]
|
||||||
|
items += `<g transform="translate(16, ${y+8})"><rect width="348" height="48" rx="8" fill="${color}" opacity="0.06"/><rect width="348" height="48" rx="8" fill="none" stroke="${color}" stroke-width="0.5" opacity="0.3"/><text x="16" y="20" font-family="${font}" font-size="13" font-weight="600" fill="${t.text}">${esc(ach.title)}</text><text x="16" y="36" font-family="${font}" font-size="10" fill="${t.text_secondary}">${esc(ach.subtitle)}${ach.event_date ? ' · ' + ach.event_date : ''}</text></g>`
|
||||||
|
}
|
||||||
|
|
||||||
|
return cardWrapper(items, 380, shown.length * 56 + 50, t, 'Achievements')
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Composite ---
|
||||||
|
|
||||||
|
function extractInner(svg: string, key: string): { inner: string; h: number } {
|
||||||
|
const hm = svg.match(/height="(\d+)"/)
|
||||||
|
const h = hm ? parseInt(hm[1]) : 160
|
||||||
|
|
||||||
|
// Prefix IDs
|
||||||
|
const ids = [...svg.matchAll(/id="([^"]+)"/g)].map(m => m[1])
|
||||||
|
let inner = svg
|
||||||
|
for (const id of ids) {
|
||||||
|
const nid = `${key}_${id}`
|
||||||
|
inner = inner.replaceAll(`id="${id}"`, `id="${nid}"`)
|
||||||
|
inner = inner.replaceAll(`url(#${id})`, `url(#${nid})`)
|
||||||
|
inner = inner.replaceAll(`href="#${id}"`, `href="#${nid}"`)
|
||||||
|
}
|
||||||
|
inner = inner.replace(/<svg[^>]*>/, '').replace(/<\/svg>\s*$/, '')
|
||||||
|
return { inner, h }
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Main export ---
|
||||||
|
|
||||||
|
export function renderAllWidgets(opts: {
|
||||||
|
data: WidgetData
|
||||||
|
theme: string
|
||||||
|
widgets: string[]
|
||||||
|
widgetOrder: string[]
|
||||||
|
achievements: AchievementInput[]
|
||||||
|
widgetSettings: PerWidgetSettings
|
||||||
|
username: string
|
||||||
|
}): string {
|
||||||
|
const t = THEMES[opts.theme] ?? THEMES.dark
|
||||||
|
const enabled = new Set(opts.widgets)
|
||||||
|
const widgetSvgs: Record<string, string> = {}
|
||||||
|
|
||||||
|
if (enabled.has('grade') && opts.data.grade)
|
||||||
|
widgetSvgs.grade = renderGrade(opts.data.grade, t, opts.widgetSettings.grade)
|
||||||
|
if (enabled.has('impact') && opts.data.impact)
|
||||||
|
widgetSvgs.impact = renderImpact(opts.data.impact, t, opts.widgetSettings.impact)
|
||||||
|
if (enabled.has('collaborators') && opts.data.collaborators)
|
||||||
|
widgetSvgs.collaborators = renderCollaborators(opts.data.collaborators, t, opts.widgetSettings.collaborators)
|
||||||
|
if (enabled.has('focus') && opts.data.focus)
|
||||||
|
widgetSvgs.focus = renderFocus(opts.data.focus, t, opts.widgetSettings.focus)
|
||||||
|
if (enabled.has('languages') && opts.data.languages)
|
||||||
|
widgetSvgs.languages = renderLanguages(opts.data.languages, t, opts.widgetSettings.languages)
|
||||||
|
if (enabled.has('achievements'))
|
||||||
|
widgetSvgs.achievements = renderAchievements(opts.achievements, t, opts.widgetSettings.achievements)
|
||||||
|
|
||||||
|
// Compose
|
||||||
|
const totalW = 420, headerH = 60, padding = 20, gap = 16
|
||||||
|
const ordered = opts.widgetOrder.filter(k => enabled.has(k) && widgetSvgs[k])
|
||||||
|
|
||||||
|
const parts = ordered.map(key => {
|
||||||
|
const { inner, h } = extractInner(widgetSvgs[key], key)
|
||||||
|
return { key, inner, h }
|
||||||
|
})
|
||||||
|
|
||||||
|
const contentH = parts.reduce((a, p) => a + p.h, 0) + gap * Math.max(parts.length - 1, 0)
|
||||||
|
const totalH = headerH + contentH + padding * 2 + 10
|
||||||
|
|
||||||
|
const avatar = `<circle cx="30" cy="30" r="16" fill="${t.accent}" opacity="0.3"/>`
|
||||||
|
const header = `${avatar}<text x="54" y="38" font-family="${font}" font-size="16" font-weight="700" fill="${t.text}">${esc(opts.username || 'Developer')}</text><line x1="${padding}" y1="${headerH}" x2="${totalW-padding}" y2="${headerH}" stroke="${t.card_border}" stroke-width="0.5"/>`
|
||||||
|
|
||||||
|
let yOffset = headerH + padding
|
||||||
|
let embedded = ''
|
||||||
|
for (const { inner, h } of parts) {
|
||||||
|
embedded += `<svg x="${padding}" y="${yOffset}" width="380" height="${h}" viewBox="0 0 380 ${h}">${inner}</svg>`
|
||||||
|
yOffset += h + gap
|
||||||
|
}
|
||||||
|
|
||||||
|
return `<svg xmlns="http://www.w3.org/2000/svg" width="${totalW}" height="${totalH}" viewBox="0 0 ${totalW} ${totalH}">
|
||||||
|
<rect width="${totalW}" height="${totalH}" rx="16" fill="${t.bg}"/>
|
||||||
|
<rect x="0.5" y="0.5" width="${totalW-1}" height="${totalH-1}" rx="16" fill="none" stroke="${t.card_border}" stroke-width="1"/>
|
||||||
|
${header}${embedded}
|
||||||
|
<text x="${totalW/2}" y="${totalH-8}" text-anchor="middle" font-family="${font}" font-size="9" fill="${t.text_secondary}" opacity="0.5">Generated with ♥</text>
|
||||||
|
</svg>`
|
||||||
|
}
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
export type Theme = {
|
||||||
|
bg: string; card_bg: string; card_border: string
|
||||||
|
text: string; text_secondary: string; accent: string
|
||||||
|
green: string; orange: string; red: string
|
||||||
|
purple: string; pink: string; grid: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export const THEMES: Record<string, Theme> = {
|
||||||
|
dark: { bg:"#121820",card_bg:"#1a2230",card_border:"#2a3444",text:"#d1d9e0",text_secondary:"#7d8895",accent:"#58a6ff",green:"#3fb950",orange:"#d29922",red:"#f85149",purple:"#bc8cff",pink:"#f778ba",grid:"#1e2836" },
|
||||||
|
onyx: { bg:"#09090b",card_bg:"#18181b",card_border:"#27272a",text:"#fafafa",text_secondary:"#a1a1aa",accent:"#a78bfa",green:"#4ade80",orange:"#fb923c",red:"#f87171",purple:"#c084fc",pink:"#f472b6",grid:"#27272a" },
|
||||||
|
nord: { bg:"#1e2433",card_bg:"#2a3142",card_border:"#3d4659",text:"#e5e9f0",text_secondary:"#8892a4",accent:"#88c0d0",green:"#a3be8c",orange:"#ebcb8b",red:"#bf616a",purple:"#b48ead",pink:"#d08770",grid:"#333d50" },
|
||||||
|
light: { bg:"#ffffff",card_bg:"#f6f8fa",card_border:"#d8dee4",text:"#24292f",text_secondary:"#656d76",accent:"#0969da",green:"#1a7f37",orange:"#9a6700",red:"#cf222e",purple:"#8250df",pink:"#bf3989",grid:"#eaeef2" },
|
||||||
|
paper: { bg:"#faf8f5",card_bg:"#f5f0eb",card_border:"#e0d8cf",text:"#3d3529",text_secondary:"#7a7062",accent:"#b45309",green:"#4d7c0f",orange:"#a16207",red:"#b91c1c",purple:"#7e22ce",pink:"#be185d",grid:"#ebe5dd" },
|
||||||
|
}
|
||||||
|
THEMES.midnight = THEMES.dark
|
||||||
|
THEMES.clean = THEMES.light
|
||||||
|
|
||||||
|
export const TAG_COLORS: Record<string, string> = {
|
||||||
|
"ml-engineer":"#bc8cff","frontend":"#58a6ff","backend":"#3fb950","fullstack":"#d29922",
|
||||||
|
"devops":"#f0883e","database":"#f778ba","mobile":"#ff6b9d","security":"#f85149",
|
||||||
|
"data-science":"#79c0ff","systems":"#7ee787","cloud":"#58a6ff","open-source":"#3fb950",
|
||||||
|
}
|
||||||
|
|
||||||
|
export const GRADE_COLORS: Record<string, string> = {
|
||||||
|
S:"#ff6b9d", A:"#3fb950", B:"#58a6ff", C:"#d29922", D:"#f0883e", F:"#f85149",
|
||||||
|
}
|
||||||
|
|
||||||
|
export const FOCUS_COLORS = [
|
||||||
|
"#58a6ff","#3fb950","#bc8cff","#d29922","#f0883e","#f778ba","#f85149","#79c0ff",
|
||||||
|
]
|
||||||
|
|
||||||
|
export const LANG_COLORS: Record<string, string> = {
|
||||||
|
Python:"#3572A5",JavaScript:"#f1e05a",TypeScript:"#3178c6",Go:"#00ADD8",
|
||||||
|
Rust:"#dea584",Java:"#b07219","C++":"#f34b7d",C:"#555555",Ruby:"#701516",
|
||||||
|
Shell:"#89e051",HTML:"#e34c26",CSS:"#563d7c",Kotlin:"#A97BFF",Swift:"#F05138",
|
||||||
|
"Jupyter Notebook":"#DA5B0B",Dockerfile:"#384d54",
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
import { StrictMode } from 'react'
|
||||||
|
import { createRoot } from 'react-dom/client'
|
||||||
|
import './index.css'
|
||||||
|
import App from './App.tsx'
|
||||||
|
|
||||||
|
createRoot(document.getElementById('root')!).render(
|
||||||
|
<StrictMode>
|
||||||
|
<App />
|
||||||
|
</StrictMode>,
|
||||||
|
)
|
||||||
@@ -0,0 +1,108 @@
|
|||||||
|
import { useState, useEffect } from 'react'
|
||||||
|
import DOMPurify from 'dompurify'
|
||||||
|
import type { WidgetSettings } from '../App'
|
||||||
|
|
||||||
|
function sanitizeSvg(raw: string): string {
|
||||||
|
return DOMPurify.sanitize(raw, {
|
||||||
|
USE_PROFILES: { svg: true, svgFilters: true },
|
||||||
|
ADD_TAGS: ['image', 'use', 'clipPath', 'defs', 'style', 'animate', 'animateTransform', 'feDropShadow', 'filter', 'linearGradient', 'stop'],
|
||||||
|
ADD_ATTR: ['xlink:href', 'href', 'clip-path', 'viewBox', 'preserveAspectRatio', 'xmlns', 'xmlns:xlink', 'rx', 'ry', 'attributeName', 'from', 'to', 'dur', 'fill', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'dominant-baseline', 'letter-spacing', 'opacity', 'filter', 'flood-color', 'flood-opacity', 'stdDeviation'],
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
type Props = {
|
||||||
|
username: string
|
||||||
|
settings: WidgetSettings
|
||||||
|
fetchDone: boolean
|
||||||
|
fetchError: string | null
|
||||||
|
onBack: () => void
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ResultScreen({ username, settings, fetchDone, fetchError, onBack }: Props) {
|
||||||
|
const [svgContent, setSvgContent] = useState<string>('')
|
||||||
|
const [loading, setLoading] = useState(true)
|
||||||
|
const [generated, setGenerated] = useState(false)
|
||||||
|
|
||||||
|
// Generate the final SVG once fetch completes
|
||||||
|
useEffect(() => {
|
||||||
|
if (!fetchDone) return
|
||||||
|
if (generated) return
|
||||||
|
|
||||||
|
setLoading(true)
|
||||||
|
fetch('/api/generate', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({
|
||||||
|
username,
|
||||||
|
theme: settings.theme,
|
||||||
|
widgets: settings.widgets,
|
||||||
|
widget_order: ['grade', 'impact', 'collaborators', 'focus', 'languages', 'achievements'],
|
||||||
|
custom_tags: settings.customTags.length ? settings.customTags : undefined,
|
||||||
|
hidden_languages: settings.hiddenLanguages.length ? settings.hiddenLanguages : undefined,
|
||||||
|
achievements: settings.achievements.filter(a => a.title.trim()),
|
||||||
|
widget_settings: settings.widgetSettings,
|
||||||
|
format: 'svg',
|
||||||
|
}),
|
||||||
|
})
|
||||||
|
.then(r => r.text())
|
||||||
|
.then(svg => {
|
||||||
|
// SVG is sanitized via DOMPurify before rendering
|
||||||
|
setSvgContent(sanitizeSvg(svg))
|
||||||
|
setLoading(false)
|
||||||
|
setGenerated(true)
|
||||||
|
})
|
||||||
|
.catch(() => setLoading(false))
|
||||||
|
}, [fetchDone])
|
||||||
|
|
||||||
|
const waiting = !fetchDone
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen flex flex-col items-center animate-fade-in-up">
|
||||||
|
{/* Back button */}
|
||||||
|
<div className="w-full max-w-2xl px-6 pt-6">
|
||||||
|
<button
|
||||||
|
onClick={onBack}
|
||||||
|
className="flex items-center gap-1.5 text-xs text-gray-400 hover:text-gray-600 transition-colors"
|
||||||
|
>
|
||||||
|
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
|
||||||
|
<path d="M19 12H5M12 19l-7-7 7-7"/>
|
||||||
|
</svg>
|
||||||
|
Back
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex-1 flex flex-col items-center justify-center px-6 pb-12">
|
||||||
|
<h2 className="font-serif text-2xl text-gray-800 tracking-tight mb-1">
|
||||||
|
Your Widget
|
||||||
|
</h2>
|
||||||
|
|
||||||
|
{waiting ? (
|
||||||
|
<div className="mt-8 flex flex-col items-center gap-3">
|
||||||
|
<div className="w-5 h-5 border-2 border-gray-300 border-t-gray-600 rounded-full animate-spin-slow" />
|
||||||
|
<p className="text-xs text-gray-400">Generating with real data...</p>
|
||||||
|
</div>
|
||||||
|
) : loading ? (
|
||||||
|
<div className="mt-8 flex flex-col items-center gap-3">
|
||||||
|
<div className="w-5 h-5 border-2 border-gray-300 border-t-gray-600 rounded-full animate-spin-slow" />
|
||||||
|
<p className="text-xs text-gray-400">Rendering...</p>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
{fetchError && (
|
||||||
|
<p className="text-[10px] text-amber-500 mb-4">
|
||||||
|
Could not fetch live data — showing demo widget
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
{!fetchError && (
|
||||||
|
<p className="text-xs text-gray-400 mb-6">
|
||||||
|
Generated with real data
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
{/* SVG content is sanitized with DOMPurify.sanitize() before rendering */}
|
||||||
|
<div dangerouslySetInnerHTML={{ __html: svgContent }} />
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
import { useState } from 'react'
|
||||||
|
|
||||||
|
type Props = {
|
||||||
|
onSearch: (username: string) => void
|
||||||
|
}
|
||||||
|
|
||||||
|
export function SearchScreen({ onSearch }: Props) {
|
||||||
|
const [value, setValue] = useState('')
|
||||||
|
|
||||||
|
const handleSubmit = (e: React.FormEvent) => {
|
||||||
|
e.preventDefault()
|
||||||
|
const trimmed = value.trim()
|
||||||
|
if (trimmed) onSearch(trimmed)
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen flex items-center justify-center animate-fade-in-up">
|
||||||
|
<div className="text-center w-full max-w-md px-6">
|
||||||
|
<h1 className="font-serif text-4xl text-gray-800 tracking-tight mb-2">
|
||||||
|
GitHub Stats
|
||||||
|
</h1>
|
||||||
|
<p className="text-sm text-gray-400 mb-8">
|
||||||
|
Generate your profile widget
|
||||||
|
</p>
|
||||||
|
<form onSubmit={handleSubmit} className="flex gap-2">
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={value}
|
||||||
|
onChange={e => setValue(e.target.value)}
|
||||||
|
placeholder="Enter GitHub username..."
|
||||||
|
autoFocus
|
||||||
|
className="flex-1 px-4 py-3 rounded-xl border border-gray-200 bg-white text-sm text-gray-800 placeholder:text-gray-300 focus:outline-none focus:ring-1 focus:ring-gray-300 transition-colors"
|
||||||
|
/>
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
disabled={!value.trim()}
|
||||||
|
className="px-6 py-3 rounded-xl bg-gray-800 text-white text-sm font-medium hover:bg-gray-700 disabled:opacity-40 disabled:cursor-not-allowed transition-colors"
|
||||||
|
>
|
||||||
|
Go
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,455 @@
|
|||||||
|
import { useState, useEffect, useRef, useMemo } from 'react'
|
||||||
|
import type { WidgetSettings, Achievement, PerWidgetSettings } from '../App'
|
||||||
|
import { renderAllWidgets, type WidgetData } from '../lib/renderWidgets'
|
||||||
|
|
||||||
|
const THEMES = [
|
||||||
|
{ id: 'midnight', label: 'Midnight', color: '#121820' },
|
||||||
|
{ id: 'onyx', label: 'Onyx', color: '#09090b' },
|
||||||
|
{ id: 'nord', label: 'Nord', color: '#1e2433' },
|
||||||
|
{ id: 'clean', label: 'Clean', color: '#ffffff', border: true },
|
||||||
|
{ id: 'paper', label: 'Paper', color: '#faf8f5', border: true },
|
||||||
|
]
|
||||||
|
|
||||||
|
const ALL_WIDGETS = [
|
||||||
|
{ id: 'grade', label: 'Grade' },
|
||||||
|
{ id: 'impact', label: 'Impact Timeline' },
|
||||||
|
{ id: 'collaborators', label: 'Top Collaborators' },
|
||||||
|
{ id: 'focus', label: 'Recent Focus' },
|
||||||
|
{ id: 'languages', label: 'Languages' },
|
||||||
|
{ id: 'achievements', label: 'Achievements' },
|
||||||
|
]
|
||||||
|
|
||||||
|
const ICONS = [
|
||||||
|
{ id: 'trophy', label: '🏆' },
|
||||||
|
{ id: 'medal', label: '🥇' },
|
||||||
|
{ id: 'star', label: '⭐' },
|
||||||
|
{ id: 'hackathon', label: '💻' },
|
||||||
|
]
|
||||||
|
|
||||||
|
const COLOR_PRESETS = [
|
||||||
|
'#58a6ff', '#a78bfa', '#4ade80', '#fb923c', '#f472b6',
|
||||||
|
'#ff6b6b', '#38bdf8', '#facc15', '#34d399', '#c084fc',
|
||||||
|
]
|
||||||
|
|
||||||
|
function ChevronIcon({ open }: { open: boolean }) {
|
||||||
|
return (
|
||||||
|
<svg
|
||||||
|
width="12" height="12" viewBox="0 0 24 24" fill="none"
|
||||||
|
stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"
|
||||||
|
className={`transition-transform ${open ? 'rotate-90' : ''}`}
|
||||||
|
>
|
||||||
|
<path d="M9 18l6-6-6-6" />
|
||||||
|
</svg>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function NumberStepper({ value, min, max, onChange }: {
|
||||||
|
value: number; min: number; max: number; onChange: (v: number) => void
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<div className="flex items-center gap-1.5">
|
||||||
|
<button
|
||||||
|
onClick={() => onChange(Math.max(min, value - 1))}
|
||||||
|
className="w-6 h-6 rounded bg-gray-100 text-gray-500 hover:bg-gray-200 text-xs font-medium flex items-center justify-center"
|
||||||
|
>-</button>
|
||||||
|
<span className="text-xs text-gray-700 w-5 text-center tabular-nums">{value}</span>
|
||||||
|
<button
|
||||||
|
onClick={() => onChange(Math.min(max, value + 1))}
|
||||||
|
className="w-6 h-6 rounded bg-gray-100 text-gray-500 hover:bg-gray-200 text-xs font-medium flex items-center justify-center"
|
||||||
|
>+</button>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function ColorPicker({ value, onChange }: { value: string; onChange: (v: string) => void }) {
|
||||||
|
return (
|
||||||
|
<div className="flex gap-1.5 flex-wrap">
|
||||||
|
{COLOR_PRESETS.map(c => (
|
||||||
|
<button
|
||||||
|
key={c}
|
||||||
|
onClick={() => onChange(c)}
|
||||||
|
className={`w-5 h-5 rounded-full transition-all ${
|
||||||
|
value === c ? 'ring-2 ring-offset-1 ring-blue-500' : 'hover:ring-1 hover:ring-gray-300'
|
||||||
|
}`}
|
||||||
|
style={{ backgroundColor: c }}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
type Props = {
|
||||||
|
username: string
|
||||||
|
settings: WidgetSettings
|
||||||
|
onSettingsChange: (s: WidgetSettings) => void
|
||||||
|
onGenerate: () => void
|
||||||
|
onBack: () => void
|
||||||
|
fetchDone: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
export function WorkshopScreen({
|
||||||
|
username,
|
||||||
|
settings,
|
||||||
|
onSettingsChange,
|
||||||
|
onGenerate,
|
||||||
|
onBack,
|
||||||
|
fetchDone,
|
||||||
|
}: Props) {
|
||||||
|
const [widgetData, setWidgetData] = useState<WidgetData | null>(null)
|
||||||
|
const [dataLoading, setDataLoading] = useState(true)
|
||||||
|
const [expandedWidget, setExpandedWidget] = useState<string | null>(null)
|
||||||
|
const dataFetched = useRef(false)
|
||||||
|
|
||||||
|
const updateSetting = <K extends keyof WidgetSettings>(key: K, val: WidgetSettings[K]) => {
|
||||||
|
onSettingsChange({ ...settings, [key]: val })
|
||||||
|
}
|
||||||
|
|
||||||
|
const updateWidgetSetting = (widget: keyof PerWidgetSettings, key: string, val: unknown) => {
|
||||||
|
const current = settings.widgetSettings[widget] || {}
|
||||||
|
const next = { ...settings.widgetSettings, [widget]: { ...current, [key]: val } }
|
||||||
|
updateSetting('widgetSettings', next)
|
||||||
|
}
|
||||||
|
|
||||||
|
const getWidgetSetting = <T,>(widget: keyof PerWidgetSettings, key: string, fallback: T): T => {
|
||||||
|
const ws = settings.widgetSettings[widget] as Record<string, unknown> | undefined
|
||||||
|
return (ws?.[key] as T) ?? fallback
|
||||||
|
}
|
||||||
|
|
||||||
|
const toggleWidget = (id: string) => {
|
||||||
|
const next = settings.widgets.includes(id)
|
||||||
|
? settings.widgets.filter(w => w !== id)
|
||||||
|
: [...settings.widgets, id]
|
||||||
|
updateSetting('widgets', next)
|
||||||
|
}
|
||||||
|
|
||||||
|
const toggleAdvanced = (id: string) => {
|
||||||
|
setExpandedWidget(expandedWidget === id ? null : id)
|
||||||
|
}
|
||||||
|
|
||||||
|
const addAchievement = () => {
|
||||||
|
updateSetting('achievements', [
|
||||||
|
...settings.achievements,
|
||||||
|
{ title: '', subtitle: '', event_date: '', icon: 'trophy' },
|
||||||
|
])
|
||||||
|
}
|
||||||
|
|
||||||
|
const updateAchievement = (idx: number, field: keyof Achievement, val: string) => {
|
||||||
|
const next = settings.achievements.map((a, i) =>
|
||||||
|
i === idx ? { ...a, [field]: val } : a
|
||||||
|
)
|
||||||
|
updateSetting('achievements', next)
|
||||||
|
}
|
||||||
|
|
||||||
|
const removeAchievement = (idx: number) => {
|
||||||
|
updateSetting('achievements', settings.achievements.filter((_, i) => i !== idx))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fetch widget data once on mount (or when fetch completes)
|
||||||
|
useEffect(() => {
|
||||||
|
if (dataFetched.current || !fetchDone) return
|
||||||
|
dataFetched.current = true
|
||||||
|
setDataLoading(true)
|
||||||
|
|
||||||
|
fetch('/api/generate', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({
|
||||||
|
username,
|
||||||
|
widgets: ['grade', 'impact', 'collaborators', 'focus', 'languages'],
|
||||||
|
widget_order: ['grade', 'impact', 'collaborators', 'focus', 'languages'],
|
||||||
|
custom_tags: settings.customTags.length ? settings.customTags : undefined,
|
||||||
|
hidden_languages: settings.hiddenLanguages.length ? settings.hiddenLanguages : undefined,
|
||||||
|
format: 'data',
|
||||||
|
}),
|
||||||
|
})
|
||||||
|
.then(r => r.json())
|
||||||
|
.then(json => {
|
||||||
|
setWidgetData(json.data)
|
||||||
|
setDataLoading(false)
|
||||||
|
})
|
||||||
|
.catch(() => setDataLoading(false))
|
||||||
|
}, [fetchDone])
|
||||||
|
|
||||||
|
// Render SVG client-side whenever settings change (instant, no API call)
|
||||||
|
const svgContent = useMemo(() => {
|
||||||
|
if (!widgetData) return ''
|
||||||
|
return renderAllWidgets({
|
||||||
|
data: widgetData,
|
||||||
|
theme: settings.theme,
|
||||||
|
widgets: settings.widgets,
|
||||||
|
widgetOrder: ['grade', 'impact', 'collaborators', 'focus', 'languages', 'achievements'],
|
||||||
|
achievements: settings.achievements,
|
||||||
|
widgetSettings: settings.widgetSettings,
|
||||||
|
username,
|
||||||
|
})
|
||||||
|
}, [widgetData, settings, username])
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen animate-fade-in-up">
|
||||||
|
<div className="flex min-h-screen">
|
||||||
|
{/* Left settings panel */}
|
||||||
|
<div className="w-80 flex-shrink-0 border-r border-gray-200 bg-white p-6 flex flex-col overflow-y-auto">
|
||||||
|
{/* Back */}
|
||||||
|
<button
|
||||||
|
onClick={onBack}
|
||||||
|
className="flex items-center gap-1.5 text-xs text-gray-400 hover:text-gray-600 mb-6 transition-colors self-start"
|
||||||
|
>
|
||||||
|
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
|
||||||
|
<path d="M19 12H5M12 19l-7-7 7-7"/>
|
||||||
|
</svg>
|
||||||
|
Back
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<div className="text-sm font-semibold text-gray-800 mb-1">{username}</div>
|
||||||
|
<div className="flex items-center gap-1.5 text-[10px] text-gray-400 mb-6">
|
||||||
|
{fetchDone ? (
|
||||||
|
<>
|
||||||
|
<div className="w-1.5 h-1.5 rounded-full bg-emerald-400" />
|
||||||
|
Data ready
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<div className="w-1.5 h-1.5 rounded-full bg-amber-400 animate-pulse" />
|
||||||
|
Fetching data...
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Theme */}
|
||||||
|
<div className="mb-5">
|
||||||
|
<div className="text-[10px] uppercase tracking-wider text-gray-400 font-medium mb-3">Theme</div>
|
||||||
|
<div className="flex gap-2 flex-wrap">
|
||||||
|
{THEMES.map(t => (
|
||||||
|
<button
|
||||||
|
key={t.id}
|
||||||
|
onClick={() => updateSetting('theme', t.id)}
|
||||||
|
title={t.label}
|
||||||
|
className={`w-9 h-9 rounded-lg transition-all ${
|
||||||
|
settings.theme === t.id
|
||||||
|
? 'ring-2 ring-blue-500 ring-offset-2'
|
||||||
|
: t.border
|
||||||
|
? 'border border-gray-200 hover:border-gray-300'
|
||||||
|
: 'hover:ring-1 hover:ring-gray-300 hover:ring-offset-1'
|
||||||
|
}`}
|
||||||
|
style={{ backgroundColor: t.color }}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
<div className="text-[10px] text-gray-400 mt-1.5">
|
||||||
|
{THEMES.find(t => t.id === settings.theme)?.label}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Widgets with inline advanced settings */}
|
||||||
|
<div className="mb-5">
|
||||||
|
<div className="text-[10px] uppercase tracking-wider text-gray-400 font-medium mb-3">Widgets</div>
|
||||||
|
<div className="flex flex-col gap-0.5">
|
||||||
|
{ALL_WIDGETS.map(w => {
|
||||||
|
const enabled = settings.widgets.includes(w.id)
|
||||||
|
const hasAdvanced = ['grade', 'impact', 'collaborators', 'focus', 'languages', 'achievements'].includes(w.id)
|
||||||
|
const isExpanded = expandedWidget === w.id && enabled
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div key={w.id}>
|
||||||
|
<div className="flex items-center">
|
||||||
|
<button
|
||||||
|
onClick={() => toggleWidget(w.id)}
|
||||||
|
className={`flex-1 flex items-center gap-2.5 px-2.5 py-1.5 rounded-lg text-xs transition-colors text-left ${
|
||||||
|
enabled
|
||||||
|
? 'text-gray-800 bg-gray-50'
|
||||||
|
: 'text-gray-400 hover:text-gray-500 hover:bg-gray-50/50'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<div className={`w-3.5 h-3.5 rounded flex-shrink-0 transition-colors ${enabled ? 'bg-blue-500' : 'bg-gray-200'}`} />
|
||||||
|
{w.label}
|
||||||
|
</button>
|
||||||
|
{hasAdvanced && enabled && (
|
||||||
|
<button
|
||||||
|
onClick={() => toggleAdvanced(w.id)}
|
||||||
|
className="p-1.5 text-gray-400 hover:text-gray-600 transition-colors"
|
||||||
|
title="Advanced settings"
|
||||||
|
>
|
||||||
|
<ChevronIcon open={isExpanded} />
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{isExpanded && (
|
||||||
|
<div className="ml-6 mt-1 mb-2 p-2.5 rounded-lg bg-gray-50/80 border border-gray-100 flex flex-col gap-2.5">
|
||||||
|
{w.id === 'grade' && (
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<span className="text-[10px] text-gray-500">Max tags</span>
|
||||||
|
<NumberStepper
|
||||||
|
value={getWidgetSetting('grade', 'max_tags', 6)}
|
||||||
|
min={1} max={20}
|
||||||
|
onChange={v => updateWidgetSetting('grade', 'max_tags', v)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{w.id === 'impact' && (
|
||||||
|
<div>
|
||||||
|
<span className="text-[10px] text-gray-500 block mb-1.5">Line color</span>
|
||||||
|
<ColorPicker
|
||||||
|
value={getWidgetSetting('impact', 'line_color', '#58a6ff')}
|
||||||
|
onChange={v => updateWidgetSetting('impact', 'line_color', v)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{w.id === 'collaborators' && (
|
||||||
|
<div className="flex flex-col gap-2.5">
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<span className="text-[10px] text-gray-500">Max shown</span>
|
||||||
|
<NumberStepper
|
||||||
|
value={getWidgetSetting('collaborators', 'max_count', 5)}
|
||||||
|
min={1} max={10}
|
||||||
|
onChange={v => updateWidgetSetting('collaborators', 'max_count', v)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<span className="text-[10px] text-gray-500 block mb-1.5">Bar color</span>
|
||||||
|
<ColorPicker
|
||||||
|
value={getWidgetSetting('collaborators', 'bar_color', '#a78bfa')}
|
||||||
|
onChange={v => updateWidgetSetting('collaborators', 'bar_color', v)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{w.id === 'focus' && (
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<span className="text-[10px] text-gray-500">Max categories</span>
|
||||||
|
<NumberStepper
|
||||||
|
value={getWidgetSetting('focus', 'max_categories', 6)}
|
||||||
|
min={1} max={10}
|
||||||
|
onChange={v => updateWidgetSetting('focus', 'max_categories', v)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{w.id === 'languages' && (
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<span className="text-[10px] text-gray-500">Max languages</span>
|
||||||
|
<NumberStepper
|
||||||
|
value={getWidgetSetting('languages', 'max_languages', 5)}
|
||||||
|
min={1} max={10}
|
||||||
|
onChange={v => updateWidgetSetting('languages', 'max_languages', v)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{w.id === 'achievements' && (
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<span className="text-[10px] text-gray-500">Max shown</span>
|
||||||
|
<NumberStepper
|
||||||
|
value={getWidgetSetting('achievements', 'max_items', 5)}
|
||||||
|
min={1} max={10}
|
||||||
|
onChange={v => updateWidgetSetting('achievements', 'max_items', v)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Achievements editor */}
|
||||||
|
{settings.widgets.includes('achievements') && (
|
||||||
|
<div className="mb-5">
|
||||||
|
<div className="text-[10px] uppercase tracking-wider text-gray-400 font-medium mb-3">Achievements</div>
|
||||||
|
<div className="flex flex-col gap-2">
|
||||||
|
{settings.achievements.map((ach, idx) => (
|
||||||
|
<div key={idx} className="p-2.5 rounded-lg border border-gray-100 bg-gray-50/50">
|
||||||
|
<div className="flex items-center gap-1.5 mb-2">
|
||||||
|
{ICONS.map(ic => (
|
||||||
|
<button
|
||||||
|
key={ic.id}
|
||||||
|
onClick={() => updateAchievement(idx, 'icon', ic.id)}
|
||||||
|
className={`w-7 h-7 rounded-md text-sm flex items-center justify-center transition-colors ${
|
||||||
|
ach.icon === ic.id
|
||||||
|
? 'bg-gray-800 ring-1 ring-gray-800'
|
||||||
|
: 'bg-white border border-gray-200 hover:border-gray-300'
|
||||||
|
}`}
|
||||||
|
title={ic.id}
|
||||||
|
>
|
||||||
|
{ic.label}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
<div className="flex-1" />
|
||||||
|
<button
|
||||||
|
onClick={() => removeAchievement(idx)}
|
||||||
|
className="text-gray-300 hover:text-red-400 transition-colors text-xs px-1"
|
||||||
|
title="Remove"
|
||||||
|
>
|
||||||
|
✕
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={ach.title}
|
||||||
|
onChange={e => updateAchievement(idx, 'title', e.target.value)}
|
||||||
|
placeholder="Title (e.g. Hackathon Winner)"
|
||||||
|
className="w-full px-2 py-1.5 rounded-md border border-gray-200 bg-white text-xs text-gray-800 placeholder:text-gray-300 focus:outline-none focus:ring-1 focus:ring-gray-300 mb-1.5"
|
||||||
|
/>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={ach.subtitle}
|
||||||
|
onChange={e => updateAchievement(idx, 'subtitle', e.target.value)}
|
||||||
|
placeholder="Subtitle (e.g. 1st Place · AI Track)"
|
||||||
|
className="w-full px-2 py-1.5 rounded-md border border-gray-200 bg-white text-xs text-gray-800 placeholder:text-gray-300 focus:outline-none focus:ring-1 focus:ring-gray-300 mb-1.5"
|
||||||
|
/>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={ach.event_date}
|
||||||
|
onChange={e => updateAchievement(idx, 'event_date', e.target.value)}
|
||||||
|
placeholder="Date (e.g. 2025-01)"
|
||||||
|
className="w-full px-2 py-1.5 rounded-md border border-gray-200 bg-white text-xs text-gray-800 placeholder:text-gray-300 focus:outline-none focus:ring-1 focus:ring-gray-300"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
<button
|
||||||
|
onClick={addAchievement}
|
||||||
|
className="w-full py-2 rounded-lg border border-dashed border-gray-200 text-xs text-gray-400 hover:text-gray-600 hover:border-gray-300 transition-colors"
|
||||||
|
>
|
||||||
|
+ Add achievement
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Spacer */}
|
||||||
|
<div className="flex-1 min-h-4" />
|
||||||
|
|
||||||
|
{/* Generate button */}
|
||||||
|
<button
|
||||||
|
onClick={onGenerate}
|
||||||
|
className="w-full py-3 rounded-xl bg-gray-800 text-white text-sm font-medium hover:bg-gray-700 transition-colors"
|
||||||
|
>
|
||||||
|
Generate →
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Right preview area */}
|
||||||
|
<div className="flex-1 flex items-start justify-center p-8 overflow-auto">
|
||||||
|
<div className="relative">
|
||||||
|
{svgContent ? (
|
||||||
|
<div dangerouslySetInnerHTML={{ __html: svgContent }} />
|
||||||
|
) : (
|
||||||
|
<div className="w-[420px] h-[600px] rounded-2xl border border-gray-200 bg-white flex items-center justify-center">
|
||||||
|
{dataLoading ? (
|
||||||
|
<div className="w-5 h-5 border-2 border-gray-300 border-t-gray-600 rounded-full animate-spin-slow" />
|
||||||
|
) : (
|
||||||
|
<p className="text-xs text-gray-400">No data available</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
|
||||||
|
"target": "es2023",
|
||||||
|
"lib": ["ES2023", "DOM", "DOM.Iterable"],
|
||||||
|
"module": "esnext",
|
||||||
|
"types": ["vite/client"],
|
||||||
|
"skipLibCheck": true,
|
||||||
|
|
||||||
|
/* Bundler mode */
|
||||||
|
"moduleResolution": "bundler",
|
||||||
|
"allowImportingTsExtensions": true,
|
||||||
|
"verbatimModuleSyntax": true,
|
||||||
|
"moduleDetection": "force",
|
||||||
|
"noEmit": true,
|
||||||
|
"jsx": "react-jsx",
|
||||||
|
|
||||||
|
/* Linting */
|
||||||
|
"noUnusedLocals": true,
|
||||||
|
"noUnusedParameters": true,
|
||||||
|
"erasableSyntaxOnly": true,
|
||||||
|
"noFallthroughCasesInSwitch": true
|
||||||
|
},
|
||||||
|
"include": ["src"]
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
{
|
||||||
|
"files": [],
|
||||||
|
"references": [
|
||||||
|
{ "path": "./tsconfig.app.json" },
|
||||||
|
{ "path": "./tsconfig.node.json" }
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
|
||||||
|
"target": "es2023",
|
||||||
|
"lib": ["ES2023"],
|
||||||
|
"module": "esnext",
|
||||||
|
"types": ["node"],
|
||||||
|
"skipLibCheck": true,
|
||||||
|
|
||||||
|
/* Bundler mode */
|
||||||
|
"moduleResolution": "bundler",
|
||||||
|
"allowImportingTsExtensions": true,
|
||||||
|
"verbatimModuleSyntax": true,
|
||||||
|
"moduleDetection": "force",
|
||||||
|
"noEmit": true,
|
||||||
|
|
||||||
|
/* Linting */
|
||||||
|
"noUnusedLocals": true,
|
||||||
|
"noUnusedParameters": true,
|
||||||
|
"erasableSyntaxOnly": true,
|
||||||
|
"noFallthroughCasesInSwitch": true
|
||||||
|
},
|
||||||
|
"include": ["vite.config.ts"]
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
import { defineConfig } from 'vite'
|
||||||
|
import react from '@vitejs/plugin-react'
|
||||||
|
import tailwindcss from '@tailwindcss/vite'
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
plugins: [react(), tailwindcss()],
|
||||||
|
server: {
|
||||||
|
port: 3000,
|
||||||
|
proxy: {
|
||||||
|
'/api': 'http://localhost:5002',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
[pytest]
|
||||||
|
testpaths = tests
|
||||||
|
python_files = test_*.py
|
||||||
|
pythonpath = .
|
||||||
|
addopts = -ra --strict-markers
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
flask==3.0.3
|
||||||
|
flask-caching==2.3.0
|
||||||
|
flask-compress==1.15
|
||||||
|
requests==2.32.3
|
||||||
|
pytest==8.3.3
|
||||||
|
responses==0.25.3
|
||||||
|
gunicorn==23.0.0
|
||||||
@@ -0,0 +1,149 @@
|
|||||||
|
"""Flask app for the generator service.
|
||||||
|
|
||||||
|
Serves:
|
||||||
|
/ -> React SPA (static/index.html)
|
||||||
|
/assets/<p> -> SPA bundles
|
||||||
|
/api/* -> JSON/SVG API
|
||||||
|
"""
|
||||||
|
import os
|
||||||
|
from functools import wraps
|
||||||
|
from flask import Flask, jsonify, request, Response, send_from_directory
|
||||||
|
|
||||||
|
from . import config, db, fetcher_client, placeholder
|
||||||
|
|
||||||
|
_STATIC_DIR = os.path.join(os.path.dirname(__file__), "static")
|
||||||
|
|
||||||
|
app = Flask(__name__, static_folder=None)
|
||||||
|
|
||||||
|
|
||||||
|
def require_auth(fn):
|
||||||
|
@wraps(fn)
|
||||||
|
def wrapper(*args, **kwargs):
|
||||||
|
return fn(*args, **kwargs)
|
||||||
|
return wrapper
|
||||||
|
|
||||||
|
|
||||||
|
@app.route("/", defaults={"path": ""})
|
||||||
|
@app.route("/<path:path>")
|
||||||
|
def spa(path: str):
|
||||||
|
if path.startswith("api/"):
|
||||||
|
return jsonify({"error": "not found"}), 404
|
||||||
|
if path:
|
||||||
|
try:
|
||||||
|
return send_from_directory(_STATIC_DIR, path)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
index = os.path.join(_STATIC_DIR, "index.html")
|
||||||
|
if os.path.isfile(index):
|
||||||
|
return send_from_directory(_STATIC_DIR, "index.html")
|
||||||
|
return jsonify({"error": "frontend not built"}), 503
|
||||||
|
|
||||||
|
|
||||||
|
@app.route("/api/health", methods=["GET"])
|
||||||
|
def health():
|
||||||
|
return jsonify({"status": "ok", "service": "generator"})
|
||||||
|
|
||||||
|
|
||||||
|
@app.route("/api/<username>", methods=["GET"])
|
||||||
|
def get_widget(username: str):
|
||||||
|
return _serve(username, widget_name="composite")
|
||||||
|
|
||||||
|
|
||||||
|
@app.route("/api/<username>/<widget>.svg", methods=["GET"])
|
||||||
|
def get_widget_named(username: str, widget: str):
|
||||||
|
return _serve(username, widget_name=widget)
|
||||||
|
|
||||||
|
|
||||||
|
def _serve(username: str, widget_name: str) -> Response:
|
||||||
|
settings_row = db.get_settings(username)
|
||||||
|
|
||||||
|
if settings_row is None:
|
||||||
|
if db.enrollments_today() >= config.ENROLLMENT_DAILY_CAP:
|
||||||
|
return _placeholder_response("rate_limited", username)
|
||||||
|
defaults = {
|
||||||
|
"theme": "dark",
|
||||||
|
"enabled": config.ENABLED_WIDGETS,
|
||||||
|
"widget_order": config.WIDGET_ORDER,
|
||||||
|
}
|
||||||
|
db.enroll(username, defaults)
|
||||||
|
return _placeholder_response("building", username)
|
||||||
|
|
||||||
|
db.touch_last_requested(username)
|
||||||
|
svg = db.get_current_widget(username, widget_name)
|
||||||
|
if svg is None:
|
||||||
|
return _placeholder_response("building", username, theme=settings_row["settings"].get("theme", "dark"))
|
||||||
|
|
||||||
|
if settings_row.get("settings_hash") == "not_found":
|
||||||
|
return Response(svg, mimetype="image/svg+xml",
|
||||||
|
headers={"X-Widget-Status": "not_found", "Cache-Control": "no-store"})
|
||||||
|
|
||||||
|
return Response(svg, mimetype="image/svg+xml",
|
||||||
|
headers={"X-Widget-Status": "ready",
|
||||||
|
"Cache-Control": "public, max-age=3600"})
|
||||||
|
|
||||||
|
|
||||||
|
def _placeholder_response(variant: str, username: str, theme: str = "dark") -> Response:
|
||||||
|
svg = placeholder.render(variant, username, theme=theme)
|
||||||
|
return Response(svg, mimetype="image/svg+xml",
|
||||||
|
headers={"X-Widget-Status": variant, "Cache-Control": "no-store"})
|
||||||
|
|
||||||
|
|
||||||
|
@app.route("/api/enroll", methods=["POST"])
|
||||||
|
def enroll_endpoint():
|
||||||
|
body = request.get_json(silent=True) or {}
|
||||||
|
username = body.get("username")
|
||||||
|
if not username:
|
||||||
|
return jsonify({"error": "username required"}), 400
|
||||||
|
if db.get_settings(username) is not None:
|
||||||
|
return jsonify({"error": "already_enrolled"}), 409
|
||||||
|
if db.enrollments_today() >= config.ENROLLMENT_DAILY_CAP:
|
||||||
|
return jsonify({"error": "rate_limited"}), 429
|
||||||
|
defaults = {"theme": "dark", "enabled": config.ENABLED_WIDGETS, "widget_order": config.WIDGET_ORDER}
|
||||||
|
job_id = db.enroll(username, defaults)
|
||||||
|
return jsonify({"enrolled": True, "job_id": job_id})
|
||||||
|
|
||||||
|
|
||||||
|
@app.route("/api/<username>/settings", methods=["GET"])
|
||||||
|
@require_auth
|
||||||
|
def get_settings(username: str):
|
||||||
|
s = db.get_settings(username)
|
||||||
|
if s is None:
|
||||||
|
return jsonify({"error": "not_enrolled"}), 404
|
||||||
|
return jsonify(s)
|
||||||
|
|
||||||
|
|
||||||
|
@app.route("/api/<username>/settings", methods=["PATCH"])
|
||||||
|
@require_auth
|
||||||
|
def patch_settings(username: str):
|
||||||
|
current = db.get_settings(username)
|
||||||
|
if current is None:
|
||||||
|
return jsonify({"error": "not_enrolled"}), 404
|
||||||
|
body = request.get_json(silent=True) or {}
|
||||||
|
merged = {**current["settings"], **body}
|
||||||
|
job_id = db.update_settings(username, merged)
|
||||||
|
return jsonify({"updated": True, "job_id": job_id})
|
||||||
|
|
||||||
|
|
||||||
|
@app.route("/api/<username>/refresh", methods=["POST"])
|
||||||
|
@require_auth
|
||||||
|
def refresh(username: str):
|
||||||
|
s = db.get_settings(username)
|
||||||
|
if s is None:
|
||||||
|
return jsonify({"error": "not_enrolled"}), 404
|
||||||
|
if not db.mark_manual_refresh(username):
|
||||||
|
return jsonify({"error": "already_used"}), 409
|
||||||
|
try:
|
||||||
|
fetcher_client.force_fetch(username)
|
||||||
|
except Exception as e:
|
||||||
|
return jsonify({"error": f"fetch failed: {e}"}), 502
|
||||||
|
job_id = db.enqueue_build(username)
|
||||||
|
return jsonify({"refreshed": True, "job_id": job_id})
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
db.init_dbs()
|
||||||
|
app.run(host="0.0.0.0", port=config.PORT)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
"""Tiny cache wrapper. v1 = no-op (REDIS_URL empty). v2 = real Redis."""
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
from . import config
|
||||||
|
|
||||||
|
|
||||||
|
class Cache:
|
||||||
|
def __init__(self):
|
||||||
|
self.enabled = bool(config.REDIS_URL)
|
||||||
|
self._client = None
|
||||||
|
if self.enabled:
|
||||||
|
import redis # local import so v1 doesn't require redis in runtime path
|
||||||
|
self._client = redis.from_url(config.REDIS_URL, decode_responses=True)
|
||||||
|
|
||||||
|
def get(self, key: str) -> Optional[str]:
|
||||||
|
if not self.enabled:
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
return self._client.get(key)
|
||||||
|
except Exception:
|
||||||
|
return None
|
||||||
|
|
||||||
|
def set(self, key: str, value: str, ttl_seconds: int) -> None:
|
||||||
|
if not self.enabled:
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
self._client.setex(key, ttl_seconds, value)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
def delete(self, *keys: str) -> None:
|
||||||
|
if not self.enabled or not keys:
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
self._client.delete(*keys)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
@@ -103,3 +103,15 @@ TAG_TOPIC_MAP = {
|
|||||||
"gcp": "Cloud",
|
"gcp": "Cloud",
|
||||||
}
|
}
|
||||||
"""Map repository topics to developer role categories."""
|
"""Map repository topics to developer role categories."""
|
||||||
|
|
||||||
|
# --- Service-specific additions (v2 of config) ---
|
||||||
|
|
||||||
|
PORT = int(os.getenv("GENERATOR_PORT", "5002"))
|
||||||
|
SETTINGS_DB_PATH = os.getenv("GENERATOR_SETTINGS_DB_PATH", "./data/settings.db")
|
||||||
|
WIDGETS_DB_PATH = os.getenv("GENERATOR_WIDGETS_DB_PATH", "./data/widgets.db")
|
||||||
|
FETCHER_URL = os.getenv("FETCHER_URL", "http://localhost:5001")
|
||||||
|
FETCHER_INTERNAL_TOKEN = os.getenv("FETCHER_INTERNAL_TOKEN", "")
|
||||||
|
REDIS_URL = os.getenv("REDIS_URL", "")
|
||||||
|
ENROLLMENT_DAILY_CAP = int(os.getenv("ENROLLMENT_DAILY_CAP", "50"))
|
||||||
|
WIDGET_LRU_PER_USER = int(os.getenv("WIDGET_LRU_PER_USER", "10"))
|
||||||
|
POLL_INTERVAL_MINUTES = int(os.getenv("GENERATOR_POLL_INTERVAL_MINUTES", "15"))
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
"""Generator cron: poll fetcher for payload-hash changes, enqueue rebuilds.
|
||||||
|
|
||||||
|
Run as its own container: CMD python -m src.cron
|
||||||
|
"""
|
||||||
|
import logging
|
||||||
|
import time
|
||||||
|
|
||||||
|
from . import config, db, fetcher_client
|
||||||
|
|
||||||
|
log = logging.getLogger("generator.cron")
|
||||||
|
|
||||||
|
|
||||||
|
def tick() -> dict:
|
||||||
|
enqueued = 0
|
||||||
|
failed = 0
|
||||||
|
for username in db.list_enrolled():
|
||||||
|
try:
|
||||||
|
info = db.get_settings(username)
|
||||||
|
current = info.get("last_fetcher_payload_hash")
|
||||||
|
r = fetcher_client.get_data(username)
|
||||||
|
latest = r.get("payload_hash")
|
||||||
|
if latest and latest != current:
|
||||||
|
db.enqueue_build(username)
|
||||||
|
db.set_last_fetcher_hash(username, latest)
|
||||||
|
enqueued += 1
|
||||||
|
except Exception as e:
|
||||||
|
log.warning("poll failed for %s: %s", username, e)
|
||||||
|
failed += 1
|
||||||
|
return {"enqueued": enqueued, "failed": failed}
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s %(message)s")
|
||||||
|
db.init_dbs()
|
||||||
|
interval_s = config.POLL_INTERVAL_MINUTES * 60
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
log.info("tick: %s", tick())
|
||||||
|
except Exception:
|
||||||
|
log.exception("tick failed")
|
||||||
|
time.sleep(interval_s)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,313 @@
|
|||||||
|
"""Generator's two SQLite DBs: settings.db (settings + jobs + enrollments) and widgets.db (svg cache).
|
||||||
|
|
||||||
|
All access goes through this module so a future Postgres swap is local to here.
|
||||||
|
Both DBs are opened with WAL mode.
|
||||||
|
"""
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import sqlite3
|
||||||
|
from contextlib import contextmanager
|
||||||
|
from datetime import datetime, timedelta
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
from . import config
|
||||||
|
|
||||||
|
SETTINGS_DB_PATH = config.SETTINGS_DB_PATH
|
||||||
|
WIDGETS_DB_PATH = config.WIDGETS_DB_PATH
|
||||||
|
|
||||||
|
_SETTINGS_SCHEMA = """
|
||||||
|
CREATE TABLE IF NOT EXISTS users (
|
||||||
|
username TEXT PRIMARY KEY,
|
||||||
|
settings_json TEXT NOT NULL,
|
||||||
|
settings_hash TEXT NOT NULL,
|
||||||
|
enrolled_at TEXT NOT NULL,
|
||||||
|
last_fetcher_payload_hash TEXT,
|
||||||
|
manual_refresh_used INTEGER DEFAULT 0,
|
||||||
|
last_requested_at TEXT NOT NULL
|
||||||
|
);
|
||||||
|
CREATE TABLE IF NOT EXISTS enrollments_daily (
|
||||||
|
day TEXT PRIMARY KEY,
|
||||||
|
count INTEGER NOT NULL
|
||||||
|
);
|
||||||
|
CREATE TABLE IF NOT EXISTS jobs (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
kind TEXT NOT NULL,
|
||||||
|
username TEXT NOT NULL,
|
||||||
|
status TEXT NOT NULL,
|
||||||
|
attempts INTEGER DEFAULT 0,
|
||||||
|
last_error TEXT,
|
||||||
|
created_at TEXT NOT NULL,
|
||||||
|
updated_at TEXT NOT NULL
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_jobs_pending ON jobs(status, created_at);
|
||||||
|
"""
|
||||||
|
|
||||||
|
_WIDGETS_SCHEMA = """
|
||||||
|
CREATE TABLE IF NOT EXISTS widgets (
|
||||||
|
username TEXT NOT NULL,
|
||||||
|
settings_hash TEXT NOT NULL,
|
||||||
|
widget_name TEXT NOT NULL,
|
||||||
|
svg TEXT NOT NULL,
|
||||||
|
built_at TEXT NOT NULL,
|
||||||
|
PRIMARY KEY (username, settings_hash, widget_name)
|
||||||
|
);
|
||||||
|
CREATE TABLE IF NOT EXISTS current_widget (
|
||||||
|
username TEXT PRIMARY KEY,
|
||||||
|
settings_hash TEXT NOT NULL,
|
||||||
|
updated_at TEXT NOT NULL
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_widgets_username ON widgets(username);
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
def _now() -> str:
|
||||||
|
return datetime.utcnow().isoformat(timespec="seconds") + "Z"
|
||||||
|
|
||||||
|
|
||||||
|
def _today() -> str:
|
||||||
|
return datetime.utcnow().strftime("%Y-%m-%d")
|
||||||
|
|
||||||
|
|
||||||
|
def _open(path: str) -> sqlite3.Connection:
|
||||||
|
os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
|
||||||
|
conn = sqlite3.connect(path, timeout=10)
|
||||||
|
conn.row_factory = sqlite3.Row
|
||||||
|
conn.execute("PRAGMA journal_mode=WAL")
|
||||||
|
conn.execute("PRAGMA synchronous=NORMAL")
|
||||||
|
conn.execute("PRAGMA foreign_keys=ON")
|
||||||
|
conn.execute("PRAGMA busy_timeout=5000")
|
||||||
|
return conn
|
||||||
|
|
||||||
|
|
||||||
|
@contextmanager
|
||||||
|
def _settings_conn():
|
||||||
|
conn = _open(SETTINGS_DB_PATH)
|
||||||
|
try:
|
||||||
|
yield conn
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
@contextmanager
|
||||||
|
def _widgets_conn():
|
||||||
|
conn = _open(WIDGETS_DB_PATH)
|
||||||
|
try:
|
||||||
|
yield conn
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def init_dbs() -> None:
|
||||||
|
with _settings_conn() as c:
|
||||||
|
c.executescript(_SETTINGS_SCHEMA)
|
||||||
|
c.commit()
|
||||||
|
with _widgets_conn() as c:
|
||||||
|
c.executescript(_WIDGETS_SCHEMA)
|
||||||
|
c.commit()
|
||||||
|
|
||||||
|
|
||||||
|
def settings_hash(settings: dict) -> str:
|
||||||
|
canonical = json.dumps(settings, sort_keys=True, separators=(",", ":"))
|
||||||
|
return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
|
||||||
|
|
||||||
|
|
||||||
|
# ---- settings / enrollment ----
|
||||||
|
|
||||||
|
def enroll(username: str, defaults: dict) -> int:
|
||||||
|
"""Insert a settings row + increment daily counter + enqueue build. Returns job_id."""
|
||||||
|
sh = settings_hash(defaults)
|
||||||
|
now = _now()
|
||||||
|
with _settings_conn() as c:
|
||||||
|
c.execute(
|
||||||
|
"""INSERT INTO users(username, settings_json, settings_hash, enrolled_at, last_requested_at)
|
||||||
|
VALUES (?, ?, ?, ?, ?)
|
||||||
|
ON CONFLICT(username) DO NOTHING""",
|
||||||
|
(username, json.dumps(defaults), sh, now, now),
|
||||||
|
)
|
||||||
|
c.execute(
|
||||||
|
"""INSERT INTO enrollments_daily(day, count) VALUES (?, 1)
|
||||||
|
ON CONFLICT(day) DO UPDATE SET count = count + 1""",
|
||||||
|
(_today(),),
|
||||||
|
)
|
||||||
|
cur = c.execute(
|
||||||
|
"""INSERT INTO jobs(kind, username, status, created_at, updated_at)
|
||||||
|
VALUES ('build', ?, 'pending', ?, ?)""",
|
||||||
|
(username, now, now),
|
||||||
|
)
|
||||||
|
c.commit()
|
||||||
|
return cur.lastrowid
|
||||||
|
|
||||||
|
|
||||||
|
def enrollments_today() -> int:
|
||||||
|
with _settings_conn() as c:
|
||||||
|
row = c.execute("SELECT count FROM enrollments_daily WHERE day=?", (_today(),)).fetchone()
|
||||||
|
return row["count"] if row else 0
|
||||||
|
|
||||||
|
|
||||||
|
def get_settings(username: str) -> Optional[dict]:
|
||||||
|
with _settings_conn() as c:
|
||||||
|
row = c.execute("SELECT * FROM users WHERE username=?", (username,)).fetchone()
|
||||||
|
if row is None:
|
||||||
|
return None
|
||||||
|
return {
|
||||||
|
"settings": json.loads(row["settings_json"]),
|
||||||
|
"settings_hash": row["settings_hash"],
|
||||||
|
"manual_refresh_used": row["manual_refresh_used"],
|
||||||
|
"last_fetcher_payload_hash": row["last_fetcher_payload_hash"],
|
||||||
|
"enrolled_at": row["enrolled_at"],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def update_settings(username: str, new_settings: dict) -> int:
|
||||||
|
"""Updates settings + enqueues rebuild. Returns job_id."""
|
||||||
|
sh = settings_hash(new_settings)
|
||||||
|
now = _now()
|
||||||
|
with _settings_conn() as c:
|
||||||
|
c.execute(
|
||||||
|
"UPDATE users SET settings_json=?, settings_hash=? WHERE username=?",
|
||||||
|
(json.dumps(new_settings), sh, username),
|
||||||
|
)
|
||||||
|
cur = c.execute(
|
||||||
|
"""INSERT INTO jobs(kind, username, status, created_at, updated_at)
|
||||||
|
VALUES ('build', ?, 'pending', ?, ?)""",
|
||||||
|
(username, now, now),
|
||||||
|
)
|
||||||
|
c.commit()
|
||||||
|
return cur.lastrowid
|
||||||
|
|
||||||
|
|
||||||
|
def mark_manual_refresh(username: str) -> bool:
|
||||||
|
"""Sets manual_refresh_used=1 only if it was 0. Returns True if successfully flipped."""
|
||||||
|
with _settings_conn() as c:
|
||||||
|
cur = c.execute(
|
||||||
|
"UPDATE users SET manual_refresh_used=1 WHERE username=? AND manual_refresh_used=0",
|
||||||
|
(username,),
|
||||||
|
)
|
||||||
|
c.commit()
|
||||||
|
return cur.rowcount == 1
|
||||||
|
|
||||||
|
|
||||||
|
def touch_last_requested(username: str) -> None:
|
||||||
|
with _settings_conn() as c:
|
||||||
|
c.execute("UPDATE users SET last_requested_at=? WHERE username=?", (_now(), username))
|
||||||
|
c.commit()
|
||||||
|
|
||||||
|
|
||||||
|
def list_enrolled() -> list[str]:
|
||||||
|
with _settings_conn() as c:
|
||||||
|
return [r["username"] for r in c.execute("SELECT username FROM users").fetchall()]
|
||||||
|
|
||||||
|
|
||||||
|
def set_last_fetcher_hash(username: str, h: str) -> None:
|
||||||
|
with _settings_conn() as c:
|
||||||
|
c.execute("UPDATE users SET last_fetcher_payload_hash=? WHERE username=?", (h, username))
|
||||||
|
c.commit()
|
||||||
|
|
||||||
|
|
||||||
|
# ---- jobs ----
|
||||||
|
|
||||||
|
def enqueue_build(username: str) -> int:
|
||||||
|
now = _now()
|
||||||
|
with _settings_conn() as c:
|
||||||
|
cur = c.execute(
|
||||||
|
"""INSERT INTO jobs(kind, username, status, created_at, updated_at)
|
||||||
|
VALUES ('build', ?, 'pending', ?, ?)""",
|
||||||
|
(username, now, now),
|
||||||
|
)
|
||||||
|
c.commit()
|
||||||
|
return cur.lastrowid
|
||||||
|
|
||||||
|
|
||||||
|
def claim_next_job() -> Optional[dict]:
|
||||||
|
now = _now()
|
||||||
|
with _settings_conn() as c:
|
||||||
|
row = c.execute(
|
||||||
|
"SELECT * FROM jobs WHERE status='pending' ORDER BY created_at LIMIT 1"
|
||||||
|
).fetchone()
|
||||||
|
if row is None:
|
||||||
|
return None
|
||||||
|
c.execute("UPDATE jobs SET status='running', updated_at=?, attempts=attempts+1 WHERE id=?",
|
||||||
|
(now, row["id"]))
|
||||||
|
c.commit()
|
||||||
|
return {"id": row["id"], "username": row["username"], "kind": row["kind"],
|
||||||
|
"status": "running", "attempts": row["attempts"] + 1}
|
||||||
|
|
||||||
|
|
||||||
|
def complete_job(job_id: int) -> None:
|
||||||
|
with _settings_conn() as c:
|
||||||
|
c.execute("UPDATE jobs SET status='done', updated_at=? WHERE id=?", (_now(), job_id))
|
||||||
|
c.commit()
|
||||||
|
|
||||||
|
|
||||||
|
def fail_job(job_id: int, err: str, retry: bool) -> None:
|
||||||
|
status = "pending" if retry else "failed"
|
||||||
|
with _settings_conn() as c:
|
||||||
|
c.execute("UPDATE jobs SET status=?, last_error=?, updated_at=? WHERE id=?",
|
||||||
|
(status, err, _now(), job_id))
|
||||||
|
c.commit()
|
||||||
|
|
||||||
|
|
||||||
|
def reclaim_stuck_jobs(older_than_minutes: int) -> int:
|
||||||
|
cutoff = (datetime.utcnow() - timedelta(minutes=older_than_minutes)).isoformat(timespec="seconds") + "Z"
|
||||||
|
with _settings_conn() as c:
|
||||||
|
cur = c.execute(
|
||||||
|
"UPDATE jobs SET status='pending', updated_at=? WHERE status='running' AND updated_at < ?",
|
||||||
|
(_now(), cutoff),
|
||||||
|
)
|
||||||
|
c.commit()
|
||||||
|
return cur.rowcount
|
||||||
|
|
||||||
|
|
||||||
|
# ---- widgets ----
|
||||||
|
|
||||||
|
def put_widgets(username: str, hash_: str, widgets: dict[str, str]) -> None:
|
||||||
|
"""Insert widget rows for this (user, hash) and flip current_widget to point at it."""
|
||||||
|
now = _now()
|
||||||
|
with _widgets_conn() as c:
|
||||||
|
for name, svg in widgets.items():
|
||||||
|
c.execute(
|
||||||
|
"""INSERT INTO widgets(username, settings_hash, widget_name, svg, built_at)
|
||||||
|
VALUES (?, ?, ?, ?, ?)
|
||||||
|
ON CONFLICT(username, settings_hash, widget_name) DO UPDATE SET
|
||||||
|
svg = excluded.svg, built_at = excluded.built_at""",
|
||||||
|
(username, hash_, name, svg, now),
|
||||||
|
)
|
||||||
|
c.execute(
|
||||||
|
"""INSERT INTO current_widget(username, settings_hash, updated_at)
|
||||||
|
VALUES (?, ?, ?)
|
||||||
|
ON CONFLICT(username) DO UPDATE SET settings_hash=excluded.settings_hash, updated_at=excluded.updated_at""",
|
||||||
|
(username, hash_, now),
|
||||||
|
)
|
||||||
|
c.commit()
|
||||||
|
|
||||||
|
|
||||||
|
def get_current_widget(username: str, widget_name: str) -> Optional[str]:
|
||||||
|
with _widgets_conn() as c:
|
||||||
|
row = c.execute(
|
||||||
|
"""SELECT w.svg FROM widgets w
|
||||||
|
JOIN current_widget cw ON cw.username=w.username AND cw.settings_hash=w.settings_hash
|
||||||
|
WHERE w.username=? AND w.widget_name=?""",
|
||||||
|
(username, widget_name),
|
||||||
|
).fetchone()
|
||||||
|
return row["svg"] if row else None
|
||||||
|
|
||||||
|
|
||||||
|
def lru_trim(username: str, keep: int) -> int:
|
||||||
|
"""Keep only the N newest settings_hashes per user; delete older rows."""
|
||||||
|
with _widgets_conn() as c:
|
||||||
|
hashes = [r["settings_hash"] for r in c.execute(
|
||||||
|
"""SELECT settings_hash, MAX(built_at) AS latest FROM widgets
|
||||||
|
WHERE username=? GROUP BY settings_hash ORDER BY latest DESC""",
|
||||||
|
(username,),
|
||||||
|
).fetchall()]
|
||||||
|
to_delete = hashes[keep:]
|
||||||
|
if not to_delete:
|
||||||
|
return 0
|
||||||
|
placeholders = ",".join("?" * len(to_delete))
|
||||||
|
cur = c.execute(
|
||||||
|
f"DELETE FROM widgets WHERE username=? AND settings_hash IN ({placeholders})",
|
||||||
|
(username, *to_delete),
|
||||||
|
)
|
||||||
|
c.commit()
|
||||||
|
return cur.rowcount
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
"""HTTP client to the fetcher service. Used by api.py, worker.py, cron.py."""
|
||||||
|
import requests
|
||||||
|
|
||||||
|
from . import config
|
||||||
|
|
||||||
|
|
||||||
|
def _headers() -> dict:
|
||||||
|
return {"X-Internal-Token": config.FETCHER_INTERNAL_TOKEN}
|
||||||
|
|
||||||
|
|
||||||
|
def get_data(username: str) -> dict:
|
||||||
|
r = requests.get(f"{config.FETCHER_URL}/data/{username}", headers=_headers(), timeout=30)
|
||||||
|
r.raise_for_status()
|
||||||
|
return r.json()
|
||||||
|
|
||||||
|
|
||||||
|
def force_fetch(username: str) -> dict:
|
||||||
|
r = requests.post(f"{config.FETCHER_URL}/fetch", headers=_headers(),
|
||||||
|
json={"username": username}, timeout=30)
|
||||||
|
r.raise_for_status()
|
||||||
|
return r.json()
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
"""Placeholder SVG renderer — three variants for unknown / rate-limited / not-found users.
|
||||||
|
|
||||||
|
Uses the same card wrapper + theme system as real widgets so they look consistent.
|
||||||
|
"""
|
||||||
|
from .themes.themes import THEMES
|
||||||
|
from .utils.svg_helpers import card_wrapper, escape
|
||||||
|
|
||||||
|
_MESSAGES = {
|
||||||
|
"building": ("Building @{u}'s widget\u2026", "This usually takes under a minute."),
|
||||||
|
"rate_limited": ("Too many new users today", "Try again tomorrow."),
|
||||||
|
"not_found": ("GitHub user @{u} doesn't exist", "Check the spelling of the username."),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def render(variant: str, username: str, theme: str = "dark") -> str:
|
||||||
|
if variant not in _MESSAGES:
|
||||||
|
raise ValueError(f"unknown placeholder variant: {variant}")
|
||||||
|
title_tpl, subtitle = _MESSAGES[variant]
|
||||||
|
title = title_tpl.format(u=username)
|
||||||
|
palette = THEMES.get(theme, THEMES["dark"])
|
||||||
|
|
||||||
|
inner = (
|
||||||
|
f'<text x="24" y="56" font-family="-apple-system,Segoe UI,sans-serif" '
|
||||||
|
f'font-size="18" font-weight="600" fill="{palette["text"]}">{escape(title)}</text>'
|
||||||
|
f'<text x="24" y="82" font-family="-apple-system,Segoe UI,sans-serif" '
|
||||||
|
f'font-size="13" fill="{palette["text_secondary"]}">{escape(subtitle)}</text>'
|
||||||
|
)
|
||||||
|
return card_wrapper(inner, width=400, height=120, theme=palette)
|
||||||
@@ -3,7 +3,7 @@
|
|||||||
from datetime import datetime, timedelta
|
from datetime import datetime, timedelta
|
||||||
from collections import defaultdict
|
from collections import defaultdict
|
||||||
|
|
||||||
from ..models import (
|
from .models import (
|
||||||
GradeData,
|
GradeData,
|
||||||
TagData,
|
TagData,
|
||||||
ImpactWeek,
|
ImpactWeek,
|
||||||
@@ -11,7 +11,7 @@ from ..models import (
|
|||||||
FocusCategory,
|
FocusCategory,
|
||||||
LanguageData,
|
LanguageData,
|
||||||
)
|
)
|
||||||
from ..widgets import (
|
from .widgets import (
|
||||||
render_grade_widget,
|
render_grade_widget,
|
||||||
render_impact_widget,
|
render_impact_widget,
|
||||||
render_collaborators_widget,
|
render_collaborators_widget,
|
||||||
@@ -150,7 +150,7 @@ def _compute_tags(github_data: dict, max_tags: int = None, custom_tags: list[str
|
|||||||
Returns:
|
Returns:
|
||||||
List of TagData objects with inferred developer roles
|
List of TagData objects with inferred developer roles
|
||||||
"""
|
"""
|
||||||
from ..config import TAG_MAX_COUNT, TAG_LANGUAGE_MAP, TAG_TOPIC_MAP, HIDDEN_LANGUAGES
|
from .config import TAG_MAX_COUNT, TAG_LANGUAGE_MAP, TAG_TOPIC_MAP, HIDDEN_LANGUAGES
|
||||||
|
|
||||||
if max_tags is None:
|
if max_tags is None:
|
||||||
max_tags = TAG_MAX_COUNT
|
max_tags = TAG_MAX_COUNT
|
||||||
@@ -372,7 +372,7 @@ def compute_focus(github_data: dict, hidden_languages: list[str] = None) -> list
|
|||||||
github_data: GitHub profile data
|
github_data: GitHub profile data
|
||||||
hidden_languages: Optional list of languages to exclude
|
hidden_languages: Optional list of languages to exclude
|
||||||
"""
|
"""
|
||||||
from ..config import HIDDEN_LANGUAGES
|
from .config import HIDDEN_LANGUAGES
|
||||||
|
|
||||||
if hidden_languages is None:
|
if hidden_languages is None:
|
||||||
hidden_languages = HIDDEN_LANGUAGES
|
hidden_languages = HIDDEN_LANGUAGES
|
||||||
@@ -465,7 +465,7 @@ def compute_languages(github_data: dict, hidden_languages: list[str] = None) ->
|
|||||||
github_data: GitHub profile data
|
github_data: GitHub profile data
|
||||||
hidden_languages: Optional list of languages to exclude (e.g., ["HTML", "CSS"])
|
hidden_languages: Optional list of languages to exclude (e.g., ["HTML", "CSS"])
|
||||||
"""
|
"""
|
||||||
from ..config import HIDDEN_LANGUAGES
|
from .config import HIDDEN_LANGUAGES
|
||||||
|
|
||||||
if hidden_languages is None:
|
if hidden_languages is None:
|
||||||
hidden_languages = HIDDEN_LANGUAGES
|
hidden_languages = HIDDEN_LANGUAGES
|
||||||
@@ -510,7 +510,7 @@ def generate_widgets_from_github(
|
|||||||
widget_settings: Optional per-widget settings dict, keyed by widget name.
|
widget_settings: Optional per-widget settings dict, keyed by widget name.
|
||||||
Each value is a dict of settings for that widget's renderer.
|
Each value is a dict of settings for that widget's renderer.
|
||||||
"""
|
"""
|
||||||
from ..config import ENABLED_WIDGETS
|
from .config import ENABLED_WIDGETS
|
||||||
|
|
||||||
if enabled is None:
|
if enabled is None:
|
||||||
enabled = ENABLED_WIDGETS
|
enabled = ENABLED_WIDGETS
|
||||||
@@ -0,0 +1,84 @@
|
|||||||
|
"""Build worker. Pulls pending jobs and renders widgets.
|
||||||
|
|
||||||
|
Run as its own container: CMD python -m src.worker
|
||||||
|
"""
|
||||||
|
import logging
|
||||||
|
import time
|
||||||
|
|
||||||
|
from . import cache, config, db, fetcher_client, placeholder, processor
|
||||||
|
from .widgets import compose_widget
|
||||||
|
|
||||||
|
log = logging.getLogger("generator.worker")
|
||||||
|
MAX_ATTEMPTS = 3
|
||||||
|
|
||||||
|
|
||||||
|
def _render_widgets(username: str, payload: dict, settings: dict) -> dict[str, str]:
|
||||||
|
enabled = settings.get("enabled") or config.ENABLED_WIDGETS
|
||||||
|
order = settings.get("widget_order") or config.WIDGET_ORDER
|
||||||
|
theme = settings.get("theme", "dark")
|
||||||
|
widgets = processor.generate_widgets_from_github(
|
||||||
|
payload,
|
||||||
|
theme=theme,
|
||||||
|
custom_tags=settings.get("custom_tags"),
|
||||||
|
hidden_languages=settings.get("hidden_languages"),
|
||||||
|
enabled=enabled,
|
||||||
|
widget_settings=settings.get("widget_settings") or {},
|
||||||
|
)
|
||||||
|
ordered = [w for w in order if w in enabled and w in widgets and widgets[w]]
|
||||||
|
composite = compose_widget(
|
||||||
|
widgets=widgets, enabled=ordered, theme_name=theme,
|
||||||
|
username=username, avatar_b64=payload.get("avatar_b64", ""),
|
||||||
|
)
|
||||||
|
out = {name: svg for name, svg in widgets.items() if svg}
|
||||||
|
out["composite"] = composite
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def process_one() -> bool:
|
||||||
|
job = db.claim_next_job()
|
||||||
|
if job is None:
|
||||||
|
return False
|
||||||
|
username = job["username"]
|
||||||
|
try:
|
||||||
|
result = fetcher_client.get_data(username)
|
||||||
|
payload = result.get("data") or {}
|
||||||
|
if payload.get("error") == "not_found":
|
||||||
|
svg = placeholder.render("not_found", username, theme="dark")
|
||||||
|
db.put_widgets(username, "not_found", {"composite": svg})
|
||||||
|
cache.Cache().delete(f"widget:composite:{username}")
|
||||||
|
db.complete_job(job["id"])
|
||||||
|
log.info("not_found marker persisted for %s", username)
|
||||||
|
return True
|
||||||
|
|
||||||
|
settings_row = db.get_settings(username)
|
||||||
|
if settings_row is None:
|
||||||
|
db.fail_job(job["id"], "settings missing", retry=False)
|
||||||
|
return True
|
||||||
|
|
||||||
|
widgets = _render_widgets(username, payload, settings_row["settings"])
|
||||||
|
db.put_widgets(username, settings_row["settings_hash"], widgets)
|
||||||
|
db.set_last_fetcher_hash(username, result.get("payload_hash", ""))
|
||||||
|
db.lru_trim(username, config.WIDGET_LRU_PER_USER)
|
||||||
|
c = cache.Cache()
|
||||||
|
c.delete(f"widget:composite:{username}", *[f"widget:{n}:{username}" for n in widgets])
|
||||||
|
db.complete_job(job["id"])
|
||||||
|
log.info("built widgets for %s", username)
|
||||||
|
return True
|
||||||
|
except Exception as e:
|
||||||
|
retry = job["attempts"] < MAX_ATTEMPTS
|
||||||
|
db.fail_job(job["id"], str(e)[:500], retry=retry)
|
||||||
|
log.warning("build failed for %s (retry=%s): %s", username, retry, e)
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s %(message)s")
|
||||||
|
db.init_dbs()
|
||||||
|
while True:
|
||||||
|
db.reclaim_stuck_jobs(older_than_minutes=10)
|
||||||
|
if not process_one():
|
||||||
|
time.sleep(0.5)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
"""End-to-end: api + worker in-process + mocked fetcher HTTP."""
|
||||||
|
import os, tempfile
|
||||||
|
import pytest
|
||||||
|
import responses
|
||||||
|
from src import api as apimod, db as dbmod, worker
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def env(monkeypatch):
|
||||||
|
with tempfile.TemporaryDirectory() as d:
|
||||||
|
monkeypatch.setattr(dbmod, "SETTINGS_DB_PATH", os.path.join(d, "s.db"))
|
||||||
|
monkeypatch.setattr(dbmod, "WIDGETS_DB_PATH", os.path.join(d, "w.db"))
|
||||||
|
monkeypatch.setattr(apimod.config, "FETCHER_URL", "http://fetcher-mock")
|
||||||
|
monkeypatch.setattr(apimod.config, "FETCHER_INTERNAL_TOKEN", "t")
|
||||||
|
dbmod.init_dbs()
|
||||||
|
yield
|
||||||
|
|
||||||
|
|
||||||
|
@responses.activate
|
||||||
|
def test_first_request_builds_then_serves_ready(env):
|
||||||
|
responses.add(
|
||||||
|
responses.GET, "http://fetcher-mock/data/alice",
|
||||||
|
json={"data": {"user": {"login": "alice"}, "repos": [], "events": [],
|
||||||
|
"commits": [], "total_commits": 0, "recent_commits": 0,
|
||||||
|
"total_prs": 0, "collaborators_data": [], "avatar_b64": ""},
|
||||||
|
"payload_hash": "h1"}, status=200,
|
||||||
|
)
|
||||||
|
client = apimod.app.test_client()
|
||||||
|
|
||||||
|
r1 = client.get("/api/alice")
|
||||||
|
assert r1.headers["X-Widget-Status"] == "building"
|
||||||
|
|
||||||
|
for _ in range(5):
|
||||||
|
if not worker.process_one():
|
||||||
|
break
|
||||||
|
|
||||||
|
r2 = client.get("/api/alice")
|
||||||
|
assert r2.headers["X-Widget-Status"] == "ready"
|
||||||
|
assert r2.data.startswith(b"<svg") or r2.data.startswith(b"<?xml")
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
import os, tempfile, pytest
|
||||||
|
from unittest.mock import patch
|
||||||
|
from src import db as dbmod
|
||||||
|
from src import api as apimod
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def client(monkeypatch):
|
||||||
|
with tempfile.TemporaryDirectory() as d:
|
||||||
|
monkeypatch.setattr(dbmod, "SETTINGS_DB_PATH", os.path.join(d, "s.db"))
|
||||||
|
monkeypatch.setattr(dbmod, "WIDGETS_DB_PATH", os.path.join(d, "w.db"))
|
||||||
|
dbmod.init_dbs()
|
||||||
|
app = apimod.app
|
||||||
|
app.config["TESTING"] = True
|
||||||
|
with app.test_client() as c:
|
||||||
|
yield c
|
||||||
|
|
||||||
|
|
||||||
|
def test_health(client):
|
||||||
|
r = client.get("/api/health")
|
||||||
|
assert r.status_code == 200
|
||||||
|
assert r.get_json()["service"] == "generator"
|
||||||
|
|
||||||
|
|
||||||
|
def test_get_unknown_user_auto_enrolls_and_returns_placeholder(client):
|
||||||
|
r = client.get("/api/alice")
|
||||||
|
assert r.status_code == 200
|
||||||
|
assert r.headers["X-Widget-Status"] == "building"
|
||||||
|
assert "Building" in r.data.decode()
|
||||||
|
assert dbmod.get_settings("alice") is not None
|
||||||
|
|
||||||
|
|
||||||
|
def test_rate_limit_returns_rate_limited_placeholder(client, monkeypatch):
|
||||||
|
monkeypatch.setattr(apimod.config, "ENROLLMENT_DAILY_CAP", 1)
|
||||||
|
client.get("/api/alice")
|
||||||
|
r = client.get("/api/bob")
|
||||||
|
assert r.headers["X-Widget-Status"] == "rate_limited"
|
||||||
|
|
||||||
|
|
||||||
|
def test_enrolled_user_with_built_widget_returns_ready(client):
|
||||||
|
dbmod.enroll("alice", {"theme": "dark"})
|
||||||
|
dbmod.put_widgets("alice", "h1", {"composite": "<svg>ready</svg>"})
|
||||||
|
with dbmod._settings_conn() as c:
|
||||||
|
c.execute("UPDATE users SET settings_hash='h1' WHERE username='alice'")
|
||||||
|
c.commit()
|
||||||
|
r = client.get("/api/alice")
|
||||||
|
assert r.status_code == 200
|
||||||
|
assert r.headers["X-Widget-Status"] == "ready"
|
||||||
|
assert b"ready" in r.data
|
||||||
|
|
||||||
|
|
||||||
|
def test_settings_patch_enqueues_rebuild(client):
|
||||||
|
dbmod.enroll("alice", {"theme": "dark"})
|
||||||
|
r = client.patch("/api/alice/settings", json={"theme": "light"})
|
||||||
|
assert r.status_code == 200
|
||||||
|
assert dbmod.get_settings("alice")["settings"]["theme"] == "light"
|
||||||
|
|
||||||
|
|
||||||
|
def test_refresh_is_one_shot(client):
|
||||||
|
dbmod.enroll("alice", {"theme": "dark"})
|
||||||
|
with patch("src.api.fetcher_client.force_fetch", return_value={"changed": True, "payload_hash": "x", "stored": True}):
|
||||||
|
r1 = client.post("/api/alice/refresh")
|
||||||
|
assert r1.status_code == 200
|
||||||
|
r2 = client.post("/api/alice/refresh")
|
||||||
|
assert r2.status_code == 409
|
||||||
|
|
||||||
|
|
||||||
|
def test_not_found_status_header(client):
|
||||||
|
dbmod.enroll("ghost", {"theme": "dark"})
|
||||||
|
dbmod.put_widgets("ghost", "not_found", {"composite": "<svg>404</svg>"})
|
||||||
|
with dbmod._settings_conn() as c:
|
||||||
|
c.execute("UPDATE users SET settings_hash='not_found' WHERE username='ghost'")
|
||||||
|
c.commit()
|
||||||
|
r = client.get("/api/ghost")
|
||||||
|
assert r.headers["X-Widget-Status"] == "not_found"
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
from src import cache
|
||||||
|
|
||||||
|
|
||||||
|
def test_noop_when_redis_url_empty(monkeypatch):
|
||||||
|
monkeypatch.setattr(cache.config, "REDIS_URL", "")
|
||||||
|
c = cache.Cache()
|
||||||
|
assert c.get("k") is None
|
||||||
|
c.set("k", "v", 60)
|
||||||
|
c.delete("k")
|
||||||
|
assert c.get("k") is None # still None because no-op
|
||||||
|
|
||||||
|
|
||||||
|
def test_enabled_flag_reflects_config(monkeypatch):
|
||||||
|
monkeypatch.setattr(cache.config, "REDIS_URL", "")
|
||||||
|
assert cache.Cache().enabled is False
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
import os, tempfile, pytest
|
||||||
|
from unittest.mock import patch
|
||||||
|
from src import db as dbmod
|
||||||
|
from src import cron as cronmod
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def tmp_dbs(monkeypatch):
|
||||||
|
with tempfile.TemporaryDirectory() as d:
|
||||||
|
monkeypatch.setattr(dbmod, "SETTINGS_DB_PATH", os.path.join(d, "s.db"))
|
||||||
|
monkeypatch.setattr(dbmod, "WIDGETS_DB_PATH", os.path.join(d, "w.db"))
|
||||||
|
dbmod.init_dbs()
|
||||||
|
yield
|
||||||
|
|
||||||
|
|
||||||
|
def test_tick_enqueues_build_when_hash_changed(tmp_dbs):
|
||||||
|
dbmod.enroll("alice", {"theme": "dark"})
|
||||||
|
dbmod.set_last_fetcher_hash("alice", "old")
|
||||||
|
with dbmod._settings_conn() as c:
|
||||||
|
c.execute("DELETE FROM jobs")
|
||||||
|
c.commit()
|
||||||
|
with patch("src.cron.fetcher_client.get_data",
|
||||||
|
return_value={"data": {}, "payload_hash": "new"}):
|
||||||
|
stats = cronmod.tick()
|
||||||
|
assert stats["enqueued"] == 1
|
||||||
|
|
||||||
|
|
||||||
|
def test_tick_skips_when_hash_unchanged(tmp_dbs):
|
||||||
|
dbmod.enroll("alice", {"theme": "dark"})
|
||||||
|
dbmod.set_last_fetcher_hash("alice", "same")
|
||||||
|
with dbmod._settings_conn() as c:
|
||||||
|
c.execute("DELETE FROM jobs")
|
||||||
|
c.commit()
|
||||||
|
with patch("src.cron.fetcher_client.get_data",
|
||||||
|
return_value={"data": {}, "payload_hash": "same"}):
|
||||||
|
stats = cronmod.tick()
|
||||||
|
assert stats["enqueued"] == 0
|
||||||
@@ -0,0 +1,92 @@
|
|||||||
|
import os
|
||||||
|
import tempfile
|
||||||
|
import pytest
|
||||||
|
from src import db as dbmod
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def tmp_dbs(monkeypatch):
|
||||||
|
with tempfile.TemporaryDirectory() as d:
|
||||||
|
monkeypatch.setattr(dbmod, "SETTINGS_DB_PATH", os.path.join(d, "s.db"))
|
||||||
|
monkeypatch.setattr(dbmod, "WIDGETS_DB_PATH", os.path.join(d, "w.db"))
|
||||||
|
dbmod.init_dbs()
|
||||||
|
yield d
|
||||||
|
|
||||||
|
|
||||||
|
def test_settings_hash_is_deterministic():
|
||||||
|
h1 = dbmod.settings_hash({"theme": "dark", "widgets": ["a", "b"]})
|
||||||
|
h2 = dbmod.settings_hash({"widgets": ["a", "b"], "theme": "dark"})
|
||||||
|
assert h1 == h2
|
||||||
|
|
||||||
|
|
||||||
|
def test_enroll_and_get_settings(tmp_dbs):
|
||||||
|
defaults = {"theme": "dark", "widgets": ["grade"]}
|
||||||
|
job_id = dbmod.enroll("alice", defaults)
|
||||||
|
assert job_id > 0
|
||||||
|
s = dbmod.get_settings("alice")
|
||||||
|
assert s["settings"] == defaults
|
||||||
|
assert s["manual_refresh_used"] == 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_enrollments_daily_counter(tmp_dbs):
|
||||||
|
dbmod.enroll("alice", {"theme": "dark"})
|
||||||
|
dbmod.enroll("bob", {"theme": "dark"})
|
||||||
|
assert dbmod.enrollments_today() == 2
|
||||||
|
|
||||||
|
|
||||||
|
def test_update_settings_changes_hash(tmp_dbs):
|
||||||
|
dbmod.enroll("alice", {"theme": "dark"})
|
||||||
|
h_before = dbmod.get_settings("alice")["settings_hash"]
|
||||||
|
dbmod.update_settings("alice", {"theme": "light"})
|
||||||
|
h_after = dbmod.get_settings("alice")["settings_hash"]
|
||||||
|
assert h_before != h_after
|
||||||
|
|
||||||
|
|
||||||
|
def test_claim_job_marks_running(tmp_dbs):
|
||||||
|
job_id = dbmod.enroll("alice", {"theme": "dark"})
|
||||||
|
job = dbmod.claim_next_job()
|
||||||
|
assert job["id"] == job_id
|
||||||
|
assert job["status"] == "running"
|
||||||
|
assert dbmod.claim_next_job() is None # already running
|
||||||
|
|
||||||
|
|
||||||
|
def test_complete_job(tmp_dbs):
|
||||||
|
jid = dbmod.enroll("alice", {"theme": "dark"})
|
||||||
|
dbmod.claim_next_job()
|
||||||
|
dbmod.complete_job(jid)
|
||||||
|
with dbmod._settings_conn() as c:
|
||||||
|
status = c.execute("SELECT status FROM jobs WHERE id=?", (jid,)).fetchone()[0]
|
||||||
|
assert status == "done"
|
||||||
|
|
||||||
|
|
||||||
|
def test_widgets_put_and_get(tmp_dbs):
|
||||||
|
dbmod.put_widgets("alice", "hash1", {"composite": "<svg/>", "grade": "<svg/>"})
|
||||||
|
row = dbmod.get_current_widget("alice", "composite")
|
||||||
|
assert row == "<svg/>"
|
||||||
|
|
||||||
|
|
||||||
|
def test_current_widget_flips_atomically(tmp_dbs):
|
||||||
|
dbmod.put_widgets("alice", "hash1", {"composite": "<svg>v1</svg>"})
|
||||||
|
dbmod.put_widgets("alice", "hash2", {"composite": "<svg>v2</svg>"})
|
||||||
|
assert dbmod.get_current_widget("alice", "composite") == "<svg>v2</svg>"
|
||||||
|
|
||||||
|
|
||||||
|
def test_lru_trim_keeps_n_newest(tmp_dbs):
|
||||||
|
for i in range(12):
|
||||||
|
dbmod.put_widgets("alice", f"hash{i}", {"composite": f"<svg>{i}</svg>"})
|
||||||
|
dbmod.lru_trim("alice", keep=10)
|
||||||
|
with dbmod._widgets_conn() as c:
|
||||||
|
n = c.execute("SELECT COUNT(DISTINCT settings_hash) FROM widgets WHERE username='alice'").fetchone()[0]
|
||||||
|
assert n == 10
|
||||||
|
|
||||||
|
|
||||||
|
def test_reclaim_stuck_running_jobs(tmp_dbs):
|
||||||
|
jid = dbmod.enroll("alice", {"theme": "dark"})
|
||||||
|
dbmod.claim_next_job()
|
||||||
|
# Backdate updated_at to simulate dead worker
|
||||||
|
with dbmod._settings_conn() as c:
|
||||||
|
c.execute("UPDATE jobs SET updated_at='2020-01-01T00:00:00Z' WHERE id=?", (jid,))
|
||||||
|
c.commit()
|
||||||
|
dbmod.reclaim_stuck_jobs(older_than_minutes=10)
|
||||||
|
job = dbmod.claim_next_job()
|
||||||
|
assert job["id"] == jid
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
import responses
|
||||||
|
import pytest
|
||||||
|
from src import fetcher_client as fc
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(autouse=True)
|
||||||
|
def cfg(monkeypatch):
|
||||||
|
monkeypatch.setattr(fc.config, "FETCHER_URL", "http://fetcher:5001")
|
||||||
|
monkeypatch.setattr(fc.config, "FETCHER_INTERNAL_TOKEN", "secret")
|
||||||
|
|
||||||
|
|
||||||
|
@responses.activate
|
||||||
|
def test_get_data_returns_payload_and_hash():
|
||||||
|
responses.add(
|
||||||
|
responses.GET, "http://fetcher:5001/data/alice",
|
||||||
|
json={"data": {"user": {"login": "alice"}}, "payload_hash": "abc"},
|
||||||
|
status=200,
|
||||||
|
)
|
||||||
|
result = fc.get_data("alice")
|
||||||
|
assert result["payload_hash"] == "abc"
|
||||||
|
assert result["data"]["user"]["login"] == "alice"
|
||||||
|
|
||||||
|
|
||||||
|
@responses.activate
|
||||||
|
def test_get_data_sends_auth_header():
|
||||||
|
responses.add(responses.GET, "http://fetcher:5001/data/alice",
|
||||||
|
json={"data": {}, "payload_hash": "h"}, status=200)
|
||||||
|
fc.get_data("alice")
|
||||||
|
assert responses.calls[0].request.headers["X-Internal-Token"] == "secret"
|
||||||
|
|
||||||
|
|
||||||
|
@responses.activate
|
||||||
|
def test_force_fetch():
|
||||||
|
responses.add(responses.POST, "http://fetcher:5001/fetch",
|
||||||
|
json={"stored": True, "payload_hash": "new", "changed": True}, status=200)
|
||||||
|
r = fc.force_fetch("alice")
|
||||||
|
assert r["changed"] is True
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
from src import placeholder
|
||||||
|
|
||||||
|
|
||||||
|
def test_building_contains_username_and_svg_tag():
|
||||||
|
svg = placeholder.render("building", "alice", theme="dark")
|
||||||
|
assert svg.startswith("<svg") and "</svg>" in svg
|
||||||
|
assert "alice" in svg
|
||||||
|
assert "Building" in svg or "building" in svg.lower()
|
||||||
|
|
||||||
|
|
||||||
|
def test_rate_limited_variant():
|
||||||
|
svg = placeholder.render("rate_limited", "alice", theme="dark")
|
||||||
|
assert "tomorrow" in svg.lower() or "try again" in svg.lower()
|
||||||
|
|
||||||
|
|
||||||
|
def test_not_found_variant():
|
||||||
|
svg = placeholder.render("not_found", "ghost", theme="dark")
|
||||||
|
assert "ghost" in svg
|
||||||
|
assert "doesn't exist" in svg or "not found" in svg.lower()
|
||||||
|
|
||||||
|
|
||||||
|
def test_unknown_variant_raises():
|
||||||
|
import pytest
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
placeholder.render("bogus", "alice", theme="dark")
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
import os, tempfile, pytest
|
||||||
|
from unittest.mock import patch, MagicMock
|
||||||
|
from src import db as dbmod
|
||||||
|
from src import worker
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def tmp_dbs(monkeypatch):
|
||||||
|
with tempfile.TemporaryDirectory() as d:
|
||||||
|
monkeypatch.setattr(dbmod, "SETTINGS_DB_PATH", os.path.join(d, "s.db"))
|
||||||
|
monkeypatch.setattr(dbmod, "WIDGETS_DB_PATH", os.path.join(d, "w.db"))
|
||||||
|
dbmod.init_dbs()
|
||||||
|
yield d
|
||||||
|
|
||||||
|
|
||||||
|
def test_process_one_renders_and_stores_widgets(tmp_dbs):
|
||||||
|
dbmod.enroll("alice", {"theme": "dark", "enabled": ["grade"]})
|
||||||
|
fake_payload = {"user": {"login": "alice"}, "repos": [], "events": [],
|
||||||
|
"commits": [], "total_commits": 0, "recent_commits": [],
|
||||||
|
"total_prs": 0, "collaborators_data": [], "avatar_b64": ""}
|
||||||
|
with patch("src.worker.fetcher_client.get_data",
|
||||||
|
return_value={"data": fake_payload, "payload_hash": "h1"}), \
|
||||||
|
patch("src.worker._render_widgets",
|
||||||
|
return_value={"composite": "<svg>c</svg>", "grade": "<svg>g</svg>"}):
|
||||||
|
worker.process_one()
|
||||||
|
svg = dbmod.get_current_widget("alice", "composite")
|
||||||
|
assert svg == "<svg>c</svg>"
|
||||||
|
|
||||||
|
|
||||||
|
def test_not_found_payload_renders_not_found_placeholder(tmp_dbs):
|
||||||
|
dbmod.enroll("ghost", {"theme": "dark"})
|
||||||
|
with patch("src.worker.fetcher_client.get_data",
|
||||||
|
return_value={"data": {"error": "not_found"}, "payload_hash": "x"}):
|
||||||
|
worker.process_one()
|
||||||
|
svg = dbmod.get_current_widget("ghost", "composite")
|
||||||
|
assert svg and "ghost" in svg
|
||||||
|
|
||||||
|
|
||||||
|
def test_worker_retries_on_fetcher_failure(tmp_dbs):
|
||||||
|
dbmod.enroll("alice", {"theme": "dark"})
|
||||||
|
with patch("src.worker.fetcher_client.get_data", side_effect=RuntimeError("boom")):
|
||||||
|
worker.process_one()
|
||||||
|
with dbmod._settings_conn() as c:
|
||||||
|
row = c.execute("SELECT status, attempts, last_error FROM jobs WHERE username='alice'").fetchone()
|
||||||
|
assert row["status"] == "pending"
|
||||||
|
assert row["attempts"] == 1
|
||||||
|
assert "boom" in row["last_error"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_worker_marks_failed_after_max_attempts(tmp_dbs):
|
||||||
|
dbmod.enroll("alice", {"theme": "dark"})
|
||||||
|
with patch("src.worker.fetcher_client.get_data", side_effect=RuntimeError("boom")):
|
||||||
|
for _ in range(4):
|
||||||
|
worker.process_one()
|
||||||
|
with dbmod._settings_conn() as c:
|
||||||
|
row = c.execute("SELECT status, attempts FROM jobs WHERE username='alice'").fetchone()
|
||||||
|
assert row["status"] == "failed"
|
||||||
|
assert row["attempts"] >= 3
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
#!/usr/bin/env python3
|
|
||||||
"""
|
|
||||||
Entry point for running the GitHub profile widget generator.
|
|
||||||
Run this from the project root directory.
|
|
||||||
"""
|
|
||||||
|
|
||||||
import sys
|
|
||||||
from src.generate import main
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
main()
|
|
||||||
-112
@@ -1,112 +0,0 @@
|
|||||||
# GitHub Profile Widget Generator
|
|
||||||
|
|
||||||
A modular system for generating polished SVG widgets from GitHub profile data.
|
|
||||||
|
|
||||||
## Project Structure
|
|
||||||
|
|
||||||
```
|
|
||||||
src/
|
|
||||||
├── models/ # Data classes and types
|
|
||||||
│ ├── __init__.py
|
|
||||||
│ └── types.py # Widget data models
|
|
||||||
│
|
|
||||||
├── themes/ # Color schemes and styling
|
|
||||||
│ ├── __init__.py
|
|
||||||
│ └── themes.py # Theme definitions
|
|
||||||
│
|
|
||||||
├── widgets/ # Widget rendering modules
|
|
||||||
│ ├── __init__.py
|
|
||||||
│ ├── grade.py # Developer grade widget
|
|
||||||
│ ├── impact.py # Impact timeline chart
|
|
||||||
│ ├── collaborators.py # Top collaborators
|
|
||||||
│ ├── focus.py # Focus areas bars
|
|
||||||
│ ├── languages.py # Languages donut chart
|
|
||||||
│ ├── achievements.py # Achievements list
|
|
||||||
│ └── composite.py # Full widget composer
|
|
||||||
│
|
|
||||||
├── data/ # Data fetching and processing
|
|
||||||
│ ├── __init__.py
|
|
||||||
│ ├── fetcher.py # GitHub API client
|
|
||||||
│ └── processor.py # Data transformation
|
|
||||||
│
|
|
||||||
├── utils/ # Helper functions
|
|
||||||
│ ├── __init__.py
|
|
||||||
│ └── svg_helpers.py # SVG utilities
|
|
||||||
│
|
|
||||||
└── generate.py # Main CLI entry point
|
|
||||||
```
|
|
||||||
|
|
||||||
## Usage
|
|
||||||
|
|
||||||
Run from the project root directory:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Generate widgets for a user
|
|
||||||
python run.py <username> [theme]
|
|
||||||
|
|
||||||
# Or run as a module
|
|
||||||
python -m src.generate <username> [theme]
|
|
||||||
|
|
||||||
# With GitHub token for higher rate limits
|
|
||||||
GITHUB_TOKEN=your_token python run.py <username>
|
|
||||||
|
|
||||||
# Use light theme
|
|
||||||
python run.py <username> light
|
|
||||||
```
|
|
||||||
|
|
||||||
## Extending
|
|
||||||
|
|
||||||
### Adding a New Widget
|
|
||||||
|
|
||||||
1. Create a new file in `widgets/` (e.g., `widgets/my_widget.py`)
|
|
||||||
2. Implement `render_my_widget(data, theme_name="dark") -> str`
|
|
||||||
3. Add to `widgets/__init__.py` exports
|
|
||||||
4. Update `data/processor.py` to include it in `generate_widgets_from_github()`
|
|
||||||
|
|
||||||
### Adding a New Theme
|
|
||||||
|
|
||||||
1. Add theme definition to `themes/themes.py`
|
|
||||||
2. Use the theme name when calling `generate_full_widget(theme="my_theme")`
|
|
||||||
|
|
||||||
## Configuration
|
|
||||||
|
|
||||||
Customize behavior via environment variables:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Collaborator settings
|
|
||||||
export COLLABORATOR_MIN_COMMITS=10 # Min commits to be a collaborator (default: 10)
|
|
||||||
export COLLABORATOR_MAX_REPO_SIZE=100 # Skip repos with 100+ contributors (default: 100)
|
|
||||||
export COLLABORATOR_TOP_REPOS=5 # Check top N repos for collaborators (default: 5)
|
|
||||||
|
|
||||||
# Commit fetching
|
|
||||||
export COMMIT_MAX_REPOS=10 # Fetch commits from top N repos (default: 10)
|
|
||||||
export COMMIT_PER_REPO=30 # Commits per repo (default: 30)
|
|
||||||
|
|
||||||
# API settings
|
|
||||||
export API_TIMEOUT=5 # Request timeout in seconds (default: 5)
|
|
||||||
|
|
||||||
# Run with custom settings
|
|
||||||
COLLABORATOR_MIN_COMMITS=15 python run.py username
|
|
||||||
```
|
|
||||||
|
|
||||||
## How Collaborators Are Detected
|
|
||||||
|
|
||||||
The widget finds **meaningful collaborators** by:
|
|
||||||
|
|
||||||
1. **Identifying shared repositories**: Looks at repos where the user has committed
|
|
||||||
2. **Fetching contributors**: Gets all contributors from those repos
|
|
||||||
3. **Applying thresholds**:
|
|
||||||
- Only includes contributors with 10+ commits (configurable)
|
|
||||||
- Filters out huge OSS projects (100+ contributors)
|
|
||||||
- Focuses on user's top 5 most active repos
|
|
||||||
4. **Ranking by collaboration**: Sorts by total shared commits across all repos
|
|
||||||
|
|
||||||
This ensures collaborators are people you've actually worked with closely, not random contributors from large open-source projects.
|
|
||||||
|
|
||||||
## Development
|
|
||||||
|
|
||||||
All widgets follow the same pattern:
|
|
||||||
- Accept data models from `models/`
|
|
||||||
- Use themes from `themes/`
|
|
||||||
- Return SVG strings
|
|
||||||
- Use `utils.card_wrapper()` for consistent styling
|
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user