PEP-216: Главная и «Подписки» без задержек — прогресс без запроса на проект, поток, индекс событий
Главная 80 → 30 мс, 40 запросов разом p95 2,98 → 1,12 с; «Подписки» 36 → 22 мс. Замер на копии живой базы (apps/web/scripts/bench-pages.ts). Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
b170560cba
commit
65a5d15aae
@ -20,7 +20,7 @@
|
||||
- git-прокси релея (allowedGitPath) отклоняет %2e/%2f/%5c/%25 и `\`: fetch сворачивает %2e%2e как dot-сегмент. Строгий script-CSP не включён (inline-скрипты Next).
|
||||
- act-runner: `capacity` применяется только перезапуском `peppa-act-runner` (убивает идущие проверки); после правок compose — `scripts/infra-up.sh act-runner`.
|
||||
- Новая фраза Claude о лимите — в `parseResetTime` и таблицу limits.test.ts, иначе подписка зря считается свободной. Codex 0.169 без `--full-auto`: режим — `CODEX_DEFAULT_MODE` (providers.ts), срочно — `PEPPA_CODEX_MODE` в .env.
|
||||
- bench: check.mjs не импортирует run-checks.mjs (главный модуль с top-level await — взаимная блокировка), помощники — bench/lib/check-kit.mjs.
|
||||
- Скорость: замер `apps/web/scripts/bench-pages.ts`; N+1 по проектам — `workLineIndex`. Не `pkill -f next-server` — убьёт живой веб.
|
||||
- Хук грузит только лёгкий `runner/limit-delay.ts` — не тянуть в него flow.ts. В тесте хука PEPPA_GENERATION = поколение сессии (вставленной руками — 0).
|
||||
- Память ветки при мерже main склеивается построчно и разрастается дублями — после конфликта в `.peppa/memory.md` убери повторы (тест project-memory-size.test.ts).
|
||||
- Проверки «none» бывает от упавшего задания (DNS на git clone): смотри не-peppa статусы коммита (PEP-205). Codex-экран: `trimEnd()`, апостроф `’`.
|
||||
|
||||
@ -18,22 +18,23 @@ export const dynamic = "force-dynamic";
|
||||
/** Console layout (PEP-38): navigation on the left, each page renders centre + right panel via <Workspace>. */
|
||||
export default async function AppLayout({ children }: { children: ReactNode }) {
|
||||
const user = await requireUser();
|
||||
const counts = await navCounts(user.id);
|
||||
const { sound } = await getNotifyPrefs(db, user.id);
|
||||
const superadmin = await isSuperadmin(db, user);
|
||||
const mode = await uiMode();
|
||||
// PEP-216: independent reads together, not one after another on every page.
|
||||
const [counts, { sound }, superadmin, mode] = await Promise.all([navCounts(user.id), getNotifyPrefs(db, user.id), isSuperadmin(db, user), uiMode()]);
|
||||
const engineer = mode === "engineer";
|
||||
// PEP-5: subscription limit windows over every page — for «Инженер»; PEP-121: «Продакт»
|
||||
// reads one line: agents work, or when they go on.
|
||||
const accounts = engineer ? await accountUsageForUser(db, user).catch(() => []) : [];
|
||||
const line = engineer ? null : await agentsLine(db, user).catch(() => ({ state: "working" as const }));
|
||||
const [accounts, line, feedback] = await Promise.all([
|
||||
engineer ? accountUsageForUser(db, user).catch(() => []) : [],
|
||||
engineer ? null : agentsLine(db, user).catch(() => ({ state: "working" as const })),
|
||||
superadmin ? pendingFeedbackCount(db) : 0,
|
||||
]);
|
||||
// PEP-186: agents stand — the owner may ask the superadmin for a subscription right from the strip.
|
||||
const offers = line?.state === "paused" ? await subscriptionRequestOffers(db, user).catch(() => []) : [];
|
||||
return (
|
||||
<WordsProvider mode={mode}>
|
||||
<div className="min-h-dvh md:grid md:grid-cols-[232px_minmax(0,1fr)]">
|
||||
<AttentionBadge count={counts.questions + counts.waitingRunners} sound={sound} />
|
||||
<Sidebar login={user.login} avatarUrl={user.avatarUrl} counts={{ ...counts, feedback: superadmin ? await pendingFeedbackCount(db) : 0 }} superadmin={superadmin} engineer={engineer} />
|
||||
<Sidebar login={user.login} avatarUrl={user.avatarUrl} counts={{ ...counts, feedback }} superadmin={superadmin} engineer={engineer} />
|
||||
<div className="flex min-w-0 flex-col pb-16 md:pb-0">
|
||||
<VersionWatch boot={bootId()} />
|
||||
{line ? <AgentsStrip line={line} offers={offers} /> : <UsageStrip accounts={accounts} admin={superadmin} />}
|
||||
|
||||
@ -1,3 +1,4 @@
|
||||
import { Suspense } from "react";
|
||||
import { redirect } from "next/navigation";
|
||||
import Link from "next/link";
|
||||
import { agentTaskSummary, claimWelcome, isSuperadmin, listUserProjects, onboardingChecklist, pendingFeedback, platformDelayCounts, progressOverview, proposedCount, reviewCounts } from "@peppa/core";
|
||||
@ -16,29 +17,49 @@ import { db } from "@/lib/db";
|
||||
import { getT } from "@/lib/i18n";
|
||||
import { acceptInbox, activeSessions, inbox } from "@/lib/queries";
|
||||
|
||||
function BlockSkeleton() {
|
||||
return <div className="h-24 animate-pulse rounded-md bg-muted/40" aria-hidden />;
|
||||
}
|
||||
|
||||
async function ProgressBlock({ userId }: { userId: number }) {
|
||||
return <ProgressOverview data={await progressOverview(db, userId)} />;
|
||||
}
|
||||
|
||||
async function AgentsBlock({ userId, engineer }: { userId: number; engineer: boolean }) {
|
||||
const t = await getT();
|
||||
const sessions = await activeSessions(userId);
|
||||
return (
|
||||
<Section title={t("Агенты за работой")} count={sessions.length} actions={engineer ? <MoreLink href="/runners">{t("вся работа агентов")}</MoreLink> : undefined}>
|
||||
{sessions.length === 0 ? <Empty>{t("Сейчас никто не работает: напишите задачу — и агент возьмёт её.")}</Empty> : sessions.map((s) => <AgentAtWork key={s.id} s={s} back="/" engineer={engineer} />)}
|
||||
</Section>
|
||||
);
|
||||
}
|
||||
|
||||
export default async function Home({ searchParams }: { searchParams: Promise<{ error?: string }> }) {
|
||||
const user = await requireUser();
|
||||
const { error } = await searchParams;
|
||||
const t = await getT();
|
||||
const w = await words();
|
||||
if (await claimWelcome(db, user.id)) redirect("/welcome");
|
||||
const [items, ready, sessions, projects, onboarding, progress] = await Promise.all([inbox(user.id), acceptInbox(user.id), activeSessions(user.id), listUserProjects(db, user.id), onboardingChecklist(db, user), progressOverview(db, user.id)]);
|
||||
// PEP-216: the top of the page needs only what waits for the person; the heavy blocks below
|
||||
// (progress, agents, projects) stream in their own Suspense boundaries.
|
||||
const [items, ready, projects, onboarding, superadmin] = await Promise.all([inbox(user.id), acceptInbox(user.id), listUserProjects(db, user.id), onboardingChecklist(db, user), isSuperadmin(db, user)]);
|
||||
// PEP-143: users' reports about Peppa FACTORY wait for the superadmin's decision here.
|
||||
const reports = (await isSuperadmin(db, user)) ? await pendingFeedback(db) : [];
|
||||
// PEP-150/209: delays on the platform's side are the superadmin's to watch — one line here, the list in the dashboard.
|
||||
const delays = (await isSuperadmin(db, user)) ? await platformDelayCounts(db) : null;
|
||||
// PEP-209: what waits for the user comes first — accept, answer, decide on «Предложено».
|
||||
const toAccept = await reviewCounts(db, projects.map((p) => p.id));
|
||||
const proposed = new Map<number, number>();
|
||||
for (const p of projects) {
|
||||
const n = await proposedCount(db, p.id);
|
||||
if (n) proposed.set(p.id, n);
|
||||
}
|
||||
// PEP-197: people against factory-made tasks per project — the superadmin's view.
|
||||
const [reports, delays, toAccept, proposedList, agentTasksAll] = await Promise.all([
|
||||
superadmin ? pendingFeedback(db) : [],
|
||||
superadmin ? platformDelayCounts(db) : null,
|
||||
reviewCounts(db, projects.map((p) => p.id)),
|
||||
Promise.all(projects.map(async (p) => [p.id, await proposedCount(db, p.id)] as const)),
|
||||
superadmin ? agentTaskSummary(db) : [],
|
||||
]);
|
||||
const proposed = new Map(proposedList.filter(([, n]) => n > 0));
|
||||
const acceptN = [...toAccept.values()].reduce((a, b) => a + b, 0);
|
||||
const decideN = [...proposed.values()].reduce((a, b) => a + b, 0);
|
||||
const waits = [acceptN ? t("принять {n}", { n: acceptN }) : null, items.length ? t("ответить {n}", { n: items.length }) : null, decideN ? t("решить {n}", { n: decideN }) : null].filter(Boolean).join(", ");
|
||||
// PEP-197: people against factory-made tasks per project — the superadmin's view.
|
||||
const agentTasks = (await isSuperadmin(db, user)) ? (await agentTaskSummary(db)).filter((r) => r.agents > 0).slice(0, 15) : [];
|
||||
const agentTasks = agentTasksAll.filter((r) => r.agents > 0).slice(0, 15);
|
||||
return (
|
||||
<Workspace aside={<ActivityAside questions={false} />}>
|
||||
<LiveRefresh scope="home" />
|
||||
@ -97,11 +118,13 @@ export default async function Home({ searchParams }: { searchParams: Promise<{ e
|
||||
</Section>
|
||||
)}
|
||||
<Section title={t("Прогресс")}>
|
||||
<ProgressOverview data={progress} />
|
||||
</Section>
|
||||
<Section title={t("Агенты за работой")} count={sessions.length} actions={w.engineer ? <MoreLink href="/runners">{t("вся работа агентов")}</MoreLink> : undefined}>
|
||||
{sessions.length === 0 ? <Empty>{t("Сейчас никто не работает: напишите задачу — и агент возьмёт её.")}</Empty> : sessions.map((s) => <AgentAtWork key={s.id} s={s} back="/" engineer={w.engineer} />)}
|
||||
<Suspense fallback={<BlockSkeleton />}>
|
||||
<ProgressBlock userId={user.id} />
|
||||
</Suspense>
|
||||
</Section>
|
||||
<Suspense fallback={<Section title={t("Агенты за работой")}><BlockSkeleton /></Section>}>
|
||||
<AgentsBlock userId={user.id} engineer={w.engineer} />
|
||||
</Suspense>
|
||||
<Section title={t("Мои проекты")} actions={<MoreLink href="/projects">{t("все проекты")}</MoreLink>}>
|
||||
<ProjectList projects={projects} userId={user.id} engineer={w.engineer} />
|
||||
</Section>
|
||||
|
||||
@ -34,6 +34,14 @@ import {
|
||||
updatePoolAction,
|
||||
} from "./actions";
|
||||
|
||||
// PEP-216: the backfill reads auth files — once per process is enough, not on every visit.
|
||||
let backfilled = false;
|
||||
async function backfillOnce(d: typeof db) {
|
||||
if (backfilled) return;
|
||||
backfilled = true;
|
||||
await backfillCodexAccounts(d).catch(() => {});
|
||||
}
|
||||
|
||||
export async function generateMetadata() {
|
||||
const t = await getT();
|
||||
return { title: t("Подписки — Peppa FACTORY") };
|
||||
@ -262,7 +270,7 @@ export default async function Subscriptions({ searchParams }: { searchParams: Pr
|
||||
if (!(await isSuperadmin(db, user))) notFound();
|
||||
const { error, added, switched, left } = await searchParams;
|
||||
// PEP-178: ChatGPT logins carry their account — fill in the ones signed in before it was kept.
|
||||
await backfillCodexAccounts(db).catch(() => {});
|
||||
await backfillOnce(db);
|
||||
let subs = await listSubscriptions(db);
|
||||
// Codex device sign-ins finish on the user's device: look whether they are done.
|
||||
let polled = false;
|
||||
|
||||
@ -2,6 +2,7 @@ import { pausedProjectIds, listSessions, needsPerson, questionType, PeppaError,
|
||||
import { events, projects, questions, sessions, tasks } from "@peppa/db";
|
||||
import { formatTaskKey } from "@peppa/shared";
|
||||
import { m } from "@peppa/shared/i18n";
|
||||
import { cache } from "react";
|
||||
import { and, asc, count, desc, eq, inArray, isNull, ne } from "drizzle-orm";
|
||||
import { db } from "./db";
|
||||
|
||||
@ -21,8 +22,11 @@ export async function acceptInbox(userId: number) {
|
||||
return (await openMessages(userId)).filter((q) => questionType(q, q.taskStatus) === "done" && q.taskStatus === "review");
|
||||
}
|
||||
|
||||
/** Every open message of the user's projects (any type), oldest first. */
|
||||
async function openMessages(userId: number) {
|
||||
/**
|
||||
* Every open message of the user's projects (any type), oldest first. PEP-216: once per request —
|
||||
* the sidebar counters, «Вопросы агентов», «Принять» and the right panel all read it.
|
||||
*/
|
||||
const openMessages = cache(async (userId: number) => {
|
||||
// PEP-174: a project on pause asks nothing — its messages wait until «Продолжить».
|
||||
const paused = await pausedProjectIds(db);
|
||||
const ids = (await userProjectIds(db, userId)).filter((id) => !paused.has(id));
|
||||
@ -36,7 +40,7 @@ async function openMessages(userId: number) {
|
||||
.where(and(inArray(projects.id, ids), isNull(questions.answeredAt)))
|
||||
.orderBy(asc(questions.id));
|
||||
return rows.map((r) => ({ ...r.q, taskKey: r.taskNumber != null ? formatTaskKey(r.projectKey, r.taskNumber) : null, taskTitle: r.taskTitle, taskStatus: r.taskStatus, tmux: r.tmux }));
|
||||
}
|
||||
});
|
||||
|
||||
export async function activeSessions(userId: number) {
|
||||
const ids = new Set(await userProjectIds(db, userId));
|
||||
|
||||
46
apps/web/scripts/bench-pages.ts
Normal file
46
apps/web/scripts/bench-pages.ts
Normal file
@ -0,0 +1,46 @@
|
||||
// PEP-216: times the data behind Home and /subscriptions on a COPY of the live database.
|
||||
// PEPPA_DB=<copy> PEPPA_SECRET=x node apps/web/scripts/bench-pages.ts [userId] [rounds]
|
||||
import { accountUsageForUser, agentsLine, getNotifyPrefs, isSuperadmin, pendingFeedbackCount, discussionUnread, userProjectIds, agentTaskSummary, listSubscriptions, onboardingChecklist, pendingFeedback, platformDelayCounts, poolOverviews, progressOverview, proposedCount, reviewCounts, listUserProjects } from "@peppa/core";
|
||||
import { subscriptionRequestOffers, openSubscriptionRequests, backfillCodexAccounts, pendingLogin } from "@peppa/runner";
|
||||
import { createDb } from "@peppa/db";
|
||||
import { acceptInbox, activeSessions, inbox, navCounts } from "../lib/queries.ts";
|
||||
|
||||
const userId = Number(process.argv[2] ?? 2);
|
||||
const rounds = Number(process.argv[3] ?? 3);
|
||||
const db = createDb();
|
||||
const user = (await db.query?.users?.findFirst?.({ where: (u: any, { eq }: any) => eq(u.id, userId) })) as any;
|
||||
const rows: Record<string, number[]> = {};
|
||||
async function time<T>(name: string, f: () => Promise<T>): Promise<T> {
|
||||
const t = performance.now();
|
||||
const r = await f();
|
||||
(rows[name] ??= []).push(performance.now() - t);
|
||||
return r;
|
||||
}
|
||||
for (let i = 0; i < rounds; i++) {
|
||||
const projects = await time("listUserProjects", () => listUserProjects(db, userId));
|
||||
await time("L getNotifyPrefs", () => getNotifyPrefs(db, userId));
|
||||
await time("L isSuperadmin", () => isSuperadmin(db, user));
|
||||
await time("L accountUsageForUser", () => accountUsageForUser(db, user));
|
||||
await time("L agentsLine", () => agentsLine(db, user));
|
||||
await time("L offers", () => subscriptionRequestOffers(db, user));
|
||||
await time("L pendingFeedbackCount", () => pendingFeedbackCount(db));
|
||||
await time("L discussionUnread", () => discussionUnread(db, userId));
|
||||
await time("L userProjectIds", () => userProjectIds(db, userId));
|
||||
await time("inbox", () => inbox(userId));
|
||||
await time("acceptInbox", () => acceptInbox(userId));
|
||||
await time("activeSessions", () => activeSessions(userId));
|
||||
await time("onboarding", () => onboardingChecklist(db, user));
|
||||
await time("progressOverview", () => progressOverview(db, userId));
|
||||
await time("pendingFeedback", () => pendingFeedback(db));
|
||||
await time("platformDelayCounts", () => platformDelayCounts(db));
|
||||
await time("reviewCounts", () => reviewCounts(db, projects.map((p) => p.id)));
|
||||
await time("proposedCount x projects", async () => { for (const p of projects) await (await import("@peppa/core")).proposedCount(db, p.id); });
|
||||
await time("agentTaskSummary", () => agentTaskSummary(db));
|
||||
await time("navCounts", () => navCounts(userId));
|
||||
await time("SUBS backfillCodexAccounts", () => backfillCodexAccounts(db));
|
||||
const subs = await time("SUBS listSubscriptions", () => listSubscriptions(db));
|
||||
await time("SUBS pendingLogin x subs", async () => { for (const s of subs) await pendingLogin(db, s.id); });
|
||||
await time("SUBS poolOverviews", () => poolOverviews(db));
|
||||
await time("SUBS openSubscriptionRequests", () => openSubscriptionRequests(db));
|
||||
}
|
||||
for (const [k, v] of Object.entries(rows)) console.log(k.padEnd(32), Math.min(...v).toFixed(0).padStart(6), "ms min", Math.max(...v).toFixed(0).padStart(6), "ms max");
|
||||
10
openspec/changes/pep-216-home-subscriptions-fast/design.md
Normal file
10
openspec/changes/pep-216-home-subscriptions-fast/design.md
Normal file
@ -0,0 +1,10 @@
|
||||
## Решения
|
||||
- Причина — не одна медленная функция: на копии живой базы каждая выборка занимает миллисекунды,
|
||||
но запросы страницы складываются (Главная ≈ 75 мс процессора), а поток один — 40 запросов подряд
|
||||
дают секунды ожидания. Поэтому режем процессорное время запроса и убираем N+1.
|
||||
- `workLineIndex(db, projectIds)` (core/capacity.ts): один запрос сессий и одна очередь ёмкости,
|
||||
функция выдаёт «Делается · В очереди» для любого набора проектов. `workLine` остался для одиночных вызовов.
|
||||
- `openMessages` обёрнут в `cache` из React: результат живёт один запрос.
|
||||
- Suspense вокруг «Прогресса» и «Агентов за работой»; верх (заголовок, вопросы, «Принять», «Предложено») ждёт только дешёвые чтения.
|
||||
- Миграция 0025: индекс `events(type, created_at)`; `peppa db backup && peppa db migrate` перед кодом (делает live-deploy.sh).
|
||||
- Кэш медленного внешнего не нужен: в пути рендера нет вызовов tmux и сети, кроме проверки ожидающих входов (только при записи о входе).
|
||||
23
openspec/changes/pep-216-home-subscriptions-fast/proposal.md
Normal file
23
openspec/changes/pep-216-home-subscriptions-fast/proposal.md
Normal file
@ -0,0 +1,23 @@
|
||||
## Зачем
|
||||
Главная — первая страница каждого пользователя, «Подписки» — страница суперадмина. Под нагрузкой
|
||||
(много людей и вкладок, один процесс веба) ответы доходят до 12 с: каждый запрос тратит
|
||||
процессорное время единственного потока, а SQLite в Node синхронный.
|
||||
|
||||
## Что меняется
|
||||
- Прогресс на Главной считал «Делается · В очереди» отдельной парой запросов на каждый проект
|
||||
(184 запроса, 46 мс). Теперь один проход по сессиям и одна очередь на все проекты (52 запроса, 6 мс).
|
||||
- Открытые вопросы пользователя читаются один раз за запрос страницы (боковая панель, «Вопросы
|
||||
агентов», «Принять», правая панель).
|
||||
- Верх Главной (что ждёт вас) рисуется сразу; «Прогресс» и «Агенты за работой» приходят потоком (Suspense).
|
||||
- Боковая панель: независимые чтения вместе, а не по очереди.
|
||||
- «Подписки»: лента переключений за неделю идёт по индексу `events(type, created_at)` (9 мс → ~0),
|
||||
дозаполнение учёток Codex читает файлы один раз за процесс, а не на каждый визит.
|
||||
|
||||
## Замер (копия живой базы, `next start`, один процесс)
|
||||
| | до | после |
|
||||
|---|---|---|
|
||||
| `/` последовательно | 80 мс | 30 мс |
|
||||
| `/` 40 запросов разом, p95 | 2,98 с | 1,12 с |
|
||||
| `/subscriptions` последовательно | 36 мс | 22 мс |
|
||||
| `/subscriptions` 40 разом, p95 | 1,40 с | 0,88 с |
|
||||
Скрипт: `apps/web/scripts/bench-pages.ts`.
|
||||
@ -0,0 +1,17 @@
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: Главная и «Подписки» отвечают быстро
|
||||
Серверный ответ Главной и страницы «Подписки» SHALL занимать меньше 500 мс на копии живой базы.
|
||||
Данные Главной SHALL считаться без запроса на каждый проект; верх Главной SHALL появляться, не
|
||||
дожидаясь блоков «Прогресс» и «Агенты за работой».
|
||||
|
||||
#### Scenario: Главная при большом числе проектов
|
||||
- **GIVEN** пользователь с 33 проектами и 1600 сессиями в базе
|
||||
- **WHEN** он открывает Главную
|
||||
- **THEN** серверный ответ приходит быстрее 500 мс
|
||||
- **AND** заголовок «Вас ждут…» виден до загрузки прогресса
|
||||
|
||||
#### Scenario: Лента переключений подписок
|
||||
- **GIVEN** в базе 45 000 событий
|
||||
- **WHEN** суперадмин открывает «Подписки»
|
||||
- **THEN** лента переключений за неделю читается по индексу, без просмотра всех событий
|
||||
12
openspec/changes/pep-216-home-subscriptions-fast/tasks.md
Normal file
12
openspec/changes/pep-216-home-subscriptions-fast/tasks.md
Normal file
@ -0,0 +1,12 @@
|
||||
## 1. Замер
|
||||
- [x] 1.1 Скрипт `apps/web/scripts/bench-pages.ts`, замер до/после на копии живой базы
|
||||
|
||||
## 2. Правки
|
||||
- [x] 2.1 `workLineIndex`: прогресс без запроса на проект
|
||||
- [x] 2.2 `openMessages` — один раз за запрос
|
||||
- [x] 2.3 Suspense для «Прогресса» и «Агентов за работой», параллельные чтения в раскладке и на Главной
|
||||
- [x] 2.4 Индекс `events(type, created_at)` (миграция 0025), дозаполнение Codex раз за процесс
|
||||
|
||||
## 3. Проверки
|
||||
- [x] 3.1 typecheck, словарь, e2e
|
||||
- [x] 3.2 Проверка в браузере
|
||||
@ -241,6 +241,24 @@ export interface WorkLine {
|
||||
}
|
||||
|
||||
/** «Делается: 4 · В очереди: 3» of the projects (product view: no subscriptions, no capacity). */
|
||||
/**
|
||||
* PEP-216: `workLine` of many project sets from one pass over the sessions and one queue —
|
||||
* the Home page asks it for every project, and a query pair per project cost ~25 ms there.
|
||||
*/
|
||||
export async function workLineIndex(db: Db, projectIds: number[]): Promise<(ids: number[]) => WorkLine> {
|
||||
if (!projectIds.length) return () => ({ doing: 0, queued: 0 });
|
||||
const rows = await db
|
||||
.selectDistinct({ taskId: sessions.taskId, projectId: sessions.projectId })
|
||||
.from(sessions)
|
||||
.innerJoin(tasks, eq(sessions.taskId, tasks.id))
|
||||
.where(and(inArray(sessions.projectId, projectIds), notInArray(sessions.status, FINISHED_SESSION_STATUSES), inArray(tasks.status, [...WORKING])));
|
||||
const queue = await capacityQueue(db, { projectIds });
|
||||
return (ids) => {
|
||||
const set = new Set(ids);
|
||||
return { doing: new Set(rows.filter((r) => set.has(r.projectId)).map((r) => r.taskId)).size, queued: queue.filter((q) => set.has(q.projectId)).length };
|
||||
};
|
||||
}
|
||||
|
||||
export async function workLine(db: Db, projectIds: number[]): Promise<WorkLine> {
|
||||
if (!projectIds.length) return { doing: 0, queued: 0 };
|
||||
const rows = await db
|
||||
|
||||
@ -8,7 +8,7 @@ import { formatTaskKey } from "@peppa/shared";
|
||||
import { and, asc, eq, inArray, isNull } from "drizzle-orm";
|
||||
import { taskProgress } from "./openspec.ts";
|
||||
import { taskAgentNames } from "./team.ts";
|
||||
import { capacityQueue, workLine, type WorkLine } from "./capacity.ts";
|
||||
import { capacityQueue, workLineIndex, type WorkLine } from "./capacity.ts";
|
||||
import { pausedProjectIds } from "./project-pause.ts";
|
||||
import { listOtherProjects, userProjectIds } from "./users.ts";
|
||||
|
||||
@ -68,14 +68,15 @@ export async function progressOverview(db: Db, userId: number): Promise<Progress
|
||||
const empty: ProgressOverview = { mine: [], others: [], totals: { backlog: 0, inProgress: 0, review: 0, done: 0, total: 0 }, work: { doing: 0, queued: 0 } };
|
||||
if (!ids.length) return empty;
|
||||
const ps = await db.select({ p: projects, ownerLogin: users.login }).from(projects).leftJoin(users, eq(users.id, projects.ownerId)).where(inArray(projects.id, ids)).orderBy(asc(projects.key));
|
||||
const ts = await db.select().from(tasks).where(and(inArray(tasks.projectId, ids), isNull(tasks.archivedAt))).orderBy(asc(tasks.position), asc(tasks.number));
|
||||
const ts = await db.select({ id: tasks.id, projectId: tasks.projectId, number: tasks.number, title: tasks.title, status: tasks.status, openspecChange: tasks.openspecChange }).from(tasks).where(and(inArray(tasks.projectId, ids), isNull(tasks.archivedAt))).orderBy(asc(tasks.position), asc(tasks.number));
|
||||
const mine = new Set(mineIds);
|
||||
const paused = await pausedProjectIds(db);
|
||||
const out = empty;
|
||||
const queue = new Map((await capacityQueue(db, { projectIds: ids })).map((q) => [q.taskId, q.position]));
|
||||
out.work = await workLine(db, mineIds);
|
||||
const lineOf = await workLineIndex(db, ids);
|
||||
out.work = lineOf(mineIds);
|
||||
for (const { p, ownerLogin } of ps) {
|
||||
const row: ProjectProgress = { key: p.key, name: p.name, ownerLogin: mine.has(p.id) ? null : (ownerLogin ?? tr("без владельца")), backlog: 0, inProgress: 0, review: 0, done: 0, total: 0, working: [], reviewKeys: [], product: products.get(p.id) ?? null, productFix: null, work: await workLine(db, [p.id]), paused: paused.has(p.id) };
|
||||
const row: ProjectProgress = { key: p.key, name: p.name, ownerLogin: mine.has(p.id) ? null : (ownerLogin ?? tr("без владельца")), backlog: 0, inProgress: 0, review: 0, done: 0, total: 0, working: [], reviewKeys: [], product: products.get(p.id) ?? null, productFix: null, work: lineOf([p.id]), paused: paused.has(p.id) };
|
||||
const fix = row.product ? null : await openProductLinkTask(db, p.id);
|
||||
if (fix) row.productFix = formatTaskKey(p.key, fix.number);
|
||||
const own = ts.filter((t) => t.projectId === p.id);
|
||||
|
||||
1
packages/db/migrations/0025_events_type_created.sql
Normal file
1
packages/db/migrations/0025_events_type_created.sql
Normal file
@ -0,0 +1 @@
|
||||
CREATE INDEX `events_type_created` ON `events` (`type`,`created_at`);
|
||||
4621
packages/db/migrations/meta/0025_snapshot.json
Normal file
4621
packages/db/migrations/meta/0025_snapshot.json
Normal file
File diff suppressed because it is too large
Load Diff
@ -176,6 +176,13 @@
|
||||
"when": 1795017454043,
|
||||
"tag": "0024_events_session_type",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 25,
|
||||
"version": "6",
|
||||
"when": 1795173370063,
|
||||
"tag": "0025_events_type_created",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@ -492,7 +492,7 @@ export const events = sqliteTable(
|
||||
actorClientId: text("actor_client_id"),
|
||||
createdAt: createdAt(),
|
||||
},
|
||||
(t) => [index("events_created_at").on(t.createdAt), index("events_session_type").on(t.sessionId, t.type)],
|
||||
(t) => [index("events_created_at").on(t.createdAt), index("events_session_type").on(t.sessionId, t.type), index("events_type_created").on(t.type, t.createdAt)],
|
||||
);
|
||||
|
||||
/** Small key/value store for service state (Telegram offset, pairing, binding). */
|
||||
|
||||
@ -126,6 +126,8 @@ describe("Очередь задач по ёмкости", () => {
|
||||
const q = await core.capacityQueue(db, { projectIds: [projectId] });
|
||||
assert.deepEqual(q.map((x) => [x.key, x.position]), [[first.key, 1], [second.key, 2]]);
|
||||
assert.deepEqual(await core.workLine(db, [projectId]), { doing: 0, queued: 2 });
|
||||
// PEP-216: the indexed form (one pass for many projects) gives the same line.
|
||||
assert.deepEqual((await core.workLineIndex(db, [projectId]))([projectId]), { doing: 0, queued: 2 });
|
||||
|
||||
// Still full — nothing starts.
|
||||
assert.equal(await runner.capacityQueueTick(db), 0);
|
||||
@ -137,6 +139,7 @@ describe("Очередь задач по ёмкости", () => {
|
||||
const left = await core.capacityQueue(db, { projectIds: [projectId] });
|
||||
assert.deepEqual(left.map((x) => [x.key, x.position]), [[second.key, 1]]);
|
||||
assert.deepEqual(await core.workLine(db, [projectId]), { doing: 1, queued: 1 });
|
||||
assert.deepEqual((await core.workLineIndex(db, [projectId]))([projectId]), { doing: 1, queued: 1 });
|
||||
await runner.stopSession(db, live[0]!.id);
|
||||
await waitFor("runner stopped", async () => (await core.getSession(db, live[0]!.id)).status === "done" || (await core.getSession(db, live[0]!.id)).status === "failed");
|
||||
await runner.moveTask(db, second, "backlog");
|
||||
|
||||
Loading…
Reference in New Issue
Block a user