Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

πŸ› fix: redis에 μΊμ‹±λœ μ΅œμ‹  ν”Όλ“œκ°€ μ‚­μ œλ˜μ§€ μ•ŠλŠ” 버그 μˆ˜μ • #262

Merged
merged 7 commits into from
Dec 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 27 additions & 13 deletions rss-notifier/src/db-access.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import * as dotenv from "dotenv";
import * as mysql from "mysql2/promise";
import Redis from "ioredis";
import * as process from "node:process";
import { PoolConnection } from "mysql2/promise";

dotenv.config({
path: process.env.NODE_ENV === "production" ? "rss-notifier/.env" : ".env",
Expand Down Expand Up @@ -34,12 +35,12 @@ export const createRedisClient = async () => {
});
};

export const executeQuery = async (query: string, params: any[] = []) => {
let connection;
export const executeQuery = async <T>(query: string, params: any[] = []) => {
let connection: PoolConnection;
try {
connection = await pool.getConnection();
const [rows] = await connection.query(query, params);
return rows;
return rows as T[];
} catch (err) {
logger.error("쿼리 " + query + " μ‹€ν–‰ 쀑 였λ₯˜ λ°œμƒ:", err);
throw err;
Expand All @@ -58,15 +59,15 @@ export const selectAllRss = async (): Promise<RssObj[]> => {

export const insertFeeds = async (resultData: FeedDetail[]) => {
let successCount = 0;
let lastFeedId;
let lastFeedId: number;
const query = `
INSERT INTO feed (blog_id, created_at, title, path, thumbnail)
VALUES (?, ?, ?, ?, ?)
`;
for (const feed of resultData) {
try {
lastFeedId = (
await executeQuery(query, [
await executeQuery<FeedDetail>(query, [
feed.blogId,
feed.pubDate,
feed.title,
Expand All @@ -81,23 +82,36 @@ export const insertFeeds = async (resultData: FeedDetail[]) => {
}

logger.info(
`${successCount}개의 ν”Όλ“œ 데이터가 μ„±κ³΅μ μœΌλ‘œ λ°μ΄ν„°λ² μ΄μŠ€μ— μ‚½μž…λ˜μ—ˆμŠ΅λ‹ˆλ‹€.`
`${successCount}개의 ν”Όλ“œ 데이터가 μ„±κ³΅μ μœΌλ‘œ λ°μ΄ν„°λ² μ΄μŠ€μ— μ‚½μž…λ˜μ—ˆμŠ΅λ‹ˆλ‹€.`,
);
lastFeedId = lastFeedId - successCount + 1;
return lastFeedId;
};

export const deleteRecentFeedStartId = async () => {
export const deleteRecentFeed = async () => {
const redis = await createRedisClient();
try {
const keys = await redis.keys(redisConstant.FEED_RECENT_ALL_KEY);
if (keys.length > 0) {
await redis.del(...keys);
const keysToDelete = [];
let cursor = "0";
do {
const [newCursor, keys] = await redis.scan(
cursor,
"MATCH",
redisConstant.FEED_RECENT_ALL_KEY,
"COUNT",
"100",
);
keysToDelete.push(...keys);
cursor = newCursor;
} while (cursor !== "0");

if (keysToDelete.length > 0) {
await redis.del(...keysToDelete);
}
await redis.set(redisConstant.FEED_RECENT_KEY, "false");
} catch (error) {
logger.error(
`Redis의 feed:recent:*λ₯Ό μ‚­μ œν•˜λŠ” 도쀑 μ—λŸ¬κ°€ λ°œμƒν–ˆμŠ΅λ‹ˆλ‹€. μ—λŸ¬ λ‚΄μš©: ${error}`
`Redis의 feed:recent:*λ₯Ό μ‚­μ œν•˜λŠ” 도쀑 μ—λŸ¬κ°€ λ°œμƒν–ˆμŠ΅λ‹ˆλ‹€. μ—λŸ¬ λ‚΄μš©: ${error}`,
);
} finally {
if (redis) await redis.quit();
Expand All @@ -120,7 +134,7 @@ export const setRecentFeedList = async (startId: number) => {
FROM feed f
JOIN rss_accept r ON f.blog_id = r.id
WHERE f.id >= ${startId}`;
const resultList = await executeQuery(query);
const resultList = await executeQuery<RssObj>(query);
const pipeLine = redis.pipeline();
for (const feed of resultList) {
pipeLine.hset(`feed:recent:${feed.id}`, feed);
Expand All @@ -129,7 +143,7 @@ export const setRecentFeedList = async (startId: number) => {
await pipeLine.exec();
} catch (error) {
logger.error(
`Redis의 feed:recent:*λ₯Ό μ €μž₯ν•˜λŠ” 도쀑 μ—λŸ¬κ°€ λ°œμƒν–ˆμŠ΅λ‹ˆλ‹€. μ—λŸ¬ λ‚΄μš©: ${error}`
`Redis의 feed:recent:*λ₯Ό μ €μž₯ν•˜λŠ” 도쀑 μ—λŸ¬κ°€ λ°œμƒν–ˆμŠ΅λ‹ˆλ‹€. μ—λŸ¬ λ‚΄μš©: ${error}`,
);
} finally {
if (redis) await redis.quit();
Expand Down
14 changes: 7 additions & 7 deletions rss-notifier/src/rss-notifier.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ import "dotenv/config";
import {
selectAllRss,
insertFeeds,
deleteRecentFeedStartId,
setRecentFeedList,
deleteRecentFeed,
} from "./db-access.js";
import { RssObj, FeedDetail, RawFeed } from "./types.js";
import { XMLParser } from "fast-xml-parser";
Expand Down Expand Up @@ -57,7 +57,7 @@ const fetchRss = async (rssUrl: string): Promise<RawFeed[]> => {

const findNewFeeds = async (
rssObj: RssObj,
now: number
now: number,
): Promise<FeedDetail[]> => {
try {
const TIME_INTERVAL = process.env.TIME_INTERVAL
Expand All @@ -84,13 +84,13 @@ const findNewFeeds = async (
link: decodeURIComponent(feed.link),
imageUrl: imageUrl,
};
})
}),
);

return detailedFeeds;
} catch (err) {
logger.warn(
`[${rssObj.rssUrl}] μ—μ„œ 데이터 쑰회 쀑 였λ₯˜ λ°œμƒμœΌλ‘œ μΈν•œ μŠ€ν‚΅ 처리. 였λ₯˜ λ‚΄μš© : ${err}`
`[${rssObj.rssUrl}] μ—μ„œ 데이터 쑰회 쀑 였λ₯˜ λ°œμƒμœΌλ‘œ μΈν•œ μŠ€ν‚΅ 처리. 였λ₯˜ λ‚΄μš© : ${err}`,
);
return [];
}
Expand Down Expand Up @@ -123,10 +123,10 @@ export const performTask = async () => {
const newFeeds = await Promise.all(
rssObjects.map(async (rssObj) => {
logger.info(
`[${++idx}번째 rss [${rssObj.rssUrl}] μ—μ„œ 데이터 μ‘°νšŒν•˜λŠ” 쀑...`
`[${++idx}번째 rss [${rssObj.rssUrl}] μ—μ„œ 데이터 μ‘°νšŒν•˜λŠ” 쀑...`,
);
return await findNewFeeds(rssObj, currentTime.setSeconds(0, 0));
})
}),
);

const result = newFeeds.flat().sort((currentFeed, nextFeed) => {
Expand All @@ -135,9 +135,9 @@ export const performTask = async () => {
return dateCurrent.getTime() - dateNext.getTime();
});

await deleteRecentFeed();
if (result.length === 0) {
logger.info("μƒˆλ‘œμš΄ ν”Όλ“œκ°€ μ—†μŠ΅λ‹ˆλ‹€.");
await deleteRecentFeedStartId();
return;
}

Expand Down
88 changes: 88 additions & 0 deletions server/src/feed/api-docs/readFeedList.api-docs.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
import { applyDecorators } from '@nestjs/common';
import {
ApiBadRequestResponse,
ApiOkResponse,
ApiOperation,
ApiQuery,
} from '@nestjs/swagger';

export function ApiReadFeedList() {
return applyDecorators(
ApiOperation({
summary: `메인 ν™”λ©΄ κ²Œμ‹œκΈ€ 쑰회 API`,
}),
ApiQuery({
name: 'lastId',
required: false,
type: Number,
description: 'λ§ˆμ§€λ§‰μœΌλ‘œ 받은 ν”Όλ“œμ˜ ID',
example: 10,
}),
ApiQuery({
name: 'limit',
required: false,
type: Number,
description: 'ν•œ λ²ˆμ— κ°€μ Έμ˜¬ ν”Όλ“œ 수',
example: 5,
default: 12,
}),
ApiOkResponse({
description: 'Ok',
schema: {
properties: {
message: {
type: 'string',
},
data: {
type: 'object',
properties: {
result: {
type: 'array',
items: {
type: 'object',
properties: {
id: { type: 'number' },
author: { type: 'string' },
blogPlatform: { type: 'string' },
title: { type: 'string' },
path: { type: 'string', format: 'url' },
createAt: { type: 'string', format: 'date-time' },
thumbnail: { type: 'string', format: 'url' },
viewCount: { type: 'number' },
},
},
},
lastId: { type: 'number' },
hasMore: { type: 'boolean' },
},
},
},
},
example: {
message: 'ν”Όλ“œ 쑰회 μ™„λ£Œ',
data: {
result: [
{
id: 3,
author: 'λΈ”λ‘œκ·Έ 이름',
blogPlatform: 'λΈ”λ‘œκ·Έ μ„œλΉ„μŠ€ ν”Œλž«νΌ',
title: 'ν”Όλ“œ 제λͺ©',
path: 'https://test.com',
createAt: '2024-06-16T20:00:57.000Z',
thumbnail: 'https://test.com/image.png',
viewCount: 1,
},
],
lastId: 3,
hasMore: true,
},
},
}),
ApiBadRequestResponse({
description: 'Bad Request',
example: {
message: '였λ₯˜ 메세지',
},
}),
);
}
54 changes: 54 additions & 0 deletions server/src/feed/api-docs/readRecentFeedList.api-docs.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import { applyDecorators } from '@nestjs/common';
import { ApiOkResponse, ApiOperation } from '@nestjs/swagger';

export function ApiReadRecentFeedList() {
return applyDecorators(
ApiOperation({
summary: 'μ΅œμ‹  ν”Όλ“œ μ—…λ°μ΄νŠΈ API',
}),
ApiOkResponse({
description: 'Ok',
schema: {
properties: {
message: {
type: 'string',
},
data: {
type: 'array',
items: {
type: 'object',
properties: {
id: { type: 'number' },
author: { type: 'string' },
blogPlatform: { type: 'string' },
title: { type: 'string' },
path: { type: 'string' },
createdAt: {
type: 'string',
format: 'date-time',
},
thumbnail: { type: 'string' },
viewCount: { type: 'number' },
},
},
},
},
},
example: {
message: 'μ΅œμ‹  ν”Όλ“œ μ—…λ°μ΄νŠΈ μ™„λ£Œ',
data: [
{
id: 1,
author: 'λΈ”λ‘œκ·Έ 이름',
blogPlatform: 'etc',
title: 'κ²Œμ‹œκΈ€ 제λͺ©',
path: 'https://test1.com/1',
createdAt: '2024-11-24T01:00:00.000Z',
thumbnail: 'https://test1.com/test.png',
viewCount: 0,
},
],
},
}),
);
}
Loading