chore: port lab4 solution as lab5 base

This commit is contained in:
2026-11-15 14:42:12 +03:00
parent 276dbdad8a
commit 19dda6e286
90 changed files with 18537 additions and 0 deletions
+41
View File
@@ -0,0 +1,41 @@
import {
ArrayMaxSize,
IsArray,
IsString,
Validate,
ValidateIf,
ValidatorConstraint,
ValidatorConstraintInterface,
} from 'class-validator';
import { CodePointLength } from '../../common/dto/code-point-length.validator';
import { validate as isUuid } from '../../common/uuid';
@ValidatorConstraint({ name: 'uniqueUuidList' })
class UniqueUuidList implements ValidatorConstraintInterface {
validate(value: unknown): boolean {
if (
!Array.isArray(value) ||
!value.every((id) => typeof id === 'string' && isUuid(id))
) {
return false;
}
const normalized = (value as string[]).map((id) => id.toLowerCase());
return new Set(normalized).size === normalized.length;
}
defaultMessage(): string {
return 'attachment_ids must contain unique UUIDs';
}
}
export class CreateMessageDto {
@IsString()
@CodePointLength(0, 4000)
text!: string;
@ValidateIf((dto: CreateMessageDto) => dto.attachment_ids !== undefined)
@IsArray()
@ArrayMaxSize(10)
@Validate(UniqueUuidList)
attachment_ids?: string[];
}
+26
View File
@@ -0,0 +1,26 @@
import { Message } from '../../common/domain';
export interface MessageResponse {
id: string;
chat_id: string;
sender_id: string;
text: string;
created_at: string;
attachment_ids: string[];
}
export interface MessagePageResponse {
items: MessageResponse[];
next_cursor: string | null;
}
export function toMessageResponse(message: Message): MessageResponse {
return {
id: message.id,
chat_id: message.chatId,
sender_id: message.senderId,
text: message.text,
created_at: message.createdAt,
attachment_ids: message.attachmentIds,
};
}
+70
View File
@@ -0,0 +1,70 @@
import {
Body,
Controller,
Get,
Headers,
HttpCode,
Param,
Post,
Query,
UseGuards,
} from '@nestjs/common';
import { AuthGuard } from '../auth/auth.guard';
import { CurrentUser } from '../auth/current-user.decorator';
import { parseLimit, rawCursorParam } from '../common/dto/pagination-query.dto';
import { User } from '../common/domain';
import { ApiError } from '../common/filters/api-error';
import { CreateMessageDto } from './dto/create-message.dto';
import {
MessagePageResponse,
MessageResponse,
toMessageResponse,
} from './dto/message.response';
import { MessagesService } from './messages.service';
@Controller('api/v1/chats/:chatId/messages')
@UseGuards(AuthGuard)
export class MessagesController {
constructor(private readonly messages: MessagesService) {}
@Post()
@HttpCode(201)
async create(
@Param('chatId') chatId: string,
@Body() dto: CreateMessageDto,
@Headers('idempotency-key') keyRaw: unknown,
@CurrentUser() user: User,
): Promise<MessageResponse> {
const key = parseIdempotencyKey(keyRaw);
const message = await this.messages.create(
chatId,
user.id,
dto.text,
(dto.attachment_ids ?? []).map((id) => id.toLowerCase()),
key,
);
return toMessageResponse(message);
}
@Get()
async list(
@Param('chatId') chatId: string,
@CurrentUser() user: User,
@Query('limit') limitRaw: unknown,
@Query('cursor') cursorRaw: unknown,
): Promise<MessagePageResponse> {
const limit = parseLimit(limitRaw);
const cursor = rawCursorParam(cursorRaw);
return this.messages.list(chatId, user.id, limit, cursor);
}
}
function parseIdempotencyKey(raw: unknown): string {
if (typeof raw !== 'string' || !/^[A-Za-z0-9._:-]{1,128}$/.test(raw)) {
throw new ApiError(
'invalid_request',
'Idempotency-Key header must match [A-Za-z0-9._:-]{1,128}',
);
}
return raw;
}
+9
View File
@@ -0,0 +1,9 @@
import { Module } from '@nestjs/common';
import { MessagesController } from './messages.controller';
import { MessagesService } from './messages.service';
@Module({
controllers: [MessagesController],
providers: [MessagesService],
})
export class MessagesModule {}
+194
View File
@@ -0,0 +1,194 @@
import { Injectable } from '@nestjs/common';
import { Prisma } from '@prisma/client';
import { createHash } from 'crypto';
import { assertChatMember } from '../chats/chat-access';
import { codePointLength } from '../common/dto/code-point-length.validator';
import { decodeMessageCursor, encodeMessageCursor } from '../common/cursor';
import { Message } from '../common/domain';
import { ApiError } from '../common/filters/api-error';
import { PrismaService } from '../db/prisma.service';
import { MessagePageResponse, toMessageResponse } from './dto/message.response';
interface MessageRow {
id: string;
chatId: string;
senderId: string;
text: string;
createdAt: Date;
attachmentIds: string[];
}
const ATTACHMENT_LINKS = {
attachments: {
orderBy: { position: 'asc' },
select: { attachmentId: true },
},
} satisfies Prisma.MessageInclude;
type MessageWithLinks = Prisma.MessageGetPayload<{
include: typeof ATTACHMENT_LINKS;
}>;
class KeyAlreadyUsed extends Error {}
@Injectable()
export class MessagesService {
private readonly keyTtlMs =
Number(process.env.IDEMPOTENCY_TTL_SECONDS ?? 86400) * 1000;
constructor(private readonly prisma: PrismaService) {}
async create(
chatId: string,
callerId: string,
text: string,
attachmentIds: string[],
key: string,
): Promise<Message> {
await this.assertMember(chatId, callerId);
if (codePointLength(text.trim()) === 0 && attachmentIds.length === 0) {
throw new ApiError(
'invalid_request',
'text must not be empty or whitespace-only without attachments',
);
}
await this.assertAttachmentsInChat(chatId, attachmentIds);
const scope = { userId: callerId, chatId, key };
const requestHash = createHash('sha256')
.update(JSON.stringify({ text, attachment_ids: attachmentIds }))
.digest('hex');
try {
return await this.prisma.$transaction(async (tx) => {
await tx.idempotencyKey.deleteMany({
where: {
...scope,
createdAt: { lt: new Date(Date.now() - this.keyTtlMs) },
},
});
const row = await tx.message.create({
data: {
chatId,
senderId: callerId,
text,
attachments: {
create: attachmentIds.map((attachmentId, position) => ({
attachmentId,
position,
})),
},
},
include: ATTACHMENT_LINKS,
});
const { count } = await tx.idempotencyKey.createMany({
data: [{ ...scope, requestHash, messageId: row.id }],
skipDuplicates: true,
});
if (count === 0) {
throw new KeyAlreadyUsed();
}
return linkedMessage(row);
});
} catch (error) {
if (!(error instanceof KeyAlreadyUsed)) {
throw error;
}
}
const stored = await this.prisma.idempotencyKey.findUnique({
where: { userId_chatId_key: scope },
include: { message: { include: ATTACHMENT_LINKS } },
});
if (!stored || stored.requestHash !== requestHash) {
throw new ApiError(
'conflict',
'Idempotency-Key was already used with a different request',
);
}
return linkedMessage(stored.message);
}
async list(
chatId: string,
callerId: string,
limit: number,
rawCursor: string | null,
): Promise<MessagePageResponse> {
await this.assertMember(chatId, callerId);
let after = Prisma.empty;
if (rawCursor !== null) {
const cursor = decodeMessageCursor(rawCursor);
if (cursor && cursor.chatId !== chatId) {
throw new ApiError(
'invalid_request',
'cursor belongs to a different chat',
);
}
const anchor = cursor
? await this.prisma.message.findFirst({
where: { id: cursor.id, chatId },
select: { id: true, createdAt: true },
})
: null;
if (!anchor) {
throw new ApiError('invalid_request', 'invalid cursor');
}
after = Prisma.sql`AND (created_at, id) > (${anchor.createdAt}::timestamptz, ${anchor.id}::uuid)`;
}
const rows = await this.prisma.$queryRaw<MessageRow[]>`
SELECT id, chat_id AS "chatId", sender_id AS "senderId", text, created_at AS "createdAt",
ARRAY(
SELECT attachment_id::text FROM message_attachments
WHERE message_id = messages.id
ORDER BY position
) AS "attachmentIds"
FROM messages
WHERE chat_id = ${chatId}::uuid ${after}
ORDER BY created_at, id
LIMIT ${limit + 1}`;
const items = rows.slice(0, limit).map(toMessage);
const last = items[items.length - 1];
return {
items: items.map(toMessageResponse),
next_cursor:
rows.length > limit
? encodeMessageCursor({ chatId, id: last.id })
: null,
};
}
private assertMember(chatId: string, callerId: string): Promise<void> {
return assertChatMember(this.prisma, chatId, callerId);
}
private async assertAttachmentsInChat(
chatId: string,
attachmentIds: string[],
): Promise<void> {
if (attachmentIds.length === 0) {
return;
}
const found = await this.prisma.attachment.count({
where: { id: { in: attachmentIds }, chatId },
});
if (found !== attachmentIds.length) {
throw new ApiError('not_found', 'attachment not found');
}
}
}
function linkedMessage(row: MessageWithLinks): Message {
return toMessage({
...row,
attachmentIds: row.attachments.map((link) => link.attachmentId),
});
}
function toMessage(row: MessageRow): Message {
return {
id: row.id,
chatId: row.chatId,
senderId: row.senderId,
text: row.text,
createdAt: row.createdAt.toISOString(),
attachmentIds: row.attachmentIds,
};
}