Skip to content

Commit 4d8c295

Browse files
committed
fix: sincronizacion de repos
1 parent cca0ea9 commit 4d8c295

13 files changed

Lines changed: 606 additions & 273 deletions

File tree

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
-- 0014 — Estado de sincronización (backfill del historial) por repo, para mostrar progreso en el
2+
-- dashboard. Hasta ahora el backfill era una caja negra (se encolaba y corría en segundo plano sin
3+
-- señal); estas columnas lo hacen visible: la UI muestra en cola → sincronizando (barra) → listo.
4+
-- sync_status: idle | queued | syncing | done | error
5+
-- sync_pages / sync_commits: progreso de la corrida actual (páginas de 100 procesadas / commits persistidos)
6+
-- sync_total_pages: total estimado de páginas (del header Link de GitHub); null = progreso indeterminado
7+
-- sync_error: último error (solo cuando status=error, tras agotar reintentos)
8+
alter table roz.project_repo
9+
add column if not exists sync_status text not null default 'idle',
10+
add column if not exists sync_pages int not null default 0,
11+
add column if not exists sync_commits int not null default 0,
12+
add column if not exists sync_total_pages int,
13+
add column if not exists sync_error text,
14+
add column if not exists sync_started_at timestamptz,
15+
add column if not exists sync_updated_at timestamptz;

‎src/adapters/github.ts‎

Lines changed: 111 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,11 @@ function encRepo(repo: string): string {
1111
}
1212

1313
async function gh<T>(path: string): Promise<T> {
14+
return (await ghRes<T>(path)).data;
15+
}
16+
17+
/** Igual que gh() pero devuelve también los headers (para leer el `Link` de paginación). */
18+
async function ghRes<T>(path: string): Promise<{ data: T; headers: Headers }> {
1419
const res = await fetch(`${API}${path}`, {
1520
headers: {
1621
authorization: `Bearer ${config.github.token}`,
@@ -19,7 +24,37 @@ async function gh<T>(path: string): Promise<T> {
1924
},
2025
});
2126
if (!res.ok) throw new Error(`GitHub API error ${res.status}: ${await res.text()}`);
22-
return (await res.json()) as T;
27+
return { data: (await res.json()) as T, headers: res.headers };
28+
}
29+
30+
/** Nº de la última página del header `Link` (rel="last"), o null si no hay más páginas. */
31+
function parseLastPage(link: string | null): number | null {
32+
if (!link) return null;
33+
const m = link.match(/[?&]page=(\d+)[^>]*>;\s*rel="last"/);
34+
return m ? Number(m[1]) : null;
35+
}
36+
37+
// Rutas de "trabajo no-real": dependencias, artefactos generados y lockfiles. Sus líneas NO cuentan
38+
// como contribución (un commit que versiona node_modules metía cientos de miles de líneas basura).
39+
// Se filtran por commit recalculando additions/deletions solo sobre los archivos que SÍ son código.
40+
const GENERATED_DIRS = [
41+
'node_modules/', 'vendor/', 'dist/', 'build/', '.next/', 'out/', 'coverage/', '.venv/',
42+
'venv/', '__pycache__/', 'bin/', 'obj/', '.turbo/', 'target/',
43+
];
44+
const GENERATED_FILES = new Set([
45+
'package-lock.json', 'yarn.lock', 'pnpm-lock.yaml', 'composer.lock', 'gemfile.lock',
46+
'poetry.lock', 'cargo.lock', 'go.sum', 'podfile.lock', 'flake.lock',
47+
]);
48+
const GENERATED_SUFFIXES = ['.lock', '.min.js', '.min.css', '.map', '.snap'];
49+
50+
/** ¿La ruta es de trabajo generado/dependencias (no cuenta como líneas)? Case-insensitive. */
51+
export function isGeneratedPath(filename: string): boolean {
52+
const f = filename.toLowerCase();
53+
const base = f.split('/').pop() ?? f;
54+
if (GENERATED_FILES.has(base)) return true;
55+
if (GENERATED_SUFFIXES.some((s) => base.endsWith(s))) return true;
56+
// Directorio generado en cualquier nivel del path (p.ej. "apps/web/node_modules/...").
57+
return GENERATED_DIRS.some((d) => f.startsWith(d) || f.includes(`/${d}`));
2358
}
2459

2560
/** Llama a la GraphQL API v4 (la REST v3 no expone el calendario de contribuciones). */
@@ -119,23 +154,55 @@ export interface CommitMeta {
119154
}
120155

121156
export async function getCommit(repo: string, sha: string): Promise<CommitMeta> {
122-
const data = await gh<{
157+
type FileEntry = { filename: string; additions?: number; deletions?: number };
158+
type CommitResp = {
123159
sha: string;
124160
html_url: string;
125161
commit: { message: string; author?: { email?: string; date?: string } };
126162
author: { login: string } | null;
127163
stats?: { additions?: number; deletions?: number };
128164
parents?: unknown[];
129-
}>(`/repos/${encRepo(repo)}/commits/${sha}`);
165+
files?: FileEntry[];
166+
};
167+
168+
// El endpoint devuelve el desglose por archivo (`files`), paginado a 100. Un commit que versiona
169+
// node_modules trae miles de archivos: paginamos hasta un tope defensivo para poder filtrarlos.
170+
const enc = `/repos/${encRepo(repo)}/commits/${encodeURIComponent(sha)}`;
171+
const data = await gh<CommitResp>(`${enc}?per_page=100&page=1`);
172+
const files: FileEntry[] = [...(data.files ?? [])];
173+
const MAX_FILE_PAGES = 30; // 30×100 = 3000 archivos: de sobra para código real; acota los dumps.
174+
let batchLen = data.files?.length ?? 0;
175+
for (let page = 2; batchLen === 100 && page <= MAX_FILE_PAGES; page++) {
176+
const next = await gh<CommitResp>(`${enc}?per_page=100&page=${page}`);
177+
const batch = next.files ?? [];
178+
files.push(...batch);
179+
batchLen = batch.length;
180+
}
181+
182+
// Recalcular líneas contando SOLO archivos que no son generados/dependencias. Si el desglose no
183+
// vino (caso raro), se cae a los stats totales del commit para no quedarnos sin dato.
184+
let additions = 0;
185+
let deletions = 0;
186+
if (data.files != null) {
187+
for (const f of files) {
188+
if (isGeneratedPath(f.filename)) continue;
189+
additions += f.additions ?? 0;
190+
deletions += f.deletions ?? 0;
191+
}
192+
} else {
193+
additions = data.stats?.additions ?? 0;
194+
deletions = data.stats?.deletions ?? 0;
195+
}
196+
130197
return {
131198
sha: data.sha,
132199
message: data.commit.message,
133200
url: data.html_url,
134201
author: data.author?.login ?? null,
135202
authorEmail: data.commit.author?.email ?? null,
136203
committedAt: data.commit.author?.date ?? null,
137-
additions: data.stats?.additions ?? null,
138-
deletions: data.stats?.deletions ?? null,
204+
additions,
205+
deletions,
139206
isMerge: (data.parents?.length ?? 0) >= 2,
140207
};
141208
}
@@ -156,20 +223,29 @@ export interface RepoCommitListItem {
156223
* sí trae `parents` para descartar merges sin una llamada extra. La lista omite ramas no mergeadas
157224
* (default branch), igual que el conteo en vivo. Devuelve [] en 404 (repo sin acceso).
158225
*/
159-
export async function listRepoCommits(repo: string, sinceISO: string, page = 1): Promise<RepoCommitListItem[]> {
160-
const data = await gh<
161-
{
162-
sha: string;
163-
html_url: string;
164-
commit: { message: string; author?: { email?: string; date?: string } };
165-
author: { login?: string } | null;
166-
parents?: unknown[];
167-
}[]
168-
>(`/repos/${encRepo(repo)}/commits?since=${encodeURIComponent(sinceISO)}&per_page=100&page=${page}`).catch((e) => {
169-
if (String(e).includes('404')) return [] as never[];
226+
export interface RepoCommitsPage {
227+
items: RepoCommitListItem[];
228+
lastPage: number; // total de páginas (del header Link); = page actual si es la única/última.
229+
}
230+
231+
export async function listRepoCommits(repo: string, sinceISO: string, page = 1): Promise<RepoCommitsPage> {
232+
type Row = {
233+
sha: string;
234+
html_url: string;
235+
commit: { message: string; author?: { email?: string; date?: string } };
236+
author: { login?: string } | null;
237+
parents?: unknown[];
238+
};
239+
let res: { data: Row[]; headers: Headers };
240+
try {
241+
res = await ghRes<Row[]>(
242+
`/repos/${encRepo(repo)}/commits?since=${encodeURIComponent(sinceISO)}&per_page=100&page=${page}`,
243+
);
244+
} catch (e) {
245+
if (String(e).includes('404')) return { items: [], lastPage: page }; // repo sin acceso
170246
throw e;
171-
});
172-
return data.map((d) => ({
247+
}
248+
const items = res.data.map((d) => ({
173249
sha: d.sha,
174250
message: d.commit.message,
175251
url: d.html_url,
@@ -178,6 +254,23 @@ export async function listRepoCommits(repo: string, sinceISO: string, page = 1):
178254
committedAt: d.commit.author?.date ?? null,
179255
isMerge: (d.parents?.length ?? 0) >= 2,
180256
}));
257+
return { items, lastPage: parseLastPage(res.headers.get('link')) ?? page };
258+
}
259+
260+
/**
261+
* Todos los repos de la organización (full_name en minúsculas), para el autocomplete al vincular.
262+
* Ordenados por push reciente. Best-effort: si una página falla, corta y devuelve lo acumulado.
263+
*/
264+
export async function listOrgRepos(org = 'hyperlabs-ai'): Promise<string[]> {
265+
const out: string[] = [];
266+
for (let page = 1; page <= 20; page++) {
267+
const batch = await gh<{ full_name: string }[]>(
268+
`/orgs/${encodeURIComponent(org)}/repos?per_page=100&sort=pushed&page=${page}`,
269+
).catch(() => [] as { full_name: string }[]);
270+
for (const r of batch) out.push(r.full_name.toLowerCase());
271+
if (batch.length < 100) break;
272+
}
273+
return out;
181274
}
182275

183276
export interface RepoMeta {

‎src/dashboard/queries.ts‎

Lines changed: 68 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -176,6 +176,71 @@ export async function removeProjectRepo(projectId: string, repo: string) {
176176
if (error) throw error;
177177
}
178178

179+
/** Repos (full_name) vinculados a un proyecto. Para el re-sync (backfill forzado de cada uno). */
180+
export async function listProjectRepos(projectId: string): Promise<string[]> {
181+
const { data } = await db().from('project_repo').select('repo').eq('project_id', projectId);
182+
return ((data ?? []) as unknown as { repo: string }[]).map((r) => r.repo);
183+
}
184+
185+
export interface RepoSync {
186+
repo: string;
187+
status: string; // idle | queued | syncing | done | error
188+
pages: number;
189+
commits: number;
190+
totalPages: number | null;
191+
error: string | null;
192+
updatedAt: string | null;
193+
}
194+
195+
export interface ActiveSync extends RepoSync {
196+
projectId: string | null;
197+
}
198+
199+
/**
200+
* Sincronizaciones (backfill) activas en TODA la org, para el widget global de progreso: las que
201+
* están en cola/corriendo, más las recién terminadas (2 min) para alcanzar a mostrar el ✓/error.
202+
* Ligero (una fila por repo). Tolerante: si la migración 0014 falta, devuelve [].
203+
*/
204+
export async function listActiveSyncs(): Promise<ActiveSync[]> {
205+
const since = new Date(Date.now() - 2 * 60_000).toISOString();
206+
const { data, error } = await db()
207+
.from('project_repo')
208+
.select('repo, project_id, sync_status, sync_pages, sync_commits, sync_total_pages, sync_error, sync_updated_at')
209+
.or(`sync_status.in.(queued,syncing),and(sync_status.in.(done,error),sync_updated_at.gte.${since})`);
210+
if (error) return [];
211+
return ((data ?? []) as any[]).map((r) => ({
212+
repo: r.repo,
213+
projectId: r.project_id ?? null,
214+
status: r.sync_status ?? 'idle',
215+
pages: r.sync_pages ?? 0,
216+
commits: r.sync_commits ?? 0,
217+
totalPages: r.sync_total_pages ?? null,
218+
error: r.sync_error ?? null,
219+
updatedAt: r.sync_updated_at ?? null,
220+
}));
221+
}
222+
223+
/**
224+
* Estado de sincronización (backfill) de los repos de un proyecto. Tolerante: si la migración 0014
225+
* aún no se aplicó (columnas sync_* inexistentes), devuelve [] y el front no muestra badges.
226+
*/
227+
async function projectRepoSync(projectId: string): Promise<RepoSync[]> {
228+
const { data, error } = await db()
229+
.from('project_repo')
230+
.select('repo, sync_status, sync_pages, sync_commits, sync_total_pages, sync_error, sync_updated_at')
231+
.eq('project_id', projectId);
232+
if (error) return [];
233+
return ((data ?? []) as any[]).map((r) => ({
234+
repo: r.repo,
235+
status: r.sync_status ?? 'idle',
236+
pages: r.sync_pages ?? 0,
237+
commits: r.sync_commits ?? 0,
238+
totalPages: r.sync_total_pages ?? null,
239+
error: r.sync_error ?? null,
240+
updatedAt: r.sync_updated_at ?? null,
241+
}));
242+
}
243+
179244
export interface ProjectRow {
180245
id: string;
181246
name: string;
@@ -816,7 +881,7 @@ export async function getProject(projectId: string, period: Period) {
816881
if (!p) return null;
817882
const color = (await projectColors()).get(projectId) ?? null;
818883

819-
const [commits, devs, resolved, repoRows, openRows, allItemRows] = await Promise.all([
884+
const [commits, devs, resolved, repoRows, openRows, allItemRows, repoSync] = await Promise.all([
820885
commitsInRange(period.from, period.to, { projectId }),
821886
allDevs(),
822887
resolvedInRange(period.from, period.to, { projectId }),
@@ -828,6 +893,7 @@ export async function getProject(projectId: string, period: Period) {
828893
.in('state', OPEN_STATES),
829894
// Todos los work_items del proyecto (para el desglose por estado, incluidos cerrados).
830895
db().from('work_item').select('state, state_name').eq('project_id', projectId),
896+
projectRepoSync(projectId),
831897
]);
832898
const repos = ((repoRows.data ?? []) as unknown as { repo: string }[]).map((r) => r.repo).sort();
833899
const devName = new Map(devs.map((d) => [d.id, d.name]));
@@ -908,6 +974,7 @@ export async function getProject(projectId: string, period: Period) {
908974
return {
909975
project: { id: p.id, name: p.name, key: p.key, kind: p.kind, color },
910976
repos,
977+
repoSync,
911978
period,
912979
totals: { commits: commits.length, additions: lines.additions, deletions: lines.deletions, ticketsResolved: resolved.length, contributors: contribMap.size, openTickets: openTickets.length },
913980
contributors: [...contribMap.values()].sort((a, b) => b.commits - a.commits),

‎src/events/outbox.ts‎

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ import { db } from '../db/supabase.js';
66
import { notifyAssignment, notifyChangesDocumented, notifyRepoDetected } from '../notify/notifications.js';
77
import { syncIssueFromWebhook, removeMirror } from '../sync/linear-issue.js';
88
import { reconcileCommit, backfillPushCommits } from '../reconcile/commits.js';
9-
import { backfillRepoCommits } from '../reconcile/backfill.js';
9+
import { backfillRepoCommits, markRepoSyncError } from '../reconcile/backfill.js';
1010
import { reconcilePullRequest } from '../reconcile/pull-request.js';
1111
import { handleRepoDetected, handleRepoRenamed } from '../reconcile/repos.js';
1212
import type { RepoMeta } from '../adapters/github.js';
@@ -157,6 +157,11 @@ async function processEvent(ev: any): Promise<boolean | null> {
157157
next_attempt_at: new Date(Date.now() + backoffSec * 1000).toISOString(),
158158
})
159159
.eq('id', ev.id);
160+
// Backfill agotado: refleja el fallo en el estado de sync del repo (badge rojo + reintento en UI).
161+
// Solo al morir, para no parpadear en fallos transitorios que aún se reintentan.
162+
if (dead && ev.type === 'repo.backfill' && ev.payload?.repo) {
163+
await markRepoSyncError(String(ev.payload.repo), String(err)).catch(() => {});
164+
}
160165
return false;
161166
}
162167
}
@@ -225,12 +230,13 @@ async function dispatch(type: OutboxEventType, payload: Record<string, unknown>)
225230
const projectId = (payload.projectId as string | null) ?? null;
226231
const sinceISO = String(payload.sinceISO ?? '');
227232
const page = Number(payload.page ?? 1);
233+
const runKey = String(payload.runKey ?? '1');
228234
const r = await backfillRepoCommits({ repo, projectId, sinceISO, page });
229235
if (r.hasMore) {
230236
await emit(
231237
'repo.backfill',
232-
{ repo, projectId, sinceISO, page: r.nextPage },
233-
{ idempotencyKey: `repo-backfill:${repo}:${r.nextPage}` },
238+
{ repo, projectId, sinceISO, page: r.nextPage, runKey },
239+
{ idempotencyKey: `repo-backfill:${repo}:${runKey}:${r.nextPage}` },
234240
);
235241
}
236242
return;

0 commit comments

Comments
 (0)