PEP-214: индексы горячих запросов, keyPrefix вместо LIKE по settings, PRAGMA optimize
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
c0a590623d
commit
aff895db27
@ -15,7 +15,7 @@
|
||||
- CLI из теста с моком в том же процессе — только async execFile. Тест testkit не импортирует apps/web статически (типы Next ломают ProcessEnv) — `import(new URL(…).href)`.
|
||||
- Шаблонная строка с t()/m() внутри (`` `<b>${t("…")}</b>` ``) i18n-check считает непереведённой — собирай конкатенацией. В apps/bot `m` импортирован как `tr`.
|
||||
- localizeText выбирает вариант по числу НЕпереведённых русских букв, не по кириллице: казахский тоже кириллица.
|
||||
- Gitea 1.22 `GET /compare/<base>...<head>` — только имена веток (SHA → 404; mock-gitea так же). peppa-bot не создаёт организации (403) — их создаёт админ.
|
||||
- Gitea 1.22 `GET /compare/<base>...<head>` — только имена веток (SHA → 404; mock-gitea так же).
|
||||
- mock-gitea `POST /tags` ставит настоящий git-тег: нужны коммиты (`addRepo(…, { files })`) и существующий SHA (`gitea.sha(owner, repo, "main")`), иначе `deployProd`/`autoPublish` в тесте молча не срабатывают. Gitea «лежит» — `gitea.down = true`.
|
||||
- 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`.
|
||||
@ -25,6 +25,8 @@
|
||||
- Память ветки при мерже main склеивается построчно и разрастается дублями — после конфликта в `.peppa/memory.md` убери повторы (тест project-memory-size.test.ts).
|
||||
- Проверки «none» бывает от упавшего задания (DNS на git clone): смотри не-peppa статусы коммита (PEP-205).
|
||||
- QuickJS (PEP-212): строки из хост-функции читай синхронно до await (хэндлы аргументов слабые); все хэндлы и deferred dispose-ить, иначе rt.dispose падает.
|
||||
- Проверки «none» бывает от упавшего задания (DNS на git clone): смотри не-peppa статусы коммита (PEP-205). Codex-экран: `trimEnd()`, апостроф `’`.
|
||||
- Настройки по префиксу — `keyPrefix(settings.key, "x:")` из @peppa/db, не `like(…"x:%")` (LIKE без индекса). Новый индекс: schema.ts + `pnpm db:generate`, план — `explain query plan` (db-indexes.test.ts); `PRAGMA optimize` — в backupDb.
|
||||
|
||||
## Соглашения
|
||||
- Специалисты (PEP-183): агент с непустым character — специалист; подбор — `runner/team-match.ts` (haiku, `PEPPA_TEAM_BIN`), результат `team.match:<taskId>`, порог ожидания `platform.team.waitMin`; в `ensureSessionAgent` порядок: прежний → свободный специалист по профилю → универсал → специалист без очереди.
|
||||
|
||||
18
openspec/changes/pep-214-db-indexes/design.md
Normal file
18
openspec/changes/pep-214-db-indexes/design.md
Normal file
@ -0,0 +1,18 @@
|
||||
## Решения
|
||||
- Индексы только те, для которых на копии живой базы (events 42 тыс., chat_messages 10 тыс., check_runs 7 тыс.) план был `SCAN`: `events(project_id, created_at)`, `events(task_id, type)`, `questions(project_id, answered_at)`, `questions(task_id)`, `sessions(task_id, status)`, `sessions(status)`, `chat_messages(chat_id, thread_key, id)`, `tasks(project_id, status, position)`, `check_runs(task_id, sha)`. `runner_tasks` уже покрыт.
|
||||
- `LIKE 'x:%'` в SQLite нечувствителен к регистру и не берёт индекс. Вместо смены `case_sensitive_like` (ломает остальные LIKE) — `keyPrefix(column, prefix)`: `key >= 'x:' AND key < 'x;'`. Строже: `_` и `%` в префиксе больше не маски.
|
||||
- `json_extract` в WHERE (`team.match`) идёт по уже отобранным по префиксу строкам — индекс по выражению не нужен.
|
||||
- `PRAGMA optimize(0x10002)` после успешной ежедневной копии; сбой не портит копию.
|
||||
|
||||
## Замер (копия живой базы, мс на запрос, 300 повторов)
|
||||
| запрос | план до | после | до | после |
|
||||
|---|---|---|---|---|
|
||||
| events проекта по времени | SCAN events_created_at | SEARCH events_project_created | 7.70 | 0.003 |
|
||||
| events задачи+тип | SCAN | SEARCH events_task_type | 3.07 | 0.023 |
|
||||
| check_runs задачи+sha | SCAN | SEARCH check_runs_task_sha | 1.92 | 0.004 |
|
||||
| questions проекта открытые | SCAN | SEARCH questions_project_answered | 0.044 | 0.003 |
|
||||
| questions задачи | SCAN | SEARCH questions_task | 0.055 | 0.004 |
|
||||
| sessions задачи+статус | SCAN | SEARCH sessions_task_status | 0.024 | 0.004 |
|
||||
| sessions по статусу | SCAN | SEARCH sessions_status | 0.096 | 0.056 |
|
||||
| tasks колонка доски | SEARCH + TEMP B-TREE | SEARCH tasks_project_status_pos | 0.004 | 0.004 |
|
||||
| settings по префиксу | SCAN (LIKE) | SEARCH по ключу (диапазон) | 0.129 | 0.004 |
|
||||
10
openspec/changes/pep-214-db-indexes/proposal.md
Normal file
10
openspec/changes/pep-214-db-indexes/proposal.md
Normal file
@ -0,0 +1,10 @@
|
||||
## Why
|
||||
Главная, доска и чаты иногда отвечают 6–12 с: частые запросы к `events`, `questions`, `sessions`, `tasks`, `check_runs`, `chat_messages` просматривают таблицы целиком, а `settings` ищется через `LIKE 'префикс:%'`, который индекс не использует.
|
||||
|
||||
## What Changes
|
||||
- Миграция 0025: индексы под реальные запросы (проверены `EXPLAIN QUERY PLAN` на копии живой базы).
|
||||
- `keyPrefix()` в `@peppa/db` — поиск настройки по префиксу диапазоном по первичному ключу вместо `LIKE`.
|
||||
- `PRAGMA optimize` рядом с ежедневной копией базы в вачдоге.
|
||||
|
||||
## Impact
|
||||
Только скорость; поведение и тексты не меняются.
|
||||
15
openspec/changes/pep-214-db-indexes/specs/db-indexes/spec.md
Normal file
15
openspec/changes/pep-214-db-indexes/specs/db-indexes/spec.md
Normal file
@ -0,0 +1,15 @@
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: Горячие запросы используют индексы
|
||||
Частые запросы к `events`, `questions`, `sessions`, `tasks`, `check_runs`, `chat_messages` и поиск настроек по префиксу SHALL выполняться по индексу, без просмотра всей таблицы.
|
||||
|
||||
#### Scenario: События проекта по времени
|
||||
- **GIVEN** база с десятками тысяч событий
|
||||
- **WHEN** запрашиваются последние события проекта
|
||||
- **THEN** план запроса — `SEARCH events USING INDEX events_project_created`
|
||||
|
||||
#### Scenario: Настройки по префиксу
|
||||
- **GIVEN** в `settings` есть ключи «project.paused:1» и «project.pausedX»
|
||||
- **WHEN** запрашиваются ключи с префиксом «project.paused:»
|
||||
- **THEN** возвращается только «project.paused:1»
|
||||
- **AND** план запроса — `SEARCH settings` по ключу
|
||||
7
openspec/changes/pep-214-db-indexes/tasks.md
Normal file
7
openspec/changes/pep-214-db-indexes/tasks.md
Normal file
@ -0,0 +1,7 @@
|
||||
## 1. Индексы
|
||||
- [x] 1.1 Снять планы запросов на копии живой базы, добавить индексы в схему, миграция 0025
|
||||
- [x] 1.2 `keyPrefix` вместо `LIKE` по `settings.key`
|
||||
- [x] 1.3 `PRAGMA optimize` в ежедневной копии
|
||||
## 2. Проверка
|
||||
- [x] 2.1 Замер до/после (таблица в design.md)
|
||||
- [ ] 2.2 Тест `db-indexes.test.ts`, проверки CI, память, PR
|
||||
@ -1,6 +1,6 @@
|
||||
// PEP-127: «Принять» pressed while the story's PR conflicts with the main branch is remembered —
|
||||
// the agent rebases, Peppa merges and closes the story by itself (runner/accept-pending.ts).
|
||||
import { settings, type Db } from "@peppa/db";
|
||||
import { settings, type Db, keyPrefix } from "@peppa/db";
|
||||
import { m } from "@peppa/shared/i18n";
|
||||
import { like } from "drizzle-orm";
|
||||
import { deleteSetting, getSetting, setSetting } from "./settings.ts";
|
||||
@ -30,6 +30,6 @@ export const clearPendingAccept = (db: Db, taskId: number) => deleteSetting(db,
|
||||
|
||||
/** All remembered accepts: task id → state. */
|
||||
export async function listPendingAccepts(db: Db): Promise<Map<number, PendingAccept>> {
|
||||
const rows = await db.select().from(settings).where(like(settings.key, `${PREFIX}%`));
|
||||
const rows = await db.select().from(settings).where(keyPrefix(settings.key, `${PREFIX}`));
|
||||
return new Map(rows.map((r) => [Number(r.key.slice(PREFIX.length)), r.value as PendingAccept]));
|
||||
}
|
||||
|
||||
@ -2,7 +2,7 @@
|
||||
// the product page it changes, each with one plain sentence of what changed and the screenshots
|
||||
// «было» (the working version, staging — else what everyone sees) and «стало» (the story's own
|
||||
// version to check). No screenshot — a link to open the story's version to check.
|
||||
import { releases, settings, tasks, type Db } from "@peppa/db";
|
||||
import { releases, settings, tasks, type Db, keyPrefix } from "@peppa/db";
|
||||
import { formatTaskKey } from "@peppa/shared";
|
||||
import { m as tr } from "@peppa/shared/i18n";
|
||||
import { and, desc, eq, inArray, isNull, like } from "drizzle-orm";
|
||||
@ -142,7 +142,7 @@ export async function acceptFailure(db: Db, taskId: number): Promise<string | nu
|
||||
|
||||
/** Old failure notes of stories no longer in review go. */
|
||||
export async function pruneAcceptFailures(db: Db): Promise<void> {
|
||||
for (const row of await db.select().from(settings).where(like(settings.key, `${FAIL_PREFIX}%`))) {
|
||||
for (const row of await db.select().from(settings).where(keyPrefix(settings.key, `${FAIL_PREFIX}`))) {
|
||||
if (Date.now() - (row.value as { at: number }).at >= FAIL_TTL_MS) await db.delete(settings).where(eq(settings.key, row.key));
|
||||
}
|
||||
}
|
||||
|
||||
@ -69,6 +69,13 @@ export async function backupDb(db: Db, o: BackupOptions = {}): Promise<{ file?:
|
||||
const copies = readdirSync(dir).filter((f) => /^peppa-\d{4}-\d{2}-\d{2}\.db$/.test(f)).sort();
|
||||
for (const old of copies.slice(0, Math.max(0, copies.length - keep))) rmSync(join(dir, old), { force: true });
|
||||
await setSetting(db, KEY, { at: now.getTime(), file });
|
||||
// PEP-214: statistics for the query planner next to the daily copy (0x10002 = also analyse
|
||||
// tables that never had statistics). A failure here must not spoil the backup.
|
||||
try {
|
||||
db.$client.db.prepare("PRAGMA optimize(0x10002)").all();
|
||||
} catch (e) {
|
||||
log(`optimize failed: ${(e as Error).message}`);
|
||||
}
|
||||
log(`backup: ${file}`);
|
||||
return { file };
|
||||
}
|
||||
|
||||
@ -4,7 +4,7 @@
|
||||
// grows only within the capacity.
|
||||
import { m as tr } from "@peppa/shared/i18n";
|
||||
import { formatTaskKey } from "@peppa/shared";
|
||||
import { projects, sessions, settings, subscriptionPoolMembers, subscriptions, tasks, type Db } from "@peppa/db";
|
||||
import { projects, sessions, settings, subscriptionPoolMembers, subscriptions, tasks, type Db, keyPrefix } from "@peppa/db";
|
||||
import { and, eq, inArray, isNotNull, like, notInArray } from "drizzle-orm";
|
||||
import { PeppaError } from "./errors.ts";
|
||||
import { FINISHED_SESSION_STATUSES } from "./sessions.ts";
|
||||
@ -40,7 +40,7 @@ export async function poolCapacity(db: Db, poolId: number): Promise<number> {
|
||||
|
||||
/** Own capacities of the sets: poolId → value (sets with the default are absent). */
|
||||
export async function poolCapacities(db: Db): Promise<Map<number, number>> {
|
||||
const rows = await db.select().from(settings).where(like(settings.key, `${CAPACITY_PREFIX}%`));
|
||||
const rows = await db.select().from(settings).where(keyPrefix(settings.key, `${CAPACITY_PREFIX}`));
|
||||
return new Map(rows.map((r) => [Number(r.key.slice(CAPACITY_PREFIX.length)), Number(r.value)]));
|
||||
}
|
||||
|
||||
@ -112,7 +112,7 @@ export function teamHasRoomSync(tx: SyncDb, session: { subscriptionId: number |
|
||||
tx
|
||||
.select()
|
||||
.from(settings)
|
||||
.where(like(settings.key, `${CAPACITY_PREFIX}%`))
|
||||
.where(keyPrefix(settings.key, `${CAPACITY_PREFIX}`))
|
||||
.all()
|
||||
.map((r) => [Number(r.key.slice(CAPACITY_PREFIX.length)), Number(r.value)] as const),
|
||||
);
|
||||
@ -181,7 +181,7 @@ const WORKING = ["proposing", "awaiting_approval", "in_progress", "blocked"] as
|
||||
* Rows of stories that left work or were archived are not returned (`capacityQueueTick` drops them).
|
||||
*/
|
||||
export async function capacityQueue(db: Db, o: { projectIds?: number[] } = {}): Promise<CapacityQueueItem[]> {
|
||||
const rows = await db.select().from(settings).where(like(settings.key, `${WAIT_PREFIX}%`));
|
||||
const rows = await db.select().from(settings).where(keyPrefix(settings.key, `${WAIT_PREFIX}`));
|
||||
if (!rows.length) return [];
|
||||
const waits = new Map(rows.map((r) => [Number(r.key.slice(WAIT_PREFIX.length)), r.value as WaitRow] as const));
|
||||
const ts = await db
|
||||
@ -221,7 +221,7 @@ export async function capacityQueue(db: Db, o: { projectIds?: number[] } = {}):
|
||||
|
||||
/** Stories that left the queue's reach (out of work, archived, gone) — their rows are dropped. */
|
||||
export async function staleCapacityWaits(db: Db): Promise<number[]> {
|
||||
const rows = await db.select().from(settings).where(like(settings.key, `${WAIT_PREFIX}%`));
|
||||
const rows = await db.select().from(settings).where(keyPrefix(settings.key, `${WAIT_PREFIX}`));
|
||||
if (!rows.length) return [];
|
||||
const ids = rows.map((r) => Number(r.key.slice(WAIT_PREFIX.length)));
|
||||
const kept = new Set((await capacityQueue(db)).map((q) => q.taskId));
|
||||
|
||||
@ -3,7 +3,7 @@
|
||||
// fresh text, an «обновлено» time and a repeat counter (and waits for an answer again).
|
||||
// The state lives in `settings` (no schema change): questions without a row are older than the
|
||||
// rule and are never matched.
|
||||
import { checkRuns, questions, settings, tasks, type Db } from "@peppa/db";
|
||||
import { checkRuns, questions, settings, tasks, type Db, keyPrefix } from "@peppa/db";
|
||||
import { createHash } from "node:crypto";
|
||||
import { and, desc, eq, gt, inArray, isNull, like, lt } from "drizzle-orm";
|
||||
import { getSetting, setSetting } from "./settings.ts";
|
||||
@ -163,6 +163,6 @@ export async function chatRepeats(db: Db, messageIds: number[]): Promise<Map<num
|
||||
|
||||
/** Drops the state of messages nobody can repeat any more. */
|
||||
export async function pruneMessageStates(db: Db, before: Date): Promise<void> {
|
||||
await db.delete(settings).where(and(like(settings.key, `${PREFIX}%`), lt(settings.updatedAt, before)));
|
||||
await db.delete(settings).where(and(like(settings.key, `${CHAT_PREFIX}%`), lt(settings.updatedAt, before)));
|
||||
await db.delete(settings).where(and(keyPrefix(settings.key, `${PREFIX}`), lt(settings.updatedAt, before)));
|
||||
await db.delete(settings).where(and(keyPrefix(settings.key, `${CHAT_PREFIX}`), lt(settings.updatedAt, before)));
|
||||
}
|
||||
|
||||
@ -3,7 +3,7 @@
|
||||
// not the owner's business. The story is marked «задержка на нашей стороне» — one line in its
|
||||
// header and on its board card — the platform retries by itself, and the superadmin gets ONE
|
||||
// message with the details: again only when the state changed or the attempts ran out.
|
||||
import { projects, settings, tasks, type Db } from "@peppa/db";
|
||||
import { projects, settings, tasks, type Db, keyPrefix } from "@peppa/db";
|
||||
import { formatTaskKey } from "@peppa/shared";
|
||||
import { m as tr } from "@peppa/shared/i18n";
|
||||
import { inArray, like } from "drizzle-orm";
|
||||
@ -191,7 +191,7 @@ export async function platformDelay(db: Db, scope: DelayScope, r: DelayReport):
|
||||
export async function clearPlatformDelay(db: Db, scope: DelayScope, reason?: DelayReason): Promise<number> {
|
||||
const rows = reason
|
||||
? [{ key: key(scope, reason), value: await getSetting<PlatformDelay>(db, key(scope, reason)) }].filter((r) => r.value)
|
||||
: await db.select().from(settings).where(like(settings.key, `${PREFIX}${scopeKey(scope)}:%`));
|
||||
: await db.select().from(settings).where(keyPrefix(settings.key, `${PREFIX}${scopeKey(scope)}:`));
|
||||
for (const row of rows) {
|
||||
const d = row.value as PlatformDelay;
|
||||
await deleteSetting(db, row.key);
|
||||
@ -202,7 +202,7 @@ export async function clearPlatformDelay(db: Db, scope: DelayScope, reason?: Del
|
||||
|
||||
/** Every open delay, oldest first. */
|
||||
export async function listPlatformDelays(db: Db): Promise<PlatformDelay[]> {
|
||||
const rows = await db.select().from(settings).where(like(settings.key, `${PREFIX}%`));
|
||||
const rows = await db.select().from(settings).where(keyPrefix(settings.key, `${PREFIX}`));
|
||||
return rows.map((r) => r.value as PlatformDelay).sort((a, b) => a.since - b.since);
|
||||
}
|
||||
|
||||
@ -212,7 +212,7 @@ export async function delayedTaskIds(db: Db): Promise<Set<number>> {
|
||||
}
|
||||
|
||||
export async function taskDelayed(db: Db, taskId: number): Promise<boolean> {
|
||||
return (await db.select({ key: settings.key }).from(settings).where(like(settings.key, `${PREFIX}t${taskId}:%`))).length > 0;
|
||||
return (await db.select({ key: settings.key }).from(settings).where(keyPrefix(settings.key, `${PREFIX}t${taskId}:`))).length > 0;
|
||||
}
|
||||
|
||||
export const savePlatformDelay = (db: Db, d: PlatformDelay) => setSetting(db, key(d, d.reason), d);
|
||||
@ -278,7 +278,7 @@ export async function platformDelayOverview(db: Db): Promise<DelayView[]> {
|
||||
|
||||
/** PEP-209: the owner's one line on a delayed story — what to expect, never the terminal's text. */
|
||||
export async function taskDelayLine(db: Db, taskId: number, o: { now?: Date; timeZone?: string } = {}): Promise<string | null> {
|
||||
const list = (await db.select().from(settings).where(like(settings.key, `${PREFIX}t${taskId}:%`))).map((r) => r.value as PlatformDelay);
|
||||
const list = (await db.select().from(settings).where(keyPrefix(settings.key, `${PREFIX}t${taskId}:`))).map((r) => r.value as PlatformDelay);
|
||||
if (!list.length) return null;
|
||||
if (list.some((d) => d.exhausted)) return tr("Нужен администратор, мы ему сообщили");
|
||||
const now = (o.now ?? new Date()).getTime();
|
||||
|
||||
@ -2,7 +2,7 @@
|
||||
// AI roles (analyst, product agent, reviewer, triage) are not called, nobody gets notifications,
|
||||
// auto-merge and auto-close stand. Every such place asks `isProjectPaused` / `assertProjectActive`;
|
||||
// pausing and resuming themselves live in runner/pause.ts (they stop and resume the agents).
|
||||
import { settings, type Db } from "@peppa/db";
|
||||
import { settings, type Db, keyPrefix } from "@peppa/db";
|
||||
import { m } from "@peppa/shared/i18n";
|
||||
import { like } from "drizzle-orm";
|
||||
import { PeppaError } from "./errors.ts";
|
||||
@ -45,7 +45,7 @@ export async function assertProjectActive(db: Db, projectId: number | null | und
|
||||
|
||||
/** Ids of the paused projects (one query — for ticks and lists). */
|
||||
export async function pausedProjectIds(db: Db): Promise<Set<number>> {
|
||||
const rows = await db.select({ key: settings.key }).from(settings).where(like(settings.key, `${PREFIX}%`));
|
||||
const rows = await db.select({ key: settings.key }).from(settings).where(keyPrefix(settings.key, `${PREFIX}`));
|
||||
return new Set(rows.map((r) => Number(r.key.slice(PREFIX.length))));
|
||||
}
|
||||
|
||||
|
||||
@ -2,7 +2,7 @@
|
||||
// be merged right now — green checks of the PR head and no conflict. Otherwise the message is
|
||||
// held (`review.hold:<taskId>`) and the watchdog sends it once the gate opens
|
||||
// (runner/review-card.ts).
|
||||
import { settings, type Db } from "@peppa/db";
|
||||
import { settings, type Db, keyPrefix } from "@peppa/db";
|
||||
import { asIs, m } from "@peppa/shared/i18n";
|
||||
import { like } from "drizzle-orm";
|
||||
import { logEvent } from "./audit.ts";
|
||||
@ -41,7 +41,7 @@ export const setReviewHold = (db: Db, taskId: number, h: ReviewHold) => setSetti
|
||||
export const clearReviewHold = (db: Db, taskId: number) => deleteSetting(db, key(taskId));
|
||||
|
||||
export async function listReviewHolds(db: Db): Promise<Map<number, ReviewHold>> {
|
||||
const rows = await db.select().from(settings).where(like(settings.key, `${PREFIX}%`));
|
||||
const rows = await db.select().from(settings).where(keyPrefix(settings.key, `${PREFIX}`));
|
||||
return new Map(rows.map((r) => [Number(r.key.slice(PREFIX.length)), r.value as ReviewHold]));
|
||||
}
|
||||
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
// PEP-107: development doesn't stop on a limit — what a pool looks like right now (which
|
||||
// subscription is at work, when a limit resets), an early warning when a project is down to
|
||||
// its last subscription, and a superadmin lending a spare subscription to someone's pool.
|
||||
import { events, projects, sessions, settings, subscriptionPoolMembers, tasks, type Db } from "@peppa/db";
|
||||
import { events, projects, sessions, settings, subscriptionPoolMembers, tasks, type Db, keyPrefix } from "@peppa/db";
|
||||
import { and, desc, eq, inArray, like } from "drizzle-orm";
|
||||
import { m as tr, ruPlural } from "@peppa/shared/i18n";
|
||||
import { logEvent } from "./audit.ts";
|
||||
@ -35,7 +35,7 @@ interface LoanRow {
|
||||
}
|
||||
|
||||
export async function listLoans(db: Db): Promise<Loan[]> {
|
||||
const rows = await db.select().from(settings).where(like(settings.key, `${LOAN_PREFIX}%`));
|
||||
const rows = await db.select().from(settings).where(keyPrefix(settings.key, `${LOAN_PREFIX}`));
|
||||
return rows.map((r) => {
|
||||
const [poolId, subscriptionId] = r.key.slice(LOAN_PREFIX.length).split(":").map(Number);
|
||||
const v = r.value as LoanRow;
|
||||
|
||||
@ -6,7 +6,7 @@
|
||||
// description is built from the list. State lives in `settings` (`task.decisions:<taskId>`,
|
||||
// `task.split-of:<partId>`): no schema change. What a change sets in motion is runner/decisions.ts.
|
||||
import { m as tr } from "@peppa/shared/i18n";
|
||||
import { settings, tasks, type Db } from "@peppa/db";
|
||||
import { settings, tasks, type Db, keyPrefix } from "@peppa/db";
|
||||
import { and, eq, inArray, like } from "drizzle-orm";
|
||||
import { logEvent } from "./audit.ts";
|
||||
import { PeppaError } from "./errors.ts";
|
||||
@ -120,7 +120,7 @@ export const clearSplitPart = (db: Db, partId: number) => deleteSetting(db, spli
|
||||
|
||||
/** Parts of a split whose first story is not accepted yet: the dispatcher does not take them (4.1). */
|
||||
export async function splitWaiting(db: Db, projectId: number): Promise<Set<number>> {
|
||||
const rows = await db.select().from(settings).where(like(settings.key, `${SPLIT_OF_PREFIX}%`));
|
||||
const rows = await db.select().from(settings).where(keyPrefix(settings.key, `${SPLIT_OF_PREFIX}`));
|
||||
if (!rows.length) return new Set();
|
||||
const pairs = rows.map((r) => ({ part: Number(r.key.slice(SPLIT_OF_PREFIX.length)), parent: Number(r.value) })).filter((p) => p.part && p.parent);
|
||||
const ids = [...new Set(pairs.flatMap((p) => [p.part, p.parent]))];
|
||||
|
||||
@ -3,7 +3,7 @@
|
||||
// decided once by a short model call (runner/team-match.ts) and kept here in `settings`
|
||||
// (`team.match:<taskId>`); `ensureSessionAgent` (team.ts) and the dispatcher read it.
|
||||
import { asIs, m as tr } from "@peppa/shared/i18n";
|
||||
import { agents, sessions, settings, type Db } from "@peppa/db";
|
||||
import { agents, sessions, settings, type Db, keyPrefix } from "@peppa/db";
|
||||
import { and, eq, isNull, like, notInArray, sql } from "drizzle-orm";
|
||||
import { PeppaError } from "./errors.ts";
|
||||
import { getSetting, setSetting } from "./settings.ts";
|
||||
@ -104,7 +104,7 @@ export async function queuedForSpecialist(db: Db, agentId: number): Promise<numb
|
||||
const rows = await db
|
||||
.select({ key: settings.key, v: settings.value, status: sql<string>`(select status from tasks t where t.id = cast(substr(${settings.key}, 12) as integer))` })
|
||||
.from(settings)
|
||||
.where(and(like(settings.key, "team.match:%"), sql`json_extract(${settings.value}, '$.agentId') = ${agentId}`));
|
||||
.where(and(keyPrefix(settings.key, "team.match:"), sql`json_extract(${settings.value}, '$.agentId') = ${agentId}`));
|
||||
return rows.filter((r) => r.status === "backlog").length;
|
||||
}
|
||||
|
||||
@ -113,7 +113,7 @@ export async function profileTaskCounts(db: Db): Promise<Map<number, number>> {
|
||||
const rows = await db
|
||||
.select({ id: sql<number>`json_extract(${settings.value}, '$.agentId')`, n: sql<number>`count(*)` })
|
||||
.from(settings)
|
||||
.where(and(like(settings.key, "team.match:%"), sql`json_extract(${settings.value}, '$.given') = 1`))
|
||||
.where(and(keyPrefix(settings.key, "team.match:"), sql`json_extract(${settings.value}, '$.given') = 1`))
|
||||
.groupBy(sql`json_extract(${settings.value}, '$.agentId')`);
|
||||
return new Map(rows.map((r) => [Number(r.id), Number(r.n)]));
|
||||
}
|
||||
|
||||
@ -3,7 +3,7 @@
|
||||
// and across the story's later runners; the PM gives each a character (markdown) that goes into
|
||||
// the agent's prompt on top of the shared rules and the project's AGENTS.md.
|
||||
import { m as tr } from "@peppa/shared/i18n";
|
||||
import { agents, sessions, settings, tasks, type Db } from "@peppa/db";
|
||||
import { agents, sessions, settings, tasks, type Db, keyPrefix } from "@peppa/db";
|
||||
import { and, asc, desc, eq, isNotNull, isNull, notInArray, sql } from "drizzle-orm";
|
||||
import { PeppaError } from "./errors.ts";
|
||||
import { isSpecialist, matchKey, profileTaskCounts, type TeamMatch } from "./team-match.ts";
|
||||
@ -143,7 +143,7 @@ export async function ensureSessionAgent(db: Db, sessionId: number): Promise<Age
|
||||
// No free generalist: a free specialist, unless stories of his profile are in the queue.
|
||||
if (!agent) {
|
||||
const wanted = new Set(
|
||||
tx.select({ key: settings.key, v: settings.value, status: tasks.status }).from(settings).innerJoin(tasks, sql`${tasks.id} = cast(substr(${settings.key}, 12) as integer)`).where(sql`${settings.key} like 'team.match:%'`).all()
|
||||
tx.select({ key: settings.key, v: settings.value, status: tasks.status }).from(settings).innerJoin(tasks, sql`${tasks.id} = cast(substr(${settings.key}, 12) as integer)`).where(keyPrefix(settings.key, "team.match:")).all()
|
||||
.filter((r) => r.status === "backlog").map((r) => (r.v as TeamMatch).agentId),
|
||||
);
|
||||
agent = free.find((a) => isSpecialist(a) && !wanted.has(a.id));
|
||||
|
||||
@ -4,7 +4,7 @@
|
||||
// neither — the UI says «нет данных» rather than inventing numbers.
|
||||
import { m as tr } from "@peppa/shared/i18n";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { projects, sessions, settings, subscriptionPoolMembers, subscriptions, type Db, type SessionUsage, type UsageTokens } from "@peppa/db";
|
||||
import { projects, sessions, settings, subscriptionPoolMembers, subscriptions, type Db, type SessionUsage, type UsageTokens, keyPrefix } from "@peppa/db";
|
||||
import { and, eq, inArray, like, notInArray } from "drizzle-orm";
|
||||
import type { User } from "./users.ts";
|
||||
import { userProjectIds } from "./users.ts";
|
||||
@ -358,7 +358,7 @@ export async function agentsLine(db: Db, user: Pick<User, "id" | "login">, now =
|
||||
|
||||
export async function listAccountUsage(db: Db, o: { subscriptionIds?: number[] | null; machine?: boolean; now?: number } = {}): Promise<AccountUsage[]> {
|
||||
const now = o.now ?? Date.now();
|
||||
const rows = await db.select().from(settings).where(like(settings.key, "usage.account:%"));
|
||||
const rows = await db.select().from(settings).where(keyPrefix(settings.key, "usage.account:"));
|
||||
const byKey = new Map(rows.map((r) => [r.key, r.value as AccountWindows]));
|
||||
const subs = o.subscriptionIds === undefined || o.subscriptionIds === null ? await db.select().from(subscriptions) : o.subscriptionIds.length ? await db.select().from(subscriptions).where(inArray(subscriptions.id, o.subscriptionIds)) : [];
|
||||
const view = (key: string, base: Omit<AccountUsage, "key" | "fiveHour" | "sevenDay" | "at" | "stale">): AccountUsage => {
|
||||
|
||||
@ -3,7 +3,7 @@
|
||||
// <system-reminder>, any XML/HTML-like tag), ANSI sequences, code and command output, shell
|
||||
// prompt lines, stack traces, absolute paths. The original stays under «Подробнее» for a
|
||||
// superadmin and the «Инженер» view (`question.details:<id>`), never in the main text.
|
||||
import { settings, type Db } from "@peppa/db";
|
||||
import { settings, type Db, keyPrefix } from "@peppa/db";
|
||||
import { and, like, lt } from "drizzle-orm";
|
||||
import { PeppaError } from "./errors.ts";
|
||||
import { deleteSetting, getSetting, setSetting } from "./settings.ts";
|
||||
@ -140,5 +140,5 @@ export async function questionDetails(db: Db, questionId: number): Promise<strin
|
||||
}
|
||||
|
||||
export async function pruneQuestionDetails(db: Db, before: Date): Promise<void> {
|
||||
await db.delete(settings).where(and(like(settings.key, `${DETAILS_PREFIX}%`), lt(settings.updatedAt, before)));
|
||||
await db.delete(settings).where(and(keyPrefix(settings.key, `${DETAILS_PREFIX}`), lt(settings.updatedAt, before)));
|
||||
}
|
||||
|
||||
9
packages/db/migrations/0026_redundant_black_bolt.sql
Normal file
9
packages/db/migrations/0026_redundant_black_bolt.sql
Normal file
@ -0,0 +1,9 @@
|
||||
CREATE INDEX `chat_messages_thread` ON `chat_messages` (`chat_id`,`thread_key`,`id`);--> statement-breakpoint
|
||||
CREATE INDEX `check_runs_task_sha` ON `check_runs` (`task_id`,`sha`);--> statement-breakpoint
|
||||
CREATE INDEX `events_project_created` ON `events` (`project_id`,`created_at`);--> statement-breakpoint
|
||||
CREATE INDEX `events_task_type` ON `events` (`task_id`,`type`);--> statement-breakpoint
|
||||
CREATE INDEX `questions_project_answered` ON `questions` (`project_id`,`answered_at`);--> statement-breakpoint
|
||||
CREATE INDEX `questions_task` ON `questions` (`task_id`);--> statement-breakpoint
|
||||
CREATE INDEX `sessions_task_status` ON `sessions` (`task_id`,`status`);--> statement-breakpoint
|
||||
CREATE INDEX `sessions_status` ON `sessions` (`status`);--> statement-breakpoint
|
||||
CREATE INDEX `tasks_project_status_pos` ON `tasks` (`project_id`,`status`,`position`);
|
||||
4694
packages/db/migrations/meta/0026_snapshot.json
Normal file
4694
packages/db/migrations/meta/0026_snapshot.json
Normal file
File diff suppressed because it is too large
Load Diff
@ -183,6 +183,13 @@
|
||||
"when": 1795173370063,
|
||||
"tag": "0025_events_type_created",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 26,
|
||||
"version": "6",
|
||||
"when": 1795183002485,
|
||||
"tag": "0026_redundant_black_bolt",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@ -2,7 +2,7 @@ import { loadEnv } from "@peppa/shared";
|
||||
import { BetterSQLiteSession } from "drizzle-orm/better-sqlite3/session";
|
||||
import { migrate as drizzleMigrate } from "drizzle-orm/better-sqlite3/migrator";
|
||||
import { createTableRelationsHelpers, extractTablesRelationalConfig } from "drizzle-orm/relations";
|
||||
import { is } from "drizzle-orm";
|
||||
import { and, gte, is, lt, type SQL, type SQLWrapper } from "drizzle-orm";
|
||||
import { getTableConfig, SQLiteTable } from "drizzle-orm/sqlite-core";
|
||||
import { BaseSQLiteDatabase } from "drizzle-orm/sqlite-core/db";
|
||||
import { SQLiteSyncDialect } from "drizzle-orm/sqlite-core/dialect";
|
||||
@ -15,6 +15,15 @@ import * as schema from "./schema.ts";
|
||||
export * from "./schema.ts";
|
||||
export { schema, SqliteClient };
|
||||
|
||||
/**
|
||||
* PEP-214: «ключ начинается с префикса» диапазоном по первичному ключу. `LIKE 'x:%'` в SQLite
|
||||
* не берёт индекс (нечувствителен к регистру, `_` и `%` — маски) и просматривает всю таблицу.
|
||||
*/
|
||||
export function keyPrefix(column: SQLWrapper, prefix: string): SQL {
|
||||
const end = prefix.slice(0, -1) + String.fromCharCode(prefix.charCodeAt(prefix.length - 1) + 1);
|
||||
return and(gte(column as never, prefix), lt(column as never, end)) as SQL;
|
||||
}
|
||||
|
||||
export type Db = BaseSQLiteDatabase<"sync", StatementResultingChanges, typeof schema> & { $client: SqliteClient };
|
||||
|
||||
/** Opens Peppa's SQLite database (PEPPA_DB, default ~/.peppa/peppa.db). */
|
||||
|
||||
@ -153,7 +153,7 @@ export const tasks = sqliteTable(
|
||||
createdAt: createdAt(),
|
||||
updatedAt: updatedAt(),
|
||||
},
|
||||
(t) => [uniqueIndex("tasks_project_number").on(t.projectId, t.number), uniqueIndex("tasks_project_issue").on(t.projectId, t.giteaIssue)],
|
||||
(t) => [uniqueIndex("tasks_project_number").on(t.projectId, t.number), uniqueIndex("tasks_project_issue").on(t.projectId, t.giteaIssue), index("tasks_project_status_pos").on(t.projectId, t.status, t.position)],
|
||||
);
|
||||
|
||||
/** PEP-42: "task waits for blocked_by" — a story is blocked until its predecessors reach review/done. */
|
||||
@ -211,7 +211,7 @@ export const checkRuns = sqliteTable(
|
||||
createdAt: createdAt(),
|
||||
updatedAt: updatedAt(),
|
||||
},
|
||||
(t) => [uniqueIndex("check_runs_project_sha_check").on(t.projectId, t.sha, t.check)],
|
||||
(t) => [uniqueIndex("check_runs_project_sha_check").on(t.projectId, t.sha, t.check), index("check_runs_task_sha").on(t.taskId, t.sha)],
|
||||
);
|
||||
|
||||
export const sessionStatus = { enumValues: [
|
||||
@ -353,7 +353,8 @@ export const sessions = sqliteTable("sessions", {
|
||||
lastActivityAt: integer("last_activity_at", { mode: "timestamp_ms" }),
|
||||
startedAt: createdAt(),
|
||||
endedAt: integer("ended_at", { mode: "timestamp_ms" }),
|
||||
});
|
||||
},
|
||||
(t) => [index("sessions_task_status").on(t.taskId, t.status), index("sessions_status").on(t.status)]);
|
||||
|
||||
/**
|
||||
* PEP-10: stories of a runner — its history (`active` → `done`) and queue (`queued`, by id;
|
||||
@ -402,7 +403,8 @@ export const questions = sqliteTable("questions", {
|
||||
reminders: integer("reminders").notNull().default(0),
|
||||
createdAt: createdAt(),
|
||||
answeredAt: integer("answered_at", { mode: "timestamp_ms" }),
|
||||
});
|
||||
},
|
||||
(t) => [index("questions_project_answered").on(t.projectId, t.answeredAt), index("questions_task").on(t.taskId)]);
|
||||
|
||||
/** PEP-28: the watchdog's memory of a runner (sessions.watch_state). */
|
||||
export type WatchState = {
|
||||
@ -492,7 +494,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), index("events_type_created").on(t.type, t.createdAt)],
|
||||
(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), index("events_project_created").on(t.projectId, t.createdAt), index("events_task_type").on(t.taskId, t.type)],
|
||||
);
|
||||
|
||||
/** Small key/value store for service state (Telegram offset, pairing, binding). */
|
||||
@ -569,7 +571,7 @@ export const chatMessages = sqliteTable(
|
||||
tgMessageId: integer("tg_message_id"),
|
||||
createdAt: createdAt(),
|
||||
},
|
||||
(t) => [index("chat_messages_chat").on(t.chatId, t.id), index("chat_messages_created_at").on(t.createdAt), index("chat_messages_tg").on(t.tgChatId, t.tgMessageId)],
|
||||
(t) => [index("chat_messages_chat").on(t.chatId, t.id), index("chat_messages_thread").on(t.chatId, t.threadKey, t.id), index("chat_messages_created_at").on(t.createdAt), index("chat_messages_tg").on(t.tgChatId, t.tgMessageId)],
|
||||
);
|
||||
|
||||
/** Telegram updates already taken: recorded before acting, so a restart never replays one. */
|
||||
|
||||
@ -6,7 +6,7 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { promisify } from "node:util";
|
||||
import { getSetting, listProjects, logEvent, setSetting } from "@peppa/core";
|
||||
import { settings, type Db } from "@peppa/db";
|
||||
import { settings, type Db, keyPrefix } from "@peppa/db";
|
||||
import { like } from "drizzle-orm";
|
||||
import { platformKey } from "./platform-release.ts";
|
||||
|
||||
@ -33,7 +33,7 @@ export async function actRunnerTick(db: Db, o: { now?: Date; log?: (m: string) =
|
||||
let reason: ActRunnerRestart | null = state === "running" ? null : "down";
|
||||
const last = (await getSetting<{ at: number }>(db, RESTART_KEY))?.at ?? 0;
|
||||
if (!reason && now - last >= RESTART_GAP_MS) {
|
||||
const waits = await db.select().from(settings).where(like(settings.key, "checks.wait:%"));
|
||||
const waits = await db.select().from(settings).where(keyPrefix(settings.key, "checks.wait:"));
|
||||
const hung = waits.some((w) => {
|
||||
const v = w.value as { stuck?: boolean; cause?: string; since: number };
|
||||
return v.stuck && v.cause === "no_job" && now - v.since >= HUNG_AFTER_MS;
|
||||
|
||||
@ -4,7 +4,7 @@
|
||||
// `deploy-prod-*` tag at the healthy staging commit (Gitea 1.22 has no workflow_dispatch API).
|
||||
import { asIs, m } from "@peppa/shared/i18n";
|
||||
import { clearPlatformDelay, listPlatformDelays, platformDelay, taskForCheck, answerQuestion, askPmProject, deleteSetting, getPublishMode, getSetting, setSetting, resolveTask, giteaForBot, logEvent, markSecretsRestart, needsLine, openNeeds, PeppaError, projectSecretMasker, queueProductReview, runLink, type GiteaClient, type Project, type Question, platformFailure, isProjectPaused } from "@peppa/core";
|
||||
import { projects, questions, releases, settings, type Db } from "@peppa/db";
|
||||
import { projects, questions, releases, settings, type Db, keyPrefix } from "@peppa/db";
|
||||
import { and, desc, eq, inArray, isNull, sql } from "drizzle-orm";
|
||||
import { deployPlatform, isPlatform } from "./platform-release.ts";
|
||||
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
||||
@ -260,7 +260,7 @@ export async function productRedeployTick(db: Db, o: { now?: Date; client?: Gite
|
||||
const now = (o.now ?? new Date()).getTime();
|
||||
const quietMs = Math.max(0, Number(process.env.PEPPA_SECRETS_REDEPLOY_DELAY_SEC ?? 120)) * 1000;
|
||||
const created: string[] = [];
|
||||
const rows = await db.select().from(settings).where(sql`${settings.key} like ${`${REDEPLOY_PREFIX}%`}`);
|
||||
const rows = await db.select().from(settings).where(keyPrefix(settings.key, REDEPLOY_PREFIX));
|
||||
for (const row of rows) {
|
||||
const at = (row.value as { at?: number } | null)?.at ?? 0;
|
||||
if (now - at < quietMs) continue;
|
||||
|
||||
@ -28,7 +28,7 @@ import {
|
||||
type Question,
|
||||
type TaskRef,
|
||||
} from "@peppa/core";
|
||||
import { settings, type Db } from "@peppa/db";
|
||||
import { settings, type Db, keyPrefix } from "@peppa/db";
|
||||
import { like } from "drizzle-orm";
|
||||
import { wakeOnGreen } from "./ci-feedback.ts";
|
||||
import { moveTask } from "./flow.ts";
|
||||
@ -181,7 +181,7 @@ export async function checksQueueTick(db: Db, o: { stuckMin: number; now?: Date;
|
||||
}
|
||||
}
|
||||
// Stories that left work/review or lost their result: nothing to wait for.
|
||||
for (const row of await db.select().from(settings).where(like(settings.key, `${WAIT_PREFIX}%`))) {
|
||||
for (const row of await db.select().from(settings).where(keyPrefix(settings.key, `${WAIT_PREFIX}`))) {
|
||||
const taskId = Number(row.key.slice(WAIT_PREFIX.length));
|
||||
if (seen.has(taskId)) continue;
|
||||
const ref = await resolveTaskById(db, taskId).catch(() => null);
|
||||
|
||||
@ -44,7 +44,7 @@ import {
|
||||
type Project,
|
||||
isProjectPaused,
|
||||
} from "@peppa/core";
|
||||
import { projects, releases, settings, tasks, type Db } from "@peppa/db";
|
||||
import { projects, releases, settings, tasks, type Db, keyPrefix } from "@peppa/db";
|
||||
import { and, desc, eq, isNull, ne, sql } from "drizzle-orm";
|
||||
import { m as tr, t, type Locale } from "@peppa/shared/i18n";
|
||||
import { sayInDiscussion } from "./analyst-chat.ts";
|
||||
@ -69,7 +69,7 @@ export async function productReviewTick(db: Db, opts: ProductReviewOptions = {})
|
||||
const log = opts.log ?? (() => {});
|
||||
const jobs: Promise<void>[] = [];
|
||||
await productDigestTick(db, opts.now ?? new Date(), log).catch((e) => log(`product digest: ${(e as Error).message}`));
|
||||
const rows = await db.select().from(settings).where(sql`${settings.key} like ${`${PRODUCT_REVIEW_PENDING_PREFIX}%`}`);
|
||||
const rows = await db.select().from(settings).where(keyPrefix(settings.key, PRODUCT_REVIEW_PENDING_PREFIX));
|
||||
for (const row of rows) {
|
||||
const projectId = Number(row.key.slice(PRODUCT_REVIEW_PENDING_PREFIX.length));
|
||||
// PEP-174: the product agent waits while the project is on pause.
|
||||
@ -258,7 +258,7 @@ const DIGEST_EVERY_MS = 7 * 86_400_000;
|
||||
* one message (to «Предложено», with the same buttons).
|
||||
*/
|
||||
export async function productDigestTick(db: Db, now: Date, log: (m: string) => void = () => {}): Promise<void> {
|
||||
const rows = await db.select().from(settings).where(sql`${settings.key} like ${"product.digest:%"}`);
|
||||
const rows = await db.select().from(settings).where(keyPrefix(settings.key, "product.digest:"));
|
||||
for (const row of rows) {
|
||||
const projectId = Number(row.key.slice("product.digest:".length));
|
||||
const d = await getDigest(db, projectId);
|
||||
|
||||
@ -5,7 +5,7 @@
|
||||
// sends the «ready for review» card — with no turn of the agent. Red checks drop the mark: the CI
|
||||
// feedback brings the log to the agent, who asks for review again after the fix.
|
||||
import { buildReviewCard, deleteSetting, getSetting, listSessions, prGate, sendReviewCard, setSetting, updateTask, logEvent, isProjectPaused, type TaskRef } from "@peppa/core";
|
||||
import { settings, type Db } from "@peppa/db";
|
||||
import { settings, type Db, keyPrefix } from "@peppa/db";
|
||||
import { like } from "drizzle-orm";
|
||||
import { REVIEW_WANTED_PREFIX, type ReviewWanted } from "./review-wanted-state.ts";
|
||||
import { requestReview } from "./reviewer.ts";
|
||||
@ -15,7 +15,7 @@ import { resolveTaskById } from "./sessions.ts";
|
||||
export async function reviewWantedTick(db: Db, o: { log?: (m: string) => void } = {}): Promise<number> {
|
||||
const log = o.log ?? (() => {});
|
||||
let moved = 0;
|
||||
for (const row of await db.select().from(settings).where(like(settings.key, `${REVIEW_WANTED_PREFIX}%`))) {
|
||||
for (const row of await db.select().from(settings).where(keyPrefix(settings.key, `${REVIEW_WANTED_PREFIX}`))) {
|
||||
const taskId = Number(row.key.slice(REVIEW_WANTED_PREFIX.length));
|
||||
const want = row.value as ReviewWanted;
|
||||
try {
|
||||
|
||||
@ -37,7 +37,7 @@ import {
|
||||
type SessionView,
|
||||
type TaskRef,
|
||||
} from "@peppa/core";
|
||||
import { settings, type Db } from "@peppa/db";
|
||||
import { settings, type Db, keyPrefix } from "@peppa/db";
|
||||
import { formatTaskKey } from "@peppa/shared";
|
||||
import { m } from "@peppa/shared/i18n";
|
||||
import { like } from "drizzle-orm";
|
||||
@ -189,7 +189,7 @@ export async function stuckTaskTick(db: Db, o: { now?: Date; log?: Log; gitea?:
|
||||
}
|
||||
}
|
||||
// The count is per stay in work: a story that left work starts afresh next time.
|
||||
for (const row of await db.select({ key: settings.key }).from(settings).where(like(settings.key, `${HEAL_PREFIX}%`))) {
|
||||
for (const row of await db.select({ key: settings.key }).from(settings).where(keyPrefix(settings.key, `${HEAL_PREFIX}`))) {
|
||||
const id = Number(row.key.slice(HEAL_PREFIX.length));
|
||||
if (!inWork.has(id) && !(await resolveTaskById(db, id).then((r) => r.task.status === "in_progress" && paused.has(r.project.id), () => false))) await deleteSetting(db, row.key);
|
||||
}
|
||||
|
||||
@ -39,7 +39,7 @@ import {
|
||||
type Subscription,
|
||||
type User,
|
||||
} from "@peppa/core";
|
||||
import { projects, settings, type Db } from "@peppa/db";
|
||||
import { projects, settings, type Db, keyPrefix } from "@peppa/db";
|
||||
import { eq, like } from "drizzle-orm";
|
||||
import { onAnswer } from "./sessions.ts";
|
||||
import { isRunnerClient } from "./runner-client.ts";
|
||||
@ -84,7 +84,7 @@ export async function subscriptionRequest(db: Db, projectId: number): Promise<Su
|
||||
}
|
||||
|
||||
async function allRequests(db: Db): Promise<Array<{ projectId: number; req: SubscriptionRequest }>> {
|
||||
const rows = await db.select().from(settings).where(like(settings.key, `${PREFIX}%`));
|
||||
const rows = await db.select().from(settings).where(keyPrefix(settings.key, `${PREFIX}`));
|
||||
return rows.map((r) => ({ projectId: Number(r.key.slice(PREFIX.length)), req: r.value as SubscriptionRequest })).filter((x) => Number.isFinite(x.projectId));
|
||||
}
|
||||
|
||||
|
||||
41
packages/testkit/test/db-indexes.test.ts
Normal file
41
packages/testkit/test/db-indexes.test.ts
Normal file
@ -0,0 +1,41 @@
|
||||
// PEP-214: горячие запросы идут по индексам; поиск настроек по префиксу — диапазоном по ключу.
|
||||
import assert from "node:assert/strict";
|
||||
import { after, describe, test } from "node:test";
|
||||
import { db, teardown } from "./helpers.ts";
|
||||
import { keyPrefix, settings } from "@peppa/db";
|
||||
|
||||
after(teardown);
|
||||
|
||||
const plan = (sql: string) => (db.$client.db.prepare(`explain query plan ${sql}`).all() as { detail: string }[]).map((r) => r.detail).join(" | ");
|
||||
|
||||
describe("Индексы горячих запросов", () => {
|
||||
test("Scenario: события проекта по времени — поиск по индексу", () => {
|
||||
assert.match(plan("select * from events where project_id = 1 order by created_at desc limit 50"), /SEARCH events USING INDEX events_project_created/);
|
||||
});
|
||||
test("Scenario Outline: частые фильтры не просматривают таблицу целиком", () => {
|
||||
const cases: [string, RegExp][] = [
|
||||
["select * from events where task_id = 5 and type = 'x'", /events_task_type/],
|
||||
["select * from questions where project_id = 1 and answered_at is null", /questions_project_answered/],
|
||||
["select * from questions where task_id = 5", /questions_task/],
|
||||
["select * from sessions where task_id = 5 and status = 'idle'", /sessions_task_status/],
|
||||
["select * from sessions where status = 'idle'", /sessions_status/],
|
||||
["select * from chat_messages where chat_id = 1 and thread_key = 'task:5' order by id desc", /chat_messages_thread/],
|
||||
["select * from tasks where project_id = 1 and status = 'review' order by position", /tasks_project_status_pos/],
|
||||
["select * from check_runs where task_id = 5 and sha = 'a'", /check_runs_task_sha/],
|
||||
];
|
||||
for (const [q, re] of cases) assert.match(plan(q), re, q);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Настройки по префиксу", () => {
|
||||
test("Scenario: только ключи с префиксом, без масок LIKE", async () => {
|
||||
for (const key of ["pep214.paused:1", "pep214.paused:2", "pep214.pausedX", "pep214_paused:3", "PEP214.PAUSED:4"]) {
|
||||
await db.insert(settings).values({ key, value: "1" }).onConflictDoNothing();
|
||||
}
|
||||
const rows = await db.select().from(settings).where(keyPrefix(settings.key, "pep214.paused:"));
|
||||
assert.deepEqual(rows.map((r) => r.key).sort(), ["pep214.paused:1", "pep214.paused:2"]);
|
||||
});
|
||||
test("Scenario: поиск по префиксу идёт по ключу", () => {
|
||||
assert.match(plan("select * from settings where key >= 'a:' and key < 'a;'"), /SEARCH settings USING (COVERING )?INDEX/);
|
||||
});
|
||||
});
|
||||
@ -6,7 +6,7 @@ import { after, before, beforeEach, describe, test } from "node:test";
|
||||
import { core, db, teardown, waitFor } from "./helpers.ts";
|
||||
import { MockTelegram } from "../src/mock-telegram.ts";
|
||||
import { MockPushService } from "../src/mock-push.ts";
|
||||
import { projects, pushOutbox, pushSubscriptions, questions, sessions, settings, tasks, telegramOutbox, users } from "@peppa/db";
|
||||
import { projects, pushOutbox, pushSubscriptions, questions, sessions, settings, tasks, telegramOutbox, users, keyPrefix } from "@peppa/db";
|
||||
import { eq, like, sql } from "drizzle-orm";
|
||||
import type { Bot } from "@peppa/bot";
|
||||
|
||||
@ -195,7 +195,7 @@ describe("daily digest", () => {
|
||||
|
||||
test("Сценарий: утренний дайджест — одна сводка за день с сделанным, в работе и ждущим", async () => {
|
||||
await db.delete(questions);
|
||||
await db.delete(settings).where(like(settings.key, "digest.last:%"));
|
||||
await db.delete(settings).where(keyPrefix(settings.key, "digest.last:"));
|
||||
// Only this project counts for the digest (older ones are muted for the PM).
|
||||
await setPrefs(pm, { mutedProjects: (await db.select({ id: projects.id }).from(projects)).map((p) => p.id) });
|
||||
const p = await newProject("Digest");
|
||||
@ -221,7 +221,7 @@ describe("daily digest", () => {
|
||||
});
|
||||
|
||||
test("Сценарий: выкат вечером — до завтрашних 09:00 сводки нет; выключенный дайджест не приходит", async () => {
|
||||
await db.delete(settings).where(like(settings.key, "digest.last:%"));
|
||||
await db.delete(settings).where(keyPrefix(settings.key, "digest.last:"));
|
||||
assert.equal(await core.digestTick(db, { now: at("20:00", 12) }), 0);
|
||||
await setPrefs(pm, { events: { ...(await prefs(pm)).events, digest: { telegram: false, push: false } } });
|
||||
await setPrefs(bob, { events: { ...(await prefs(bob)).events, digest: { telegram: false, push: false } } });
|
||||
|
||||
@ -8,7 +8,7 @@ import { after, before, beforeEach, describe, test } from "node:test";
|
||||
import { core, db, project, runner, setDefaultOwner, teardown, waitFor, type TestProject } from "./helpers.ts";
|
||||
import { MockGitea } from "../src/mock-gitea.ts";
|
||||
import { MockBugsink } from "../src/mock-bugsink.ts";
|
||||
import { questions, telegramOutbox, users } from "@peppa/db";
|
||||
import { questions, telegramOutbox, users, keyPrefix } from "@peppa/db";
|
||||
import { eq, sql } from "drizzle-orm";
|
||||
import { stripAsIs } from "@peppa/shared/i18n";
|
||||
|
||||
@ -345,7 +345,7 @@ describe("PEP-205: очередь проверок стоит", () => {
|
||||
beforeEach(async () => {
|
||||
const { settings } = await import("@peppa/db");
|
||||
const { like, or } = await import("drizzle-orm");
|
||||
await db.delete(settings).where(or(like(settings.key, "checks.wait:%"), eq(settings.key, "checks.queue"))!);
|
||||
await db.delete(settings).where(or(keyPrefix(settings.key, "checks.wait:"), eq(settings.key, "checks.queue"))!);
|
||||
});
|
||||
const ciJob = (proj: { giteaOwner: string; giteaRepo: string }, sha: string, status: string) => gitea.setStatus(proj.giteaOwner, proj.giteaRepo, sha, "ci / checks (pull_request)", status);
|
||||
const queueMsgs = async (key: string) => (await sentTo(ADMIN_CHAT)).filter((x) => x.includes("Очередь проверок") && x.includes(key));
|
||||
|
||||
@ -9,7 +9,7 @@ import { fileURLToPath } from "node:url";
|
||||
import { promisify } from "node:util";
|
||||
import { after, describe, test } from "node:test";
|
||||
import { core, db, teardown } from "./helpers.ts";
|
||||
import { createDb, events, projects, settings } from "@peppa/db";
|
||||
import { createDb, events, projects, settings, keyPrefix } from "@peppa/db";
|
||||
import type { PeppaNotification } from "@peppa/core";
|
||||
import { like, sql } from "drizzle-orm";
|
||||
import postgres from "postgres";
|
||||
@ -26,7 +26,7 @@ describe("Одна база SQLite для всех процессов", () => {
|
||||
const results = await Promise.allSettled(Array.from({ length: 20 }, (_, i) => worker("settings", "25", `p${i}`)));
|
||||
const failed = results.filter((r) => r.status === "rejected");
|
||||
assert.equal(failed.length, 0, failed.map((r) => String((r as PromiseRejectedResult).reason)).join("\n"));
|
||||
const [{ n }] = await db.select({ n: sql<number>`count(*)` }).from(settings).where(like(settings.key, "storage:%"));
|
||||
const [{ n }] = await db.select({ n: sql<number>`count(*)` }).from(settings).where(keyPrefix(settings.key, "storage:"));
|
||||
assert.equal(n, 20 * 25);
|
||||
});
|
||||
|
||||
|
||||
Loading…
Reference in New Issue
Block a user