Author SHA1 Message Date
shay 1d0fd3013e feat(streaks): persist streaks on refresh and pass to renderer
Phase 1 worker now reads the stored streak, computes an updated one via
processor.compute_streaks, persists it to the DB (preserving the all-time
max across settings changes), and includes it in widget_data. Phase 2
_render_widgets pre-reads the stored streak and passes it to the processor.
2026-04-20 11:52:22 -04:00
shay 788470cae0 feat(streaks): enable streaks widget by default 2026-04-20 11:49:43 -04:00
shayandClaude Opus 4.7 f23449a17e feat(streaks): render streaks widget in generate_widgets_from_github
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-20 11:48:09 -04:00
shay cb7a00d7c4 feat(streaks): add streaks widget renderer
Add render_streaks_widget() to generator/src/widgets/streaks.py with
flame/trophy icons, two-column layout, optional date display, and
export it from the widgets package; append 3 smoke tests (all 11 pass).
2026-04-20 11:45:51 -04:00
shayandClaude Sonnet 4.6 3b00a0aeac feat(streaks): compute current and max streak with grace day
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-20 11:42:59 -04:00
shayandClaude Sonnet 4.6 7fb1ba3e01 feat(streaks): add user_streaks table and get/put helpers
Adds the user_streaks table to settings.db schema and implements
get_user_streak / put_user_streak helpers with upsert semantics.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-20 11:40:13 -04:00
shay dd4a3d50d8 feat(streaks): add StreakData model 2026-04-20 11:36:45 -04:00
shay 5a2bc11840 feat(ui): enhance AuthButton styling and position for better UX. 2026-04-19 21:51:30 -04:00
shay fa96adb5d1 feat(docs): update instance URL and enhance README formatting. 2026-04-19 21:51:23 -04:00
Shay ManorandGitHub 728f3f038d Merge pull request #2 from ShayManor/oauth
Oauth
2026-04-19 21:02:25 -04:00
shayandClaude Opus 4.7 f9caa61c77 fix(frontend): send cookies on /generate POST
Without credentials: 'include', the session cookie isn't attached and
the OAuth-guarded endpoint returns 401.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-19 20:10:14 -04:00
shayandClaude Opus 4.7 9e837519cc feat(deploy): wire OAuth secrets; rename env vars off GITHUB_ prefix
GitHub Actions rejects secret names starting with GITHUB_. Rename the
OAuth env vars to GH_OAUTH_* in config.py, compose.yml, and the deploy
workflow so the values can flow through Actions secrets into the
generator container.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-19 20:02:52 -04:00
shayandClaude Opus 4.7 be8823c4cf chore(frontend): delete lib/editToken.ts (replaced by OAuth)
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-19 19:18:32 -04:00
shay ccdd8231ce feat(frontend): gate WorkshopScreen edit UI on OAuth login match 2026-04-19 19:16:59 -04:00
shay cd927e686f feat(frontend): AuthButton — GitHub sign-in / avatar chip 2026-04-19 19:14:06 -04:00
shayandClaude Sonnet 4.6 8ccc0af1cf feat(frontend): App fetches /me, removes editToken plumbing
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-19 19:12:36 -04:00
shay b2baded94a feat(frontend): add lib/auth.ts with fetchMe, signInUrl, signOut 2026-04-19 19:10:05 -04:00
shay 8b7f999adc feat(api): per-login mutate rate limit layered on per-IP 2026-04-19 19:09:04 -04:00
shay 0cd7bf339d feat(api): remove public /enroll endpoint and auto-enroll on /data 2026-04-19 19:06:38 -04:00
shay 91f6328efd feat(api): /generate and /refresh use OAuth session; remove edit_token helpers 2026-04-19 19:03:16 -04:00
shay 4ee71e0b86 feat(api): PATCH /settings uses OAuth session + same-origin 2026-04-19 18:59:46 -04:00
shayandClaude Opus 4.7 eb4b68bf0d feat(api): OAuth callback — verify state, fetch profile, implicit enroll
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-19 18:57:20 -04:00
shayandClaude Opus 4.7 98c40ff993 feat(api): add /api/auth/github/login with CSRF state + local-only next
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-19 18:54:44 -04:00
shay a6356d4d1d feat(api): add /api/auth/me and /api/auth/logout 2026-04-19 18:53:12 -04:00
shay 232812b3a0 feat(api): configure Flask session + init OAuth client 2026-04-19 18:51:22 -04:00
shay 4602bb9494 test(auth): unit tests for require_github_owner and require_same_origin 2026-04-19 18:49:39 -04:00
shay ccd0f63fa8 feat(auth): add OAuth client + require_github_owner/require_same_origin decorators 2026-04-19 18:48:14 -04:00
shay ec9d4c3672 db: remove dead _hash_edit_token; convert verify_edit_token to stub
_hash_edit_token was only called by verify_edit_token and has no remaining
callers in db.py (enroll no longer hashes tokens). Remove it along with the
unused 'secrets' and 'hmac' imports.

Keep verify_edit_token as a NotImplementedError stub since api.py's
require_edit_token decorator still references it. Task 12 will remove both
the decorator and this function together when switching to session-based auth.
2026-04-19 18:47:11 -04:00
shay 22483aea19 db: enroll() accepts github profile; no longer returns edit_token 2026-04-19 18:45:26 -04:00
shay 57b782ceaf db: add github_id and github_avatar_url columns + set_github_profile 2026-04-19 18:44:01 -04:00
shay 4822272b49 config: add GitHub OAuth + session env vars 2026-04-19 18:40:28 -04:00
shayandClaude Opus 4.7 1501139143 deps: add authlib for GitHub OAuth
Pins authlib>=1.3,<2 so the generator can register a GitHub OAuth
client for the upcoming login flow.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-19 18:39:45 -04:00
shay 58e794fd57 feat(tags): add auto-awarded profile tags and validation utilities. 2026-04-19 09:37:32 -04:00
shay ca74e91e3e feat(readme): update README to describe new SVG widget features. 2026-04-19 09:34:40 -04:00
shay 016583c9f3 feat(api): implement per-user edit token for settings mutations 2026-04-19 09:34:26 -04:00
shay 3ecb6ad67b feat(tags): implement custom tag color merging and label support 2026-04-18 14:52:32 -04:00
shay 3e70e4b4ef feat(languages): add hidden languages picker and enrich language data 2026-04-18 13:39:44 -04:00
shay 5198eab86a feat(icons): replace inline SVGs with consistent JSX properties for icons 2026-04-18 13:17:00 -04:00
shay 12fb6c331b feat(worker): add achievements parameter to widget settings processing 2026-04-18 13:05:49 -04:00
shay 89a05f2a59 chore(WorkshopScreen): update ICONS type from JSX.Element to ReactNode 2026-04-18 12:51:48 -04:00
shay 3aebd40279 chore(favicon): replace old SVG with new design for favicon icon
chore(ResultScreen): simplify embed section layout and improve copy button
chore(WorkshopScreen): replace emoji icons with inline SVGs for consistency
chore(index.html): update page
2026-04-18 12:50:23 -04:00
shay eadd074402 chore(App): add PATCH request to sync user settings with backend before render 2026-04-18 12:40:16 -04:00
shay dd45d49c22 chore(ResultScreen): add copy functionality for embed snippet button 2026-04-18 12:35:27 -04:00
shay 8ac657b874 chore(ResultScreen): update props to reflect SVG generation process changes 2026-04-18 12:17:25 -04:00
shay 7b2301cec0 chore(api): rename test function for clarity on enrollment behavior 2026-04-18 11:58:02 -04:00
shay f9c59d934d chore(api): add asynchronous build kickoff for improved responsiveness 2026-04-18 11:26:25 -04:00
shay 3ffb2cfb6f chore(frontend): add demo data 2026-04-18 11:15:16 -04:00
shay 79b9c31197 feat(api): implement precomputed widget data storage and retrieval. 2026-04-18 11:13:43 -04:00
shay f0c6edacf6 feat(api): add endpoint for fetching computed widget data by username. 2026-04-18 10:54:41 -04:00
shay a63c1891a0 feat(deploy): change deployment runner from minipc to self-hosted. 2026-04-18 01:06:59 -04:00
shay 873ca512bd feat(readme): update Docker badge to reflect new deployment workflow. 2026-04-18 00:52:46 -04:00
shay 19a357d92b feat(readme): remove references to deleted production pipeline design. 2026-04-18 00:02:34 -04:00
Shay ManorandGitHub a96b0d0b3f Merge pull request #1 from ShayManor/smanor/production-pipeline
Split monolith into fetcher/generator/edge services + React SPA + CI
2026-04-17 18:38:38 -04:00
51 changed files with 3638 additions and 4085 deletions
+87
View File
@@ -0,0 +1,87 @@
name: build and deploy
on:
push:
branches: [main]
pull_request:
branches: [main]
env:
REGISTRY: ghcr.io
jobs:
build:
name: build ${{ matrix.service }}
runs-on: ubuntu-latest
permissions:
contents: read
packages: write
strategy:
fail-fast: false
matrix:
service: [fetcher, generator, edge]
outputs:
image_tag: ${{ steps.tag.outputs.value }}
steps:
- uses: actions/checkout@v4
- uses: docker/setup-buildx-action@v3
- name: Log in to GHCR
if: github.event_name == 'push'
uses: docker/login-action@v3
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Compute image tag (sha-<short>)
id: tag
env:
SHA: ${{ github.sha }}
run: echo "value=sha-${SHA:0:7}" >> "$GITHUB_OUTPUT"
- name: Compute image name (lowercase)
id: img
env:
OWNER: ${{ github.repository_owner }}
SERVICE: ${{ matrix.service }}
run: echo "name=${REGISTRY}/${OWNER,,}/ghstats-${SERVICE}" >> "$GITHUB_OUTPUT"
- name: Extract metadata
id: meta
uses: docker/metadata-action@v5
with:
images: ${{ steps.img.outputs.name }}
tags: |
type=raw,value=${{ steps.tag.outputs.value }}
type=raw,value=latest,enable={{is_default_branch}}
- name: Build ${{ matrix.service }} image
uses: docker/build-push-action@v6
with:
context: ./${{ matrix.service }}
push: ${{ github.event_name == 'push' }}
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
cache-from: type=gha,scope=${{ matrix.service }}
cache-to: type=gha,mode=max,scope=${{ matrix.service }}
deploy:
name: deploy to mini PC
needs: build
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
runs-on: self-hosted
steps:
- uses: actions/checkout@v4
- name: Deploy compose stack
env:
IMAGE_TAG: ${{ needs.build.outputs.image_tag }}
GITHUB_PAT: ${{ secrets.FETCHER_GITHUB_PAT }}
FETCHER_INTERNAL_TOKEN: ${{ secrets.FETCHER_INTERNAL_TOKEN }}
GH_OAUTH_CLIENT_ID: ${{ secrets.GH_OAUTH_CLIENT_ID }}
GH_OAUTH_CLIENT_SECRET: ${{ secrets.GH_OAUTH_CLIENT_SECRET }}
GENERATOR_SECRET_KEY: ${{ secrets.GENERATOR_SECRET_KEY }}
ALLOWED_ORIGINS: ${{ secrets.ALLOWED_ORIGINS }}
run: ./deploy/deploy.sh
-29
View File
@@ -1,29 +0,0 @@
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 }}
+7
View File
@@ -234,3 +234,10 @@ generator/frontend/node_modules/
.superpowers/
.playwright-mcp/
screenshots/
# Kept locally, not tracked
/CLAUDE.md
/docs/
**/*.md
!README.md
!**/README.md
-63
View File
@@ -1,63 +0,0 @@
# 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`.
+193 -17
View File
@@ -1,43 +1,219 @@
# github-readme-stats
[![tests](https://github.com/ShayManor/github-readme-stats/actions/workflows/tests.yml/badge.svg)](https://github.com/ShayManor/github-readme-stats/actions/workflows/tests.yml)
[![docker](https://github.com/ShayManor/github-readme-stats/actions/workflows/docker.yml/badge.svg)](https://github.com/ShayManor/github-readme-stats/actions/workflows/docker.yml)
[![build and deploy](https://github.com/ShayManor/github-readme-stats/actions/workflows/deploy.yml/badge.svg)](https://github.com/ShayManor/github-readme-stats/actions/workflows/deploy.yml)
A monorepo of three independent Python services plus a React frontend,
each self-contained. See each service's README for details.
A single SVG widget you drop into your GitHub profile README. It scores
your account, charts your contribution timeline, highlights your top
collaborators, breaks down your languages, and earns you tags like
`Backend`, `ML`, or `Founder #42`.
## Services
![hero widget](https://gh-stats.com/ShayManor)
| Folder | Port | Responsibility |
---
## Get your widget in 30 seconds
1. Open `https://gh-stats.com/` in a browser.
2. Type your GitHub username and hit **Continue**.
3. Pick a theme, reorder widgets, add custom tags / achievements.
4. Click **Generate** — the SVG is built on the server and cached.
5. Copy the one-liner and paste it into your profile README:
```markdown
![my stats](https://gh-stats.com/YOUR_USERNAME)
```
That's it. Every push of GitHub activity is picked up by a 15-minute
refresh cron, so the image stays current without you doing anything.
---
## What's in the widget
| Widget | What it shows |
|---|---|
| **Grade** | Overall score (0–100) + letter grade + top tags |
| **Impact Timeline** | Smooth contribution curve over the last 6 months |
| **Top Collaborators** | Avatars + shared-repo + commit bars |
| **Recent Focus** | What you've actually been working on lately |
| **Languages** | Your language mix, weighted by active code |
| **Achievements** | Hand-entered credentials — hackathons, talks, awards |
Widgets are composed into a single card, or you can embed any one of
them on its own — see [Individual widgets](#individual-widgets).
---
## Themes
Pass `?theme=<name>` or pick in the Workshop. Five built-ins:
| Theme | Tone |
|---|---|
| `midnight` *(default)* | dark, soft blue accents |
| `onyx` | deep black, neon violet |
| `nord` | muted pastel on slate |
| `clean` | white, understated |
| `paper` | warm off-white |
```markdown
![my stats](https://gh-stats.com/YOUR_USERNAME?theme=onyx)
```
---
## Individual widgets
Don't want the full composite? Embed exactly one:
```markdown
![grade](https://gh-stats.com/YOUR_USERNAME/grade.svg)
![impact](https://gh-stats.com/YOUR_USERNAME/impact.svg)
![collaborators](https://gh-stats.com/YOUR_USERNAME/collaborators.svg)
![focus](https://gh-stats.com/YOUR_USERNAME/focus.svg)
![languages](https://gh-stats.com/YOUR_USERNAME/languages.svg)
![achievements](https://gh-stats.com/YOUR_USERNAME/achievements.svg)
```
Put two side-by-side with an HTML table:
```html
<table><tr>
<td><img src="https://gh-stats.com/YOUR_USERNAME/grade.svg"/></td>
<td><img src="https://gh-stats.com/YOUR_USERNAME/languages.svg"/></td>
</tr></table>
```
---
## Customization
Everything is editable from the Workshop UI — the settings are saved
against your username, so re-embedding picks them up automatically.
- **Custom tags** — add role labels like `ML`, `Systems`, `Cloud`. The
grade widget will fit them into its tag cloud.
- **Hidden languages** — exclude languages you don't want counted
(e.g. `HTML`, `CSS`, `Makefile`).
- **Widget colors** — per-widget accent overrides for the impact line
and collaborator bars (hex, `#RRGGBB`).
- **Widget limits** — cap the number of tags, collaborators, or
languages shown.
- **Achievements** — up to 10 hand-entered lines with icon
(`trophy`, `medal`, `star`, `hackathon`), title, subtitle, and date.
**Auto-awarded tags** fire from real activity — no way to fake them:
- `Founder #N` — one of the first N enrolled users, with your number
- (plus anything your languages / topics map to: `Backend`, `Frontend`,
`ML`, `Mobile`, `DevOps`, `Cloud`, …)
---
## Refreshing
Your data refreshes automatically every 15 minutes. If you just merged
something big and want it to show up immediately, click **Refresh now**
in the Workshop (one-shot per account; requires the edit token that was
issued to your browser on first visit).
---
## Status states
The SVG endpoint advertises its state via the `X-Widget-Status` header:
| Status | Meaning | Your README shows |
|---|---|---|
| [`fetcher/`](./fetcher/README.md) | 5001 | Owns GitHub PAT + `fetcher.db`; cron-refreshes data |
| [`generator/`](./generator/README.md) | 5002 | Settings + widgets DBs, build worker, serves React SPA + `/api/*` |
| [`edge/`](./edge/README.md) | 5003 | Cache-first SVG proxy; deploy globally |
| `ready` | Built and cached | the real widget |
| `building` | Enrolled, first render in progress | a placeholder card |
| `rate_limited` | Daily enrollment cap hit | a placeholder card |
| `not_found` | GitHub username doesn't exist | a 404-style card |
## Design Docs
GitHub caches the image aggressively; if a just-enrolled widget shows
the placeholder for a minute or two, that's expected.
- 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)
---
## Quick start (local dev, no Docker)
## Self-hosting
# 1) fetcher
If you want your own instance, it runs as three Docker services plus a
Vite-built React SPA served by the generator. You'll need a GitHub
Personal Access Token (classic, `read:user` + `repo:public_repo` is
enough).
```bash
# 1) fetcher — owns the PAT, talks to GitHub
(cd fetcher && pip install -r requirements.txt &&
FETCHER_INTERNAL_TOKEN=dev GITHUB_PAT=<your-pat> python -m src.api) &
# 2) generator API, worker, cron (three processes)
# 2) generator — API + worker + refresh cron
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 &
# 3) edge
# 3) edge — cache-first SVG proxy (this is what you put behind your domain)
(cd ../edge && pip install -r requirements.txt &&
GENERATOR_URL=http://localhost:5002 python -m src.api) &
# 4) frontend (dev server)
# 4) frontend (dev only — production builds are baked into the generator image)
cd ../generator/frontend && npm install && npm run dev
```
Test everything:
Per-service READMEs cover Docker, tests, and env vars:
- [`fetcher/`](./fetcher/README.md) — port 5001
- [`generator/`](./generator/README.md) — port 5002
- [`edge/`](./edge/README.md) — port 5003
The generator image serves both the API and the pre-built frontend, so
after deploying edge + generator + fetcher you can point a domain at
the edge and you're done.
### Capacity knobs
Sensible defaults; all overridable via env:
| Env | Default | What it bounds |
|---|---|---|
| `GENERATE_CONCURRENCY` | `2` | Simultaneous SVG renders |
| `PREFETCH_MAX_WORKERS` | `2` | Background prefetch threads |
| `PENDING_JOB_QUEUE_CAP` | `200` | Build queue depth before new enrolls 429 |
| `ENROLLMENT_DAILY_CAP` | `50` | New users per day |
| `RATE_LIMIT_READ_MAX` | `3000` per 60s | Per-IP README embeds |
| `RATE_LIMIT_MUTATE_MAX` | `120` per 60s | Per-IP settings edits / generates |
| `RATE_LIMIT_ENROLL_MAX` | `60` per 300s | Per-IP new enrollments |
| `EDGE_RATE_LIMIT_MAX` | `3000` per 60s | Per-IP at the edge |
---
## Running tests
```bash
(cd fetcher && pytest) && (cd generator && pytest) && (cd edge && pytest)
```
---
## FAQ
**Can I use a private GitHub account?**
No — the fetcher only sees public activity. Private repos and private
contribution counts aren't included.
**How fresh is the data?**
The refresh cron ticks every 15 minutes. You can also click **Refresh
now** in the Workshop once per account.
**Someone else already enrolled my username — can I edit it?**
The first browser to visit your username gets the edit token. If that
was you but you've lost the token (cleared localStorage, switched
browsers), there's no recovery path today — an OAuth-based reclaim
flow is on the roadmap.
**Can I change the widget without re-embedding?**
Yes. The image URL is stable. Edit settings in the Workshop, click
Generate, and the next time the image is fetched it's the new version
(GitHub's image cache may delay that by a few minutes).
+82
View File
@@ -0,0 +1,82 @@
name: ghstats
services:
fetcher:
image: ghcr.io/shaymanor/ghstats-fetcher:${IMAGE_TAG:-latest}
container_name: ghstats-fetcher
restart: unless-stopped
environment:
GITHUB_PAT: ${GITHUB_PAT:?missing GITHUB_PAT}
FETCHER_INTERNAL_TOKEN: ${FETCHER_INTERNAL_TOKEN:?missing FETCHER_INTERNAL_TOKEN}
volumes:
- ${HOME}/ghstats/data/fetcher:/app/data
ports:
- "127.0.0.1:5001:5001"
fetcher-cron:
image: ghcr.io/shaymanor/ghstats-fetcher:${IMAGE_TAG:-latest}
container_name: ghstats-fetcher-cron
restart: unless-stopped
command: ["python", "-m", "src.cron"]
environment:
GITHUB_PAT: ${GITHUB_PAT:?missing GITHUB_PAT}
FETCHER_INTERNAL_TOKEN: ${FETCHER_INTERNAL_TOKEN:?missing FETCHER_INTERNAL_TOKEN}
volumes:
- ${HOME}/ghstats/data/fetcher:/app/data
depends_on:
- fetcher
generator:
image: ghcr.io/shaymanor/ghstats-generator:${IMAGE_TAG:-latest}
container_name: ghstats-generator
restart: unless-stopped
environment:
FETCHER_URL: http://fetcher:5001
FETCHER_INTERNAL_TOKEN: ${FETCHER_INTERNAL_TOKEN:?missing FETCHER_INTERNAL_TOKEN}
GH_OAUTH_CLIENT_ID: ${GH_OAUTH_CLIENT_ID:?missing GH_OAUTH_CLIENT_ID}
GH_OAUTH_CLIENT_SECRET: ${GH_OAUTH_CLIENT_SECRET:?missing GH_OAUTH_CLIENT_SECRET}
GENERATOR_SECRET_KEY: ${GENERATOR_SECRET_KEY:?missing GENERATOR_SECRET_KEY}
ALLOWED_ORIGINS: ${ALLOWED_ORIGINS:-https://gh-stats.com}
volumes:
- ${HOME}/ghstats/data/generator:/app/data
ports:
- "5002:5002"
depends_on:
- fetcher
generator-worker:
image: ghcr.io/shaymanor/ghstats-generator:${IMAGE_TAG:-latest}
container_name: ghstats-generator-worker
restart: unless-stopped
command: ["python", "-m", "src.worker"]
environment:
FETCHER_URL: http://fetcher:5001
FETCHER_INTERNAL_TOKEN: ${FETCHER_INTERNAL_TOKEN:?missing FETCHER_INTERNAL_TOKEN}
volumes:
- ${HOME}/ghstats/data/generator:/app/data
depends_on:
- generator
generator-cron:
image: ghcr.io/shaymanor/ghstats-generator:${IMAGE_TAG:-latest}
container_name: ghstats-generator-cron
restart: unless-stopped
command: ["python", "-m", "src.cron"]
environment:
FETCHER_URL: http://fetcher:5001
FETCHER_INTERNAL_TOKEN: ${FETCHER_INTERNAL_TOKEN:?missing FETCHER_INTERNAL_TOKEN}
volumes:
- ${HOME}/ghstats/data/generator:/app/data
depends_on:
- generator
edge:
image: ghcr.io/shaymanor/ghstats-edge:${IMAGE_TAG:-latest}
container_name: ghstats-edge
restart: unless-stopped
environment:
GENERATOR_URL: http://generator:5002
ports:
- "5003:5003"
depends_on:
- generator
+13
View File
@@ -0,0 +1,13 @@
#!/usr/bin/env bash
# Pulls the current image tag and brings up the compose stack.
# Expects GITHUB_PAT, FETCHER_INTERNAL_TOKEN, and IMAGE_TAG to be present in
# the environment (exported by the GitHub Actions deploy job).
set -euo pipefail
cd "$(dirname "$0")"
mkdir -p "$HOME/ghstats/data/fetcher" "$HOME/ghstats/data/generator"
docker compose pull
docker compose up -d --remove-orphans
docker compose ps
File diff suppressed because it is too large Load Diff
@@ -1,531 +0,0 @@
# 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.
+2 -1
View File
@@ -6,4 +6,5 @@ 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"]
# Bind to $PORT when set (e.g. Cloud Run injects PORT=8080); default to 5003.
CMD ["sh", "-c", "exec gunicorn -b 0.0.0.0:${PORT:-5003} -w 2 src.api:app"]
+63 -4
View File
@@ -1,7 +1,11 @@
"""Edge service — cache-first SVG proxy in front of the generator."""
import logging
import re
import time
from collections import defaultdict, deque
from threading import Lock
import requests
from flask import Flask, Response, jsonify
from flask import Flask, Response, jsonify, request
from flask_compress import Compress
from . import cache as cache_mod, config
@@ -11,14 +15,59 @@ Compress(app)
cache_ext = cache_mod.build_cache(app)
log = logging.getLogger("edge")
# GitHub usernames: 1-39 chars, alnum, single hyphens. Keep the regex in
# sync with generator/src/utils/validate.py so invalid paths get rejected
# before they waste an upstream round-trip.
_USERNAME_RE = re.compile(r"^[A-Za-z0-9](?:[A-Za-z0-9]|-(?=[A-Za-z0-9])){0,38}$")
_ALLOWED_WIDGETS = {"grade", "impact", "collaborators", "focus", "languages", "achievements", "composite"}
def _valid_username(u: str) -> bool:
return bool(u) and bool(_USERNAME_RE.match(u))
# ---- Per-IP rate limiter ---------------------------------------------------
# The edge is the mini PC's front door. Cache hits are cheap, but a hostile
# cache-miss storm (unique usernames, unique widget names) would funnel into
# the generator's render path. Bound it here so the generator's own limiter
# isn't the only layer. Operators who run behind a CDN / nginx should prefer
# the upstream limiter and raise these env vars.
_rate_lock = Lock()
_rate_hits: dict[str, deque] = defaultdict(deque)
def _client_ip() -> str:
fwd = request.headers.get("X-Forwarded-For", "")
if fwd:
return fwd.split(",")[-1].strip()
return request.remote_addr or "unknown"
def _allow(ip: str) -> bool:
now = time.time()
cutoff = now - config.RATE_LIMIT_WINDOW
with _rate_lock:
q = _rate_hits[ip]
while q and q[0] < cutoff:
q.popleft()
if len(q) >= config.RATE_LIMIT_MAX:
return False
q.append(now)
return True
def _cache_key(path: str) -> str:
return f"edge:{path}"
def _fetch_origin(path: str) -> requests.Response:
def _fetch_origin(path: str, client_ip: str) -> requests.Response:
url = f"{config.GENERATOR_URL}/api/{path}"
return requests.get(url, timeout=config.UPSTREAM_TIMEOUT)
# Forward the caller's IP so the generator's rate limiter can
# discriminate per user rather than treating the edge's single IP as
# one client — otherwise the first 300 requests/min exhaust the bucket
# for everyone behind the edge.
headers = {"X-Forwarded-For": client_ip}
return requests.get(url, headers=headers, timeout=config.UPSTREAM_TIMEOUT)
@app.route("/health", methods=["GET"])
@@ -34,15 +83,25 @@ def health():
@app.route("/<username>", methods=["GET"])
def serve(username: str):
if not _valid_username(username):
return jsonify({"error": "invalid_username"}), 400
return _serve(username, path=username)
@app.route("/<username>/<widget>.svg", methods=["GET"])
def serve_widget(username: str, widget: str):
if not _valid_username(username):
return jsonify({"error": "invalid_username"}), 400
if widget not in _ALLOWED_WIDGETS:
return jsonify({"error": "unknown_widget"}), 400
return _serve(f"{username}/{widget}", path=f"{username}/{widget}.svg")
def _serve(key_suffix: str, path: str) -> Response:
ip = _client_ip()
if not _allow(ip):
return jsonify({"error": "rate_limited"}), 429
ck = _cache_key(key_suffix)
cached = cache_ext.get(ck)
if cached is not None:
@@ -54,7 +113,7 @@ def _serve(key_suffix: str, path: str) -> Response:
})
try:
r = _fetch_origin(path)
r = _fetch_origin(path, ip)
except Exception as e:
log.warning("origin unreachable for %s: %s", path, e)
return jsonify({"error": "origin unreachable"}), 503
+7
View File
@@ -7,3 +7,10 @@ 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"))
# Per-IP rate limit at the edge. Anti-abuse only — cache hits are cheap
# and cache misses are already bounded by the generator's global
# semaphore, so normal traffic should never notice this. Generous by
# default; tighten via env if a specific IP misbehaves.
RATE_LIMIT_MAX = int(os.getenv("EDGE_RATE_LIMIT_MAX", "3000"))
RATE_LIMIT_WINDOW = int(os.getenv("EDGE_RATE_LIMIT_WINDOW", "60"))
+41 -5
View File
@@ -1,5 +1,7 @@
"""Flask app for the fetcher service. All endpoints require X-Internal-Token."""
import hmac
import logging
import re
import requests
from flask import Flask, jsonify, request, Response
from functools import wraps
@@ -7,6 +9,17 @@ from functools import wraps
from . import config, db, github
app = Flask(__name__)
log = logging.getLogger("fetcher.api")
# Must stay in sync with github.py's _USERNAME_RE. Trust boundary: the
# fetcher is called only by the generator over the internal network, but
# a compromised/bugged generator must not be able to turn us into an
# arbitrary GitHub URL fetcher.
_USERNAME_RE = re.compile(r"^[A-Za-z0-9](?:[A-Za-z0-9]|-(?=[A-Za-z0-9])){0,38}$")
def _valid_username(u) -> bool:
return isinstance(u, str) and bool(_USERNAME_RE.match(u))
def require_internal_token(fn):
@@ -27,10 +40,16 @@ def health():
@app.route("/data/<username>", methods=["GET"])
@require_internal_token
def get_data(username: str):
if not _valid_username(username):
return jsonify({"error": "invalid_username"}), 400
row = db.get_user(username)
if row is None:
# Auto-fetch path
try:
data = github.fetch_github_data(username, token=config.GITHUB_PAT)
except Exception:
log.exception("github fetch failed for %s", username)
return jsonify({"error": "fetch_failed"}), 502
if _is_github_not_found(data):
data = {"error": "not_found"}
h = db.upsert_user(username, data)
@@ -48,12 +67,15 @@ def get_data(username: str):
def force_fetch():
body = request.get_json(silent=True) or {}
username = body.get("username")
if not username:
return jsonify({"error": "username required"}), 400
if not _valid_username(username):
return jsonify({"error": "invalid_username"}), 400
try:
data = github.fetch_github_data(username, token=config.GITHUB_PAT)
except Exception as e:
return jsonify({"error": f"fetch failed: {e}"}), 502
except Exception:
# Previously returned f"fetch failed: {e}" which leaks internal
# exception text (URLs, stack fragments) across the trust boundary.
log.exception("github fetch failed for %s", username)
return jsonify({"error": "fetch_failed"}), 502
if _is_github_not_found(data):
data = {"error": "not_found"}
old = db.get_user(username)
@@ -65,7 +87,21 @@ def force_fetch():
@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)
# SSRF surface: we build https://github.com/<u>.png from path input. The
# <username> Flask converter already refuses slashes, but allowlist the
# shape anyway so any future change to the proxy path can't turn into a
# URL-smuggling primitive.
if not _valid_username(username):
return jsonify({"error": "invalid_username"}), 400
try:
r = requests.get(
f"https://github.com/{username}.png",
timeout=config.API_TIMEOUT,
allow_redirects=True,
)
except Exception:
log.exception("avatar fetch failed for %s", username)
return jsonify({"error": "avatar_unavailable"}), 502
if r.status_code != 200:
return jsonify({"error": "avatar unavailable"}), 404
return Response(r.content, mimetype=r.headers.get("Content-Type", "image/png"))
+138 -43
View File
@@ -1,12 +1,41 @@
"""GitHub data fetching functions."""
import re
import requests
import base64
from concurrent.futures import ThreadPoolExecutor, as_completed
from typing import Optional, Protocol
from . import config
# GitHub's own username rules: alphanumerics and hyphens, 1–39 chars, no
# leading/trailing hyphen, no double-hyphens. The fetcher hard-refuses
# anything else before it reaches URL construction or GraphQL interpolation —
# the generator validates too, but this is the last line of defense before
# we talk to GitHub on a caller's behalf.
_USERNAME_RE = re.compile(r"^[A-Za-z0-9](?:[A-Za-z0-9]|-(?=[A-Za-z0-9])){0,38}$")
# Repo full names: owner/repo. Owner matches the username rule; repo allows the
# same chars plus dot and underscore (matches GitHub's repo-name regex).
_REPO_FULL_NAME_RE = re.compile(
r"^[A-Za-z0-9](?:[A-Za-z0-9]|-(?=[A-Za-z0-9])){0,38}"
r"/[A-Za-z0-9_.-]{1,100}$"
)
def _assert_username(name: str) -> str:
if not isinstance(name, str) or not _USERNAME_RE.match(name):
raise ValueError(f"invalid github username: {name!r}")
return name
def _assert_repo_full_name(name: str) -> str:
if not isinstance(name, str) or not _REPO_FULL_NAME_RE.match(name):
raise ValueError(f"invalid github repo name: {name!r}")
return name
class GitHubDataSource(Protocol):
"""Protocol for GitHub data sources - allows swapping implementations."""
@@ -46,6 +75,10 @@ class GitHubDataSource(Protocol):
"""Fetch and encode avatar as base64."""
...
def fetch_repo_languages(self, full_name: str) -> dict:
"""Return {language: bytes} for a single repo, or {} on failure."""
...
class DirectAPISource:
"""Direct GitHub API implementation - for immediate requests."""
@@ -96,18 +129,22 @@ class DirectAPISource:
def fetch_user_data(self, username: str) -> dict:
"""Fetch user profile data."""
_assert_username(username)
return requests.get(
f"{self.base}/users/{username}",
headers=self.headers
headers=self.headers,
timeout=config.API_TIMEOUT,
).json()
def fetch_repos(self, username: str) -> list:
"""Fetch user repositories (owned + contributed to)."""
_assert_username(username)
# Fetch owned repos
owned = requests.get(
f"{self.base}/users/{username}/repos",
headers=self.headers,
params={"per_page": 100, "sort": "pushed", "type": "owner"},
timeout=config.API_TIMEOUT,
).json()
# Fetch all repos (includes collabs, orgs)
@@ -115,6 +152,7 @@ class DirectAPISource:
f"{self.base}/users/{username}/repos",
headers=self.headers,
params={"per_page": 100, "sort": "pushed", "type": "all"},
timeout=config.API_TIMEOUT,
).json()
# Combine and deduplicate
@@ -131,10 +169,12 @@ class DirectAPISource:
def fetch_events(self, username: str) -> list:
"""Fetch user events."""
_assert_username(username)
resp = requests.get(
f"{self.base}/users/{username}/events",
headers=self.headers,
params={"per_page": 100},
timeout=config.API_TIMEOUT,
).json()
return resp if isinstance(resp, list) else []
@@ -155,28 +195,33 @@ class DirectAPISource:
from datetime import datetime
try:
_assert_username(username)
# Get the last year of contribution data
now = datetime.now()
one_year_ago = now.replace(year=now.year - 1)
from_date = one_year_ago.strftime("%Y-%m-%dT%H:%M:%SZ")
to_date = now.strftime("%Y-%m-%dT%H:%M:%SZ")
query = f'''
query {{
user(login: "{username}") {{
contributionsCollection(from: "{from_date}", to: "{to_date}") {{
contributionCalendar {{
weeks {{
contributionDays {{
# Parameterize username + date range — interpolating username into
# the query lets a malicious name break out of the string literal
# and smuggle additional GraphQL fields. GitHub's PAT scopes bound
# the damage, but the injection is still worth shutting down.
query = """
query($login: String!, $from: DateTime!, $to: DateTime!) {
user(login: $login) {
contributionsCollection(from: $from, to: $to) {
contributionCalendar {
weeks {
contributionDays {
date
contributionCount
}}
}}
}}
}}
}}
}}
'''
}
}
}
}
}
}
"""
headers = {
**self.headers,
@@ -188,7 +233,10 @@ class DirectAPISource:
resp = requests.post(
'https://api.github.com/graphql',
json={'query': query},
json={
'query': query,
'variables': {'login': username, 'from': from_date, 'to': to_date},
},
headers=headers,
timeout=config.API_TIMEOUT
)
@@ -253,6 +301,7 @@ class DirectAPISource:
"""Fetch all-time contribution count using GraphQL."""
from datetime import datetime
_assert_username(username)
# First, get account creation date
query = '''
query($username: String!) {
@@ -292,24 +341,28 @@ class DirectAPISource:
# Fetch year by year
total_contributions = 0
print(f" Fetching contributions from {created_year} to {current_year}...")
year_query = """
query($login: String!, $from: DateTime!, $to: DateTime!) {
user(login: $login) {
contributionsCollection(from: $from, to: $to) {
contributionCalendar { totalContributions }
}
}
}
"""
for year in range(created_year, current_year + 1):
year_query = f'''
query {{
user(login: "{username}") {{
contributionsCollection(from: "{year}-01-01T00:00:00Z", to: "{year}-12-31T23:59:59Z") {{
contributionCalendar {{
totalContributions
}}
}}
}}
}}
'''
year_resp = requests.post(
'https://api.github.com/graphql',
json={'query': year_query},
json={
'query': year_query,
'variables': {
'login': username,
'from': f"{year}-01-01T00:00:00Z",
'to': f"{year}-12-31T23:59:59Z",
},
},
headers=headers,
timeout=config.API_TIMEOUT
timeout=config.API_TIMEOUT,
)
if year_resp.ok:
@@ -330,21 +383,20 @@ class DirectAPISource:
"""Fetch contribution count for a specific date range using GraphQL."""
from datetime import datetime
_assert_username(username)
# Convert since_date to proper format
from_date = f"{since_date}T00:00:00Z"
to_date = datetime.now().strftime("%Y-%m-%dT%H:%M:%SZ")
query = f'''
query {{
user(login: "{username}") {{
contributionsCollection(from: "{from_date}", to: "{to_date}") {{
contributionCalendar {{
totalContributions
}}
}}
}}
}}
'''
query = """
query($login: String!, $from: DateTime!, $to: DateTime!) {
user(login: $login) {
contributionsCollection(from: $from, to: $to) {
contributionCalendar { totalContributions }
}
}
}
"""
headers = {
**self.headers,
@@ -356,9 +408,12 @@ class DirectAPISource:
resp = requests.post(
'https://api.github.com/graphql',
json={'query': query},
json={
'query': query,
'variables': {'login': username, 'from': from_date, 'to': to_date},
},
headers=headers,
timeout=config.API_TIMEOUT
timeout=config.API_TIMEOUT,
)
if resp.ok:
@@ -502,6 +557,22 @@ class DirectAPISource:
pass
return ""
def fetch_repo_languages(self, full_name: str) -> dict:
"""Return {language: bytes} for a repo. REST returns exactly this
shape — total is summed client-side."""
try:
resp = requests.get(
f"{self.base}/repos/{full_name}/languages",
headers=self.headers,
timeout=config.API_TIMEOUT,
)
if resp.ok:
data = resp.json()
return data if isinstance(data, dict) else {}
except Exception:
pass
return {}
# TODO: Future implementation for queue-based batching
# class QueuedAPISource:
@@ -542,6 +613,12 @@ def fetch_github_data(
events = source.fetch_events(username)
commits = source.fetch_commits(username)
# Attach per-repo language byte breakdown. Without this, the languages
# widget falls back to a primary-language repo-count tally, which
# heavily under-represents repos whose primary language has small files
# (e.g. HTML, Jupyter Notebook).
_enrich_repo_languages(repos, source)
# Fetch contribution counts (commits + PRs + issues + reviews)
print(" Fetching all-time contribution count...")
total_commits = source.fetch_commit_count(username, repos)
@@ -578,6 +655,24 @@ def fetch_github_data(
}
def _enrich_repo_languages(repos: list, source: GitHubDataSource) -> None:
"""Mutates `repos` in-place, attaching `language_bytes: {lang: bytes}` to
each repo. Uses a small thread pool — one REST call per repo is cheap
individually, but sequentially N repos would block the fetch noticeably."""
if not repos:
return
names = [(i, r["full_name"]) for i, r in enumerate(repos) if r.get("full_name")]
print(f" Fetching language byte breakdown for {len(names)} repos...")
with ThreadPoolExecutor(max_workers=10) as pool:
futures = {pool.submit(source.fetch_repo_languages, fn): i for i, fn in names}
for fut in as_completed(futures):
i = futures[fut]
try:
repos[i]["language_bytes"] = fut.result() or {}
except Exception:
repos[i]["language_bytes"] = {}
def _fetch_collaborators_data(
username: str,
repos: list,
+1 -1
View File
@@ -4,7 +4,7 @@
<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>
<title>GitHub Widgets</title>
</head>
<body>
<div id="root"></div>
File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 9.3 KiB

After

Width:  |  Height:  |  Size: 365 B

+141 -27
View File
@@ -1,8 +1,12 @@
import { useState, useRef, useCallback } from 'react'
import { useState, useRef, useCallback, useEffect } from 'react'
import './index.css'
import { SearchScreen } from './screens/SearchScreen'
import { WorkshopScreen } from './screens/WorkshopScreen'
import { ResultScreen } from './screens/ResultScreen'
import { AuthButton } from './components/AuthButton'
import type { WidgetData } from './lib/renderWidgets'
import { DEMO_WIDGET_DATA } from './lib/demoData'
import { fetchMe, type Me } from './lib/auth'
export type Achievement = {
title: string
@@ -42,40 +46,87 @@ const DEFAULT_SETTINGS: WidgetSettings = {
type Step = 'search' | 'workshop' | 'result'
const POLL_INTERVAL_MS = 2000
const POLL_TIMEOUT_MS = 120_000
export default function App() {
const [me, setMe] = useState<Me>({ login: null })
const [step, setStep] = useState<Step>('search')
const [username, setUsername] = useState('')
const [settings, setSettings] = useState<WidgetSettings>({ ...DEFAULT_SETTINGS })
const [widgetData, setWidgetData] = useState<WidgetData | null>(null)
const [fetchDone, setFetchDone] = useState(false)
const [fetchError, setFetchError] = useState<string | null>(null)
const fetchRef = useRef<AbortController | null>(null)
// Final SVG produced by POST /api/<u>/generate. Rendered on the Result
// screen so the user sees the actual backend output, not demo data.
const [generatedSvg, setGeneratedSvg] = useState<string | null>(null)
const [generateError, setGenerateError] = useState<string | null>(null)
const [generating, setGenerating] = useState(false)
const pollTimer = useRef<number | null>(null)
const pollStart = useRef<number>(0)
const aborted = useRef(false)
const stopPolling = useCallback(() => {
if (pollTimer.current != null) {
window.clearTimeout(pollTimer.current)
pollTimer.current = null
}
}, [])
useEffect(() => stopPolling, [stopPolling])
useEffect(() => { fetchMe().then(setMe) }, [])
const startFetch = useCallback((user: string) => {
if (fetchRef.current) fetchRef.current.abort()
const ctrl = new AbortController()
fetchRef.current = ctrl
stopPolling()
aborted.current = false
pollStart.current = Date.now()
setFetchDone(false)
setFetchError(null)
// Show demo data immediately so Workshop is interactive while the worker builds.
setWidgetData(DEMO_WIDGET_DATA)
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)
const poll = async () => {
if (aborted.current) return
try {
const r = await fetch(`/api/${encodeURIComponent(user)}/data`)
if (aborted.current) return
const body = await r.json().catch(
() => ({} as { status?: string; data?: WidgetData })
)
const status = body.status
if (r.status === 200 && status === 'ready' && body.data) {
setWidgetData(body.data)
setFetchDone(true)
return
}
if (r.status === 404 || status === 'not_found') {
setFetchError('User not found')
setFetchDone(true)
return
}
if (r.status === 429 || status === 'rate_limited') {
setFetchError('Enrollment limit reached — try again tomorrow')
setFetchDone(true)
return
}
// 202 building (or any non-terminal) — poll again until timeout.
if (Date.now() - pollStart.current > POLL_TIMEOUT_MS) {
setFetchError('Still building — refresh to keep waiting')
setFetchDone(true)
return
}
pollTimer.current = window.setTimeout(poll, POLL_INTERVAL_MS)
} catch (e) {
if (aborted.current) return
console.warn('Data poll failed:', e)
setFetchError('Network error')
setFetchDone(true)
}
})
}, [])
}
poll()
}, [stopPolling])
const handleSearch = (user: string) => {
setUsername(user)
@@ -83,20 +134,79 @@ export default function App() {
setStep('workshop')
}
const handleGenerate = () => {
const handleGenerate = async () => {
setStep('result')
setGenerating(true)
setGeneratedSvg(null)
setGenerateError(null)
try {
// Push the user's Workshop choices to the backend BEFORE rendering.
// The backend's /generate endpoint re-reads settings from SQLite and
// renders with them, so without this PATCH the SVG would reflect
// whatever was last persisted (usually the enroll-time defaults)
// rather than the user's current selections.
const backendSettings = {
theme: settings.theme,
enabled: settings.widgets,
custom_tags: settings.customTags,
hidden_languages: settings.hiddenLanguages,
widget_settings: settings.widgetSettings,
achievements: settings.achievements.filter(a => a.title.trim()),
}
const patchRes = await fetch(`/api/${encodeURIComponent(username)}/settings`, {
method: 'PATCH',
credentials: 'include',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(backendSettings),
})
if (!patchRes.ok && patchRes.status !== 404) {
setGenerateError(`Settings sync failed (HTTP ${patchRes.status})`)
return
}
const r = await fetch(`/api/${encodeURIComponent(username)}/generate`, {
method: 'POST',
credentials: 'include',
})
if (r.status === 404) {
const body = await r.json().catch(() => ({} as { status?: string }))
setGenerateError(body.status === 'not_found' ? 'User not found' : 'Not enrolled')
return
}
if (!r.ok) {
setGenerateError(`Generate failed (HTTP ${r.status})`)
return
}
// Fetch the backend-rendered composite SVG. Cache-bust so regenerate
// after settings change shows the new version, not a stale browser copy.
const svgRes = await fetch(`/api/${encodeURIComponent(username)}?t=${Date.now()}`)
if (!svgRes.ok) {
setGenerateError(`SVG fetch failed (HTTP ${svgRes.status})`)
return
}
setGeneratedSvg(await svgRes.text())
} catch (e) {
console.warn('generate call failed:', e)
setGenerateError('Network error')
} finally {
setGenerating(false)
}
}
const handleBack = () => {
if (step === 'result') setStep('workshop')
else if (step === 'workshop') {
if (fetchRef.current) fetchRef.current.abort()
aborted.current = true
stopPolling()
setStep('search')
}
}
return (
<div className="min-h-screen bg-gray-50">
<div className="fixed right-4 top-4 z-50">
<AuthButton me={me} onChange={setMe} />
</div>
{step === 'search' && (
<SearchScreen onSearch={handleSearch} />
)}
@@ -108,14 +218,18 @@ export default function App() {
onGenerate={handleGenerate}
onBack={handleBack}
fetchDone={fetchDone}
fetchError={fetchError}
widgetData={widgetData}
me={me}
onAuthChange={setMe}
/>
)}
{step === 'result' && (
<ResultScreen
username={username}
settings={settings}
fetchDone={fetchDone}
fetchError={fetchError}
generating={generating}
generatedSvg={generatedSvg}
generateError={generateError}
onBack={handleBack}
/>
)}
@@ -0,0 +1,36 @@
import type { Me } from '../lib/auth'
import { signInUrl, signOut } from '../lib/auth'
export function AuthButton({ me, onChange }: { me: Me; onChange: (m: Me) => void }) {
if (!me.login) {
return (
<a
href={signInUrl()}
className="inline-flex items-center gap-2 rounded-full bg-gray-900 px-4 py-1.5 text-sm font-medium text-white shadow-sm transition hover:bg-gray-800"
>
<svg viewBox="0 0 16 16" fill="currentColor" aria-hidden="true" className="h-4 w-4">
<path d="M8 0C3.58 0 0 3.58 0 8a8 8 0 0 0 5.47 7.59c.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82a7.42 7.42 0 0 1 4 0c1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.01 8.01 0 0 0 16 8c0-4.42-3.58-8-8-8Z" />
</svg>
Sign in with GitHub
</a>
)
}
return (
<div className="inline-flex items-center gap-2 rounded-full border border-gray-200 bg-white py-1 pr-1 pl-3 text-sm shadow-sm">
{me.avatar_url && (
<img
src={me.avatar_url}
alt=""
className="h-6 w-6 rounded-full object-cover"
/>
)}
<span className="font-medium text-gray-900">{me.login}</span>
<button
onClick={async () => { await signOut(); onChange({ login: null }) }}
className="rounded-full bg-gray-100 px-3 py-1 text-xs font-medium text-gray-700 transition hover:bg-gray-200"
>
Sign out
</button>
</div>
)
}
+20
View File
@@ -0,0 +1,20 @@
export type Me = { login: string | null; avatar_url?: string }
export async function fetchMe(): Promise<Me> {
const r = await fetch('/api/auth/me', { credentials: 'include' })
if (!r.ok) return { login: null }
return r.json() as Promise<Me>
}
export function signInUrl(next?: string): string {
const n = next ?? (window.location.pathname + window.location.search)
return `/api/auth/github/login?next=${encodeURIComponent(n)}`
}
export async function signOut(): Promise<void> {
await fetch('/api/auth/logout', {
method: 'POST',
credentials: 'include',
headers: { 'Content-Type': 'application/json' },
})
}
+39
View File
@@ -0,0 +1,39 @@
import type { WidgetData } from './renderWidgets'
// Used to show a fully-populated Workshop preview instantly while the real
// data is building asynchronously on the server. Swapped out when the
// /data endpoint returns status=ready.
export const DEMO_WIDGET_DATA: WidgetData = {
grade: {
grade: 'A',
score: 78,
stats: { commits: 842, prs: 47, stars: 156, repos: 28, followers: 92 },
tags: [
{ tag: 'backend', source: 'earned', confidence: 0.7 },
{ tag: 'frontend', source: 'earned', confidence: 0.55 },
{ tag: 'devops', source: 'earned', confidence: 0.3 },
],
breakdown: {},
},
impact: Array.from({ length: 24 }, (_, i) => ({
week_start: new Date(Date.now() - (23 - i) * 7 * 86400000).toISOString().slice(0, 10),
commits: Math.max(0, Math.round(14 + Math.sin(i * 0.5) * 9 + (i % 3) * 2)),
})),
collaborators: [
{ username: 'alex', shared_repos: 4, shared_commits: 87 },
{ username: 'jordan', shared_repos: 2, shared_commits: 54 },
{ username: 'sam', shared_repos: 3, shared_commits: 31 },
],
focus: [
{ category: 'Backend', percentage: 45, commit_count: 379 },
{ category: 'Frontend', percentage: 30, commit_count: 252 },
{ category: 'DevOps', percentage: 15, commit_count: 126 },
{ category: 'ML', percentage: 10, commit_count: 84 },
],
languages: [
{ language: 'Python', percentage: 42, loc: 12 },
{ language: 'TypeScript', percentage: 28, loc: 8 },
{ language: 'Go', percentage: 18, loc: 5 },
{ language: 'Rust', percentage: 12, loc: 3 },
],
}
+38 -7
View File
@@ -5,7 +5,7 @@ import { THEMES, TAG_COLORS, GRADE_COLORS, FOCUS_COLORS, LANG_COLORS, type Theme
export type GradeData = {
grade: string; score: number
stats: Record<string, number>
tags: { tag: string; source: string; confidence: number }[]
tags: { tag: string; source: string; confidence: number; label?: string | null }[]
breakdown: Record<string, number>
}
export type ImpactWeek = { week_start: string; commits: number }
@@ -36,6 +36,15 @@ export type PerWidgetSettings = {
const esc = (s: string) => s.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;')
const font = '-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif'
const TAG_ACRONYMS = new Set(['ml','ai','ui','ux','api','cli','sql','css','html','js','ios'])
function formatTagLabel(tag: string): string {
return tag.split('-')
.map(w => TAG_ACRONYMS.has(w.toLowerCase())
? w.toUpperCase()
: w.charAt(0).toUpperCase() + w.slice(1))
.join(' ')
}
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">
@@ -50,7 +59,7 @@ 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"/>`,
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="none" stroke="${color}" stroke-width="1.2" stroke-linejoin="round"/>`,
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"/>`,
}
@@ -82,7 +91,7 @@ function renderGrade(data: GradeData, t: Theme, s?: { max_tags?: number }): stri
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 label = tag.label || formatTagLabel(tag.tag)
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 }
@@ -238,6 +247,18 @@ function renderLanguages(languages: LanguageData[], t: Theme, s?: { max_language
return cardWrapper(inner, 380, rowsH + 36, t, 'Languages')
}
function achievementIconSvg(iconType: string, color: string): string {
// Mirrors generator/src/widgets/achievements.py::_achievement_icon_svg so
// the Workshop client preview matches the backend-rendered composite.
const icons: Record<string, string> = {
trophy: `<svg viewBox="0 0 24 24" width="24" height="24"><path d="M7 2h10v2h2.5c.8 0 1.5.7 1.5 1.5V8c0 1.7-1.3 3-3 3h-.5c-.5 1.5-1.8 2.7-3.5 3v2.5h3c.6 0 1 .4 1 1s-.4 1-1 1H7c-.6 0-1-.4-1-1s.4-1 1-1h3V14c-1.7-.3-3-1.5-3.5-3H6c-1.7 0-3-1.3-3-3V5.5C3 4.7 3.7 4 4.5 4H7V2zm0 4H4.5v2c0 .8.7 1.5 1.5 1.5h1V6zm12.5 0H17v3.5h1c.8 0 1.5-.7 1.5-1.5V6z" fill="${color}" opacity="0.85"/></svg>`,
medal: `<svg viewBox="0 0 24 24" width="24" height="24"><circle cx="12" cy="14" r="5" fill="${color}" opacity="0.2"/><circle cx="12" cy="14" r="4" fill="none" stroke="${color}" stroke-width="1.5"/><path d="M12 11.5l1 2 2.2.3-1.6 1.5.4 2.2-2-1-2 1 .4-2.2-1.6-1.5 2.2-.3z" fill="${color}"/><path d="M9 3l3 8m0-8l3 8m-6-8h6" stroke="${color}" stroke-width="1.5" fill="none" stroke-linecap="round"/></svg>`,
star: `<svg viewBox="0 0 24 24" width="24" height="24"><path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z" fill="none" stroke="${color}" stroke-width="1.5" stroke-linejoin="round"/></svg>`,
hackathon: `<svg viewBox="0 0 24 24" width="24" height="24"><rect x="4" y="5" width="16" height="11" rx="1" fill="none" stroke="${color}" stroke-width="1.5"/><rect x="3" y="16" width="18" height="1.5" rx="0.5" fill="${color}" opacity="0.85"/><path d="M9 9l-2 3 2 3m6-6l2 3-2 3" stroke="${color}" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" fill="none"/></svg>`,
}
return icons[iconType] ?? icons.trophy
}
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)
@@ -249,7 +270,8 @@ function renderAchievements(achievements: AchievementInput[], t: Theme, s?: { ma
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>`
const icon = achievementIconSvg(ach.icon, color)
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"/><g transform="translate(12, 12)">${icon}</g><text x="48" y="20" font-family="${font}" font-size="13" font-weight="600" fill="${t.text}">${esc(ach.title)}</text><text x="48" 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')
@@ -283,6 +305,7 @@ export function renderAllWidgets(opts: {
widgetOrder: string[]
achievements: AchievementInput[]
widgetSettings: PerWidgetSettings
hiddenLanguages?: string[]
username: string
}): string {
const t = THEMES[opts.theme] ?? THEMES.dark
@@ -297,8 +320,16 @@ export function renderAllWidgets(opts: {
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('languages') && opts.data.languages) {
// Apply hidden_languages client-side too so the Workshop preview reflects
// the user's choice instantly — backend filtering only kicks in on the
// next prefetch or on POST /generate.
const hiddenSet = new Set(opts.hiddenLanguages ?? [])
const filtered = opts.data.languages.filter(l => !hiddenSet.has(l.language))
const total = filtered.reduce((a, l) => a + l.percentage, 0) || 1
const rescaled = filtered.map(l => ({ ...l, percentage: Math.round(l.percentage / total * 1000) / 10 }))
widgetSvgs.languages = renderLanguages(rescaled, t, opts.widgetSettings.languages)
}
if (enabled.has('achievements'))
widgetSvgs.achievements = renderAchievements(opts.achievements, t, opts.widgetSettings.achievements)
@@ -328,6 +359,6 @@ export function renderAllWidgets(opts: {
<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>
<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 gh-stats</text>
</svg>`
}
+68 -65
View File
@@ -1,6 +1,5 @@
import { useState, useEffect } from 'react'
import DOMPurify from 'dompurify'
import type { WidgetSettings } from '../App'
import { useMemo, useState } from 'react'
function sanitizeSvg(raw: string): string {
return DOMPurify.sanitize(raw, {
@@ -12,54 +11,31 @@ function sanitizeSvg(raw: string): string {
type Props = {
username: string
settings: WidgetSettings
fetchDone: boolean
fetchError: string | null
generating: boolean
generatedSvg: string | null
generateError: 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)
export function ResultScreen({ username, generating, generatedSvg, generateError, onBack }: Props) {
const safeSvg = useMemo(() => (generatedSvg ? sanitizeSvg(generatedSvg) : ''), [generatedSvg])
const [copied, setCopied] = useState(false)
const embedUrl = `${window.location.origin}/api/${encodeURIComponent(username)}`
const embedSnippet = `![${username}](${embedUrl})`
// 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
const copy = async () => {
try {
await navigator.clipboard.writeText(embedSnippet)
setCopied(true)
setTimeout(() => setCopied(false), 1500)
} catch {
/* ignore */
}
}
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">
<div className="w-full max-w-3xl 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"
@@ -71,35 +47,62 @@ export function ResultScreen({ username, settings, fetchDone, fetchError, onBack
</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">
<div className="flex-1 flex flex-col items-center justify-center px-6 pb-12 w-full max-w-3xl">
<h2 className="font-serif text-3xl text-gray-800 tracking-tight mb-2">
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>
{generating && (
<div className="mt-10 flex flex-col items-center gap-3">
<div className="w-6 h-6 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>
)}
{!generating && generateError && (
<div className="mt-10 flex flex-col items-center gap-3">
<p className="text-sm text-red-500">{generateError}</p>
</div>
) : (
)}
{!generating && !generateError && safeSvg && (
<>
{fetchError && (
<p className="text-[10px] text-amber-500 mb-4">
Could not fetch live data — showing demo widget
</p>
<div className="w-full mt-6 rounded-2xl bg-white shadow-lg ring-1 ring-gray-200 p-6 flex justify-center">
{/*
Force the inline SVG to scale up to the card width. The
composite is authored at 380px wide — without this the
preview looked tiny on wide screens.
*/}
<div
className="w-full max-w-xl [&_svg]:w-full [&_svg]:h-auto"
dangerouslySetInnerHTML={{ __html: safeSvg }}
/>
</div>
<div className="w-full mt-8">
<p className="text-xs uppercase tracking-wider text-gray-500 mb-2">Embed in your README</p>
<div className="relative">
<pre className="bg-gray-900 text-gray-100 text-xs p-4 pr-12 rounded-lg overflow-x-auto">
{embedSnippet}
</pre>
<button
onClick={copy}
title={copied ? 'Copied!' : 'Copy'}
className="absolute top-2 right-2 p-1.5 rounded-md text-gray-400 hover:text-gray-100 hover:bg-gray-800 transition-colors"
>
{copied ? (
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
<polyline points="20 6 9 17 4 12" />
</svg>
) : (
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
<rect x="9" y="9" width="13" height="13" rx="2" ry="2" />
<path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1" />
</svg>
)}
{!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 }} />
</button>
</div>
</div>
</>
)}
</div>
+184 -57
View File
@@ -1,6 +1,29 @@
import { useState, useEffect, useRef, useMemo } from 'react'
import { useState, useMemo, type ReactNode } from 'react'
import DOMPurify from 'dompurify'
import type { WidgetSettings, Achievement, PerWidgetSettings } from '../App'
import { renderAllWidgets, type WidgetData } from '../lib/renderWidgets'
import { signInUrl } from '../lib/auth'
import type { Me } from '../lib/auth'
// Defense-in-depth: the client-rendered preview assembles SVG from
// GitHub-sourced strings (collaborator logins, repo names) and user-typed
// achievement text. renderWidgets escapes known fields, but one missed
// interpolation anywhere upstream would turn into HTML in the preview.
// DOMPurify neutralises that without affecting normal SVG shapes/styles.
const SVG_SANITIZE_CONFIG = {
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',
],
}
const THEMES = [
{ id: 'midnight', label: 'Midnight', color: '#121820' },
@@ -19,11 +42,60 @@ const ALL_WIDGETS = [
{ id: 'achievements', label: 'Achievements' },
]
const ICONS = [
{ id: 'trophy', label: '🏆' },
{ id: 'medal', label: '🥇' },
{ id: 'star', label: '⭐' },
{ id: 'hackathon', label: '💻' },
// Lucide-style hollow glyphs: consistent stroke-weight + viewBox so the 4
// buttons line up and read as one icon family. Kept as JSX so they inherit
// currentColor from the surrounding button's text color.
const ICON_SVG_PROPS = {
width: 16,
height: 16,
viewBox: '0 0 24 24',
fill: 'none',
stroke: 'currentColor',
strokeWidth: 1.75,
strokeLinecap: 'round' as const,
strokeLinejoin: 'round' as const,
}
const ICONS: { id: string; svg: ReactNode }[] = [
{
id: 'trophy',
svg: (
<svg {...ICON_SVG_PROPS}>
<path d="M6 9H4.5a2.5 2.5 0 0 1 0-5H6" />
<path d="M18 9h1.5a2.5 2.5 0 0 0 0-5H18" />
<path d="M4 22h16" />
<path d="M10 14.66V17c0 .55-.47.98-.97 1.21C7.85 18.75 7 20.24 7 22" />
<path d="M14 14.66V17c0 .55.47.98.97 1.21C16.15 18.75 17 20.24 17 22" />
<path d="M18 2H6v7a6 6 0 0 0 12 0V2z" />
</svg>
),
},
{
id: 'medal',
svg: (
<svg {...ICON_SVG_PROPS}>
<circle cx="12" cy="8" r="6" />
<path d="m15.477 12.89 1.515 8.526a.5.5 0 0 1-.81.47l-3.58-2.687a1 1 0 0 0-1.197 0l-3.586 2.686a.5.5 0 0 1-.81-.469l1.514-8.526" />
</svg>
),
},
{
id: 'star',
svg: (
<svg {...ICON_SVG_PROPS}>
<polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26" />
</svg>
),
},
{
id: 'hackathon',
svg: (
<svg {...ICON_SVG_PROPS}>
<polyline points="16 18 22 12 16 6" />
<polyline points="8 6 2 12 8 18" />
</svg>
),
},
]
const COLOR_PRESETS = [
@@ -61,6 +133,63 @@ function NumberStepper({ value, min, max, onChange }: {
)
}
// Common "noise" languages users typically want to hide — shown even when
// the account-level detection hasn't surfaced them yet (e.g., first load).
const COMMON_HIDE_LANGS = ['HTML', 'CSS', 'SCSS', 'Jupyter Notebook', 'TeX', 'Shell', 'Dockerfile', 'Makefile', 'Batchfile']
function HiddenLanguagesPicker({
detected, hidden, onChange,
}: {
detected: { language: string }[]
hidden: string[]
onChange: (next: string[]) => void
}) {
const seen = new Set<string>()
const options: string[] = []
for (const d of detected) if (d.language && !seen.has(d.language)) { seen.add(d.language); options.push(d.language) }
for (const c of COMMON_HIDE_LANGS) if (!seen.has(c)) { seen.add(c); options.push(c) }
// Preserve any user-set hidden that we haven't otherwise seen.
for (const h of hidden) if (!seen.has(h)) { seen.add(h); options.push(h) }
const toggle = (lang: string) => {
onChange(hidden.includes(lang) ? hidden.filter(h => h !== lang) : [...hidden, lang])
}
return (
<div>
<div className="flex items-center justify-between mb-1.5">
<span className="text-[10px] text-gray-500">Hide languages</span>
{hidden.length > 0 && (
<button
onClick={() => onChange([])}
className="text-[10px] text-gray-400 hover:text-gray-600 transition-colors"
>
Clear
</button>
)}
</div>
<div className="flex flex-wrap gap-1">
{options.map(lang => {
const active = hidden.includes(lang)
return (
<button
key={lang}
onClick={() => toggle(lang)}
className={`px-2 py-0.5 rounded-md text-[10px] transition-colors ${
active
? 'bg-gray-800 text-white border border-gray-800'
: 'bg-white text-gray-500 border border-gray-200 hover:text-gray-800 hover:border-gray-300'
}`}
>
{lang}
</button>
)
})}
</div>
</div>
)
}
function ColorPicker({ value, onChange }: { value: string; onChange: (v: string) => void }) {
return (
<div className="flex gap-1.5 flex-wrap">
@@ -85,6 +214,10 @@ type Props = {
onGenerate: () => void
onBack: () => void
fetchDone: boolean
fetchError: string | null
widgetData: WidgetData | null
me: Me
onAuthChange?: (m: Me) => void
}
export function WorkshopScreen({
@@ -94,11 +227,12 @@ export function WorkshopScreen({
onGenerate,
onBack,
fetchDone,
fetchError,
widgetData,
me,
}: Props) {
const [widgetData, setWidgetData] = useState<WidgetData | null>(null)
const [dataLoading, setDataLoading] = useState(true)
const canEdit = !!me.login && me.login.toLowerCase() === username.toLowerCase()
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 })
@@ -144,44 +278,20 @@ export function WorkshopScreen({
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({
const raw = renderAllWidgets({
data: widgetData,
theme: settings.theme,
widgets: settings.widgets,
widgetOrder: ['grade', 'impact', 'collaborators', 'focus', 'languages', 'achievements'],
achievements: settings.achievements,
widgetSettings: settings.widgetSettings,
hiddenLanguages: settings.hiddenLanguages,
username,
})
return DOMPurify.sanitize(raw, SVG_SANITIZE_CONFIG)
}, [widgetData, settings, username])
return (
@@ -200,21 +310,25 @@ export function WorkshopScreen({
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 className="text-sm font-semibold text-gray-800 mb-6">{username}</div>
{fetchError && (
<div className="flex items-center gap-1.5 text-[10px] text-red-500 mb-6">
<div className="w-1.5 h-1.5 rounded-full bg-red-400" />
{fetchError}
</div>
)}
{!canEdit && (
<div className="banner">
{me.login
? `Signed in as ${me.login}. You can only edit your own widget.`
: <a href={signInUrl()}>Sign in with GitHub to edit your widget</a>}
</div>
)}
{/* Theme, Widgets, Achievements editor, Generate — owner-only */}
{canEdit && (
<>
{/* Theme */}
<div className="mb-5">
<div className="text-[10px] uppercase tracking-wider text-gray-400 font-medium mb-3">Theme</div>
@@ -329,6 +443,7 @@ export function WorkshopScreen({
)}
{w.id === 'languages' && (
<div className="flex flex-col gap-2.5">
<div className="flex items-center justify-between">
<span className="text-[10px] text-gray-500">Max languages</span>
<NumberStepper
@@ -337,6 +452,12 @@ export function WorkshopScreen({
onChange={v => updateWidgetSetting('languages', 'max_languages', v)}
/>
</div>
<HiddenLanguagesPicker
detected={widgetData?.languages ?? []}
hidden={settings.hiddenLanguages}
onChange={next => updateSetting('hiddenLanguages', next)}
/>
</div>
)}
{w.id === 'achievements' && (
@@ -365,20 +486,24 @@ export function WorkshopScreen({
{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 => (
{ICONS.map(ic => {
const selected = ach.icon === ic.id
return (
<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'
className={`w-8 h-8 rounded-md flex items-center justify-center transition-colors ${
selected
? 'bg-gray-800 text-white border border-gray-800'
: 'bg-white text-gray-500 border border-gray-200 hover:text-gray-800 hover:border-gray-300'
}`}
title={ic.id}
aria-pressed={selected}
>
{ic.label}
{ic.svg}
</button>
))}
)
})}
<div className="flex-1" />
<button
onClick={() => removeAchievement(idx)}
@@ -431,6 +556,8 @@ export function WorkshopScreen({
>
Generate →
</button>
</>
)}
</div>
{/* Right preview area */}
@@ -440,7 +567,7 @@ export function WorkshopScreen({
<div dangerouslySetInnerHTML={{ __html: svgContent }} />
) : (
<div className="w-[420px] h-[600px] rounded-2xl border border-gray-200 bg-white flex items-center justify-center">
{dataLoading ? (
{!fetchDone ? (
<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>
+1
View File
@@ -5,3 +5,4 @@ requests==2.32.3
pytest==8.3.3
responses==0.25.3
gunicorn==23.0.0
authlib>=1.3,<2
+542 -50
View File
@@ -4,23 +4,314 @@ 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
Two-phase pipeline:
* Enrollment / settings change enqueues a prefetch job and kicks it off
in a background thread so the fetcher starts pulling GitHub data the
instant the user submits a username. The thread only hydrates
widget_data for the client-side Workshop preview — it does not render
SVGs.
* POST /api/<u>/generate synchronously renders and persists the composite
SVG. This is what the user's "Generate" button calls.
"""
import logging
import os
import time
from collections import defaultdict, deque
from concurrent.futures import ThreadPoolExecutor
from datetime import timedelta
from functools import wraps
from threading import BoundedSemaphore, Lock
from flask import Flask, jsonify, request, Response, send_from_directory, session
from . import auth, config, db, fetcher_client, placeholder
from .themes import THEMES
from .utils import is_valid_username, settings_size_ok
import json as _json
log = logging.getLogger("generator.api")
# Bounded pool for prefetch kickoffs. The old code spawned an unbounded
# Thread() per request, so a burst of PATCH /settings would fork hundreds
# of threads each doing a GitHub fetch + SVG compute — easily enough to
# swamp a mini PC. The pool's workqueue absorbs spikes; excess kickoffs
# wait rather than executing in parallel.
_PREFETCH_POOL = ThreadPoolExecutor(
max_workers=max(1, config.PREFETCH_MAX_WORKERS),
thread_name_prefix="prefetch",
)
# Global cap on concurrent SVG renders. A render is the single most
# expensive user-facing operation; capping it makes the worst-case CPU
# load predictable regardless of how many callers pile on.
_GENERATE_SEMAPHORE = BoundedSemaphore(max(1, config.GENERATE_CONCURRENCY))
def _kickoff_prefetch(username: str):
"""Run one prefetch cycle in the bounded pool. Starts the fetcher
soon after enrollment / settings-change so the raw GitHub payload
is hot by the time the user clicks Generate, but never runs more
than PREFETCH_MAX_WORKERS at once."""
log.info("prefetch kickoff started for %s", username)
try:
from . import worker
worker.process_one()
log.info("prefetch kickoff finished for %s", username)
except Exception:
log.exception("prefetch kickoff failed for %s", username)
def _kickoff_prefetch_async(username: str):
try:
_PREFETCH_POOL.submit(_kickoff_prefetch, username)
except RuntimeError:
# Pool was shut down (process exiting). Dropping the kickoff is
# safe: the cron loop will pick the job up on its next tick.
log.warning("prefetch pool shut down; skipping kickoff for %s", username)
# ---- Per-IP rate limiter -----------------------------------------------------
# In-process sliding-window limiter. Good enough for v1; behind a reverse proxy
# we read X-Forwarded-For (trusting only the last hop set by the proxy). For a
# multi-node deploy, swap this for a Redis-backed limiter.
_RATE_LIMITS = {
# (endpoint_key): (max_hits, window_seconds). Defaults set in config.py
# lean toward the mini PC — tighten further via env without redeploying.
"mutate": (config.RATE_LIMIT_MUTATE_MAX, config.RATE_LIMIT_MUTATE_WINDOW),
"read": (config.RATE_LIMIT_READ_MAX, config.RATE_LIMIT_READ_WINDOW),
}
_rate_lock = Lock()
_rate_hits: dict[tuple[str, str], deque] = defaultdict(deque)
_rate_hits_per_login: dict[tuple[str, str], deque] = defaultdict(deque)
def _client_ip() -> str:
fwd = request.headers.get("X-Forwarded-For", "")
if fwd:
# Last value is the closest trusted proxy's client.
return fwd.split(",")[-1].strip()
return request.remote_addr or "unknown"
def _rate_limit(bucket: str) -> bool:
"""Return True if the request is allowed; False if it should be rejected."""
limit, window = _RATE_LIMITS[bucket]
ip = _client_ip()
now = time.time()
key = (bucket, ip)
with _rate_lock:
q = _rate_hits[key]
cutoff = now - window
while q and q[0] < cutoff:
q.popleft()
if len(q) >= limit:
return False
q.append(now)
return True
def _rate_limit_per_login(bucket: str, login: str) -> bool:
"""Per-login rate limit layered on top of per-IP limit.
Returns True if allowed; False if the login has exceeded the limit.
If no login (unauthenticated), returns True (per-IP already covers it).
"""
if not login:
return True # per-IP already covers the unauth path
if bucket == "mutate":
limit, window = config.RATE_LIMIT_MUTATE_PER_LOGIN_MAX, config.RATE_LIMIT_MUTATE_PER_LOGIN_WINDOW
else:
return True
now = time.time()
cutoff = now - window
key = (bucket, login)
with _rate_lock:
q = _rate_hits_per_login[key]
while q and q[0] < cutoff:
q.popleft()
if len(q) >= limit:
return False
q.append(now)
return True
def rate_limited(bucket: str):
def deco(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
if not _rate_limit(bucket):
return jsonify({"error": "rate_limited"}), 429
if not _rate_limit_per_login(bucket, auth.current_login() or ""):
return jsonify({"error": "rate_limited"}), 429
return fn(*args, **kwargs)
return wrapper
return deco
_STATIC_DIR = os.path.join(os.path.dirname(__file__), "static")
app = Flask(__name__, static_folder=None)
if config.SECRET_KEY:
app.secret_key = config.SECRET_KEY
else:
# In tests and local dev we allow a weak default; production must set the env.
app.secret_key = "dev-insecure-secret-do-not-use-in-prod"
def require_auth(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
return fn(*args, **kwargs)
return wrapper
app.config.update(
SESSION_COOKIE_NAME="gh_session",
SESSION_COOKIE_SECURE=config.SESSION_COOKIE_SECURE,
SESSION_COOKIE_HTTPONLY=True,
SESSION_COOKIE_SAMESITE="Lax",
PERMANENT_SESSION_LIFETIME=timedelta(days=30),
)
auth.init_oauth(app)
# Reject oversized bodies before they reach the DB. 128 KB is generous for our
# settings shape and still caps the memory footprint of a flood of PATCHes.
app.config["MAX_CONTENT_LENGTH"] = 128 * 1024
# ---- Settings shape validator -----------------------------------------------
# Settings flow from the public PATCH endpoint into SQLite and then into widget
# renderers. Unvalidated input means an attacker can DoS the render pipeline by
# storing an object that makes `int(settings["widget_settings"]["collaborators"]
# ["max_count"])` raise, or by ballooning the DB with unbounded fields.
# We normalize to an explicit allow-list of fields and coerce/trim types.
_ALLOWED_WIDGETS = {"grade", "impact", "collaborators", "focus", "languages", "achievements"}
_ALLOWED_ICONS = {"trophy", "medal", "star", "hackathon"}
_MAX_ACHIEVEMENTS = 10
_TITLE_MAX = 80
_SUBTITLE_MAX = 160
_EVENT_DATE_MAX = 32
_MAX_CUSTOM_TAGS = 10
_MAX_HIDDEN_LANGS = 40
_TAG_MAX = 40
_LANG_MAX = 40
def _clip_str(v, max_len: int) -> str:
if v is None:
return ""
s = v if isinstance(v, str) else str(v)
return s[:max_len]
def _coerce_achievement(a) -> dict | None:
if not isinstance(a, dict):
return None
title = _clip_str(a.get("title"), _TITLE_MAX).strip()
if not title:
return None
icon = a.get("icon") or "trophy"
if not isinstance(icon, str) or icon not in _ALLOWED_ICONS:
icon = "trophy"
return {
"title": title,
"subtitle": _clip_str(a.get("subtitle"), _SUBTITLE_MAX),
"event_date": _clip_str(a.get("event_date"), _EVENT_DATE_MAX),
"icon": icon,
}
def _coerce_str_list(v, max_items: int, max_item_len: int) -> list[str]:
if not isinstance(v, list):
return []
out = []
for x in v[:max_items]:
if isinstance(x, str) and x:
out.append(x[:max_item_len])
return out
def _coerce_widget_settings(v) -> dict:
"""Whitelist per-widget settings down to the shape each renderer expects.
Anything else is silently dropped — callers cannot smuggle arbitrary keys
into the SVG renderers this way."""
if not isinstance(v, dict):
return {}
out: dict[str, dict] = {}
allowed = {
"grade": {"max_tags": "int"},
"impact": {"line_color": "color"},
"collaborators": {"max_count": "int", "bar_color": "color"},
"focus": {"max_categories": "int"},
"languages": {"max_languages": "int"},
"achievements": {"max_items": "int"},
}
for widget, schema in allowed.items():
raw = v.get(widget)
if not isinstance(raw, dict):
continue
clean = {}
for key, kind in schema.items():
if key not in raw:
continue
val = raw[key]
if kind == "int":
try:
clean[key] = int(val)
except (TypeError, ValueError):
continue
elif kind == "color":
# Deep color validation happens in the widget renderer
# (safe_color). Here we only reject obviously wrong types
# and length-bomb strings.
if isinstance(val, str) and len(val) <= 32:
clean[key] = val
if clean:
out[widget] = clean
return out
def sanitize_settings(body: dict) -> dict:
"""Project an untrusted JSON object down to the fields we accept.
This is the ONLY place that decides what the settings schema is. Anything
not listed here is dropped. Widget renderers can assume the shape holds."""
if not isinstance(body, dict):
return {}
out: dict = {}
theme = body.get("theme")
if isinstance(theme, str) and theme in THEMES:
out["theme"] = theme
if "enabled" in body:
out["enabled"] = [w for w in _coerce_str_list(body["enabled"], 20, 32)
if w in _ALLOWED_WIDGETS]
if "widget_order" in body:
out["widget_order"] = [w for w in _coerce_str_list(body["widget_order"], 20, 32)
if w in _ALLOWED_WIDGETS]
if "custom_tags" in body:
out["custom_tags"] = _coerce_str_list(body["custom_tags"], _MAX_CUSTOM_TAGS, _TAG_MAX)
if "hidden_languages" in body:
out["hidden_languages"] = _coerce_str_list(
body["hidden_languages"], _MAX_HIDDEN_LANGS, _LANG_MAX
)
if "widget_settings" in body:
ws = _coerce_widget_settings(body["widget_settings"])
if ws:
out["widget_settings"] = ws
if "achievements" in body:
raw = body["achievements"] if isinstance(body["achievements"], list) else []
cleaned = []
for a in raw[:_MAX_ACHIEVEMENTS]:
ca = _coerce_achievement(a)
if ca:
cleaned.append(ca)
out["achievements"] = cleaned
return out
@app.route("/", defaults={"path": ""})
@@ -29,6 +320,7 @@ def spa(path: str):
if path.startswith("api/"):
return jsonify({"error": "not found"}), 404
if path:
# send_from_directory enforces that `path` cannot escape _STATIC_DIR.
try:
return send_from_directory(_STATIC_DIR, path)
except Exception:
@@ -39,93 +331,286 @@ def spa(path: str):
return jsonify({"error": "frontend not built"}), 503
@app.route("/api/auth/me", methods=["GET"])
def auth_me():
login = auth.current_login()
if login is None:
return jsonify({"login": None})
return jsonify({
"login": login,
"avatar_url": session.get("gh_avatar_url"),
})
@app.route("/api/auth/logout", methods=["POST"])
@auth.require_same_origin
def auth_logout():
session.clear()
return ("", 204)
@app.route("/api/auth/github/login", methods=["GET"])
def auth_github_login():
import secrets as _secrets
nxt = request.args.get("next", "/")
# Only accept local relative paths to prevent open-redirect.
if not isinstance(nxt, str) or not nxt.startswith("/"):
nxt = "/"
state = _secrets.token_urlsafe(32)
session["oauth_state"] = state
session["oauth_next"] = nxt
redirect_uri = config.GITHUB_OAUTH_REDIRECT_URI or _derived_redirect_uri()
return auth.github_client().authorize_redirect(redirect_uri, state=state)
def _derived_redirect_uri() -> str:
# Works behind cloudflared: the X-Forwarded-Proto/Host headers are set.
proto = request.headers.get("X-Forwarded-Proto") or request.scheme
host = request.headers.get("X-Forwarded-Host") or request.host
return f"{proto}://{host}/api/auth/github/callback"
def _gh_api_get(token: str, path: str) -> dict:
"""Thin wrapper over requests.get so tests can monkeypatch one function."""
import requests
r = requests.get(
f"https://api.github.com/{path.lstrip('/')}",
headers={"Authorization": f"Bearer {token}",
"Accept": "application/vnd.github+json"},
timeout=config.API_TIMEOUT,
)
if r.status_code >= 400:
raise RuntimeError(f"github {path} {r.status_code}")
return r.json()
@app.route("/api/auth/github/callback", methods=["GET"])
def auth_github_callback():
from flask import redirect
state = request.args.get("state", "")
expected = session.pop("oauth_state", None)
nxt = session.pop("oauth_next", "/") or "/"
if not expected or state != expected:
return jsonify({"error": "bad_state"}), 400
try:
token_resp = auth.github_client().authorize_access_token()
except Exception:
log.exception("token exchange failed")
return redirect("/?auth_error=exchange")
access_token = token_resp.get("access_token") if token_resp else None
if not access_token:
return redirect("/?auth_error=exchange")
try:
user = _gh_api_get(access_token, "user")
except Exception:
log.exception("github /user failed")
return redirect("/?auth_error=profile")
login_raw = user.get("login")
gh_id = user.get("id")
avatar_url = user.get("avatar_url") or ""
if not isinstance(login_raw, str) or not is_valid_username(login_raw) or not isinstance(gh_id, int):
return redirect("/?auth_error=profile")
login = login_raw.lower()
session.permanent = True
session["gh_login"] = login
session["gh_id"] = gh_id
session["gh_avatar_url"] = avatar_url
# Implicit enrollment. Idempotent; refreshes github_avatar_url on return logins.
defaults = {
"theme": "dark",
"enabled": config.ENABLED_WIDGETS,
"widget_order": config.WIDGET_ORDER,
}
db.enroll(login, defaults, github_id=gh_id, github_avatar_url=avatar_url)
_kickoff_prefetch_async(login)
return redirect(nxt)
@app.route("/api/health", methods=["GET"])
def health():
return jsonify({"status": "ok", "service": "generator"})
@app.route("/api/<username>", methods=["GET"])
@rate_limited("read")
def get_widget(username: str):
if not is_valid_username(username):
return jsonify({"error": "invalid_username"}), 400
return _serve(username, widget_name="composite")
@app.route("/api/<username>/<widget>.svg", methods=["GET"])
@rate_limited("read")
def get_widget_named(username: str, widget: str):
if not is_valid_username(username):
return jsonify({"error": "invalid_username"}), 400
if widget not in _ALLOWED_WIDGETS and widget != "composite":
return jsonify({"error": "unknown_widget"}), 400
return _serve(username, widget_name=widget)
def _serve(username: str, widget_name: str) -> Response:
settings_row = db.get_settings(username)
@app.route("/api/<username>/data", methods=["GET"])
@rate_limited("read")
def get_user_data(username: str):
"""Precomputed widget data for client-side SVG rendering.
Pure DB lookup — never touches the fetcher or runs compute on the hot
path. Enrollment is now OAuth-driven only.
"""
if not is_valid_username(username):
return jsonify({"error": "invalid_username"}), 400
settings_row = db.get_settings(username)
if settings_row is None:
return jsonify({"status": "not_found"}), 404
db.touch_last_requested(username)
row = db.get_current_widget_data(username)
if row is None:
return jsonify({"status": "building"}), 202
if row["settings_hash"] == "not_found":
return jsonify({"status": "not_found"}), 404
return jsonify({"status": "ready", "data": row["data"]})
def _serve(username: str, widget_name: str) -> Response:
"""Serves a cached SVG for README embeds.
SVGs are only produced by POST /api/<u>/generate. Before that the
endpoint returns a "building" placeholder; enrollment is now OAuth-driven
so this path never auto-enrolls on its own.
"""
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)
current_hash = db.get_current_widget_hash(username)
raw_theme = settings_row["settings"].get("theme", "dark")
theme = raw_theme if isinstance(raw_theme, str) and raw_theme in THEMES else "dark"
headers_common = {
"Content-Security-Policy": "default-src 'none'; style-src 'unsafe-inline'; img-src data:",
"X-Content-Type-Options": "nosniff",
}
if current_hash == "not_found":
svg = db.get_current_widget(username, widget_name) or placeholder.render("not_found", username, theme=theme)
headers = {"X-Widget-Status": "not_found", "Cache-Control": "no-store", **headers_common}
return Response(svg, mimetype="image/svg+xml", headers=headers)
svg = db.get_current_widget(username, widget_name)
if svg is None:
return _placeholder_response("building", username, theme=settings_row["settings"].get("theme", "dark"))
return _placeholder_response("building", username, theme=theme)
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"})
"Cache-Control": "public, max-age=3600",
**headers_common}
return Response(svg, mimetype="image/svg+xml", headers=headers)
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})
headers={"X-Widget-Status": variant, "Cache-Control": "no-store",
"Content-Security-Policy": "default-src 'none'; style-src 'unsafe-inline'; img-src data:",
"X-Content-Type-Options": "nosniff"})
@app.route("/api/<username>/settings", methods=["GET"])
@require_auth
@rate_limited("read")
def get_settings(username: str):
s = db.get_settings(username)
if s is None:
return jsonify({"error": "not_enrolled"}), 404
return jsonify(s)
# Strip internal-only fields before returning.
return jsonify({
"settings": s["settings"],
"settings_hash": s["settings_hash"],
"manual_refresh_used": s["manual_refresh_used"],
"enrolled_at": s["enrolled_at"],
})
@app.route("/api/<username>/settings", methods=["PATCH"])
@require_auth
@rate_limited("mutate")
@auth.require_same_origin
@auth.require_github_owner
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}
clean = sanitize_settings(body)
merged = {**current["settings"], **clean}
# Defense in depth: reject after-the-fact if the merged blob is pathological.
if not settings_size_ok(_json.dumps(merged)):
return jsonify({"error": "settings_too_large"}), 413
job_id = db.update_settings(username, merged)
_kickoff_prefetch_async(username)
return jsonify({"updated": True, "job_id": job_id})
@app.route("/api/<username>/generate", methods=["POST"])
@rate_limited("mutate")
@auth.require_same_origin
@auth.require_github_owner
def generate(username: str):
"""Render the composite SVG from the cached fetcher payload + current
settings, persist it to widgets.db, and return status. Called by the
Generate button; safe to call repeatedly (each call re-renders with
the latest settings). Requires OAuth session with matching login.
Capacity:
* Per-IP rate limit (mutate bucket) caps how fast any one caller can
trigger renders.
* Global semaphore caps how many renders run in parallel across all
callers — the mini PC backstop. Callers that can't acquire the
slot within GENERATE_SEMAPHORE_WAIT_S get 503 + Retry-After so the
frontend can back off cleanly.
"""
from . import worker
if not is_valid_username(username):
return jsonify({"error": "invalid_username"}), 400
if db.get_settings(username) is None:
return jsonify({"error": "not_enrolled"}), 404
acquired = _GENERATE_SEMAPHORE.acquire(timeout=config.GENERATE_SEMAPHORE_WAIT_S)
if not acquired:
resp = jsonify({"error": "busy"})
resp.status_code = 503
resp.headers["Retry-After"] = "5"
return resp
try:
widgets = worker.render_widgets_now(username)
except LookupError:
return jsonify({"error": "not_enrolled"}), 404
except Exception:
log.exception("generate failed for %s", username)
return jsonify({"error": "render_failed"}), 502
finally:
_GENERATE_SEMAPHORE.release()
current_hash = db.get_current_widget_hash(username)
if current_hash == "not_found":
return jsonify({"status": "not_found"}), 404
return jsonify({
"status": "ready",
"composite_url": f"/api/{username}",
"widgets": list(widgets.keys()),
})
@app.route("/api/<username>/refresh", methods=["POST"])
@require_auth
@rate_limited("mutate")
@auth.require_same_origin
@auth.require_github_owner
def refresh(username: str):
s = db.get_settings(username)
if s is None:
@@ -134,12 +619,19 @@ def refresh(username: str):
return jsonify({"error": "already_used"}), 409
try:
fetcher_client.force_fetch(username)
except Exception as e:
return jsonify({"error": f"fetch failed: {e}"}), 502
except Exception:
log.exception("refresh fetcher call failed for %s", username)
return jsonify({"error": "fetch_failed"}), 502
job_id = db.enqueue_build(username)
_kickoff_prefetch_async(username)
return jsonify({"refreshed": True, "job_id": job_id})
@app.errorhandler(413)
def _too_large(_e):
return jsonify({"error": "payload_too_large"}), 413
def main():
db.init_dbs()
app.run(host="0.0.0.0", port=config.PORT)
+80
View File
@@ -0,0 +1,80 @@
"""GitHub OAuth integration for the generator service.
Owns:
- OAuth client registration (authlib)
- `current_login()` — lowercase GitHub login from session, or None
- `require_github_owner` — decorator: 401 if no session, 403 if mismatch
- `require_same_origin` — decorator: 403 if Origin/Referer not in allowlist
"""
from functools import wraps
from urllib.parse import urlparse
from authlib.integrations.flask_client import OAuth
from flask import jsonify, request, session
from . import config
_oauth: OAuth | None = None
def init_oauth(app) -> OAuth:
"""Register the `github` provider. Safe to call once at app startup."""
global _oauth
oauth = OAuth(app)
oauth.register(
name="github",
client_id=config.GITHUB_OAUTH_CLIENT_ID,
client_secret=config.GITHUB_OAUTH_CLIENT_SECRET,
access_token_url="https://github.com/login/oauth/access_token",
authorize_url="https://github.com/login/oauth/authorize",
api_base_url="https://api.github.com/",
client_kwargs={"scope": "read:user"},
)
_oauth = oauth
return oauth
def github_client():
if _oauth is None:
raise RuntimeError("OAuth not initialized — call init_oauth(app) first.")
return _oauth.github
def current_login() -> str | None:
v = session.get("gh_login")
return v.lower() if isinstance(v, str) else None
def _origin_ok() -> bool:
origin = request.headers.get("Origin") or request.headers.get("Referer") or ""
if not origin:
return False
try:
o = urlparse(origin)
normalized = f"{o.scheme}://{o.netloc}"
except Exception:
return False
return normalized in config.ALLOWED_ORIGINS
def require_github_owner(fn):
"""401 if no session; 403 if session login != url username (case-insensitive)."""
@wraps(fn)
def wrapper(username: str, *args, **kwargs):
me = current_login()
if me is None:
return jsonify({"error": "login_required"}), 401
if me != (username or "").lower():
return jsonify({"error": "forbidden"}), 403
return fn(username, *args, **kwargs)
return wrapper
def require_same_origin(fn):
"""Defense in depth beyond SameSite=Lax. Rejects cross-site mutate attempts."""
@wraps(fn)
def wrapper(*args, **kwargs):
if not _origin_ok():
return jsonify({"error": "bad_origin"}), 403
return fn(*args, **kwargs)
return wrapper
+49 -2
View File
@@ -47,10 +47,10 @@ DATA_SOURCE_TYPE = os.getenv("DATA_SOURCE", "direct")
"""Data source type: 'direct' for immediate API calls, 'queued' for batch processing."""
# Widget settings
WIDGET_ORDER = ["grade", "impact", "collaborators", "focus", "languages", "achievements"]
WIDGET_ORDER = ["grade", "impact", "streaks", "collaborators", "focus", "languages", "achievements"]
"""Default order of widgets. Customize by reordering this list."""
ENABLED_WIDGETS = ["grade", "impact", "collaborators", "focus", "languages", "achievements"]
ENABLED_WIDGETS = ["grade", "impact", "streaks", "collaborators", "focus", "languages", "achievements"]
"""Which widgets to display. Remove any you don't want to show."""
# Language filtering
@@ -115,3 +115,50 @@ 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"))
# --- Mini-PC capacity controls ---
# The generator runs on a single mini PC, so the constraining resources are
# CPU (SVG render) and the GitHub PAT (fetch). Everything here is tunable via
# env so the operator can loosen limits after measuring real load.
# Per-IP sliding-window rate limits: (max_hits, window_seconds). These are
# anti-abuse ceilings, not capacity controls — the mini PC is actually
# protected by the global semaphore + worker pool + queue cap below, so
# per-IP numbers stay lenient. Tighten via env only if you see a specific
# abuser.
RATE_LIMIT_READ_MAX = int(os.getenv("RATE_LIMIT_READ_MAX", "3000"))
RATE_LIMIT_READ_WINDOW = int(os.getenv("RATE_LIMIT_READ_WINDOW", "60"))
RATE_LIMIT_MUTATE_MAX = int(os.getenv("RATE_LIMIT_MUTATE_MAX", "120"))
RATE_LIMIT_MUTATE_WINDOW = int(os.getenv("RATE_LIMIT_MUTATE_WINDOW", "60"))
RATE_LIMIT_ENROLL_MAX = int(os.getenv("RATE_LIMIT_ENROLL_MAX", "60"))
RATE_LIMIT_ENROLL_WINDOW = int(os.getenv("RATE_LIMIT_ENROLL_WINDOW", "300"))
# Global across-all-IPs caps. These are the mini-PC backstop: even a
# thousand-IP botnet can't induce more than this much work at once.
GENERATE_CONCURRENCY = int(os.getenv("GENERATE_CONCURRENCY", "2"))
PREFETCH_MAX_WORKERS = int(os.getenv("PREFETCH_MAX_WORKERS", "2"))
PENDING_JOB_QUEUE_CAP = int(os.getenv("PENDING_JOB_QUEUE_CAP", "200"))
# How long a /generate caller will wait for the semaphore before giving up.
GENERATE_SEMAPHORE_WAIT_S = float(os.getenv("GENERATE_SEMAPHORE_WAIT_S", "15"))
# --- GitHub OAuth ---
# Env names avoid the reserved GITHUB_ prefix so they can be stored as GitHub
# Actions secrets (which reject GITHUB_* names).
GITHUB_OAUTH_CLIENT_ID = os.getenv("GH_OAUTH_CLIENT_ID", "")
GITHUB_OAUTH_CLIENT_SECRET = os.getenv("GH_OAUTH_CLIENT_SECRET", "")
GITHUB_OAUTH_REDIRECT_URI = os.getenv("GH_OAUTH_REDIRECT_URI", "")
# Flask session secret. Generate once: python -c "import secrets; print(secrets.token_hex(32))"
SECRET_KEY = os.getenv("GENERATOR_SECRET_KEY", "")
# Dev-only override; defaults to True so production HTTPS cookies work.
SESSION_COOKIE_SECURE = os.getenv("SESSION_COOKIE_SECURE", "true").lower() != "false"
# CSRF defense-in-depth: Origin/Referer allowlist for state-changing routes.
ALLOWED_ORIGINS = tuple(
o.strip() for o in os.getenv("ALLOWED_ORIGINS", "https://gh-stats.com").split(",") if o.strip()
)
# Per-login rate limit on mutate routes, layered on top of per-IP limits.
RATE_LIMIT_MUTATE_PER_LOGIN_MAX = int(os.getenv("RATE_LIMIT_MUTATE_PER_LOGIN_MAX", "120"))
RATE_LIMIT_MUTATE_PER_LOGIN_WINDOW = int(os.getenv("RATE_LIMIT_MUTATE_PER_LOGIN_WINDOW", "60"))
+22 -1
View File
@@ -3,18 +3,37 @@
Run as its own container: CMD python -m src.cron
"""
import logging
import os
import time
from . import config, db, fetcher_client
log = logging.getLogger("generator.cron")
# Pacing between users in a single tick. On a mini PC with N enrolled
# users, a tight loop would fire N fetcher calls back-to-back, each of
# which can become a GitHub call — trivially enough to spike CPU and
# burn PAT budget. Default 0.25s keeps 1000 users inside a ~4-minute
# tick while leaving headroom in the 15-minute window.
_TICK_INTER_USER_SLEEP_S = float(os.getenv("GENERATOR_CRON_INTER_USER_SLEEP_S", "0.25"))
# Queue-depth backstop. If the build worker is already behind, don't
# enqueue more: let it drain. Keeps SQLite from swelling when a burst of
# GitHub changes arrives at once.
_TICK_QUEUE_CAP = int(os.getenv("GENERATOR_CRON_QUEUE_CAP", str(config.PENDING_JOB_QUEUE_CAP)))
def tick() -> dict:
enqueued = 0
failed = 0
skipped_queue_full = 0
for username in db.list_enrolled():
try:
if db.pending_job_count() >= _TICK_QUEUE_CAP:
skipped_queue_full += 1
# Don't hammer the fetcher either when the queue is full.
time.sleep(_TICK_INTER_USER_SLEEP_S)
continue
info = db.get_settings(username)
current = info.get("last_fetcher_payload_hash")
r = fetcher_client.get_data(username)
@@ -26,7 +45,9 @@ def tick() -> dict:
except Exception as e:
log.warning("poll failed for %s: %s", username, e)
failed += 1
return {"enqueued": enqueued, "failed": failed}
if _TICK_INTER_USER_SLEEP_S > 0:
time.sleep(_TICK_INTER_USER_SLEEP_S)
return {"enqueued": enqueued, "failed": failed, "skipped_queue_full": skipped_queue_full}
def main():
+195 -8
View File
@@ -24,7 +24,10 @@ CREATE TABLE IF NOT EXISTS users (
enrolled_at TEXT NOT NULL,
last_fetcher_payload_hash TEXT,
manual_refresh_used INTEGER DEFAULT 0,
last_requested_at TEXT NOT NULL
last_requested_at TEXT NOT NULL,
edit_token_hash TEXT,
github_id INTEGER,
github_avatar_url TEXT
);
CREATE TABLE IF NOT EXISTS enrollments_daily (
day TEXT PRIMARY KEY,
@@ -41,6 +44,16 @@ CREATE TABLE IF NOT EXISTS jobs (
updated_at TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_jobs_pending ON jobs(status, created_at);
CREATE TABLE IF NOT EXISTS user_streaks (
username TEXT PRIMARY KEY,
current_streak INTEGER NOT NULL DEFAULT 0,
current_start TEXT NOT NULL DEFAULT '',
last_active_date TEXT NOT NULL DEFAULT '',
max_streak INTEGER NOT NULL DEFAULT 0,
max_start TEXT NOT NULL DEFAULT '',
max_end TEXT NOT NULL DEFAULT '',
updated_at TEXT NOT NULL
);
"""
_WIDGETS_SCHEMA = """
@@ -57,7 +70,15 @@ CREATE TABLE IF NOT EXISTS current_widget (
settings_hash TEXT NOT NULL,
updated_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS widget_data (
username TEXT NOT NULL,
settings_hash TEXT NOT NULL,
data_json TEXT NOT NULL,
built_at TEXT NOT NULL,
PRIMARY KEY (username, settings_hash)
);
CREATE INDEX IF NOT EXISTS idx_widgets_username ON widgets(username);
CREATE INDEX IF NOT EXISTS idx_widget_data_username ON widget_data(username);
"""
@@ -101,6 +122,14 @@ def _widgets_conn():
def init_dbs() -> None:
with _settings_conn() as c:
c.executescript(_SETTINGS_SCHEMA)
# Additive migration for DBs created before the auth rollout.
cols = {r["name"] for r in c.execute("PRAGMA table_info(users)").fetchall()}
if "edit_token_hash" not in cols:
c.execute("ALTER TABLE users ADD COLUMN edit_token_hash TEXT")
if "github_id" not in cols:
c.execute("ALTER TABLE users ADD COLUMN github_id INTEGER")
if "github_avatar_url" not in cols:
c.execute("ALTER TABLE users ADD COLUMN github_avatar_url TEXT")
c.commit()
with _widgets_conn() as c:
c.executescript(_WIDGETS_SCHEMA)
@@ -114,17 +143,34 @@ def settings_hash(settings: dict) -> str:
# ---- settings / enrollment ----
def enroll(username: str, defaults: dict) -> int:
"""Insert a settings row + increment daily counter + enqueue build. Returns job_id."""
def enroll(username: str, defaults: dict,
github_id: int | None = None,
github_avatar_url: str | None = None) -> dict:
"""Insert a settings row if missing, bump the daily counter, enqueue a build.
Idempotent: calling again for an existing user refreshes github_avatar_url
(so login keeps the avatar fresh) and enqueues a rebuild. Always returns
{"job_id": int}. No token is returned — auth is handled by the signed
session cookie.
"""
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 (?, ?, ?, ?, ?)
cur_ins = c.execute(
"""INSERT INTO users(username, settings_json, settings_hash, enrolled_at,
last_requested_at, github_id, github_avatar_url)
VALUES (?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(username) DO NOTHING""",
(username, json.dumps(defaults), sh, now, now),
(username, json.dumps(defaults), sh, now, now, github_id, github_avatar_url),
)
inserted = cur_ins.rowcount == 1
if not inserted and (github_id is not None or github_avatar_url is not None):
c.execute(
"UPDATE users SET github_id=COALESCE(?, github_id), "
"github_avatar_url=COALESCE(?, github_avatar_url) WHERE username=?",
(github_id, github_avatar_url, username),
)
if inserted:
c.execute(
"""INSERT INTO enrollments_daily(day, count) VALUES (?, 1)
ON CONFLICT(day) DO UPDATE SET count = count + 1""",
@@ -136,7 +182,7 @@ def enroll(username: str, defaults: dict) -> int:
(username, now, now),
)
c.commit()
return cur.lastrowid
return {"job_id": cur.lastrowid}
def enrollments_today() -> int:
@@ -145,6 +191,18 @@ def enrollments_today() -> int:
return row["count"] if row else 0
def enrollment_rank(username: str) -> Optional[int]:
"""1-based position in overall enrollment order by enrolled_at. Used by
tag rules that reward early users (e.g. the 'founder' tag)."""
with _settings_conn() as c:
row = c.execute("SELECT enrolled_at FROM users WHERE username=?", (username,)).fetchone()
if row is None:
return None
return c.execute(
"SELECT COUNT(*) FROM users WHERE enrolled_at <= ?", (row["enrolled_at"],)
).fetchone()[0]
def get_settings(username: str) -> Optional[dict]:
with _settings_conn() as c:
row = c.execute("SELECT * FROM users WHERE username=?", (username,)).fetchone()
@@ -205,6 +263,65 @@ def set_last_fetcher_hash(username: str, h: str) -> None:
c.commit()
def get_user_streak(username: str) -> Optional[dict]:
"""Return the persisted streak row for a user, or None if never written."""
with _settings_conn() as c:
row = c.execute(
"SELECT * FROM user_streaks WHERE username=?", (username,)
).fetchone()
if row is None:
return None
return {
"current_streak": row["current_streak"],
"current_start": row["current_start"],
"last_active_date": row["last_active_date"],
"max_streak": row["max_streak"],
"max_start": row["max_start"],
"max_end": row["max_end"],
"updated_at": row["updated_at"],
}
def put_user_streak(username: str, streak: dict) -> None:
"""UPSERT the streak row for a user. Caller supplies the merged values."""
now = _now()
with _settings_conn() as c:
c.execute(
"""INSERT INTO user_streaks(
username, current_streak, current_start, last_active_date,
max_streak, max_start, max_end, updated_at
) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(username) DO UPDATE SET
current_streak=excluded.current_streak,
current_start=excluded.current_start,
last_active_date=excluded.last_active_date,
max_streak=excluded.max_streak,
max_start=excluded.max_start,
max_end=excluded.max_end,
updated_at=excluded.updated_at""",
(
username,
int(streak.get("current_streak", 0)),
streak.get("current_start", ""),
streak.get("last_active_date", ""),
int(streak.get("max_streak", 0)),
streak.get("max_start", ""),
streak.get("max_end", ""),
now,
),
)
c.commit()
def set_github_profile(username: str, github_id: int, github_avatar_url: str) -> None:
with _settings_conn() as c:
c.execute(
"UPDATE users SET github_id=?, github_avatar_url=? WHERE username=?",
(github_id, github_avatar_url, username),
)
c.commit()
# ---- jobs ----
def enqueue_build(username: str) -> int:
@@ -219,6 +336,14 @@ def enqueue_build(username: str) -> int:
return cur.lastrowid
def pending_job_count() -> int:
"""Depth of the build queue. Used as backpressure so bursts of
enroll/PATCH don't blow up SQLite when the worker is behind."""
with _settings_conn() as c:
row = c.execute("SELECT COUNT(*) AS n FROM jobs WHERE status='pending'").fetchone()
return int(row["n"]) if row else 0
def claim_next_job() -> Optional[dict]:
now = _now()
with _settings_conn() as c:
@@ -282,6 +407,33 @@ def put_widgets(username: str, hash_: str, widgets: dict[str, str]) -> None:
c.commit()
def get_current_widget_hash(username: str) -> Optional[str]:
"""The settings_hash that current_widget points at (or None if nothing
has been prefetched/rendered yet). Distinct from users.settings_hash,
which is the hash of the *currently configured* settings."""
with _widgets_conn() as c:
row = c.execute(
"SELECT settings_hash FROM current_widget WHERE username=?",
(username,),
).fetchone()
return row["settings_hash"] if row else None
def point_current_widget(username: str, hash_: str) -> None:
"""Flip the current_widget pointer to a settings_hash. Used by the
prefetch worker (which writes only widget_data, not SVG rows) and by
the render path (which writes both, but calls this too for clarity)."""
now = _now()
with _widgets_conn() as c:
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(
@@ -293,6 +445,37 @@ def get_current_widget(username: str, widget_name: str) -> Optional[str]:
return row["svg"] if row else None
def put_widget_data(username: str, hash_: str, data: dict) -> None:
"""Store computed widget data for client-side rendering. Keyed to the
same (username, settings_hash) that widgets are — the worker writes both
in the same build pass."""
now = _now()
with _widgets_conn() as c:
c.execute(
"""INSERT INTO widget_data(username, settings_hash, data_json, built_at)
VALUES (?, ?, ?, ?)
ON CONFLICT(username, settings_hash) DO UPDATE SET
data_json = excluded.data_json, built_at = excluded.built_at""",
(username, hash_, json.dumps(data, separators=(",", ":")), now),
)
c.commit()
def get_current_widget_data(username: str) -> Optional[dict]:
"""Returns {'data': <dict>, 'settings_hash': str} for the pointer in
current_widget, or None if nothing is built yet."""
with _widgets_conn() as c:
row = c.execute(
"""SELECT wd.data_json, wd.settings_hash FROM widget_data wd
JOIN current_widget cw ON cw.username=wd.username AND cw.settings_hash=wd.settings_hash
WHERE wd.username=?""",
(username,),
).fetchone()
if row is None:
return None
return {"data": json.loads(row["data_json"]), "settings_hash": row["settings_hash"]}
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:
@@ -309,5 +492,9 @@ def lru_trim(username: str, keep: int) -> int:
f"DELETE FROM widgets WHERE username=? AND settings_hash IN ({placeholders})",
(username, *to_delete),
)
c.execute(
f"DELETE FROM widget_data WHERE username=? AND settings_hash IN ({placeholders})",
(username, *to_delete),
)
c.commit()
return cur.rowcount
+2
View File
@@ -8,6 +8,7 @@ from .types import (
FocusCategory,
LanguageData,
AchievementData,
StreakData,
)
__all__ = [
@@ -18,4 +19,5 @@ __all__ = [
"FocusCategory",
"LanguageData",
"AchievementData",
"StreakData",
]
+11
View File
@@ -17,6 +17,7 @@ class TagData:
tag: str
source: str = "earned" # "earned" | "chosen"
confidence: float = 1.0
label: str | None = None # optional display override (e.g. "Founder #42")
@dataclass
@@ -55,3 +56,13 @@ class AchievementData:
subtitle: str = ""
event_date: str = ""
icon: str = "trophy" # trophy, medal, star, hackathon
@dataclass
class StreakData:
current: int = 0 # consecutive days ending today (or yesterday under grace)
max: int = 0 # all-time longest observed streak
current_start: str = "" # ISO date the current streak started, "" if current == 0
last_active_date: str = "" # most recent date with contributions in the window
max_start: str = "" # ISO date the max streak started (best-effort)
max_end: str = "" # ISO date the max streak ended (best-effort)
+182 -3
View File
@@ -10,6 +10,8 @@ from .models import (
CollaboratorData,
FocusCategory,
LanguageData,
AchievementData,
StreakData,
)
from .widgets import (
render_grade_widget,
@@ -17,6 +19,8 @@ from .widgets import (
render_collaborators_widget,
render_focus_widget,
render_languages_widget,
render_achievements_widget,
render_streaks_widget,
)
@@ -189,6 +193,7 @@ def _compute_tags(github_data: dict, max_tags: int = None, custom_tags: list[str
# Apply threshold rules
awarded_tags = []
tag_label_overrides: dict[str, str] = {}
# Fullstack: >25% frontend AND >25% backend
if category_percentages.get("Frontend", 0) > 0.25 and category_percentages.get("Backend", 0) > 0.25:
@@ -235,9 +240,22 @@ def _compute_tags(github_data: dict, max_tags: int = None, custom_tags: list[str
for tag in custom_tags:
awarded_tags.append((tag, 1.0))
# Auto-awarded tags (username-specific + rule-based; see src/tag_rules.py).
from . import tag_rules
username = (github_data.get("user") or {}).get("login", "")
for auto_tag, label in tag_rules.evaluate(username, github_data):
awarded_tags.append((auto_tag, 1.0))
if label:
tag_label_overrides[auto_tag] = label
# Sort by confidence and limit to max_tags
for tag, conf in sorted(awarded_tags, key=lambda x: -x[1])[:max_tags]:
tags.append(TagData(tag=tag, source="earned" if conf < 1.0 else "custom", confidence=round(conf, 2)))
tags.append(TagData(
tag=tag,
source="earned" if conf < 1.0 else "custom",
confidence=round(conf, 2),
label=tag_label_overrides.get(tag),
))
return tags
@@ -461,6 +479,11 @@ def compute_languages(github_data: dict, hidden_languages: list[str] = None) ->
"""
Compute language distribution from repos.
Prefers per-repo byte breakdowns (`repo["language_bytes"]`) when present —
that matches GitHub's own "Most Used Languages" widget. Falls back to a
primary-language repo-count tally for payloads fetched before the
enrichment step landed.
Args:
github_data: GitHub profile data
hidden_languages: Optional list of languages to exclude (e.g., ["HTML", "CSS"])
@@ -469,12 +492,36 @@ def compute_languages(github_data: dict, hidden_languages: list[str] = None) ->
if hidden_languages is None:
hidden_languages = HIDDEN_LANGUAGES
hidden_set = {h for h in hidden_languages}
repos = github_data["repos"]
lang_counts = defaultdict(int)
byte_totals: dict[str, int] = defaultdict(int)
have_bytes = False
for r in repos:
lb = r.get("language_bytes") or {}
if not isinstance(lb, dict) or not lb:
continue
have_bytes = True
for lang, n in lb.items():
if lang and lang not in hidden_set:
byte_totals[lang] += int(n or 0)
if have_bytes and byte_totals:
total = sum(byte_totals.values()) or 1
return [
LanguageData(
language=lang,
percentage=round(size / total * 100, 1),
loc=size,
)
for lang, size in sorted(byte_totals.items(), key=lambda x: -x[1])
]
# Legacy fallback: repo-count by primary language.
lang_counts: dict[str, int] = defaultdict(int)
for r in repos:
lang = r.get("language")
if lang and lang not in hidden_languages:
if lang and lang not in hidden_set:
lang_counts[lang] += 1
total = sum(lang_counts.values()) or 1
@@ -488,6 +535,115 @@ def compute_languages(github_data: dict, hidden_languages: list[str] = None) ->
]
def compute_streaks(github_data: dict, stored: dict | None) -> StreakData:
"""
Compute the user's current and longest contribution streaks.
Current streak: starts at today if today has contributions; else at
yesterday if yesterday has contributions (1-day grace for end-of-UTC).
Walks backward while consecutive days are all active.
Max streak: scans the contribution window for the longest consecutive run,
then merges with `stored["max_streak"]`. The greater value wins; when the
stored value wins, its start/end dates are preserved.
Args:
github_data: Raw fetcher payload; reads "commits" as a list of
{"date": "YYYY-MM-DD", "count": N}. Zero-count entries are ignored.
stored: Optional dict from db.get_user_streak(username). None on first
observation.
"""
entries = github_data.get("commits") or []
active = set()
for e in entries:
if not isinstance(e, dict):
continue
d = e.get("date")
n = e.get("count") or 0
if d and n > 0:
active.add(d)
stored = stored or {}
prior_max = int(stored.get("max_streak", 0) or 0)
prior_max_start = stored.get("max_start", "") or ""
prior_max_end = stored.get("max_end", "") or ""
stored_last = stored.get("last_active_date", "") or ""
if not active:
return StreakData(
current=0,
max=prior_max,
current_start="",
last_active_date=stored_last,
max_start=prior_max_start,
max_end=prior_max_end,
)
today = datetime.utcnow().date()
yesterday = today - timedelta(days=1)
if today.isoformat() in active:
cursor = today
elif yesterday.isoformat() in active:
cursor = yesterday
else:
cursor = None
current = 0
current_start = ""
if cursor is not None:
start = cursor
while start.isoformat() in active:
current += 1
start -= timedelta(days=1)
current_start = (start + timedelta(days=1)).isoformat()
sorted_dates = sorted(active)
from datetime import date as _date
max_len = 0
max_start_iso = ""
max_end_iso = ""
run_start = sorted_dates[0]
run_len = 1
prev = _date.fromisoformat(run_start)
for ds in sorted_dates[1:]:
cur = _date.fromisoformat(ds)
if (cur - prev).days == 1:
run_len += 1
else:
if run_len > max_len:
max_len = run_len
max_start_iso = run_start
max_end_iso = prev.isoformat()
run_start = ds
run_len = 1
prev = cur
if run_len > max_len:
max_len = run_len
max_start_iso = run_start
max_end_iso = prev.isoformat()
if max_len > prior_max:
merged_max = max_len
merged_start = max_start_iso
merged_end = max_end_iso
else:
merged_max = prior_max
merged_start = prior_max_start
merged_end = prior_max_end
last_active = sorted_dates[-1]
return StreakData(
current=current,
max=merged_max,
current_start=current_start,
last_active_date=last_active,
max_start=merged_start,
max_end=merged_end,
)
def generate_widgets_from_github(
github_data: dict,
theme: str = "dark",
@@ -495,6 +651,8 @@ def generate_widgets_from_github(
hidden_languages: list[str] = None,
enabled: list[str] = None,
widget_settings: dict[str, dict] | None = None,
achievements: list[dict] | None = None,
stored_streak: dict | None = None,
) -> dict[str, str]:
"""
Takes raw GitHub API data and returns rendered SVG strings
@@ -509,6 +667,8 @@ def generate_widgets_from_github(
Defaults to ENABLED_WIDGETS from config.
widget_settings: Optional per-widget settings dict, keyed by widget name.
Each value is a dict of settings for that widget's renderer.
stored_streak: Optional dict from db.get_user_streak(username); carries
the all-time longest streak forward across refreshes.
"""
from .config import ENABLED_WIDGETS
@@ -539,4 +699,23 @@ def generate_widgets_from_github(
languages = compute_languages(github_data, hidden_languages=hidden_languages)
widgets["languages"] = render_languages_widget(languages, theme, settings=ws.get("languages"))
if "streaks" in enabled_set:
streak = compute_streaks(github_data, stored_streak)
widgets["streaks"] = render_streaks_widget(streak, theme, settings=ws.get("streaks"))
if "achievements" in enabled_set:
# User-authored content — no GitHub data involved.
raw = [a for a in (achievements or []) if (a.get("title") or "").strip()]
items = [
AchievementData(
title=a.get("title", ""),
subtitle=a.get("subtitle", ""),
event_date=a.get("event_date", ""),
icon=a.get("icon", "trophy"),
)
for a in raw
]
if items:
widgets["achievements"] = render_achievements_widget(items, theme, settings=ws.get("achievements"))
return widgets
+108
View File
@@ -0,0 +1,108 @@
"""Auto-awarded profile tags.
This is the single place to add new custom tags. Three pieces plug together:
TAG_DEFS — display metadata (color, label) for each tag ID.
USER_TAGS — hardcoded tags by username. Great for VIP/creator badges.
TAG_RULES — predicate-driven awards based on account signals.
To add a new tag:
1. Add its color + label to TAG_DEFS below.
2. Award it either by listing the username in USER_TAGS, or by appending
a (tag_id, predicate) pair to TAG_RULES.
Predicates receive (username, github_data) and return one of:
False / None — not awarded
True — awarded with the default TAG_DEFS label
str — awarded with this string as a custom label (e.g. "Founder #42")
Any exception inside a predicate is swallowed — a broken rule can't break the
whole tag pipeline.
"""
from typing import Callable, Union
# ---- Display metadata -------------------------------------------------------
TAG_DEFS: dict[str, dict] = {
"creator": {"color": "#f472b6", "label": "Creator"},
"open-source": {"color": "#3fb950", "label": "Open Source"},
"founder": {"color": "#facc15", "label": "Founder"},
"hackathon-winner": {"color": "#fb923c", "label": "Hackathon Winner"},
"early-adopter": {"color": "#a78bfa", "label": "Early Adopter"},
}
# ---- Username → tags --------------------------------------------------------
# Usernames are compared case-insensitively.
USER_TAGS: dict[str, list[str]] = {
"shaymanor": ["creator"],
}
# ---- Rule predicates --------------------------------------------------------
PredicateResult = Union[bool, str, None]
def _open_source_maintainer(username: str, data: dict) -> PredicateResult:
"""At least 3 non-fork repos with ≥10 stars, OR ≥50 total stars."""
repos = data.get("repos") or []
non_fork = [r for r in repos if not r.get("fork")]
popular = sum(1 for r in non_fork if (r.get("stargazers_count") or 0) >= 10)
total_stars = sum((r.get("stargazers_count") or 0) for r in non_fork)
return popular >= 3 or total_stars >= 50
def _first_n_enrolled(n: int) -> Callable[[str, dict], PredicateResult]:
"""Returns a predicate that fires for users in the first N enrollments.
When it fires, the label includes the rank (e.g. "Founder #42").
"""
def predicate(username: str, _data: dict) -> PredicateResult:
from .db import enrollment_rank
rank = enrollment_rank(username)
if rank is None or rank > n:
return False
return f"Founder #{rank}"
return predicate
TAG_RULES: list[tuple[str, Callable[[str, dict], PredicateResult]]] = [
("open-source", _open_source_maintainer),
("founder", _first_n_enrolled(1000)),
]
# ---- Entry point ------------------------------------------------------------
def evaluate(username: str, github_data: dict) -> list[tuple[str, str | None]]:
"""Return ordered (tag_id, label_override) pairs awarded to this user.
label_override is None unless the predicate returned a string, in which
case that string replaces the default TAG_DEFS label for this user.
"""
awarded: list[tuple[str, str | None]] = []
seen: set[str] = set()
key = (username or "").lower()
for tag in USER_TAGS.get(key, []):
if tag not in seen:
awarded.append((tag, None))
seen.add(tag)
for tag, predicate in TAG_RULES:
if tag in seen:
continue
try:
result = predicate(username, github_data)
except Exception:
continue
if not result:
continue
label = result if isinstance(result, str) else None
awarded.append((tag, label))
seen.add(tag)
return awarded
+15
View File
@@ -94,6 +94,21 @@ TAG_COLORS = {
"open-source": "#3fb950",
}
# Pick up colors for custom/auto-awarded tags defined in src/tag_rules.py so
# adding a new tag there is a single-file change.
def _merge_custom_tag_colors() -> None:
try:
from .. import tag_rules
except Exception:
return
for tag_id, meta in tag_rules.TAG_DEFS.items():
color = meta.get("color")
if color and tag_id not in TAG_COLORS:
TAG_COLORS[tag_id] = color
_merge_custom_tag_colors()
GRADE_COLORS = {
"S": "#ff6b9d",
"A": "#3fb950",
+13 -1
View File
@@ -1,5 +1,17 @@
"""Utility functions for SVG generation."""
from .svg_helpers import escape, card_wrapper, icon_svg
from .validate import (
is_valid_username,
is_valid_color,
safe_color,
validate_theme_name,
clip_text,
settings_size_ok,
)
__all__ = ["escape", "card_wrapper", "icon_svg"]
__all__ = [
"escape", "card_wrapper", "icon_svg",
"is_valid_username", "is_valid_color", "safe_color",
"validate_theme_name", "clip_text", "settings_size_ok",
]
+1 -1
View File
@@ -36,7 +36,7 @@ def icon_svg(kind: str, color: str) -> str:
icons = {
"commits": f'<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": f'<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": f'<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"/>',
"stars": f'<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="none" stroke="{color}" stroke-width="1.2" stroke-linejoin="round"/>',
"repos": f'<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": f'<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"/>',
}
+62
View File
@@ -0,0 +1,62 @@
"""Input validation helpers shared across API, worker, and widget renderers.
These sit at the trust boundary between user input and anything that flows
into (a) outbound URLs to GitHub, (b) SVG markup, or (c) persisted settings.
Anything that crosses that boundary must be validated here first.
"""
from __future__ import annotations
import re
# GitHub usernames: 1–39 chars, alphanumeric or single hyphens, cannot start/end
# with a hyphen and cannot have consecutive hyphens. This matches GitHub's own
# signup regex — anything outside it is not a real account and should not be
# forwarded to the fetcher or embedded in URLs / GraphQL.
_USERNAME_RE = re.compile(r"^[A-Za-z0-9](?:[A-Za-z0-9]|-(?=[A-Za-z0-9])){0,38}$")
# CSS color accepted by the widget renderers: #rgb, #rrggbb, #rrggbbaa, or a
# short allow-list of named colors that we actually use in themes. Permissive
# parsers let an attacker smuggle quote chars into SVG attribute context.
_COLOR_HEX_RE = re.compile(r"^#[0-9a-fA-F]{3,8}$")
_COLOR_NAMES = {
"transparent", "currentcolor", "none",
"white", "black", "red", "green", "blue",
}
_MAX_SETTINGS_BYTES = 64 * 1024 # 64 KB — plenty for theme + achievements
def is_valid_username(name: str) -> bool:
return isinstance(name, str) and bool(_USERNAME_RE.match(name))
def is_valid_color(value: str) -> bool:
if not isinstance(value, str) or len(value) > 32:
return False
return bool(_COLOR_HEX_RE.match(value)) or value.lower() in _COLOR_NAMES
def safe_color(value, fallback: str) -> str:
"""Return `value` if it's a valid color string, else `fallback`."""
return value if is_valid_color(value) else fallback
def validate_theme_name(name, allowed: set[str], fallback: str = "dark") -> str:
"""Return name if it's in `allowed`, else `fallback`. Prevents KeyError DoS
on THEMES[name] when a user patches in an unknown theme."""
if isinstance(name, str) and name in allowed:
return name
return fallback
def clip_text(value, max_len: int) -> str:
"""Coerce `value` to a string and truncate. Used for user-authored fields
that flow into SVG text (title, subtitle, event_date)."""
if value is None:
return ""
s = value if isinstance(value, str) else str(value)
return s[:max_len]
def settings_size_ok(raw_json: str) -> bool:
return len(raw_json.encode("utf-8")) <= _MAX_SETTINGS_BYTES
+2
View File
@@ -6,6 +6,7 @@ from .collaborators import render_collaborators_widget
from .focus import render_focus_widget
from .languages import render_languages_widget
from .achievements import render_achievements_widget
from .streaks import render_streaks_widget
from .composite import compose_widget
__all__ = [
@@ -15,5 +16,6 @@ __all__ = [
"render_focus_widget",
"render_languages_widget",
"render_achievements_widget",
"render_streaks_widget",
"compose_widget",
]
+3 -2
View File
@@ -18,7 +18,8 @@ def _achievement_icon_svg(icon_type: str, color: str) -> str:
<path d="M9 3l3 8m0-8l3 8m-6-8h6" stroke="{color}" stroke-width="1.5" fill="none" stroke-linecap="round"/>
</svg>''',
"star": f'''<svg viewBox="0 0 24 24" width="24" height="24">
<path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z" fill="{color}" opacity="0.85"/>
<path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z"
fill="none" stroke="{color}" stroke-width="1.5" stroke-linejoin="round"/>
</svg>''',
"hackathon": f'''<svg viewBox="0 0 24 24" width="24" height="24">
<rect x="4" y="5" width="16" height="11" rx="1" fill="none" stroke="{color}" stroke-width="1.5"/>
@@ -65,7 +66,7 @@ def render_achievements_widget(
<text x="48" y="20" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="13" font-weight="600" fill="{t["text"]}">{escape(ach.title)}</text>
<text x="48" y="36" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" fill="{t["text_secondary"]}">{escape(ach.subtitle)}{(" · " + ach.event_date) if ach.event_date else ""}</text>
font-size="10" fill="{t["text_secondary"]}">{escape(ach.subtitle)}{(" · " + escape(ach.event_date)) if ach.event_date else ""}</text>
</g>'''
total_h = len(shown) * 56 + 50
+2 -2
View File
@@ -2,7 +2,7 @@
from ..models import CollaboratorData
from ..themes import THEMES
from ..utils import escape, card_wrapper
from ..utils import escape, card_wrapper, safe_color
def render_collaborators_widget(collabs: list[CollaboratorData], theme_name: str = "dark", settings: dict | None = None) -> str:
@@ -15,7 +15,7 @@ def render_collaborators_widget(collabs: list[CollaboratorData], theme_name: str
t = THEMES[theme_name]
s = settings or {}
max_count = min(max(int(s.get("max_count", 5)), 1), 10)
bar_color = s.get("bar_color") or t["purple"]
bar_color = safe_color(s.get("bar_color"), t["purple"])
items = ""
for i, c in enumerate(collabs[:max_count]):
+1 -1
View File
@@ -96,5 +96,5 @@ def compose_widget(
{embedded}
<text x="{total_w // 2}" y="{total_h - 8}" text-anchor="middle"
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="9" fill="{t["text_secondary"]}" opacity="0.5">Generated with ♥</text>
font-size="9" fill="{t["text_secondary"]}" opacity="0.5">Generated with gh-stats</text>
</svg>'''
+20 -1
View File
@@ -5,6 +5,25 @@ from ..models import GradeData
from ..themes import THEMES, TAG_COLORS, GRADE_COLORS
from ..utils import escape, card_wrapper, icon_svg
# Tokens that should render uppercase instead of title-cased (e.g. "ml-engineer"
# → "ML Engineer", not "Ml Engineer").
_TAG_ACRONYMS = {"ml", "ai", "ui", "ux", "api", "cli", "sql", "css", "html", "js", "ios"}
def _format_tag_label(tag: str) -> str:
# Custom tags may define an explicit label in src/tag_rules.py::TAG_DEFS.
try:
from .. import tag_rules
meta = tag_rules.TAG_DEFS.get(tag)
if meta and meta.get("label"):
return meta["label"]
except Exception:
pass
return " ".join(
w.upper() if w.lower() in _TAG_ACRONYMS else w.capitalize()
for w in tag.split("-")
)
def render_grade_widget(data: GradeData, theme_name: str = "dark", settings: dict | None = None) -> str:
"""Renders the developer grade widget with stats and tags.
@@ -63,7 +82,7 @@ def render_grade_widget(data: GradeData, theme_name: str = "dark", settings: dic
for tag in (data.tags or []):
tag_color = TAG_COLORS.get(tag.tag, t["accent"])
label = tag.tag.replace("-", " ").title()
label = getattr(tag, "label", None) or _format_tag_label(tag.tag)
tw = int(len(label) * 6.6 + 18)
pill_opacity = 0.9 if tag.source == "earned" else 0.55
+2 -2
View File
@@ -2,7 +2,7 @@
from ..models import ImpactWeek
from ..themes import THEMES
from ..utils import card_wrapper
from ..utils import card_wrapper, safe_color
def render_impact_widget(weeks: list[ImpactWeek], theme_name: str = "dark", period: str = "6mo", settings: dict | None = None) -> str:
@@ -13,7 +13,7 @@ def render_impact_widget(weeks: list[ImpactWeek], theme_name: str = "dark", peri
"""
t = THEMES[theme_name]
s = settings or {}
line_color = s.get("line_color") or t["accent"]
line_color = safe_color(s.get("line_color"), t["accent"])
w, h = 380, 200
chart_x, chart_y = 40, 8
chart_w, chart_h = 316, 82
+96
View File
@@ -0,0 +1,96 @@
"""Streaks widget rendering."""
from datetime import date
from ..models import StreakData
from ..themes import THEMES
from ..utils import escape, card_wrapper
_FLAME_SVG = (
'<path d="M12 2c1 4 5 5 5 10a5 5 0 1 1-10 0c0-2 1-3 2-4 0 1 1 2 2 2 '
'-1-2 0-5 1-8z" fill="{color}" opacity="0.95"/>'
)
_TROPHY_SVG = (
'<path d="M6 3h12v3a4 4 0 0 1-4 4h-4a4 4 0 0 1-4-4V3z" fill="none" '
'stroke="{color}" stroke-width="1.6"/>'
'<path d="M4 4h2v2a2 2 0 0 1-2 2H3V5a1 1 0 0 1 1-1zM20 4h-2v2a2 2 0 0 0 2 '
'2h1V5a1 1 0 0 0-1-1z" fill="none" stroke="{color}" stroke-width="1.4"/>'
'<rect x="9" y="11" width="6" height="3" fill="{color}"/>'
'<rect x="7" y="14" width="10" height="2" rx="0.5" fill="{color}"/>'
)
def _fmt_date(iso: str) -> str:
if not iso:
return ""
try:
d = date.fromisoformat(iso)
except ValueError:
return ""
return d.strftime("%b %d, %Y")
def _fmt_range(start: str, end: str) -> str:
s = _fmt_date(start)
e = _fmt_date(end)
if s and e:
return f"{s} – {e}"
return s or e
def render_streaks_widget(
data: StreakData,
theme_name: str = "dark",
settings: dict | None = None,
) -> str:
"""Render the streaks widget.
Settings:
show_dates (bool): Show date captions below each number. Default True.
"""
t = THEMES[theme_name]
s = settings or {}
show_dates = bool(s.get("show_dates", True))
width = 380
height = 170
col_w = width / 2
current_color = t["accent"]
max_color = t.get("text", "#e6e6e6")
current_sub = _fmt_date(data.current_start) if data.current_start else "—"
max_sub = _fmt_range(data.max_start, data.max_end) if (data.max_start or data.max_end) else ""
date_lines = ""
if show_dates:
date_lines = f'''
<text x="{col_w / 2}" y="130" text-anchor="middle"
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="9" fill="{t["text_secondary"]}">{escape("since " + current_sub) if data.current > 0 else ""}</text>
<text x="{col_w + col_w / 2}" y="130" text-anchor="middle"
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="9" fill="{t["text_secondary"]}">{escape(max_sub)}</text>'''
inner = f'''
<g transform="translate({col_w / 2 - 12}, 14)">{_FLAME_SVG.format(color=current_color)}</g>
<text x="{col_w / 2}" y="78" text-anchor="middle"
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="40" font-weight="800" fill="{current_color}">{data.current}</text>
<text x="{col_w / 2}" y="108" text-anchor="middle"
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="11" fill="{t["text_secondary"]}" letter-spacing="0.5">Current Streak</text>
<line x1="{col_w}" y1="24" x2="{col_w}" y2="{height - 24 - 36}" stroke="{t["grid"]}" stroke-width="1"/>
<g transform="translate({col_w + col_w / 2 - 12}, 14)">{_TROPHY_SVG.format(color=max_color)}</g>
<text x="{col_w + col_w / 2}" y="78" text-anchor="middle"
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="40" font-weight="800" fill="{max_color}">{data.max}</text>
<text x="{col_w + col_w / 2}" y="108" text-anchor="middle"
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="11" fill="{t["text_secondary"]}" letter-spacing="0.5">Longest Streak</text>
{date_lines}'''
return card_wrapper(inner, width, height, t, "")
+80 -10
View File
@@ -1,9 +1,21 @@
"""Build worker. Pulls pending jobs and renders widgets.
"""Prefetch worker. Pulls pending jobs and populates widget data.
Two-phase pipeline:
* Phase 1 (this module): on enroll/settings-change, fetch the raw GitHub
payload from the fetcher and compute widget data for the client-side
Workshop preview. No SVG rendering.
* Phase 2 (render_widgets_now, called from the API's Generate endpoint):
synchronously render composite SVG from the cached raw + current
settings and persist to widgets.db.
This split keeps the fetcher hot while the user edits settings and defers
expensive SVG composition until the user clicks Generate.
Run as its own container: CMD python -m src.worker
"""
import logging
import time
from dataclasses import asdict
from . import cache, config, db, fetcher_client, placeholder, processor
from .widgets import compose_widget
@@ -12,10 +24,39 @@ log = logging.getLogger("generator.worker")
MAX_ATTEMPTS = 3
def _compute_widget_data(payload: dict, settings: dict, username: str) -> dict:
"""Compute raw widget data dict for client-side rendering.
Also persists the user's streak state as a side effect — the longest streak
must survive settings-hash rotations, so it lives outside widget_data.
"""
custom_tags = settings.get("custom_tags")
hidden_languages = settings.get("hidden_languages")
stored_streak = db.get_user_streak(username)
streak = processor.compute_streaks(payload, stored_streak)
db.put_user_streak(username, {
"current_streak": streak.current,
"current_start": streak.current_start,
"last_active_date": streak.last_active_date,
"max_streak": streak.max,
"max_start": streak.max_start,
"max_end": streak.max_end,
})
return {
"grade": asdict(processor.compute_grade(payload, custom_tags=custom_tags)),
"impact": [asdict(w) for w in processor.compute_impact_timeline(payload)],
"collaborators": [asdict(c) for c in processor.compute_collaborators(payload)],
"focus": [asdict(f) for f in processor.compute_focus(payload, hidden_languages=hidden_languages)],
"languages": [asdict(l) for l in processor.compute_languages(payload, hidden_languages=hidden_languages)],
"streaks": asdict(streak),
}
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")
stored_streak = db.get_user_streak(username)
widgets = processor.generate_widgets_from_github(
payload,
theme=theme,
@@ -23,6 +64,8 @@ def _render_widgets(username: str, payload: dict, settings: dict) -> dict[str, s
hidden_languages=settings.get("hidden_languages"),
enabled=enabled,
widget_settings=settings.get("widget_settings") or {},
achievements=settings.get("achievements") or [],
stored_streak=stored_streak,
)
ordered = [w for w in order if w in enabled and w in widgets and widgets[w]]
composite = compose_widget(
@@ -35,6 +78,7 @@ def _render_widgets(username: str, payload: dict, settings: dict) -> dict[str, s
def process_one() -> bool:
"""Phase 1: claim a pending job and populate widget data (no SVG)."""
job = db.claim_next_job()
if job is None:
return False
@@ -43,9 +87,8 @@ def process_one() -> bool:
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.put_widget_data(username, "not_found", {"not_found": True})
db.point_current_widget(username, "not_found")
db.complete_job(job["id"])
log.info("not_found marker persisted for %s", username)
return True
@@ -55,22 +98,49 @@ def process_one() -> bool:
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)
widget_data = _compute_widget_data(payload, settings_row["settings"], username)
db.put_widget_data(username, settings_row["settings_hash"], widget_data)
db.point_current_widget(username, settings_row["settings_hash"])
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)
log.info("prefetched data 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)
log.warning("prefetch failed for %s (retry=%s): %s", username, retry, e)
return True
def render_widgets_now(username: str) -> dict[str, str]:
"""Phase 2: synchronously render composite SVG and persist it.
Called from POST /api/<u>/generate. Reuses the fetcher's cached payload
(a cheap internal HTTP lookup) so the user-facing render is fast even
if the prefetch job hasn't drained from the queue yet.
"""
settings_row = db.get_settings(username)
if settings_row is None:
raise LookupError("not_enrolled")
result = fetcher_client.get_data(username)
payload = result.get("data") or {}
if payload.get("error") == "not_found":
svg = placeholder.render("not_found", username, theme=settings_row["settings"].get("theme", "dark"))
db.put_widgets(username, "not_found", {"composite": svg})
db.point_current_widget(username, "not_found")
cache.Cache().delete(f"widget:composite:{username}")
return {"composite": svg}
widgets = _render_widgets(username, payload, settings_row["settings"])
db.put_widgets(username, settings_row["settings_hash"], widgets)
db.point_current_widget(username, settings_row["settings_hash"])
c = cache.Cache()
c.delete(f"widget:composite:{username}", *[f"widget:{n}:{username}" for n in widgets])
log.info("rendered widgets on-demand for %s", username)
return widgets
def main():
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s %(message)s")
db.init_dbs()
+36 -7
View File
@@ -1,5 +1,5 @@
"""End-to-end: api + worker in-process + mocked fetcher HTTP."""
import os, tempfile
import os, tempfile, time
import pytest
import responses
from src import api as apimod, db as dbmod, worker
@@ -17,7 +17,13 @@ def env(monkeypatch):
@responses.activate
def test_first_request_builds_then_serves_ready(env):
def test_full_flow_data_then_generate_then_serve(env):
"""End-to-end of the new two-phase pipeline:
1. OAuth callback enrolls user + kicks off prefetch (worker populates widget_data)
2. /data endpoint returns widget data
3. /generate renders SVG from the cached payload + settings
4. /api/<u> serves the stored SVG to README consumers
"""
responses.add(
responses.GET, "http://fetcher-mock/data/alice",
json={"data": {"user": {"login": "alice"}, "repos": [], "events": [],
@@ -27,13 +33,36 @@ def test_first_request_builds_then_serves_ready(env):
)
client = apimod.app.test_client()
r1 = client.get("/api/alice")
assert r1.headers["X-Widget-Status"] == "building"
# Phase 1: OAuth callback enrolls user (simulated via db.enroll).
dbmod.enroll("alice", {"theme": "dark"})
# Widget data should be building right after enrollment.
r_data = client.get("/api/alice/data")
assert r_data.status_code == 202
# Drain any residual job synchronously in case the kickoff thread lost
# the race (and to make the assertion deterministic).
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")
# Widget data should now be available for client-side preview.
deadline = time.time() + 2.0
while time.time() < deadline:
r = client.get("/api/alice/data")
if r.status_code == 200 and r.get_json().get("status") == "ready":
break
time.sleep(0.05)
assert r.status_code == 200 and r.get_json()["status"] == "ready"
# Phase 2: Generate button → render SVG (with session).
with client.session_transaction() as s:
s["gh_login"] = "alice"
r_gen = client.post("/api/alice/generate", headers={"Origin": "https://gh-stats.com"})
assert r_gen.status_code == 200
assert r_gen.get_json()["status"] == "ready"
# Phase 3: SVG is served from DB.
r_svg = client.get("/api/alice")
assert r_svg.headers["X-Widget-Status"] == "ready"
assert r_svg.data.startswith(b"<svg") or r_svg.data.startswith(b"<?xml")
+209 -16
View File
@@ -2,18 +2,28 @@ import os, tempfile, pytest
from unittest.mock import patch
from src import db as dbmod
from src import api as apimod
from src import config as cfg
@pytest.fixture
def client(monkeypatch):
# No-op the kickoff so tests don't spawn background threads that
# would try to reach the (unmocked) fetcher and race tempdir teardown.
monkeypatch.setattr(apimod, "_kickoff_prefetch_async", lambda *_a, **_kw: None)
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()
# Configure OAuth fixture with allowed origins and insecure cookies for testing.
monkeypatch.setattr(cfg, "ALLOWED_ORIGINS", ("https://gh-stats.com",))
app = apimod.app
app.config["TESTING"] = True
app.config["SESSION_COOKIE_SECURE"] = False
with app.test_client() as c:
yield c
# Clear rate limit state after each test to prevent pollution.
apimod._rate_hits.clear()
apimod._rate_hits_per_login.clear()
def test_health(client):
@@ -22,27 +32,28 @@ def test_health(client):
assert r.get_json()["service"] == "generator"
def test_get_unknown_user_auto_enrolls_and_returns_placeholder(client):
def test_get_unknown_user_returns_building_placeholder_without_enrolling(client):
"""The SVG endpoint is for README embeds — enrollment is frontend-driven
through /data or /api/enroll, so GET /api/<u> does not auto-enroll."""
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
assert dbmod.get_settings("alice") is 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_but_not_generated_returns_building(client):
"""After enrollment (via /data) but before /generate is clicked the SVG
endpoint returns a building placeholder."""
dbmod.enroll("alice", {"theme": "dark"})
r = client.get("/api/alice")
assert r.headers["X-Widget-Status"] == "building"
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()
dbmod.point_current_widget("alice", "h1")
r = client.get("/api/alice")
assert r.status_code == 200
assert r.headers["X-Widget-Status"] == "ready"
@@ -51,25 +62,207 @@ def test_enrolled_user_with_built_widget_returns_ready(client):
def test_settings_patch_enqueues_rebuild(client):
dbmod.enroll("alice", {"theme": "dark"})
r = client.patch("/api/alice/settings", json={"theme": "light"})
with client.session_transaction() as s:
s["gh_login"] = "alice"
r = client.patch(
"/api/alice/settings",
json={"theme": "light"},
headers={"Origin": "https://gh-stats.com"},
)
assert r.status_code == 200
assert dbmod.get_settings("alice")["settings"]["theme"] == "light"
def test_settings_patch_without_origin_is_unauthorized(client):
dbmod.enroll("alice", {"theme": "dark"})
with client.session_transaction() as s:
s["gh_login"] = "alice"
r = client.patch("/api/alice/settings", json={"theme": "light"})
assert r.status_code == 403
# Settings must not be mutated when the origin check fails.
assert dbmod.get_settings("alice")["settings"]["theme"] == "dark"
def test_patch_settings_without_session_is_401(client):
dbmod.enroll("alice", {"theme": "dark"})
r = client.patch("/api/alice/settings", json={"theme": "light"},
headers={"Origin": "https://gh-stats.com"})
assert r.status_code == 401
def test_patch_settings_wrong_login_is_403(client):
dbmod.enroll("alice", {"theme": "dark"})
with client.session_transaction() as s:
s["gh_login"] = "bob"
r = client.patch("/api/alice/settings", json={"theme": "light"},
headers={"Origin": "https://gh-stats.com"})
assert r.status_code == 403
def test_patch_settings_matching_login_succeeds(client):
dbmod.enroll("alice", {"theme": "dark"})
with client.session_transaction() as s:
s["gh_login"] = "alice"
r = client.patch("/api/alice/settings", json={"theme": "light"},
headers={"Origin": "https://gh-stats.com"})
assert r.status_code == 200
def test_patch_settings_bad_origin_is_403(client):
dbmod.enroll("alice", {"theme": "dark"})
with client.session_transaction() as s:
s["gh_login"] = "alice"
r = client.patch("/api/alice/settings", json={"theme": "light"},
headers={"Origin": "https://evil.example"})
assert r.status_code == 403
def test_refresh_is_one_shot(client):
dbmod.enroll("alice", {"theme": "dark"})
with client.session_transaction() as s:
s["gh_login"] = "alice"
with patch("src.api.fetcher_client.force_fetch", return_value={"changed": True, "payload_hash": "x", "stored": True}):
r1 = client.post("/api/alice/refresh")
r1 = client.post("/api/alice/refresh", headers={"Origin": "https://gh-stats.com"})
assert r1.status_code == 200
r2 = client.post("/api/alice/refresh")
r2 = client.post("/api/alice/refresh", headers={"Origin": "https://gh-stats.com"})
assert r2.status_code == 409
def test_refresh_without_token_is_unauthorized(client):
"""Old test name; now tests without session but with proper Origin."""
dbmod.enroll("alice", {"theme": "dark"})
r = client.post("/api/alice/refresh", headers={"Origin": "https://gh-stats.com"})
assert r.status_code == 401
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()
dbmod.point_current_widget("ghost", "not_found")
r = client.get("/api/ghost")
assert r.headers["X-Widget-Status"] == "not_found"
def test_generate_endpoint_renders_and_stores_svg(client):
"""POST /api/<u>/generate invokes the on-demand render path and caches
the composite SVG for subsequent README embeds."""
dbmod.enroll("alice", {"theme": "dark"})
with client.session_transaction() as s:
s["gh_login"] = "alice"
with patch("src.worker.render_widgets_now",
return_value={"composite": "<svg>r</svg>", "grade": "<svg>g</svg>"}):
# Simulate the render path also updating current_widget so the
# follow-up GET sees ready.
def fake_render(username):
dbmod.put_widgets(username, "h1", {"composite": "<svg>r</svg>"})
dbmod.point_current_widget(username, "h1")
return {"composite": "<svg>r</svg>"}
with patch("src.worker.render_widgets_now", side_effect=fake_render):
r = client.post("/api/alice/generate", headers={"Origin": "https://gh-stats.com"})
assert r.status_code == 200
body = r.get_json()
assert body["status"] == "ready"
assert body["composite_url"] == "/api/alice"
r2 = client.get("/api/alice")
assert r2.headers["X-Widget-Status"] == "ready"
assert b"<svg>r</svg>" in r2.data
def test_generate_endpoint_rejects_unenrolled(client):
"""With OAuth, unenrolled means having a session but no profile."""
with client.session_transaction() as s:
s["gh_login"] = "bob"
r = client.post("/api/bob/generate", headers={"Origin": "https://gh-stats.com"})
assert r.status_code == 404
# ---- GET /api/<username>/data: precomputed widget data for client-side rendering ----
# Pure DB lookup — fetcher is never touched on the hot path.
def test_data_endpoint_enrolled_but_unbuilt_returns_building(client):
dbmod.enroll("alice", {"theme": "dark"})
r = client.get("/api/alice/data")
assert r.status_code == 202
assert r.get_json() == {"status": "building"}
def test_data_endpoint_returns_ready_after_build(client):
dbmod.enroll("alice", {"theme": "dark"})
sample = {"grade": {"grade": "A", "score": 80, "stats": {}, "tags": [], "breakdown": {}}}
dbmod.put_widget_data("alice", "h1", sample)
with dbmod._widgets_conn() as c:
c.execute(
"""INSERT INTO current_widget(username, settings_hash, updated_at)
VALUES ('alice', 'h1', '2026-04-18T00:00:00Z')
ON CONFLICT(username) DO UPDATE SET settings_hash=excluded.settings_hash""")
c.commit()
r = client.get("/api/alice/data")
assert r.status_code == 200
body = r.get_json()
assert body["status"] == "ready"
assert body["data"] == sample
def test_data_endpoint_returns_not_found_for_unknown_github_user(client):
dbmod.enroll("ghost", {"theme": "dark"})
dbmod.put_widget_data("ghost", "not_found", {"not_found": True})
with dbmod._widgets_conn() as c:
c.execute(
"""INSERT INTO current_widget(username, settings_hash, updated_at)
VALUES ('ghost', 'not_found', '2026-04-18T00:00:00Z')
ON CONFLICT(username) DO UPDATE SET settings_hash=excluded.settings_hash""")
c.commit()
r = client.get("/api/ghost/data")
assert r.status_code == 404
assert r.get_json()["status"] == "not_found"
def test_generate_without_session_is_401(client):
dbmod.enroll("alice", {"theme": "dark"})
r = client.post("/api/alice/generate", headers={"Origin": "https://gh-stats.com"})
assert r.status_code == 401
def test_generate_wrong_login_is_403(client):
dbmod.enroll("alice", {"theme": "dark"})
with client.session_transaction() as s:
s["gh_login"] = "bob"
r = client.post("/api/alice/generate", headers={"Origin": "https://gh-stats.com"})
assert r.status_code == 403
def test_refresh_without_session_is_401(client):
dbmod.enroll("alice", {"theme": "dark"})
r = client.post("/api/alice/refresh", headers={"Origin": "https://gh-stats.com"})
assert r.status_code == 401
def test_data_unknown_user_returns_404(client):
r = client.get("/api/testuser/data")
assert r.status_code == 404
def test_enroll_endpoint_is_gone(client):
r = client.post("/api/enroll", json={"username": "alice"},
headers={"Origin": "https://gh-stats.com"})
assert r.status_code == 405
def test_per_login_mutate_rate_limit(client, monkeypatch):
"""Per-login rate limit on mutate routes allows up to MAX requests,
then rejects with 429."""
monkeypatch.setattr(cfg, "RATE_LIMIT_MUTATE_PER_LOGIN_MAX", 2)
monkeypatch.setattr(cfg, "RATE_LIMIT_MUTATE_PER_LOGIN_WINDOW", 60)
dbmod.enroll("alice", {"theme": "dark"})
with client.session_transaction() as s:
s["gh_login"] = "alice"
h = {"Origin": "https://gh-stats.com"}
# First two requests should succeed.
r1 = client.patch("/api/alice/settings", json={}, headers=h)
assert r1.status_code == 200
r2 = client.patch("/api/alice/settings", json={}, headers=h)
assert r2.status_code == 200
# Third request should be rate-limited.
r3 = client.patch("/api/alice/settings", json={}, headers=h)
assert r3.status_code == 429
+173
View File
@@ -0,0 +1,173 @@
"""Unit tests for auth helpers (no network)."""
import pytest
from flask import Flask, jsonify
from src import auth, config
@pytest.fixture
def app(monkeypatch):
monkeypatch.setattr(config, "ALLOWED_ORIGINS", ("https://gh-stats.com",))
app = Flask(__name__)
app.secret_key = "test-secret"
@app.route("/protected/<username>", methods=["POST"])
@auth.require_same_origin
@auth.require_github_owner
def protected(username):
return jsonify({"ok": True, "you": auth.current_login()})
return app
def _good_hdrs():
return {"Origin": "https://gh-stats.com"}
def test_current_login_none_by_default(app):
with app.test_request_context("/"):
assert auth.current_login() is None
def test_require_github_owner_401_without_session(app):
with app.test_client() as c:
r = c.post("/protected/alice", headers=_good_hdrs())
assert r.status_code == 401
assert r.get_json()["error"] == "login_required"
def test_require_github_owner_403_on_mismatch(app):
with app.test_client() as c:
with c.session_transaction() as s:
s["gh_login"] = "bob"
r = c.post("/protected/alice", headers=_good_hdrs())
assert r.status_code == 403
def test_require_github_owner_passes_with_matching_login(app):
with app.test_client() as c:
with c.session_transaction() as s:
s["gh_login"] = "Alice" # stored mixed-case on purpose
r = c.post("/protected/alice", headers=_good_hdrs())
assert r.status_code == 200
assert r.get_json()["you"] == "alice"
def test_require_same_origin_rejects_bad_origin(app):
with app.test_client() as c:
with c.session_transaction() as s:
s["gh_login"] = "alice"
r = c.post("/protected/alice", headers={"Origin": "https://evil.example"})
assert r.status_code == 403
def test_require_same_origin_rejects_missing_origin(app):
with app.test_client() as c:
with c.session_transaction() as s:
s["gh_login"] = "alice"
r = c.post("/protected/alice")
assert r.status_code == 403
from src import api as api_module
@pytest.fixture
def api_client(monkeypatch, tmp_path):
# Point DBs at tmp + configure origins.
from src import db as dbmod, config as cfg
monkeypatch.setattr(cfg, "SETTINGS_DB_PATH", str(tmp_path / "s.db"))
monkeypatch.setattr(cfg, "WIDGETS_DB_PATH", str(tmp_path / "w.db"))
monkeypatch.setattr(dbmod, "SETTINGS_DB_PATH", str(tmp_path / "s.db"))
monkeypatch.setattr(dbmod, "WIDGETS_DB_PATH", str(tmp_path / "w.db"))
dbmod.init_dbs()
monkeypatch.setattr(cfg, "ALLOWED_ORIGINS", ("https://gh-stats.com",))
api_module.app.config["TESTING"] = True
api_module.app.config["SESSION_COOKIE_SECURE"] = False
return api_module.app.test_client()
def test_me_unauthed_returns_null(api_client):
r = api_client.get("/api/auth/me")
assert r.status_code == 200
assert r.get_json() == {"login": None}
def test_me_authed_returns_login(api_client):
with api_client.session_transaction() as s:
s["gh_login"] = "alice"
s["gh_avatar_url"] = "https://x/a.png"
r = api_client.get("/api/auth/me")
assert r.status_code == 200
j = r.get_json()
assert j["login"] == "alice"
assert j["avatar_url"] == "https://x/a.png"
def test_logout_clears_session(api_client):
with api_client.session_transaction() as s:
s["gh_login"] = "alice"
r = api_client.post("/api/auth/logout", headers={"Origin": "https://gh-stats.com"})
assert r.status_code == 204
r = api_client.get("/api/auth/me")
assert r.get_json()["login"] is None
def test_logout_rejects_bad_origin(api_client):
with api_client.session_transaction() as s:
s["gh_login"] = "alice"
r = api_client.post("/api/auth/logout", headers={"Origin": "https://evil.example"})
assert r.status_code == 403
def test_login_stashes_state_and_redirects(api_client):
"""Don't depend on authlib's exact redirect URL — just confirm the route
stashes a random state, records the next path, and returns a 3xx."""
r = api_client.get("/api/auth/github/login?next=/workshop")
assert r.status_code in (302, 303)
with api_client.session_transaction() as s:
assert s.get("oauth_state")
assert s.get("oauth_next") == "/workshop"
def test_login_rejects_external_next(api_client):
r = api_client.get("/api/auth/github/login?next=https://evil.example/foo")
assert r.status_code in (302, 303)
with api_client.session_transaction() as s:
assert s.get("oauth_next") == "/"
def test_callback_state_mismatch_400(api_client):
with api_client.session_transaction() as s:
s["oauth_state"] = "correct"
r = api_client.get("/api/auth/github/callback?code=abc&state=wrong")
assert r.status_code == 400
def test_callback_happy_path_sets_session(api_client, monkeypatch):
"""End-to-end callback: stub token exchange + /user, verify session state."""
from src import auth as authmod, db as dbmod
# Pre-populate session with matching state
with api_client.session_transaction() as s:
s["oauth_state"] = "good-state"
s["oauth_next"] = "/"
# Stub authlib's token exchange
def fake_authorize_access_token(**_kwargs):
return {"access_token": "ghs_abc", "token_type": "bearer"}
monkeypatch.setattr(authmod.github_client(), "authorize_access_token", fake_authorize_access_token)
# Stub the GitHub /user call
import src.api as apimod
monkeypatch.setattr(apimod, "_gh_api_get",
lambda token, path: {"id": 123, "login": "Alice", "avatar_url": "https://x/a.png"})
r = api_client.get("/api/auth/github/callback?code=abc&state=good-state")
assert r.status_code in (302, 303)
assert r.headers["Location"].endswith("/")
with api_client.session_transaction() as s:
assert s["gh_login"] == "alice"
assert s["gh_id"] == 123
assert s["gh_avatar_url"] == "https://x/a.png"
# Row should now exist with github profile populated.
assert dbmod.get_settings("alice") is not None
+70 -10
View File
@@ -19,13 +19,24 @@ def test_settings_hash_is_deterministic():
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_enroll_returns_job_id(tmp_dbs):
r = dbmod.enroll("alice", {"theme": "dark"})
assert r["job_id"] > 0
assert "edit_token" not in r
def test_enroll_twice_noops(tmp_dbs):
r1 = dbmod.enroll("alice", {"theme": "dark"})
r2 = dbmod.enroll("alice", {"theme": "dark"})
assert r1["job_id"] > 0 and r2["job_id"] > 0
def test_enroll_with_github_profile(tmp_dbs):
dbmod.enroll("alice", {"theme": "dark"}, github_id=1, github_avatar_url="https://x/a.png")
with dbmod._settings_conn() as c:
row = c.execute("SELECT github_id, github_avatar_url FROM users WHERE username='alice'").fetchone()
assert row["github_id"] == 1
assert row["github_avatar_url"] == "https://x/a.png"
def test_enrollments_daily_counter(tmp_dbs):
@@ -43,7 +54,7 @@ def test_update_settings_changes_hash(tmp_dbs):
def test_claim_job_marks_running(tmp_dbs):
job_id = dbmod.enroll("alice", {"theme": "dark"})
job_id = dbmod.enroll("alice", {"theme": "dark"})["job_id"]
job = dbmod.claim_next_job()
assert job["id"] == job_id
assert job["status"] == "running"
@@ -51,7 +62,7 @@ def test_claim_job_marks_running(tmp_dbs):
def test_complete_job(tmp_dbs):
jid = dbmod.enroll("alice", {"theme": "dark"})
jid = dbmod.enroll("alice", {"theme": "dark"})["job_id"]
dbmod.claim_next_job()
dbmod.complete_job(jid)
with dbmod._settings_conn() as c:
@@ -81,7 +92,7 @@ def test_lru_trim_keeps_n_newest(tmp_dbs):
def test_reclaim_stuck_running_jobs(tmp_dbs):
jid = dbmod.enroll("alice", {"theme": "dark"})
jid = dbmod.enroll("alice", {"theme": "dark"})["job_id"]
dbmod.claim_next_job()
# Backdate updated_at to simulate dead worker
with dbmod._settings_conn() as c:
@@ -90,3 +101,52 @@ def test_reclaim_stuck_running_jobs(tmp_dbs):
dbmod.reclaim_stuck_jobs(older_than_minutes=10)
job = dbmod.claim_next_job()
assert job["id"] == jid
def test_set_github_profile_round_trip(tmp_dbs):
dbmod.enroll("alice", {"theme": "dark"})
dbmod.set_github_profile("alice", github_id=42, github_avatar_url="https://example.com/a.png")
with dbmod._settings_conn() as c:
row = c.execute("SELECT github_id, github_avatar_url FROM users WHERE username='alice'").fetchone()
assert row["github_id"] == 42
assert row["github_avatar_url"] == "https://example.com/a.png"
def test_get_user_streak_missing_returns_none(tmp_dbs):
assert dbmod.get_user_streak("nobody") is None
def test_put_and_get_user_streak_roundtrip(tmp_dbs):
dbmod.put_user_streak("alice", {
"current_streak": 12,
"current_start": "2026-04-08",
"last_active_date": "2026-04-19",
"max_streak": 42,
"max_start": "2025-11-01",
"max_end": "2025-12-12",
})
row = dbmod.get_user_streak("alice")
assert row["current_streak"] == 12
assert row["current_start"] == "2026-04-08"
assert row["last_active_date"] == "2026-04-19"
assert row["max_streak"] == 42
assert row["max_start"] == "2025-11-01"
assert row["max_end"] == "2025-12-12"
assert row["updated_at"] # set on write
def test_put_user_streak_upserts(tmp_dbs):
dbmod.put_user_streak("alice", {
"current_streak": 1, "current_start": "2026-04-19",
"last_active_date": "2026-04-19",
"max_streak": 1, "max_start": "2026-04-19", "max_end": "2026-04-19",
})
dbmod.put_user_streak("alice", {
"current_streak": 2, "current_start": "2026-04-18",
"last_active_date": "2026-04-19",
"max_streak": 5, "max_start": "2024-01-01", "max_end": "2024-01-05",
})
row = dbmod.get_user_streak("alice")
assert row["current_streak"] == 2
assert row["max_streak"] == 5
assert row["max_start"] == "2024-01-01"
+180
View File
@@ -0,0 +1,180 @@
from datetime import date, timedelta
from unittest.mock import patch
import pytest
from src import processor
from src.models import StreakData
TODAY = date(2026, 4, 19)
@pytest.fixture
def freeze_today(monkeypatch):
"""Pin processor's notion of 'today' so the grace rule is testable."""
class _FakeDatetime:
@staticmethod
def utcnow():
from datetime import datetime
return datetime(TODAY.year, TODAY.month, TODAY.day, 12, 0, 0)
monkeypatch.setattr(processor, "datetime", _FakeDatetime)
return TODAY
def _days(dates):
"""Turn a list of date objects into the fetcher's commits-array shape."""
return [{"date": d.isoformat(), "count": 1} for d in dates]
def test_compute_streaks_empty_preserves_stored_max(freeze_today):
stored = {
"max_streak": 30, "max_start": "2024-06-01", "max_end": "2024-06-30",
"current_streak": 0, "current_start": "",
"last_active_date": "2024-06-30",
}
s = processor.compute_streaks({"commits": []}, stored)
assert s.current == 0
assert s.max == 30
assert s.max_start == "2024-06-01"
assert s.max_end == "2024-06-30"
def test_compute_streaks_current_today(freeze_today):
dates = [freeze_today - timedelta(days=i) for i in range(5)]
s = processor.compute_streaks({"commits": _days(dates)}, None)
assert s.current == 5
assert s.current_start == (freeze_today - timedelta(days=4)).isoformat()
assert s.last_active_date == freeze_today.isoformat()
def test_compute_streaks_grace_day(freeze_today):
yesterday = freeze_today - timedelta(days=1)
dates = [yesterday - timedelta(days=i) for i in range(4)]
s = processor.compute_streaks({"commits": _days(dates)}, None)
assert s.current == 4
assert s.current_start == (yesterday - timedelta(days=3)).isoformat()
assert s.last_active_date == yesterday.isoformat()
def test_compute_streaks_current_broken(freeze_today):
two_days_ago = freeze_today - timedelta(days=2)
dates = [two_days_ago - timedelta(days=i) for i in range(10)]
s = processor.compute_streaks({"commits": _days(dates)}, None)
assert s.current == 0
assert s.current_start == ""
assert s.last_active_date == two_days_ago.isoformat()
def test_compute_streaks_max_within_window_beats_stored(freeze_today):
start = freeze_today - timedelta(days=30)
dates = [start + timedelta(days=i) for i in range(10)]
stored = {
"max_streak": 5, "max_start": "2020-01-01", "max_end": "2020-01-05",
"current_streak": 0, "current_start": "", "last_active_date": "",
}
s = processor.compute_streaks({"commits": _days(dates)}, stored)
assert s.max == 10
assert s.max_start == start.isoformat()
assert s.max_end == (start + timedelta(days=9)).isoformat()
def test_compute_streaks_stored_max_preserved(freeze_today):
start = freeze_today - timedelta(days=10)
dates = [start + timedelta(days=i) for i in range(3)]
stored = {
"max_streak": 50, "max_start": "2023-04-01", "max_end": "2023-05-20",
"current_streak": 0, "current_start": "", "last_active_date": "",
}
s = processor.compute_streaks({"commits": _days(dates)}, stored)
assert s.max == 50
assert s.max_start == "2023-04-01"
assert s.max_end == "2023-05-20"
def test_compute_streaks_current_equals_new_max(freeze_today):
dates = [freeze_today - timedelta(days=i) for i in range(100)]
s = processor.compute_streaks({"commits": _days(dates)}, None)
assert s.current == 100
assert s.max == 100
assert s.max_end == freeze_today.isoformat()
def test_compute_streaks_ignores_zero_count_entries(freeze_today):
dates = [freeze_today - timedelta(days=i) for i in range(3)]
commits = _days(dates) + [{"date": (freeze_today - timedelta(days=5)).isoformat(), "count": 0}]
s = processor.compute_streaks({"commits": commits}, None)
assert s.current == 3
assert s.max == 3
from src.widgets import render_streaks_widget
def test_render_streaks_contains_values():
data = StreakData(
current=7, max=42,
current_start="2026-04-13", last_active_date="2026-04-19",
max_start="2024-03-01", max_end="2024-04-11",
)
svg = render_streaks_widget(data, theme_name="dark")
assert svg.startswith("<svg")
assert "</svg>" in svg
assert ">7<" in svg
assert ">42<" in svg
assert "Current" in svg
assert "Longest" in svg
def test_render_streaks_zero_values_render():
data = StreakData(current=0, max=0)
svg = render_streaks_widget(data, theme_name="dark")
assert ">0<" in svg
assert "Current" in svg
assert "Longest" in svg
def test_render_streaks_hides_dates_when_disabled():
data = StreakData(
current=7, max=42,
current_start="2026-04-13", last_active_date="2026-04-19",
max_start="2024-03-01", max_end="2024-04-11",
)
svg = render_streaks_widget(data, theme_name="dark", settings={"show_dates": False})
assert "2026-04-13" not in svg
assert "2024-03-01" not in svg
def test_generate_widgets_includes_streaks_when_enabled(freeze_today):
from datetime import timedelta
dates = [freeze_today - timedelta(days=i) for i in range(4)]
payload = {
"user": {"login": "alice"},
"repos": [],
"events": [],
"commits": _days(dates),
"total_commits": 4, "recent_commits": 4, "total_prs": 0,
"collaborators_data": [],
}
widgets = processor.generate_widgets_from_github(
payload, theme="dark", enabled=["streaks"],
)
assert "streaks" in widgets
assert ">4<" in widgets["streaks"]
def test_generate_widgets_uses_stored_streak(freeze_today):
payload = {
"user": {"login": "alice"}, "repos": [], "events": [],
"commits": [],
"total_commits": 0, "recent_commits": 0, "total_prs": 0,
"collaborators_data": [],
}
stored = {
"max_streak": 99, "max_start": "2022-01-01", "max_end": "2022-04-09",
"current_streak": 0, "current_start": "", "last_active_date": "",
}
widgets = processor.generate_widgets_from_github(
payload, theme="dark", enabled=["streaks"], stored_streak=stored,
)
assert ">99<" in widgets["streaks"]
+86 -8
View File
@@ -13,27 +13,50 @@ def tmp_dbs(monkeypatch):
yield d
def test_process_one_renders_and_stores_widgets(tmp_dbs):
def test_process_one_stores_widget_data_without_rendering_svg(tmp_dbs):
"""Phase 1 worker only hydrates widget_data; SVGs are rendered by the
/generate endpoint."""
dbmod.enroll("alice", {"theme": "dark", "enabled": ["grade"]})
fake_payload = {"user": {"login": "alice"}, "repos": [], "events": [],
"commits": [], "total_commits": 0, "recent_commits": [],
"commits": [], "total_commits": 0, "recent_commits": 0,
"total_prs": 0, "collaborators_data": [], "avatar_b64": ""}
fake_data = {"grade": {"grade": "A", "score": 80, "stats": {}, "tags": [], "breakdown": {}}}
with patch("src.worker.fetcher_client.get_data",
return_value={"data": fake_payload, "payload_hash": "h1"}), \
patch("src.worker._compute_widget_data", return_value=fake_data):
worker.process_one()
# Widget data is stored for the client-side preview.
row = dbmod.get_current_widget_data("alice")
assert row is not None and row["data"] == fake_data
# SVGs are NOT rendered yet — /generate hasn't been called.
assert dbmod.get_current_widget("alice", "composite") is None
def test_render_widgets_now_produces_svg(tmp_dbs):
"""Phase 2: /generate endpoint path renders composite SVG on demand."""
dbmod.enroll("alice", {"theme": "dark", "enabled": ["grade"]})
fake_payload = {"user": {"login": "alice"}, "repos": [], "events": [],
"commits": [], "total_commits": 0, "recent_commits": 0,
"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>"
widgets = worker.render_widgets_now("alice")
assert widgets["composite"] == "<svg>c</svg>"
assert dbmod.get_current_widget("alice", "composite") == "<svg>c</svg>"
def test_not_found_payload_renders_not_found_placeholder(tmp_dbs):
def test_not_found_payload_marks_not_found_in_data(tmp_dbs):
"""Worker records a not_found sentinel in widget_data; SVG placeholder
is rendered at request time by /api/<u>, not by the worker."""
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
assert dbmod.get_current_widget_hash("ghost") == "not_found"
row = dbmod.get_current_widget_data("ghost")
assert row is not None and row["data"] == {"not_found": True}
def test_worker_retries_on_fetcher_failure(tmp_dbs):
@@ -56,3 +79,58 @@ def test_worker_marks_failed_after_max_attempts(tmp_dbs):
row = c.execute("SELECT status, attempts FROM jobs WHERE username='alice'").fetchone()
assert row["status"] == "failed"
assert row["attempts"] >= 3
def test_process_one_persists_streak(tmp_dbs):
"""Phase 1 worker must compute and persist the user's streak so max survives
future settings changes."""
from datetime import date, timedelta
today = date.today()
dates = [today - timedelta(days=i) for i in range(3)]
dbmod.enroll("alice", {"theme": "dark", "enabled": ["streaks"]})
fake_payload = {
"user": {"login": "alice"}, "repos": [], "events": [],
"commits": [{"date": d.isoformat(), "count": 1} for d in dates],
"total_commits": 3, "recent_commits": 3, "total_prs": 0,
"collaborators_data": [], "avatar_b64": "",
}
with patch("src.worker.fetcher_client.get_data",
return_value={"data": fake_payload, "payload_hash": "h1"}):
worker.process_one()
row = dbmod.get_user_streak("alice")
assert row is not None
assert row["current_streak"] == 3
assert row["max_streak"] == 3
assert row["last_active_date"] == today.isoformat()
def test_process_one_merges_stored_max(tmp_dbs):
"""A stored max of 50 must survive a refresh whose window max is only 2."""
from datetime import date, timedelta
today = date.today()
dbmod.enroll("alice", {"theme": "dark", "enabled": ["streaks"]})
dbmod.put_user_streak("alice", {
"current_streak": 0, "current_start": "",
"last_active_date": "2023-01-15",
"max_streak": 50,
"max_start": "2023-01-01", "max_end": "2023-02-19",
})
dates = [today - timedelta(days=i) for i in range(2)]
fake_payload = {
"user": {"login": "alice"}, "repos": [], "events": [],
"commits": [{"date": d.isoformat(), "count": 1} for d in dates],
"total_commits": 2, "recent_commits": 2, "total_prs": 0,
"collaborators_data": [], "avatar_b64": "",
}
with patch("src.worker.fetcher_client.get_data",
return_value={"data": fake_payload, "payload_hash": "h1"}):
worker.process_one()
row = dbmod.get_user_streak("alice")
assert row["max_streak"] == 50
assert row["max_start"] == "2023-01-01"
assert row["current_streak"] == 2