diff --git a/server/.env.example b/server/.env.example index 4b7b384..c8238d6 100644 --- a/server/.env.example +++ b/server/.env.example @@ -9,3 +9,4 @@ CLIENT_ORIGIN=http://localhost:5173 UPLOAD_DIR=uploads MAX_UPLOAD_SIZE=20971520 +SCHEDULER_INTERVAL_MS=20000 diff --git a/server/src/config/env.ts b/server/src/config/env.ts index 0e49eda..93fd2de 100644 --- a/server/src/config/env.ts +++ b/server/src/config/env.ts @@ -27,6 +27,7 @@ loadDotenv({ path: path.join(SERVER_ROOT, '.env') }); * @property {string} clientOrigin — разрешённый origin для CORS * @property {string} uploadDir — каталог для загружаемых файлов (абсолютный путь) * @property {number} maxUploadSize — максимальный размер файла в байтах + * @property {number} schedulerIntervalMs — интервал опроса scheduler в мс */ export interface Env { readonly nodeEnv: string; @@ -37,6 +38,7 @@ export interface Env { readonly clientOrigin: string; readonly uploadDir: string; readonly maxUploadSize: number; + readonly schedulerIntervalMs: number; } /** @@ -105,6 +107,7 @@ export function loadEnv(): Env { clientOrigin: process.env.CLIENT_ORIGIN ?? 'http://localhost:5173', uploadDir, maxUploadSize: parseMaxUploadSize(process.env.MAX_UPLOAD_SIZE ?? String(20 * 1024 * 1024)), + schedulerIntervalMs: Number.parseInt(process.env.SCHEDULER_INTERVAL_MS ?? '20000', 10), }; } diff --git a/server/src/routes/news.routes.ts b/server/src/routes/news.routes.ts index e0a16bb..5fc54c0 100644 --- a/server/src/routes/news.routes.ts +++ b/server/src/routes/news.routes.ts @@ -189,4 +189,74 @@ newsRouter.delete( }), ); +/** + * POST /api/news/:id/publish + * Немедленная публикация новости. + * + * @returns 200 { news: { id, title, content, status: 'published', ... } } + */ +newsRouter.post( + '/:id/publish', + asyncHandler(async (req: Request, res: Response) => { + const userId = getUserId(req); + const news = await News.findOne({ _id: req.params.id, author: userId }); + if (!news) { + throw new ApiError(404, 'NEWS_NOT_FOUND', NOT_FOUND_MSG); + } + + if (news.status === 'published') { + throw new ApiError(400, 'ALREADY_PUBLISHED', 'Новость уже опубликована'); + } + + news.status = 'published'; + news.publishedAt = new Date(); + news.scheduledAt = null; + await news.save(); + + res.json({ news: serializeNews(news) }); + }), +); + +/** + * POST /api/news/:id/schedule + * Отложенная публикация: устанавливает scheduledAt. + * + * @param req.body.scheduledAt — ISO-дата будущего времени + * @returns 200 { news: { id, ..., status: 'scheduled', scheduledAt } } + */ +newsRouter.post( + '/:id/schedule', + asyncHandler(async (req: Request, res: Response) => { + const userId = getUserId(req); + const news = await News.findOne({ _id: req.params.id, author: userId }); + if (!news) { + throw new ApiError(404, 'NEWS_NOT_FOUND', NOT_FOUND_MSG); + } + + if (news.status === 'published') { + throw new ApiError(400, 'ALREADY_PUBLISHED', 'Новость уже опубликована'); + } + + const scheduledAtRaw = bodyField(req, 'scheduledAt'); + if (typeof scheduledAtRaw !== 'string') { + throw new ApiError(400, 'VALIDATION_ERROR', 'scheduledAt должен быть строкой (ISO-дата)'); + } + + const scheduledAt = new Date(scheduledAtRaw); + if (Number.isNaN(scheduledAt.getTime())) { + throw new ApiError(400, 'VALIDATION_ERROR', 'scheduledAt не является валидной датой'); + } + if (scheduledAt.getTime() <= Date.now()) { + throw new ApiError(400, 'VALIDATION_ERROR', 'scheduledAt должен быть в будущем'); + } + + news.status = 'scheduled'; + news.scheduledAt = scheduledAt; + news.publishedAt = null; + await news.save(); + + res.json({ news: serializeNews(news) }); + }), +); + export default newsRouter; diff --git a/server/src/server.ts b/server/src/server.ts index 2edc140..dbdb3e3 100644 --- a/server/src/server.ts +++ b/server/src/server.ts @@ -3,6 +3,7 @@ import http from 'node:http'; import { createApp } from './app.js'; import { connectDatabase } from './config/database.js'; import { env } from './config/env.js'; +import { startPublicationScheduler, stopPublicationScheduler } from './services/publicationScheduler.service.js'; /** * Завершает работу процесса после закрытия сервера. @@ -12,6 +13,7 @@ import { env } from './config/env.js'; */ function shutdown(signal: string, server: http.Server): void { console.warn(`Сигнал ${signal} получен, завершение работы...`); + stopPublicationScheduler(); server.close(() => { process.exit(0); }); @@ -28,6 +30,9 @@ async function main(): Promise { const app = createApp(); const server = http.createServer(app); + // Запускаем планировщик отложенной публикации + startPublicationScheduler(env.schedulerIntervalMs); + server.listen(env.port, () => { console.warn(`News Editor API запущен на порту ${String(env.port)} (${env.nodeEnv})`); }); diff --git a/server/src/services/publicationScheduler.service.ts b/server/src/services/publicationScheduler.service.ts new file mode 100644 index 0000000..a5941d7 --- /dev/null +++ b/server/src/services/publicationScheduler.service.ts @@ -0,0 +1,68 @@ +import News from '../models/news.model.js'; + +/** + * Публикационный планировщик (MongoDB-backed poll). + * + * Каждые `intervalMs` миллисекунд выполняет атомарный запрос: + * находит все новости со status='scheduled' и scheduledAt <= now, + * атомарно переключает их в status='published'. + * + * Не использует setTimeout на конкретную статью — только poll. + */ + +let timer: ReturnType | null = null; + +/** + * Запускает периодический poll для автоматической публикации. + * + * @param intervalMs — интервал опроса в мс (по умолчанию 20000 = 20 сек) + * @returns void + */ +export function startPublicationScheduler(intervalMs = 20_000): void { + if (timer) { + return; + } + + const poll = async (): Promise => { + try { + const now = new Date(); + + // Атомарный update: только scheduled → published, если scheduledAt уже прошёл + const result = await News.updateMany( + { status: 'scheduled', scheduledAt: { $lte: now } }, + { $set: { status: 'published', publishedAt: now, scheduledAt: null } }, + ); + + if (result.modifiedCount > 0) { + // eslint-disable-next-line no-console -- логирование публикации + console.log(`[scheduler] Опубликовано новостей: ${String(result.modifiedCount)}`); + } + } catch (err) { + + console.error('[scheduler] Ошибка при публикации:', err); + } + }; + + // Первый poll сразу + poll().catch(() => { + // ошибки логируются внутри poll + }); + timer = setInterval(() => { + poll().catch(() => { + // ошибки логируются внутри poll + }); + }, intervalMs); + + // Не держать процесс живым только ради scheduler + timer.unref(); +} + +/** + * Останавливает планировщик (для тестов и graceful shutdown). + */ +export function stopPublicationScheduler(): void { + if (timer) { + clearInterval(timer); + timer = null; + } +} diff --git a/server/tests/publish.test.ts b/server/tests/publish.test.ts new file mode 100644 index 0000000..9430f40 --- /dev/null +++ b/server/tests/publish.test.ts @@ -0,0 +1,145 @@ +import request from 'supertest'; +import { describe, expect, it, beforeAll, afterAll } from 'vitest'; + +import { createApp } from '../src/app.js'; +import News from '../src/models/news.model.js'; +import { User, hashPassword } from '../src/models/user.model.js'; +import { startPublicationScheduler, stopPublicationScheduler } from '../src/services/publicationScheduler.service.js'; +import { signUserToken } from '../src/utils/jwt.js'; + +const app = createApp(); +const TEST_EMAIL = 'publish-test@example.com'; + +let authToken = ''; + +beforeAll(async () => { + const user = await User.create({ + email: TEST_EMAIL, + passwordHash: await hashPassword('Test-Pass-123'), + }); + authToken = signUserToken(user.id); +}); + +function authed(req: request.Test): request.Test { + return req.set('Authorization', `Bearer ${authToken}`); +} + +/** Создаёт тестовую новость и возвращает её id. */ +async function createTestNews(title: string): Promise { + const res = await authed(request(app).post('/api/news').send({ title, content: 'Тест' })); + // eslint-disable-next-line @typescript-eslint/no-unsafe-return -- supertest body + return res.body.news.id; +} + +describe('Публикация новостей', () => { + describe('POST /api/news/:id/publish', () => { + it('публикует draft-новость', async () => { + const id = await createTestNews('К публикации'); + const res = await authed(request(app).post(`/api/news/${id}/publish`)); + expect(res.status).toBe(200); + expect(res.body.news.status).toBe('published'); + expect(res.body.news.publishedAt).not.toBeNull(); + }); + + it('повторная публикация возвращает 400', async () => { + const id = await createTestNews('Уже опубликована'); + await authed(request(app).post(`/api/news/${id}/publish`)); + const res = await authed(request(app).post(`/api/news/${id}/publish`)); + expect(res.status).toBe(400); + expect(res.body.error.code).toBe('ALREADY_PUBLISHED'); + }); + + it('несуществующий id возвращает 404', async () => { + const res = await authed(request(app).post('/api/news/000000000000000000000000/publish')); + expect(res.status).toBe(404); + }); + + it('чужая новость — 404', async () => { + const id = await createTestNews('Своя'); + const user2 = await User.create({ + email: 'publish-other@example.com', + passwordHash: await hashPassword('Other-Pass-123'), + }); + const token2 = signUserToken(user2.id); + + const res = await request(app) + .post(`/api/news/${id}/publish`) + .set('Authorization', `Bearer ${token2}`); + expect(res.status).toBe(404); + }); + }); + + describe('POST /api/news/:id/schedule', () => { + it('устанавливает отложенную публикацию', async () => { + const id = await createTestNews('Отложенная'); + const futureDate = new Date(Date.now() + 3600_000).toISOString(); + + const res = await authed(request(app).post(`/api/news/${id}/schedule`).send({ scheduledAt: futureDate })); + expect(res.status).toBe(200); + expect(res.body.news.status).toBe('scheduled'); + expect(res.body.news.scheduledAt).toBe(futureDate); + }); + + it('дата в прошлом возвращает 400', async () => { + const id = await createTestNews('Прошлая дата'); + const pastDate = new Date(Date.now() - 3600_000).toISOString(); + + const res = await authed(request(app).post(`/api/news/${id}/schedule`).send({ scheduledAt: pastDate })); + expect(res.status).toBe(400); + }); + + it('невалидная дата возвращает 400', async () => { + const id = await createTestNews('Невалидная дата'); + const res = await authed(request(app).post(`/api/news/${id}/schedule`).send({ scheduledAt: 'not-a-date' })); + expect(res.status).toBe(400); + }); + + it('отсутствие scheduledAt возвращает 400', async () => { + const id = await createTestNews('Без даты'); + const res = await authed(request(app).post(`/api/news/${id}/schedule`).send({})); + expect(res.status).toBe(400); + }); + + it('уже опубликованная — 400', async () => { + const id = await createTestNews('Публикация и schedule'); + await authed(request(app).post(`/api/news/${id}/publish`)); + const futureDate = new Date(Date.now() + 3600_000).toISOString(); + + const res = await authed(request(app).post(`/api/news/${id}/schedule`).send({ scheduledAt: futureDate })); + expect(res.status).toBe(400); + expect(res.body.error.code).toBe('ALREADY_PUBLISHED'); + }); + }); + + describe('Publication Scheduler', () => { + afterAll(() => { + stopPublicationScheduler(); + }); + + it('автоматически публикует scheduled новости с прошедшим scheduledAt', async () => { + // Создаём новость и вручную ставим scheduledAt в прошлое + const id = await createTestNews('Авто-публикация'); + const pastDate = new Date(Date.now() - 60_000); + await News.updateOne({ _id: id }, { $set: { status: 'scheduled', scheduledAt: pastDate } }); + + // Запускаем scheduler с коротким интервалом + startPublicationScheduler(500); + + // Ждём до 3 секунд пока scheduler опубликует + const deadline = Date.now() + 3000; + let published = false; + while (Date.now() < deadline) { + const news = await News.findById(id); + if (news?.status === 'published') { + published = true; + break; + } + + await new Promise((r) => { setTimeout(r, 100); }); + } + + stopPublicationScheduler(); + expect(published).toBe(true); + }); + }); +}); diff --git a/server/vitest.config.ts b/server/vitest.config.ts index 7a5a32c..c6680ab 100644 --- a/server/vitest.config.ts +++ b/server/vitest.config.ts @@ -9,6 +9,8 @@ export default defineConfig({ setupFiles: ['tests/setup.ts'], globalSetup: ['tests/global-setup.ts'], include: ['tests/**/*.test.ts'], + // Последовательное выполнение: scheduler влияет на общее состояние БД + fileParallelism: false, coverage: { provider: 'v8', include: ['src/**/*.ts'],