fix: badly performing code

This commit is contained in:
2025-08-23 19:44:01 +02:00
parent 6a7b449363
commit 6e10da6f98
4 changed files with 34 additions and 13 deletions

View File

@@ -2,21 +2,39 @@ import { getRedisConnection, prisma } from "@hctv/db";
export async function viewerCountSync() {
const streams = await prisma.streamInfo.findMany({
where: {
isLive: true
},
include: {
channel: true
}
})
const redis = getRedisConnection();
for (const stream of streams) {
const viewerCount = await redis.keys(`viewer:${stream.channel.name}:*`);
await prisma.streamInfo.update({
where: {
username: stream.username,
},
data: {
viewers: viewerCount.length,
},
});
if (streams.length === 0) {
return;
}
const redis = getRedisConnection();
const multi = redis.multi();
for (const stream of streams) {
multi.keys(`viewer:${stream.channel.name}:*`);
}
const results = await multi.exec();
await prisma.$transaction(async (tx) => {
const updates = results?.map((res, index) => {
const count = Array.isArray(res[1]) ? res[1].length : 0;
const stream = streams[index];
return tx.streamInfo.update({
where: {
// using username here because it uses a map
username: stream.username
},
data: {
viewers: count
}
})
})
await Promise.all(updates || []);
})
}

View File

@@ -16,7 +16,8 @@
"act": "act --secret-file .env.ci",
"db:migrate": "yarn workspace @hctv/db db:migrate",
"ui:add": "yarn workspace @hctv/web ui:add",
"prisma": "yarn workspace @hctv/db prisma"
"prisma": "yarn workspace @hctv/db prisma",
"r:rtmp": "docker compose -f dev/docker-compose.yml restart nginx-rtmp -t 0"
},
"devDependencies": {
"turbo": "^2.4.4"

View File

@@ -0,0 +1,2 @@
-- CreateIndex
CREATE INDEX "StreamInfo_username_idx" ON "StreamInfo"("username");

View File

@@ -81,7 +81,7 @@ model StreamInfo {
enableNotifications Boolean @default(true)
// TODO: index on username
@@index([username])
}
model Follow {