diff --git a/Dockerfile b/Dockerfile index 559508c..afbfd17 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,11 +1,18 @@ # syntax=docker/dockerfile:1 -FROM node:20.17.0-slim AS deps +FROM node:20.17.0-slim AS base +RUN apt-get update \ + && apt-get install -y --no-install-recommends openssl \ + && rm -rf /var/lib/apt/lists/* WORKDIR /app + +FROM base AS deps COPY package.json package-lock.json ./ RUN npm ci FROM deps AS build +COPY prisma ./prisma +RUN npx prisma generate COPY tsconfig.json tsconfig.build.json nest-cli.json ./ COPY src ./src RUN npm run build @@ -14,11 +21,16 @@ FROM build AS test COPY test ./test CMD ["npm", "test"] -FROM node:20.17.0-slim AS runtime -WORKDIR /app +FROM build AS migrate +CMD ["sh", "-c", "DATABASE_URL=\"$(cat \"$DATABASE_URL_FILE\")\" exec npx prisma migrate deploy"] + +FROM build AS prod-deps +RUN npm prune --omit=dev + +FROM base AS runtime ENV NODE_ENV=production -COPY package.json package-lock.json ./ -RUN npm ci --omit=dev && npm cache clean --force +COPY package.json ./ +COPY --from=prod-deps /app/node_modules ./node_modules COPY --from=build /app/dist ./dist USER node diff --git a/compose.test.yaml b/compose.test.yaml new file mode 100644 index 0000000..f80f98c --- /dev/null +++ b/compose.test.yaml @@ -0,0 +1,27 @@ +name: messenger-lab2-test + +services: + postgres: + image: postgres:17.2-alpine + environment: + POSTGRES_USER: test + POSTGRES_PASSWORD: test + POSTGRES_DB: messenger_test + tmpfs: + - /var/lib/postgresql/data + healthcheck: + test: ["CMD", "pg_isready", "-U", "test", "-d", "messenger_test"] + interval: 2s + timeout: 3s + retries: 15 + + tests: + build: + context: . + target: test + image: mtusi-messenger-lab2-test:dev + environment: + DATABASE_URL: postgresql://test:test@postgres:5432/messenger_test?connection_limit=20 + depends_on: + postgres: + condition: service_healthy diff --git a/compose.yaml b/compose.yaml new file mode 100644 index 0000000..9fa4d34 --- /dev/null +++ b/compose.yaml @@ -0,0 +1,70 @@ +name: messenger-lab2 + +services: + secrets-init: + image: alpine:3.20.3 + volumes: + - secrets:/secrets + command: + - sh + - -ec + - | + cd /secrets + [ -s pg_password ] || head -c 24 /dev/urandom | od -An -tx1 | tr -d ' \n' > pg_password + printf 'postgresql://messenger:%s@postgres:5432/messenger?connection_limit=10&pool_timeout=5&connect_timeout=5&socket_timeout=10&application_name=api&options=-c%%20statement_timeout%%3D5000' "$$(cat pg_password)" > database_url + chmod 0444 pg_password database_url + + postgres: + image: postgres:17.2-alpine + environment: + POSTGRES_USER: messenger + POSTGRES_DB: messenger + POSTGRES_PASSWORD_FILE: /run/secrets/pg_password + volumes: + - pgdata:/var/lib/postgresql/data + - secrets:/run/secrets:ro + healthcheck: + test: ["CMD", "pg_isready", "-U", "messenger", "-d", "messenger"] + interval: 5s + timeout: 3s + retries: 10 + depends_on: + secrets-init: + condition: service_completed_successfully + restart: unless-stopped + + migrate: + build: + context: . + target: migrate + image: mtusi-messenger-lab2-migrate:dev + environment: + DATABASE_URL_FILE: /run/secrets/database_url + volumes: + - secrets:/run/secrets:ro + depends_on: + postgres: + condition: service_healthy + + api: + build: + context: . + target: runtime + image: mtusi-messenger-lab2-api:dev + environment: + APP_HOST: 0.0.0.0 + APP_PORT: 8080 + APP_ENV: ${APP_ENV:-lab} + DATABASE_URL_FILE: /run/secrets/database_url + ports: + - "127.0.0.1:${APP_PORT:-8080}:8080" + volumes: + - secrets:/run/secrets:ro + depends_on: + migrate: + condition: service_completed_successfully + restart: unless-stopped + +volumes: + pgdata: + secrets: diff --git a/package-lock.json b/package-lock.json index 55904bd..7de9764 100644 --- a/package-lock.json +++ b/package-lock.json @@ -12,6 +12,7 @@ "@nestjs/common": "^10.4.15", "@nestjs/core": "^10.4.15", "@nestjs/platform-fastify": "^10.4.15", + "@prisma/client": "6.1.0", "class-transformer": "^0.5.1", "class-validator": "^0.14.1", "reflect-metadata": "^0.2.2", @@ -28,6 +29,7 @@ "@typescript-eslint/parser": "^8.18.1", "eslint": "^8.57.1", "jest": "^29.7.0", + "prisma": "6.1.0", "source-map-support": "^0.5.21", "supertest": "^7.0.0", "ts-jest": "^29.2.5", @@ -2063,6 +2065,74 @@ "node": ">=14" } }, + "node_modules/@prisma/client": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/@prisma/client/-/client-6.1.0.tgz", + "integrity": "sha512-AbQYc5+EJKm1Ydfq3KxwcGiy7wIbm4/QbjCKWWoNROtvy7d6a3gmAGkKjK0iUCzh+rHV8xDhD5Cge8ke/kiy5Q==", + "hasInstallScript": true, + "license": "Apache-2.0", + "engines": { + "node": ">=18.18" + }, + "peerDependencies": { + "prisma": "*" + }, + "peerDependenciesMeta": { + "prisma": { + "optional": true + } + } + }, + "node_modules/@prisma/debug": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/@prisma/debug/-/debug-6.1.0.tgz", + "integrity": "sha512-0himsvcM4DGBTtvXkd2Tggv6sl2JyUYLzEGXXleFY+7Kp6rZeSS3hiTW9mwtUlXrwYbJP6pwlVNB7jYElrjWUg==", + "devOptional": true, + "license": "Apache-2.0" + }, + "node_modules/@prisma/engines": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/@prisma/engines/-/engines-6.1.0.tgz", + "integrity": "sha512-GnYJbCiep3Vyr1P/415ReYrgJUjP79fBNc1wCo7NP6Eia0CzL2Ot9vK7Infczv3oK7JLrCcawOSAxFxNFsAERQ==", + "devOptional": true, + "hasInstallScript": true, + "license": "Apache-2.0", + "dependencies": { + "@prisma/debug": "6.1.0", + "@prisma/engines-version": "6.1.0-21.11f085a2012c0f4778414c8db2651556ee0ef959", + "@prisma/fetch-engine": "6.1.0", + "@prisma/get-platform": "6.1.0" + } + }, + "node_modules/@prisma/engines-version": { + "version": "6.1.0-21.11f085a2012c0f4778414c8db2651556ee0ef959", + "resolved": "https://registry.npmjs.org/@prisma/engines-version/-/engines-version-6.1.0-21.11f085a2012c0f4778414c8db2651556ee0ef959.tgz", + "integrity": "sha512-PdJqmYM2Fd8K0weOOtQThWylwjsDlTig+8Pcg47/jszMuLL9iLIaygC3cjWJLda69siRW4STlCTMSgOjZzvKPQ==", + "devOptional": true, + "license": "Apache-2.0" + }, + "node_modules/@prisma/fetch-engine": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/@prisma/fetch-engine/-/fetch-engine-6.1.0.tgz", + "integrity": "sha512-asdFi7TvPlEZ8CzSZ/+Du5wZ27q6OJbRSXh+S8ISZguu+S9KtS/gP7NeXceZyb1Jv1SM1S5YfiCv+STDsG6rrg==", + "devOptional": true, + "license": "Apache-2.0", + "dependencies": { + "@prisma/debug": "6.1.0", + "@prisma/engines-version": "6.1.0-21.11f085a2012c0f4778414c8db2651556ee0ef959", + "@prisma/get-platform": "6.1.0" + } + }, + "node_modules/@prisma/get-platform": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/@prisma/get-platform/-/get-platform-6.1.0.tgz", + "integrity": "sha512-ia8bNjboBoHkmKGGaWtqtlgQOhCi7+f85aOkPJKgNwWvYrT6l78KgojLekE8zMhVk0R9lWcifV0Pf8l3/15V0Q==", + "devOptional": true, + "license": "Apache-2.0", + "dependencies": { + "@prisma/debug": "6.1.0" + } + }, "node_modules/@sinclair/typebox": { "version": "0.27.12", "resolved": "https://registry.npmjs.org/@sinclair/typebox/-/typebox-0.27.12.tgz", @@ -7591,6 +7661,26 @@ "url": "https://github.com/chalk/ansi-styles?sponsor=1" } }, + "node_modules/prisma": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/prisma/-/prisma-6.1.0.tgz", + "integrity": "sha512-aFI3Yi+ApUxkwCJJwyQSwpyzUX7YX3ihzuHNHOyv4GJg3X5tQsmRaJEnZ+ZyfHpMtnyahhmXVfbTZ+lS8ZtfKw==", + "devOptional": true, + "hasInstallScript": true, + "license": "Apache-2.0", + "dependencies": { + "@prisma/engines": "6.1.0" + }, + "bin": { + "prisma": "build/index.js" + }, + "engines": { + "node": ">=18.18" + }, + "optionalDependencies": { + "fsevents": "2.3.3" + } + }, "node_modules/process-warning": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/process-warning/-/process-warning-3.0.0.tgz", diff --git a/package.json b/package.json index a6a6a0b..2fd001f 100644 --- a/package.json +++ b/package.json @@ -16,6 +16,7 @@ "@nestjs/common": "^10.4.15", "@nestjs/core": "^10.4.15", "@nestjs/platform-fastify": "^10.4.15", + "@prisma/client": "6.1.0", "class-transformer": "^0.5.1", "class-validator": "^0.14.1", "reflect-metadata": "^0.2.2", @@ -32,6 +33,7 @@ "@typescript-eslint/parser": "^8.18.1", "eslint": "^8.57.1", "jest": "^29.7.0", + "prisma": "6.1.0", "source-map-support": "^0.5.21", "supertest": "^7.0.0", "ts-jest": "^29.2.5", diff --git a/prisma/migrations/20261021000000_init/migration.sql b/prisma/migrations/20261021000000_init/migration.sql new file mode 100644 index 0000000..89e61f4 --- /dev/null +++ b/prisma/migrations/20261021000000_init/migration.sql @@ -0,0 +1,50 @@ +CREATE TABLE "users" ( + "id" UUID NOT NULL, + "username" VARCHAR(32) NOT NULL, + "display_name" VARCHAR(100) NOT NULL, + "created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "users_pkey" PRIMARY KEY ("id"), + CONSTRAINT "users_username_format" CHECK ("username" ~ '^[a-z0-9_]{3,32}$'), + CONSTRAINT "users_display_name_not_blank" CHECK (btrim("display_name") <> '') +); + +CREATE TABLE "chats" ( + "id" UUID NOT NULL, + "title" VARCHAR(100) NOT NULL, + "created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "chats_pkey" PRIMARY KEY ("id"), + CONSTRAINT "chats_title_not_blank" CHECK (btrim("title") <> '') +); + +CREATE TABLE "chat_members" ( + "chat_id" UUID NOT NULL, + "user_id" UUID NOT NULL, + + CONSTRAINT "chat_members_pkey" PRIMARY KEY ("chat_id","user_id") +); + +CREATE TABLE "messages" ( + "id" UUID NOT NULL, + "chat_id" UUID NOT NULL, + "sender_id" UUID NOT NULL, + "text" VARCHAR(4000) NOT NULL, + "created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "messages_pkey" PRIMARY KEY ("id") +); + +CREATE UNIQUE INDEX "users_username_key" ON "users"("username"); + +CREATE INDEX "chat_members_user_id_idx" ON "chat_members"("user_id"); + +CREATE INDEX "messages_chat_id_created_at_id_idx" ON "messages"("chat_id", "created_at", "id"); + +ALTER TABLE "chat_members" ADD CONSTRAINT "chat_members_chat_id_fkey" FOREIGN KEY ("chat_id") REFERENCES "chats"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +ALTER TABLE "chat_members" ADD CONSTRAINT "chat_members_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE RESTRICT ON UPDATE CASCADE; + +ALTER TABLE "messages" ADD CONSTRAINT "messages_chat_id_fkey" FOREIGN KEY ("chat_id") REFERENCES "chats"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +ALTER TABLE "messages" ADD CONSTRAINT "messages_sender_id_fkey" FOREIGN KEY ("sender_id") REFERENCES "users"("id") ON DELETE RESTRICT ON UPDATE CASCADE; diff --git a/prisma/migrations/migration_lock.toml b/prisma/migrations/migration_lock.toml new file mode 100644 index 0000000..99e4f20 --- /dev/null +++ b/prisma/migrations/migration_lock.toml @@ -0,0 +1,3 @@ +# Please do not edit this file manually +# It should be added in your version-control system (i.e. Git) +provider = "postgresql" diff --git a/prisma/schema.prisma b/prisma/schema.prisma new file mode 100644 index 0000000..a75dbaf --- /dev/null +++ b/prisma/schema.prisma @@ -0,0 +1,53 @@ +generator client { + provider = "prisma-client-js" +} + +datasource db { + provider = "postgresql" + url = env("DATABASE_URL") +} + +model User { + id String @id @default(uuid()) @db.Uuid + username String @unique @db.VarChar(32) + displayName String @map("display_name") @db.VarChar(100) + createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3) + memberships ChatMember[] + messages Message[] + + @@map("users") +} + +model Chat { + id String @id @default(uuid()) @db.Uuid + title String @db.VarChar(100) + createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3) + members ChatMember[] + messages Message[] + + @@map("chats") +} + +model ChatMember { + chatId String @map("chat_id") @db.Uuid + userId String @map("user_id") @db.Uuid + chat Chat @relation(fields: [chatId], references: [id], onDelete: Cascade) + user User @relation(fields: [userId], references: [id], onDelete: Restrict) + + @@id([chatId, userId]) + @@index([userId]) + @@map("chat_members") +} + +model Message { + id String @id @default(uuid()) @db.Uuid + chatId String @map("chat_id") @db.Uuid + senderId String @map("sender_id") @db.Uuid + text String @db.VarChar(4000) + createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3) + chat Chat @relation(fields: [chatId], references: [id], onDelete: Cascade) + sender User @relation(fields: [senderId], references: [id], onDelete: Restrict) + + @@index([chatId, createdAt, id]) + @@map("messages") +} diff --git a/src/app.module.ts b/src/app.module.ts index bdd317c..28cf9e9 100644 --- a/src/app.module.ts +++ b/src/app.module.ts @@ -1,12 +1,14 @@ import { Module } from '@nestjs/common'; import { ChatsModule } from './chats/chats.module'; import { CommonModule } from './common/common.module'; +import { DbModule } from './db/db.module'; import { HealthModule } from './health/health.module'; import { MessagesModule } from './messages/messages.module'; import { UsersModule } from './users/users.module'; @Module({ imports: [ + DbModule, CommonModule, HealthModule, UsersModule, diff --git a/src/chats/chats.controller.ts b/src/chats/chats.controller.ts index 8b510a6..7d78db2 100644 --- a/src/chats/chats.controller.ts +++ b/src/chats/chats.controller.ts @@ -11,7 +11,7 @@ import { import { AuthGuard } from '../common/auth/auth.guard'; import { CurrentUser } from '../common/auth/current-user.decorator'; import { parseLimit, rawCursorParam } from '../common/dto/pagination-query.dto'; -import { User } from '../common/store/domain'; +import { User } from '../common/domain'; import { ChatsService } from './chats.service'; import { ChatPageResponse, @@ -27,31 +27,31 @@ export class ChatsController { @Post() @HttpCode(201) - create( + async create( @Body() dto: CreateChatDto, @CurrentUser() user: User, - ): ChatResponse { - const chat = this.chats.create(dto.title, dto.member_ids, user.id); + ): Promise { + const chat = await this.chats.create(dto.title, dto.member_ids, user.id); return toChatResponse(chat); } @Get() - list( + async list( @CurrentUser() user: User, @Query('limit') limitRaw: unknown, @Query('cursor') cursorRaw: unknown, - ): ChatPageResponse { + ): Promise { const limit = parseLimit(limitRaw); const cursor = rawCursorParam(cursorRaw); return this.chats.listForMember(user.id, limit, cursor); } @Get(':chatId') - getOne( + async getOne( @Param('chatId') chatId: string, @CurrentUser() user: User, - ): ChatResponse { - const chat = this.chats.getForMember(chatId, user.id); + ): Promise { + const chat = await this.chats.getForMember(chatId, user.id); return toChatResponse(chat); } } diff --git a/src/chats/chats.service.ts b/src/chats/chats.service.ts index c82a5e7..8153b2e 100644 --- a/src/chats/chats.service.ts +++ b/src/chats/chats.service.ts @@ -1,67 +1,124 @@ import { Injectable } from '@nestjs/common'; +import { Prisma } from '@prisma/client'; +import { decodeChatCursor, encodeChatCursor } from '../common/cursor'; +import { Chat } from '../common/domain'; import { ApiError } from '../common/filters/api-error'; -import { - decodeChatCursor, - encodeChatCursor, -} from '../common/store/store.service'; -import { Chat } from '../common/store/domain'; -import { StoreService } from '../common/store/store.service'; import { validate as isUuid } from '../common/uuid'; +import { PrismaService, isForeignKeyViolation } from '../db/prisma.service'; import { ChatPageResponse, toChatResponse } from './dto/chat.response'; +interface ChatRow { + id: string; + title: string; + createdAt: Date; + memberIds: string[]; +} + @Injectable() export class ChatsService { - constructor(private readonly store: StoreService) {} + constructor(private readonly prisma: PrismaService) {} - create(title: string, memberIds: string[], callerId: string): Chat { + async create( + title: string, + memberIds: string[], + callerId: string, + ): Promise { if (!memberIds.includes(callerId)) { throw new ApiError( 'invalid_request', 'member_ids must include the caller', ); } - for (const id of memberIds) { - if (!isUuid(id) || !this.store.getUserById(id)) { + const invalid = memberIds.find((id) => !isUuid(id)); + if (invalid) { + throw new ApiError('invalid_request', `unknown member_id: ${invalid}`); + } + try { + const chat = await this.prisma.$transaction(async (tx) => { + const created = await tx.chat.create({ + data: { title: title.trim() }, + }); + await tx.chatMember.createMany({ + data: memberIds.map((userId) => ({ + chatId: created.id, + userId, + })), + }); + return created; + }); + return toChat({ ...chat, memberIds }); + } catch (error) { + if (isForeignKeyViolation(error)) { throw new ApiError( 'invalid_request', - `unknown member_id: ${id}`, + 'member_ids contain an unknown user', ); } + throw error; } - return this.store.createChat(title.trim(), memberIds); } - getForMember(chatId: string, callerId: string): Chat { + async getForMember(chatId: string, callerId: string): Promise { if (!isUuid(chatId)) { throw new ApiError('invalid_request', 'chatId must be a valid UUID'); } - const chat = this.store.getChatById(chatId); - if (!chat || !chat.memberIds.includes(callerId)) { + const chat = await this.prisma.chat.findFirst({ + where: { id: chatId, members: { some: { userId: callerId } } }, + include: { members: { select: { userId: true } } }, + }); + if (!chat) { throw new ApiError('not_found', 'chat not found'); } - return chat; + return toChat({ + ...chat, + memberIds: chat.members.map((m) => m.userId), + }); } - listForMember( + async listForMember( callerId: string, limit: number, rawCursor: string | null, - ): ChatPageResponse { - const cursor = rawCursor === null ? null : decodeChatCursor(rawCursor); - if (rawCursor !== null && cursor === null) { - throw new ApiError('invalid_request', 'invalid cursor'); + ): Promise { + let after = Prisma.empty; + if (rawCursor !== null) { + const cursor = decodeChatCursor(rawCursor); + const member = cursor + ? await this.prisma.chatMember.findUnique({ + where: { + chatId_userId: { chatId: cursor.id, userId: callerId }, + }, + include: { chat: { select: { createdAt: true } } }, + }) + : null; + if (!member) { + throw new ApiError('invalid_request', 'invalid cursor'); + } + after = Prisma.sql`AND (c.created_at, c.id) > (${member.chat.createdAt}::timestamptz, ${member.chatId}::uuid)`; } - if (cursor && !this.store.chatCursorExists(callerId, cursor.id)) { - throw new ApiError('invalid_request', 'invalid cursor'); - } - const items = this.store.listChatsForMember(callerId, cursor, limit); + const rows = await this.prisma.$queryRaw` + SELECT c.id, c.title, c.created_at AS "createdAt", + ARRAY(SELECT m.user_id::text FROM chat_members m WHERE m.chat_id = c.id) AS "memberIds" + FROM chat_members cm + JOIN chats c ON c.id = cm.chat_id + WHERE cm.user_id = ${callerId}::uuid ${after} + ORDER BY c.created_at, c.id + LIMIT ${limit + 1}`; + const items = rows.slice(0, limit).map(toChat); const last = items[items.length - 1]; - const hasMore = last - ? this.store.hasMoreChatsAfter(callerId, last.id) - : false; return { items: items.map(toChatResponse), - next_cursor: hasMore ? encodeChatCursor({ id: last.id }) : null, + next_cursor: + rows.length > limit ? encodeChatCursor({ id: last.id }) : null, }; } } + +function toChat(row: ChatRow): Chat { + return { + id: row.id, + title: row.title, + memberIds: row.memberIds, + createdAt: row.createdAt.toISOString(), + }; +} diff --git a/src/chats/dto/chat.response.ts b/src/chats/dto/chat.response.ts index 80218fa..e10e4a6 100644 --- a/src/chats/dto/chat.response.ts +++ b/src/chats/dto/chat.response.ts @@ -1,4 +1,4 @@ -import { Chat } from '../../common/store/domain'; +import { Chat } from '../../common/domain'; export interface ChatResponse { id: string; diff --git a/src/common/auth/auth.guard.ts b/src/common/auth/auth.guard.ts index 4756896..bf9cca0 100644 --- a/src/common/auth/auth.guard.ts +++ b/src/common/auth/auth.guard.ts @@ -1,25 +1,26 @@ import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common'; -import { validate as isUuid } from '../uuid'; import { FastifyRequest } from 'fastify'; +import { PrismaService } from '../../db/prisma.service'; +import { toUser } from '../../users/users.service'; import { ApiError } from '../filters/api-error'; -import { StoreService } from '../store/store.service'; +import { validate as isUuid } from '../uuid'; @Injectable() export class AuthGuard implements CanActivate { - constructor(private readonly store: StoreService) {} + constructor(private readonly prisma: PrismaService) {} - canActivate(context: ExecutionContext): boolean { + async canActivate(context: ExecutionContext): Promise { const request = context.switchToHttp().getRequest(); const header = request.headers['x-user-id']; const userId = Array.isArray(header) ? header[0] : header; if (!userId || !isUuid(userId)) { throw new ApiError('unauthorized', 'Missing or invalid X-User-Id'); } - const user = this.store.getUserById(userId); - if (!user) { + const row = await this.prisma.user.findUnique({ where: { id: userId } }); + if (!row) { throw new ApiError('unauthorized', 'Missing or invalid X-User-Id'); } - request.currentUser = user; + request.currentUser = toUser(row); return true; } } diff --git a/src/common/auth/current-user.decorator.ts b/src/common/auth/current-user.decorator.ts index 7757c8c..af0401d 100644 --- a/src/common/auth/current-user.decorator.ts +++ b/src/common/auth/current-user.decorator.ts @@ -1,6 +1,6 @@ import { createParamDecorator, ExecutionContext } from '@nestjs/common'; import { FastifyRequest } from 'fastify'; -import { User } from '../store/domain'; +import { User } from '../domain'; declare module 'fastify' { interface FastifyRequest { diff --git a/src/common/common.module.ts b/src/common/common.module.ts index 8e68b7b..4233fa4 100644 --- a/src/common/common.module.ts +++ b/src/common/common.module.ts @@ -1,10 +1,9 @@ import { Global, Module } from '@nestjs/common'; import { AuthGuard } from './auth/auth.guard'; -import { StoreService } from './store/store.service'; @Global() @Module({ - providers: [StoreService, AuthGuard], - exports: [StoreService, AuthGuard], + providers: [AuthGuard], + exports: [AuthGuard], }) export class CommonModule {} diff --git a/src/common/cursor.ts b/src/common/cursor.ts new file mode 100644 index 0000000..76a22fa --- /dev/null +++ b/src/common/cursor.ts @@ -0,0 +1,49 @@ +import { validate as isUuid } from './uuid'; + +export interface ChatCursor { + id: string; +} + +export interface MessageCursor { + chatId: string; + id: string; +} + +export function encodeChatCursor(cursor: ChatCursor): string { + return encode(cursor); +} + +export function decodeChatCursor(raw: string): ChatCursor | null { + const decoded = decode(raw); + return decoded && isUuidField(decoded.id) ? { id: decoded.id } : null; +} + +export function encodeMessageCursor(cursor: MessageCursor): string { + return encode(cursor); +} + +export function decodeMessageCursor(raw: string): MessageCursor | null { + const decoded = decode(raw); + return decoded && isUuidField(decoded.chatId) && isUuidField(decoded.id) + ? { chatId: decoded.chatId, id: decoded.id } + : null; +} + +function isUuidField(value: unknown): value is string { + return typeof value === 'string' && isUuid(value); +} + +function encode(value: object): string { + return Buffer.from(JSON.stringify(value), 'utf8').toString('base64url'); +} + +function decode(raw: string): Record | null { + try { + const parsed = JSON.parse( + Buffer.from(raw, 'base64url').toString('utf8'), + ); + return typeof parsed === 'object' && parsed !== null ? parsed : null; + } catch { + return null; + } +} diff --git a/src/common/store/domain.ts b/src/common/domain.ts similarity index 100% rename from src/common/store/domain.ts rename to src/common/domain.ts diff --git a/src/common/filters/http-exception.filter.ts b/src/common/filters/http-exception.filter.ts index 7e0a3df..f9b6e4d 100644 --- a/src/common/filters/http-exception.filter.ts +++ b/src/common/filters/http-exception.filter.ts @@ -7,6 +7,7 @@ import { Logger, } from '@nestjs/common'; import { FastifyReply, FastifyRequest } from 'fastify'; +import { isDatabaseUnavailable } from '../../db/prisma.service'; import { ApiError, ErrorCode } from './api-error'; const CODE_BY_STATUS: Partial> = { @@ -75,6 +76,13 @@ export class HttpExceptionFilter implements ExceptionFilter { message, }; } + if (isDatabaseUnavailable(exception)) { + return { + status: 503, + code: 'unavailable', + message: 'database unavailable', + }; + } return { status: 500, code: 'internal_error', diff --git a/src/common/store/store.service.ts b/src/common/store/store.service.ts deleted file mode 100644 index 0df3039..0000000 --- a/src/common/store/store.service.ts +++ /dev/null @@ -1,240 +0,0 @@ -import { Injectable } from '@nestjs/common'; -import { randomUUID } from 'crypto'; -import { Chat, Message, User } from './domain'; - -export interface ChatCursor { - id: string; -} - -export interface MessageCursor { - chatId: string; - id: string; -} - -interface Ordered { - id: string; - seq: number; - createdAt: string; -} - -type StoredChat = Chat & Ordered; -type StoredMessage = Message & Ordered; - -class OrderedList { - private readonly items: T[] = []; - private readonly indexById = new Map(); - - push(item: T): void { - this.items.push(item); - let index = this.items.length - 1; - while ( - index > 0 && - this.items[index - 1].createdAt === item.createdAt && - this.items[index - 1].id > item.id - ) { - this.items[index] = this.items[index - 1]; - this.indexById.set(this.items[index].id, index); - index--; - } - this.items[index] = item; - this.indexById.set(item.id, index); - } - - get length(): number { - return this.items.length; - } - - toArray(): T[] { - return this.items; - } - - page(afterId: string | null, limit: number): T[] { - if (afterId === null) { - return this.items.slice(0, limit); - } - const cursorIndex = this.indexById.get(afterId); - const startIndex = - cursorIndex === undefined ? this.items.length : cursorIndex + 1; - return this.items.slice(startIndex, startIndex + limit); - } - - hasMoreAfter(lastId: string): boolean { - const cursorIndex = this.indexById.get(lastId); - return cursorIndex !== undefined && cursorIndex < this.items.length - 1; - } - - hasId(id: string): boolean { - return this.indexById.has(id); - } -} - -@Injectable() -export class StoreService { - private readonly usersById = new Map(); - private readonly userIdByUsername = new Map(); - private readonly chatsById = new Map(); - private readonly chatsByMember = new Map>(); - private readonly messagesByChatId = new Map< - string, - OrderedList - >(); - private nextChatSeq = 0; - private nextMessageSeq = 0; - - createUser(username: string, displayName: string): User | null { - if (this.userIdByUsername.has(username)) { - return null; - } - const user: User = { - id: randomUUID(), - username, - displayName, - createdAt: new Date().toISOString(), - }; - this.usersById.set(user.id, user); - this.userIdByUsername.set(username, user.id); - return user; - } - - getUserById(id: string): User | undefined { - return this.usersById.get(id); - } - - createChat(title: string, memberIds: string[]): Chat { - const stored: StoredChat = { - id: randomUUID(), - title, - memberIds: [...memberIds], - createdAt: new Date().toISOString(), - seq: this.nextChatSeq++, - }; - this.chatsById.set(stored.id, stored); - for (const memberId of memberIds) { - this.chatListFor(memberId).push(stored); - } - this.messagesByChatId.set(stored.id, new OrderedList()); - return toPublicChat(stored); - } - - getChatById(id: string): Chat | undefined { - const stored = this.chatsById.get(id); - return stored ? toPublicChat(stored) : undefined; - } - - isMember(chatId: string, userId: string): boolean { - return !!this.chatsById.get(chatId)?.memberIds.includes(userId); - } - - listChatsForMember( - userId: string, - afterCursor: ChatCursor | null, - limit: number, - ): Chat[] { - return this.chatListFor(userId) - .page(afterCursor?.id ?? null, limit) - .map(toPublicChat); - } - - hasMoreChatsAfter(userId: string, lastId: string): boolean { - return this.chatListFor(userId).hasMoreAfter(lastId); - } - - chatCursorExists(userId: string, cursorId: string): boolean { - return this.chatListFor(userId).hasId(cursorId); - } - - createMessage(chatId: string, senderId: string, text: string): Message { - const list = this.messagesByChatId.get(chatId); - if (!list) { - throw new Error('chat must exist before appending a message'); - } - const stored: StoredMessage = { - id: randomUUID(), - chatId, - senderId, - text, - createdAt: new Date().toISOString(), - seq: this.nextMessageSeq++, - }; - list.push(stored); - return toPublicMessage(stored); - } - - listMessages( - chatId: string, - afterCursor: MessageCursor | null, - limit: number, - ): Message[] { - const list = this.messagesByChatId.get(chatId); - if (!list) { - return []; - } - return list.page(afterCursor?.id ?? null, limit).map(toPublicMessage); - } - - hasMoreMessagesAfter(chatId: string, lastId: string): boolean { - return this.messagesByChatId.get(chatId)?.hasMoreAfter(lastId) ?? false; - } - - messageCursorExists(chatId: string, cursorId: string): boolean { - return this.messagesByChatId.get(chatId)?.hasId(cursorId) ?? false; - } - - private chatListFor(memberId: string): OrderedList { - let list = this.chatsByMember.get(memberId); - if (!list) { - list = new OrderedList(); - this.chatsByMember.set(memberId, list); - } - return list; - } -} - -function toPublicChat(stored: StoredChat): Chat { - const { seq: _seq, ...chat } = stored; - return chat; -} - -function toPublicMessage(stored: StoredMessage): Message { - const { seq: _seq, ...message } = stored; - return message; -} - -export function encodeChatCursor(cursor: ChatCursor): string { - return encode(cursor); -} - -export function decodeChatCursor(raw: string): ChatCursor | null { - const decoded = decode(raw); - return decoded && typeof decoded.id === 'string' - ? { id: decoded.id } - : null; -} - -export function encodeMessageCursor(cursor: MessageCursor): string { - return encode(cursor); -} - -export function decodeMessageCursor(raw: string): MessageCursor | null { - const decoded = decode(raw); - return decoded && - typeof decoded.chatId === 'string' && - typeof decoded.id === 'string' - ? { chatId: decoded.chatId, id: decoded.id } - : null; -} - -function encode(value: object): string { - return Buffer.from(JSON.stringify(value), 'utf8').toString('base64url'); -} - -function decode(raw: string): Record | null { - try { - const parsed = JSON.parse( - Buffer.from(raw, 'base64url').toString('utf8'), - ); - return typeof parsed === 'object' && parsed !== null ? parsed : null; - } catch { - return null; - } -} diff --git a/src/db/db.module.ts b/src/db/db.module.ts new file mode 100644 index 0000000..2dac775 --- /dev/null +++ b/src/db/db.module.ts @@ -0,0 +1,9 @@ +import { Global, Module } from '@nestjs/common'; +import { PrismaService } from './prisma.service'; + +@Global() +@Module({ + providers: [PrismaService], + exports: [PrismaService], +}) +export class DbModule {} diff --git a/src/db/prisma.service.ts b/src/db/prisma.service.ts new file mode 100644 index 0000000..e391433 --- /dev/null +++ b/src/db/prisma.service.ts @@ -0,0 +1,49 @@ +import { Injectable, OnModuleDestroy } from '@nestjs/common'; +import { Prisma, PrismaClient } from '@prisma/client'; +import { readFileSync } from 'fs'; + +const UNAVAILABLE_CODES = new Set(['P1001', 'P1002', 'P1008', 'P1017', 'P2024']); + +@Injectable() +export class PrismaService extends PrismaClient implements OnModuleDestroy { + constructor() { + super({ datasourceUrl: readDatabaseUrl() }); + } + + async onModuleDestroy(): Promise { + await this.$disconnect(); + } +} + +function readDatabaseUrl(): string { + const file = process.env.DATABASE_URL_FILE; + const url = file ? readFileSync(file, 'utf8').trim() : process.env.DATABASE_URL; + if (!url) { + throw new Error('DATABASE_URL_FILE or DATABASE_URL must be set'); + } + return url; +} + +export function isUniqueViolation(error: unknown): boolean { + return ( + error instanceof Prisma.PrismaClientKnownRequestError && + error.code === 'P2002' + ); +} + +export function isForeignKeyViolation(error: unknown): boolean { + return ( + error instanceof Prisma.PrismaClientKnownRequestError && + error.code === 'P2003' + ); +} + +export function isDatabaseUnavailable(error: unknown): boolean { + if (error instanceof Prisma.PrismaClientInitializationError) { + return true; + } + return ( + error instanceof Prisma.PrismaClientKnownRequestError && + UNAVAILABLE_CODES.has(error.code) + ); +} diff --git a/src/health/health.controller.ts b/src/health/health.controller.ts index c8d02b9..f691b56 100644 --- a/src/health/health.controller.ts +++ b/src/health/health.controller.ts @@ -1,14 +1,23 @@ import { Controller, Get } from '@nestjs/common'; +import { ApiError } from '../common/filters/api-error'; +import { PrismaService } from '../db/prisma.service'; @Controller('health') export class HealthController { + constructor(private readonly prisma: PrismaService) {} + @Get('live') live(): { status: 'ok' } { return { status: 'ok' }; } @Get('ready') - ready(): { status: 'ok' } { + async ready(): Promise<{ status: 'ok' }> { + try { + await this.prisma.$queryRaw`SELECT 1`; + } catch { + throw new ApiError('unavailable', 'database unavailable'); + } return { status: 'ok' }; } } diff --git a/src/messages/dto/message.response.ts b/src/messages/dto/message.response.ts index 55cdf75..34684d9 100644 --- a/src/messages/dto/message.response.ts +++ b/src/messages/dto/message.response.ts @@ -1,4 +1,4 @@ -import { Message } from '../../common/store/domain'; +import { Message } from '../../common/domain'; export interface MessageResponse { id: string; diff --git a/src/messages/messages.controller.ts b/src/messages/messages.controller.ts index 2b10222..da46c71 100644 --- a/src/messages/messages.controller.ts +++ b/src/messages/messages.controller.ts @@ -11,7 +11,7 @@ import { import { AuthGuard } from '../common/auth/auth.guard'; import { CurrentUser } from '../common/auth/current-user.decorator'; import { parseLimit, rawCursorParam } from '../common/dto/pagination-query.dto'; -import { User } from '../common/store/domain'; +import { User } from '../common/domain'; import { CreateMessageDto } from './dto/create-message.dto'; import { MessagePageResponse, @@ -27,22 +27,22 @@ export class MessagesController { @Post() @HttpCode(201) - create( + async create( @Param('chatId') chatId: string, @Body() dto: CreateMessageDto, @CurrentUser() user: User, - ): MessageResponse { - const message = this.messages.create(chatId, user.id, dto.text); + ): Promise { + const message = await this.messages.create(chatId, user.id, dto.text); return toMessageResponse(message); } @Get() - list( + async list( @Param('chatId') chatId: string, @CurrentUser() user: User, @Query('limit') limitRaw: unknown, @Query('cursor') cursorRaw: unknown, - ): MessagePageResponse { + ): Promise { const limit = parseLimit(limitRaw); const cursor = rawCursorParam(cursorRaw); return this.messages.list(chatId, user.id, limit, cursor); diff --git a/src/messages/messages.service.ts b/src/messages/messages.service.ts index 92cac63..ec269ef 100644 --- a/src/messages/messages.service.ts +++ b/src/messages/messages.service.ts @@ -1,73 +1,106 @@ import { Injectable } from '@nestjs/common'; -import { ApiError } from '../common/filters/api-error'; +import { Prisma } from '@prisma/client'; import { codePointLength } from '../common/dto/code-point-length.validator'; -import { Message } from '../common/store/domain'; -import { - decodeMessageCursor, - encodeMessageCursor, - StoreService, -} from '../common/store/store.service'; +import { decodeMessageCursor, encodeMessageCursor } from '../common/cursor'; +import { Message } from '../common/domain'; +import { ApiError } from '../common/filters/api-error'; import { validate as isUuid } from '../common/uuid'; +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; +} + @Injectable() export class MessagesService { - constructor(private readonly store: StoreService) {} + constructor(private readonly prisma: PrismaService) {} - create(chatId: string, callerId: string, text: string): Message { - this.assertMember(chatId, callerId); + async create( + chatId: string, + callerId: string, + text: string, + ): Promise { + await this.assertMember(chatId, callerId); if (codePointLength(text.trim()) === 0) { throw new ApiError( 'invalid_request', 'text must not be empty or whitespace-only', ); } - return this.store.createMessage(chatId, callerId, text); + const row = await this.prisma.message.create({ + data: { chatId, senderId: callerId, text }, + }); + return toMessage(row); } - list( + async list( chatId: string, callerId: string, limit: number, rawCursor: string | null, - ): MessagePageResponse { - this.assertMember(chatId, callerId); - const cursor = - rawCursor === null ? null : decodeMessageCursor(rawCursor); - if (rawCursor !== null && cursor === null) { - throw new ApiError('invalid_request', 'invalid cursor'); + ): Promise { + 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)`; } - if (cursor && cursor.chatId !== chatId) { - throw new ApiError( - 'invalid_request', - 'cursor belongs to a different chat', - ); - } - if (cursor && !this.store.messageCursorExists(chatId, cursor.id)) { - throw new ApiError('invalid_request', 'invalid cursor'); - } - const items = this.store.listMessages(chatId, cursor, limit); + const rows = await this.prisma.$queryRaw` + SELECT id, chat_id AS "chatId", sender_id AS "senderId", text, created_at AS "createdAt" + 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]; - const hasMore = last - ? this.store.hasMoreMessagesAfter(chatId, last.id) - : false; return { items: items.map(toMessageResponse), - next_cursor: hasMore - ? encodeMessageCursor({ chatId, id: last.id }) - : null, + next_cursor: + rows.length > limit + ? encodeMessageCursor({ chatId, id: last.id }) + : null, }; } - private assertMember(chatId: string, callerId: string): void { + private async assertMember(chatId: string, callerId: string): Promise { if (!isUuid(chatId)) { throw new ApiError('invalid_request', 'chatId must be a valid UUID'); } - if ( - !this.store.getChatById(chatId) || - !this.store.isMember(chatId, callerId) - ) { + const member = await this.prisma.chatMember.findUnique({ + where: { chatId_userId: { chatId, userId: callerId } }, + }); + if (!member) { throw new ApiError('not_found', 'chat not found'); } } } + +function toMessage(row: MessageRow): Message { + return { + id: row.id, + chatId: row.chatId, + senderId: row.senderId, + text: row.text, + createdAt: row.createdAt.toISOString(), + }; +} diff --git a/src/users/dto/user.response.ts b/src/users/dto/user.response.ts index 0312b66..b4626fb 100644 --- a/src/users/dto/user.response.ts +++ b/src/users/dto/user.response.ts @@ -1,4 +1,4 @@ -import { User } from '../../common/store/domain'; +import { User } from '../../common/domain'; export interface UserResponse { id: string; diff --git a/src/users/users.controller.ts b/src/users/users.controller.ts index baa9673..4868525 100644 --- a/src/users/users.controller.ts +++ b/src/users/users.controller.ts @@ -8,7 +8,7 @@ import { } from '@nestjs/common'; import { AuthGuard } from '../common/auth/auth.guard'; import { CurrentUser } from '../common/auth/current-user.decorator'; -import { User } from '../common/store/domain'; +import { User } from '../common/domain'; import { CreateUserDto } from './dto/create-user.dto'; import { toUserResponse, UserResponse } from './dto/user.response'; import { UsersService } from './users.service'; @@ -19,8 +19,8 @@ export class UsersController { @Post() @HttpCode(201) - create(@Body() dto: CreateUserDto): UserResponse { - const user = this.users.register(dto.username, dto.display_name); + async create(@Body() dto: CreateUserDto): Promise { + const user = await this.users.register(dto.username, dto.display_name); return toUserResponse(user); } diff --git a/src/users/users.service.ts b/src/users/users.service.ts index 807e4c4..554f3a0 100644 --- a/src/users/users.service.ts +++ b/src/users/users.service.ts @@ -1,17 +1,42 @@ import { Injectable } from '@nestjs/common'; import { ApiError } from '../common/filters/api-error'; -import { User } from '../common/store/domain'; -import { StoreService } from '../common/store/store.service'; +import { User } from '../common/domain'; +import { PrismaService, isUniqueViolation } from '../db/prisma.service'; @Injectable() export class UsersService { - constructor(private readonly store: StoreService) {} + constructor(private readonly prisma: PrismaService) {} - register(username: string, displayName: string): User { - const user = this.store.createUser(username, displayName.trim()); - if (!user) { - throw new ApiError('conflict', 'username is already taken'); + async register(username: string, displayName: string): Promise { + try { + const row = await this.prisma.user.create({ + data: { username, displayName: displayName.trim() }, + }); + return toUser(row); + } catch (error) { + if (isUniqueViolation(error)) { + throw new ApiError('conflict', 'username is already taken'); + } + throw error; } - return user; + } + + async findById(id: string): Promise { + const row = await this.prisma.user.findUnique({ where: { id } }); + return row ? toUser(row) : null; } } + +export function toUser(row: { + id: string; + username: string; + displayName: string; + createdAt: Date; +}): User { + return { + id: row.id, + username: row.username, + displayName: row.displayName, + createdAt: row.createdAt.toISOString(), + }; +} diff --git a/test/global-setup.ts b/test/global-setup.ts new file mode 100644 index 0000000..4f1d400 --- /dev/null +++ b/test/global-setup.ts @@ -0,0 +1,5 @@ +import { execSync } from 'child_process'; + +export default function globalSetup(): void { + execSync('npx prisma migrate deploy', { stdio: 'inherit' }); +} diff --git a/test/jest-e2e.json b/test/jest-e2e.json index f43e8a6..f4b08bb 100644 --- a/test/jest-e2e.json +++ b/test/jest-e2e.json @@ -3,6 +3,7 @@ "rootDir": ".", "testEnvironment": "node", "testRegex": ".e2e-spec.ts$", + "globalSetup": "/global-setup.ts", "transform": { "^.+\\.(t|j)s$": "ts-jest" }