Skip to content

Refactor: Modularize Scoring Engine, Unify Persistence Pipeline, and Streamline Comparison State - #215

Merged
O2sa merged 7 commits into
mainfrom
refactor/scoring-engine
Sep 14, 2026
Merged

O2sa merged 7 commits into
mainfrom
refactor/scoring-engine

Conversation

@O2sa

@O2sa O2sa commented Sep 14, 2026

Copy link
Copy Markdown
Owner

Summary of Changes

This PR executes a full architectural refactoring to remove duplicate logic, isolate domain boundaries, and improve maintainability while preserving 100% backward compatibility:

  1. Unified Scoring & Persistence Pipeline:

    • Created persistUserScores in src/features/developer/services/user-persistence.ts to coordinate canonical score computation, PostgreSQL upserts, and Redis cache invalidation in a single place.
    • Decoupled github-client.ts by removing cross-boundary dynamic imports of database and scoring internals.
    • Refactored user-service.ts, compare-service.ts, and calculate-leaderboard.ts to use persistUserScores.
  2. Scoring Engine Modularization:

    • Split score-engine.ts into isolated modules:
      • scoring-constants.ts: Weights, thresholds, and explanations
      • scoring-helpers.ts: Math utilities (safeLog, roundScore, date normalization)
      • repo-scoring.ts: Repository score breakdown and language weights
      • pr-scoring.ts: Pull request decay, size penalties, and author association logic
      • community-scoring.ts: Issues and discussions scoring
      • score-engine.ts: Lightweight coordinator (~320 lines)
  3. API Boilerplate Deduplication:

    • Created @/lib/api helpers (formatApiErrorResponse, parseSelectedLanguagesFromSearchParams).
    • Simplified /api/user/[username] (105 → 30 lines) and /api/compare (101 → 36 lines).
    • Removed await db.initializeSchema() DDL operations from leaderboard-service.ts hot read path.
    • Strongly typed raw_data and scores in db-store.ts.
  4. Frontend State Architecture:

    • Extracted useComparisonController hook to handle comparison requests, race conditions, in-flight promises, duplicate fetch prevention, and URL sync.
    • Streamlined home-page-client.tsx from 545 lines down to 125 lines.
    • Created useClipboardCopy hook with automatic timeout cleanup and integrated it into user-profile-client.tsx and result-dashboard.tsx.
    • Fixed translation placeholder interpolation in provider-hook.ts.
    • Wrapped SSR profile fetches in React.cache() for generateMetadata and page component deduplication.

Verification

  • TypeScript: npx tsc --noEmit passed with 0 errors.
  • Vitest: npx vitest run passed with all 15 test files and 117 tests green.

…umentation

- Reorganized codebase under `src/` following a Feature-Driven Scalable Next.js Architecture:
  - `src/features/` (domain modules: comparison, developer, leaderboard, scoring with colocated components, services, tests, types, and barrel exports)
  - `src/lib/` (infrastructure adapters: cache, db, geo, github, i18n, logger, seo)
  - `src/components/` (shared domain-agnostic UI: ui, layout, providers, seo)
  - `src/app/` (thin routing controllers, layouts, and API routes)
  - `src/locales/`, `src/data/`, `src/types/`, `src/utils/`
- Updated path aliases in `tsconfig.json`, `tailwind.config.ts`, and `vitest.config.ts` (`@/features/*`, `@/lib/*`, `@/components/*`, etc.).
- Updated script paths in `scripts/calculate-next-country.ts`, `scripts/init-db.ts`, and `scripts/validate-locales.js`.
- Created comprehensive `ARCHITECTURE.md` documentation detailing system design, sequence flows, encapsulation rules, and step-by-step contributor cookbooks.
- Updated `README.md`, `CONTRIBUTING.md`, and `algorithm.md` to align with the new architecture.
- Replaced hardcoded machine/absolute paths in markdown files with relative paths.
…ize responsive layout

- Move and unify shared work cards (RepoCardItem, PullRequestCardItem, CommunityCardItem, ScoreCard) under global src/components/cards/
- Fix client/server barrel boundary separation in feature index exports to avoid leaking server-only dependencies (pg, redis, dns) into client bundles
- Restructure Profile Top Work section into a responsive 1-column (mobile) and max 2-column (desktop) grid with balanced community card spanning
- Enable text wrapping with break-words leading-snug for repository and PR titles to prevent awkward truncation
- Add GitHub Linguist language color palette supporting 150+ programming languages with alias normalization and deterministic HSL fallback
- Update LanguageBreakdown and SelectedLanguageRow components to render official GitHub color bars and indicators
- Add comprehensive unit test suite for language colors (15 suites / 117 tests passing)
…streamline comparison state

- Core Domain Pipeline:
  - Introduce `persistUserScores` in `user-persistence.ts` as the canonical persistence pipeline
  - Eliminate duplicate DB upsert and Redis invalidation logic across `user-service`, `compare-service`, and `calculate-leaderboard`
  - Remove cross-boundary dynamic imports of `db` and `score-engine` from `github-client`

- Scoring Engine Modularization:
  - Decompose monolithic 1,230-line `score-engine.ts` into focused sub-calculators (`repo-scoring`, `pr-scoring`, `community-scoring`, `scoring-constants`, `scoring-helpers`)
  - Preserve 100% backward compatibility and exact mathematical output

- API & Routes:
  - Unify API error handling and search parameter parsing into `src/lib/api`
  - Reduce route handler boilerplate by ~70% across `/api/user/[username]` and `/api/compare`
  - Remove `initializeSchema()` DDL overhead from hot read path in `leaderboard-service`
  - Add strong generic typing to `db-store` rows and upsert params

- Frontend State & Polish:
  - Extract comparison orchestration into `useComparisonController` hook, slimming `home-page-client.tsx` from 545 to 125 lines
  - Introduce reusable `useClipboardCopy` hook with timeout cleanup in profile and comparison dashboards
  - Fix template placeholder replacement in `provider-hook.ts`
  - Deduplicate SSR profile fetches between `generateMetadata` and `UserProfilePage` using `React.cache()`
@vercel

vercel Bot commented Sep 14, 2026

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
dev-impact Ready Ready Preview Sep 14, 2026 11:01pm UTC

@O2sa
O2sa merged commit 7a1591b into main Sep 14, 2026
7 checks passed
@O2sa

O2sa commented Sep 14, 2026

Copy link
Copy Markdown
Owner Author

Thank you, @O2sa! Another great contribution merged! 🚀

You've been a fantastic contributor! We truly appreciate your continued support.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant