Skip to content

Commit

Permalink
refactor: session autostop
Browse files Browse the repository at this point in the history
  • Loading branch information
rharkor committed Feb 1, 2024
1 parent dcd7877 commit 865c634
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 2 deletions.
41 changes: 41 additions & 0 deletions packages/app/crons/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,3 +60,44 @@ new CronJob(
true,
"Europe/Paris"
)

new CronJob(
//* Every minute
"* * * * * *",
async () => {
const maxDurationWarning = 1000 * 60 * 2 // 5 minutes
const name = "Auto-stop session"
const now = new Date()
//? Do something
async function autoStopSession() {
const session = await prisma.session.findFirst()
if (!session || !session.enabled) return
const now = new Date()
const maxActiveTime = 1000 * 60 * 60 * 24 // 24 hours
const needToBeStopped = session.updatedAt.getTime() + maxActiveTime < now.getTime()
if (needToBeStopped) {
await prisma.session.update({
where: {
id: session.id,
},
data: {
enabled: false,
},
})
}
}
await autoStopSession().catch((err) => {
logger.error(
`[${now.toLocaleString()}] ${name} started at ${now.toLocaleString()} and failed after ${
new Date().getTime() - now.getTime()
}ms`
)
throw err
})
const took = new Date().getTime() - now.getTime()
if (took > maxDurationWarning) logger.warn(`[${now.toLocaleString()}] ${name} took ${took}ms`)
},
null,
true,
"Europe/Paris"
)
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
-- AlterTable
ALTER TABLE "Session" ADD COLUMN "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
ADD COLUMN "updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP;
6 changes: 4 additions & 2 deletions packages/app/prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -112,8 +112,10 @@ model PingResult {
}

model Session {
id String @id @default(cuid())
enabled Boolean @default(false)
id String @id @default(cuid())
enabled Boolean @default(false)
basePoints Int?
damagePerHit Int?
createdAt DateTime @default(now())
updatedAt DateTime @default(now()) @updatedAt
}

0 comments on commit 865c634

Please sign in to comment.