feat(ai,mcp): идентичность прогона реиндекса + брендированные PageId/SlugId (#495 item 14)
Аспект A — идентичность прогона реиндекса эмбеддингов. У статуса/поллинга реиндекса не было идентичности КОНКРЕТНОГО прогона, из-за чего класс багов «это тот же прогон или новый?» чинили дважды. Теперь каждый прогон получает свой runId (crypto.randomUUID в start()), он хранится в Redis- хэше рядом с total/done/startedAt и возвращается в ReindexProgress. Эндпоинт статуса (getMasked -> MaskedAiSettings) отдаёт runId и reindexStartedAt. Клиент кеит поллинг на (runId, startedAt): смена runId = НОВЫЙ прогон (сбрасываем залатанное per-run состояние поллинга), тот же runId = тот же прогон. Всё best-effort/косметика как и остальной код прогресса: пустой/отсутствующий runId деградирует мягко и никогда не ломает реиндекс. Аспект B — брендированные PageId/SlugId в MCP-клиенте + валидация формата в серверных DTO (семейство инцидентов #435: двойная идентичность страницы — внутренний id и slugId — гонялась как голая строка и молча путалась). - packages/mcp/src/lib/page-id.ts: номинальные типы PageId/SlugId + валидирующие конструкторы asPageId/asSlugId и гварды isPageId/isSlugId (формат UUID и 10-символьного slugId). PageId протянут через единственный узел канонизации и записи: resolvePageId() теперь возвращает PageId, а ключ per-page лока (withPageLock) и точки записи в collab (mutatePageContent/replacePageContent/ updatePageContentRealtime) требуют бренд — сырой slugId/непроверенный id больше не проходит проверку типов (инвариант #260 «resolve-then-lock» теперь на уровне компилятора). Публичный вход методов остаётся строкой (это legitimно UUID ИЛИ slugId), брендируется каноническое значение. - apps/server core/page/dto: PageIdDto.pageId получает валидацию формата (@Matches, UUID или 10-символьный slugId), так что кривая/подменённая идентичность отклоняется на границе, а не падает в repo голой строкой. Тесты (все зелёные, с mutation-verify каждого): - server: getMasked отдаёт runId/reindexStartedAt; стор пишет/читает runId и мягко деградирует его до ''; DTO отклоняет кривой pageId/slugId и принимает валидный. - client: чистый хелпер reindexRunKey/isNewReindexRun (кеинг поллинга на runId). - mcp: конструкторы/гварды PageId/SlugId (валидация формата). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,49 @@
|
||||
import 'reflect-metadata';
|
||||
import { plainToInstance } from 'class-transformer';
|
||||
import { validate } from 'class-validator';
|
||||
import { PageIdDto } from './page.dto';
|
||||
|
||||
// #435: PageIdDto.pageId carries a page's DOUBLE identity (internal UUID OR
|
||||
// public 10-char slugId), both as bare strings. The DTO must accept exactly
|
||||
// those two FORMATS and reject a malformed / swapped identity at the boundary.
|
||||
async function pageIdErrors(pageId: unknown) {
|
||||
const dto = plainToInstance(PageIdDto, { pageId });
|
||||
const errors = await validate(dto as object);
|
||||
return errors.some((e) => e.property === 'pageId');
|
||||
}
|
||||
|
||||
const UUID = '019f499a-9f8c-7d68-b7be-ce100d7c6c56';
|
||||
const SLUG = 'aB3xQ7kR2p';
|
||||
|
||||
describe('PageIdDto pageId format validation', () => {
|
||||
it('accepts a canonical page UUID', async () => {
|
||||
expect(await pageIdErrors(UUID)).toBe(false);
|
||||
});
|
||||
|
||||
it('accepts a 10-char slugId', async () => {
|
||||
expect(await pageIdErrors(SLUG)).toBe(false);
|
||||
});
|
||||
|
||||
it('rejects a truncated / wrong-length slug', async () => {
|
||||
expect(await pageIdErrors('aB3xQ7kR2')).toBe(true); // 9 chars
|
||||
expect(await pageIdErrors('aB3xQ7kR2pX')).toBe(true); // 11 chars
|
||||
});
|
||||
|
||||
it('rejects a slug with an illegal character', async () => {
|
||||
expect(await pageIdErrors('aB3xQ7kR2!')).toBe(true);
|
||||
});
|
||||
|
||||
it('rejects a full URL / path-shaped identity (not the bare id)', async () => {
|
||||
expect(await pageIdErrors(`my-page-title-${SLUG}`)).toBe(true);
|
||||
expect(await pageIdErrors(`https://x/p/${SLUG}`)).toBe(true);
|
||||
});
|
||||
|
||||
it('rejects a malformed UUID', async () => {
|
||||
expect(await pageIdErrors('019f499a-9f8c-7d68-b7be')).toBe(true);
|
||||
expect(await pageIdErrors('not-a-uuid-at-all-really')).toBe(true);
|
||||
});
|
||||
|
||||
it('rejects an empty string', async () => {
|
||||
expect(await pageIdErrors('')).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,39 @@
|
||||
import { applyDecorators } from '@nestjs/common';
|
||||
import { Matches, ValidationOptions } from 'class-validator';
|
||||
|
||||
/**
|
||||
* A page identity at the API boundary is EITHER the internal page UUID or the
|
||||
* public 10-char slugId (page.repo.findById matches a non-UUID input as a
|
||||
* slugId). Both arrive as bare strings, which is exactly how the two got swapped
|
||||
* silently (incident family #435). This regex pins the two accepted FORMATS so a
|
||||
* malformed / cross-wired identity (a truncated slug, a full URL, an email, an
|
||||
* id from another entity kind that isn't even shaped like either) is rejected at
|
||||
* the boundary instead of falling through to a confusing 404.
|
||||
*
|
||||
* - UUID: canonical 8-4-4-4-12 hex (version-agnostic — page ids are UUIDv7,
|
||||
* so only the shape/length is enforced, matching the MCP's UUID_RE
|
||||
* and the server's isValidUUID acceptance).
|
||||
* - slugId: exactly 10 chars over [0-9A-Za-z] (nanoid `generateSlugId`).
|
||||
*
|
||||
* The two are disjoint (a UUID is 36 chars WITH dashes, a slugId 10 chars
|
||||
* WITHOUT), so a value can only satisfy one branch.
|
||||
*/
|
||||
export const PAGE_ID_OR_SLUG_ID_REGEX =
|
||||
/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|[0-9A-Za-z]{10})$/i;
|
||||
|
||||
/**
|
||||
* Validate that a DTO string field is a well-formed page identity (page UUID OR
|
||||
* 10-char slugId). Composed decorator so the same format rule is applied
|
||||
* consistently wherever a DTO accepts a `pageId` that may be either form.
|
||||
*/
|
||||
export function IsPageIdOrSlugId(
|
||||
validationOptions?: ValidationOptions,
|
||||
): PropertyDecorator {
|
||||
return applyDecorators(
|
||||
Matches(PAGE_ID_OR_SLUG_ID_REGEX, {
|
||||
message:
|
||||
'pageId must be a page UUID or a 10-character slugId',
|
||||
...validationOptions,
|
||||
}),
|
||||
);
|
||||
}
|
||||
@@ -9,10 +9,16 @@ import {
|
||||
import { Transform } from 'class-transformer';
|
||||
|
||||
import { ContentFormat } from './create-page.dto';
|
||||
import { IsPageIdOrSlugId } from './page-identity.validator';
|
||||
|
||||
export class PageIdDto {
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
// Format-validate the double identity (#435): accept only a page UUID or a
|
||||
// 10-char slugId so a malformed / swapped identity is rejected at the boundary
|
||||
// rather than passed to the repo as a bare string. Base for PageInfoDto,
|
||||
// DeletePageDto, BacklinksListDto, AddLabelsDto/RemoveLabelDto, etc.
|
||||
@IsPageIdOrSlugId()
|
||||
pageId: string;
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user