feat: Implement a generic user timers system with a scheduler to manage cooldowns, effects, and access.
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
import { users, transactions, cooldowns } from "@/db/schema";
|
||||
import { users, transactions, userTimers } from "@/db/schema";
|
||||
import { eq, sql, and } from "drizzle-orm";
|
||||
import { DrizzleClient } from "@/lib/DrizzleClient";
|
||||
import { GameConfig } from "@/config/game";
|
||||
@@ -77,15 +77,16 @@ export const economyService = {
|
||||
startOfDay.setHours(0, 0, 0, 0);
|
||||
|
||||
// Check cooldown
|
||||
const cooldown = await txFn.query.cooldowns.findFirst({
|
||||
const cooldown = await txFn.query.userTimers.findFirst({
|
||||
where: and(
|
||||
eq(cooldowns.userId, BigInt(userId)),
|
||||
eq(cooldowns.actionKey, 'daily')
|
||||
eq(userTimers.userId, BigInt(userId)),
|
||||
eq(userTimers.type, 'COOLDOWN'),
|
||||
eq(userTimers.key, 'daily')
|
||||
),
|
||||
});
|
||||
|
||||
if (cooldown && cooldown.readyAt > now) {
|
||||
throw new Error(`Daily already claimed. Ready at ${cooldown.readyAt}`);
|
||||
if (cooldown && cooldown.expiresAt > now) {
|
||||
throw new Error(`Daily already claimed. Ready at ${cooldown.expiresAt}`);
|
||||
}
|
||||
|
||||
// Get user for streak logic
|
||||
@@ -101,7 +102,7 @@ export const economyService = {
|
||||
|
||||
// If previous cooldown exists and expired more than 24h ago (meaning >48h since last claim), reset streak
|
||||
if (cooldown) {
|
||||
const timeSinceReady = now.getTime() - cooldown.readyAt.getTime();
|
||||
const timeSinceReady = now.getTime() - cooldown.expiresAt.getTime();
|
||||
if (timeSinceReady > 24 * 60 * 60 * 1000) {
|
||||
streak = 1;
|
||||
}
|
||||
@@ -126,15 +127,16 @@ export const economyService = {
|
||||
// Set new cooldown (now + 24h)
|
||||
const nextReadyAt = new Date(now.getTime() + GameConfig.economy.daily.cooldownMs);
|
||||
|
||||
await txFn.insert(cooldowns)
|
||||
await txFn.insert(userTimers)
|
||||
.values({
|
||||
userId: BigInt(userId),
|
||||
actionKey: 'daily',
|
||||
readyAt: nextReadyAt,
|
||||
type: 'COOLDOWN',
|
||||
key: 'daily',
|
||||
expiresAt: nextReadyAt,
|
||||
})
|
||||
.onConflictDoUpdate({
|
||||
target: [cooldowns.userId, cooldowns.actionKey],
|
||||
set: { readyAt: nextReadyAt },
|
||||
target: [userTimers.userId, userTimers.type, userTimers.key],
|
||||
set: { expiresAt: nextReadyAt },
|
||||
});
|
||||
|
||||
// Log Transaction
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { users, cooldowns } from "@/db/schema";
|
||||
import { users, userTimers } from "@/db/schema";
|
||||
import { eq, sql, and } from "drizzle-orm";
|
||||
import { DrizzleClient } from "@/lib/DrizzleClient";
|
||||
import { GameConfig } from "@/config/game";
|
||||
@@ -58,15 +58,16 @@ export const levelingService = {
|
||||
processChatXp: async (id: string, tx?: any) => {
|
||||
const execute = async (txFn: any) => {
|
||||
// check if an xp cooldown is in place
|
||||
const cooldown = await txFn.query.cooldowns.findFirst({
|
||||
const cooldown = await txFn.query.userTimers.findFirst({
|
||||
where: and(
|
||||
eq(cooldowns.userId, BigInt(id)),
|
||||
eq(cooldowns.actionKey, 'xp')
|
||||
eq(userTimers.userId, BigInt(id)),
|
||||
eq(userTimers.type, 'COOLDOWN'),
|
||||
eq(userTimers.key, 'chat_xp')
|
||||
),
|
||||
});
|
||||
|
||||
const now = new Date();
|
||||
if (cooldown && cooldown.readyAt > now) {
|
||||
if (cooldown && cooldown.expiresAt > now) {
|
||||
return { awarded: false, reason: 'cooldown' };
|
||||
}
|
||||
|
||||
@@ -79,15 +80,16 @@ export const levelingService = {
|
||||
// Update/Set Cooldown
|
||||
const nextReadyAt = new Date(now.getTime() + GameConfig.leveling.chat.cooldownMs);
|
||||
|
||||
await txFn.insert(cooldowns)
|
||||
await txFn.insert(userTimers)
|
||||
.values({
|
||||
userId: BigInt(id),
|
||||
actionKey: 'xp',
|
||||
readyAt: nextReadyAt,
|
||||
type: 'COOLDOWN',
|
||||
key: 'chat_xp',
|
||||
expiresAt: nextReadyAt,
|
||||
})
|
||||
.onConflictDoUpdate({
|
||||
target: [cooldowns.userId, cooldowns.actionKey],
|
||||
set: { readyAt: nextReadyAt },
|
||||
target: [userTimers.userId, userTimers.type, userTimers.key],
|
||||
set: { expiresAt: nextReadyAt },
|
||||
});
|
||||
|
||||
return { awarded: true, amount, ...result };
|
||||
|
||||
59
src/modules/system/scheduler.ts
Normal file
59
src/modules/system/scheduler.ts
Normal file
@@ -0,0 +1,59 @@
|
||||
import { userTimers } from "@/db/schema";
|
||||
import { eq, and, lt } from "drizzle-orm";
|
||||
import { DrizzleClient } from "@/lib/DrizzleClient";
|
||||
|
||||
/**
|
||||
* The Janitor responsible for cleaning up expired ACCESS timers
|
||||
* and revoking privileges.
|
||||
*/
|
||||
export const schedulerService = {
|
||||
start: () => {
|
||||
console.log("🕒 Scheduler started: Janitor loop running every 60s");
|
||||
// Run immediately on start
|
||||
schedulerService.runJanitor();
|
||||
|
||||
// Loop every 60 seconds
|
||||
setInterval(() => {
|
||||
schedulerService.runJanitor();
|
||||
}, 60 * 1000);
|
||||
},
|
||||
|
||||
runJanitor: async () => {
|
||||
try {
|
||||
// Find all expired ACCESS timers
|
||||
// We do this in a transaction to ensure we read and delete atomically if possible,
|
||||
// though for this specific case, fetching then deleting is fine as long as we handle race conditions gracefully.
|
||||
|
||||
const now = new Date();
|
||||
|
||||
const expiredAccess = await DrizzleClient.query.userTimers.findMany({
|
||||
where: and(
|
||||
eq(userTimers.type, 'ACCESS'),
|
||||
lt(userTimers.expiresAt, now)
|
||||
)
|
||||
});
|
||||
|
||||
if (expiredAccess.length === 0) return;
|
||||
|
||||
console.log(`🧹 Janitor: Found ${expiredAccess.length} expired access timers.`);
|
||||
|
||||
for (const timer of expiredAccess) {
|
||||
// TODO: Here we would call Discord API to remove roles/overwrites.
|
||||
// e.g. discordClient.channels.cache.get(timer.metadata.channelId).permissionOverwrites.delete(timer.userId)
|
||||
|
||||
const meta = timer.metadata as any;
|
||||
console.log(`🚫 Revoking access for User ${timer.userId}: Key=${timer.key} (Channel: ${meta?.channelId || 'N/A'})`);
|
||||
|
||||
// Delete the timer row
|
||||
await DrizzleClient.delete(userTimers)
|
||||
.where(and(
|
||||
eq(userTimers.userId, timer.userId),
|
||||
eq(userTimers.type, timer.type),
|
||||
eq(userTimers.key, timer.key)
|
||||
));
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Janitor Error:", error);
|
||||
}
|
||||
}
|
||||
};
|
||||
96
src/modules/user/user.timers.ts
Normal file
96
src/modules/user/user.timers.ts
Normal file
@@ -0,0 +1,96 @@
|
||||
import { userTimers } from "@/db/schema";
|
||||
import { eq, and, lt } from "drizzle-orm";
|
||||
import { DrizzleClient } from "@/lib/DrizzleClient";
|
||||
|
||||
export type TimerType = 'COOLDOWN' | 'EFFECT' | 'ACCESS';
|
||||
|
||||
export const userTimerService = {
|
||||
/**
|
||||
* Set a timer for a user.
|
||||
* Upserts the timer (updates expiration if exists).
|
||||
*/
|
||||
setTimer: async (userId: string, type: TimerType, key: string, durationMs: number, metadata: any = {}, tx?: any) => {
|
||||
const execute = async (txFn: any) => {
|
||||
const expiresAt = new Date(Date.now() + durationMs);
|
||||
|
||||
await txFn.insert(userTimers)
|
||||
.values({
|
||||
userId: BigInt(userId),
|
||||
type,
|
||||
key,
|
||||
expiresAt,
|
||||
metadata,
|
||||
})
|
||||
.onConflictDoUpdate({
|
||||
target: [userTimers.userId, userTimers.type, userTimers.key],
|
||||
set: { expiresAt, metadata }, // Update metadata too on re-set
|
||||
});
|
||||
|
||||
return expiresAt;
|
||||
};
|
||||
|
||||
if (tx) {
|
||||
return await execute(tx);
|
||||
} else {
|
||||
return await DrizzleClient.transaction(async (t) => {
|
||||
return await execute(t);
|
||||
});
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Check if a timer is active (not expired).
|
||||
* Returns true if ACTIVE.
|
||||
*/
|
||||
checkTimer: async (userId: string, type: TimerType, key: string, tx?: any): Promise<boolean> => {
|
||||
const uniqueTx = tx || DrizzleClient; // Optimization: Read-only doesn't strictly need transaction wrapper overhead if single query
|
||||
|
||||
const timer = await uniqueTx.query.userTimers.findFirst({
|
||||
where: and(
|
||||
eq(userTimers.userId, BigInt(userId)),
|
||||
eq(userTimers.type, type),
|
||||
eq(userTimers.key, key)
|
||||
),
|
||||
});
|
||||
|
||||
if (!timer) return false;
|
||||
return timer.expiresAt > new Date();
|
||||
},
|
||||
|
||||
/**
|
||||
* Get timer details including metadata and expiry.
|
||||
*/
|
||||
getTimer: async (userId: string, type: TimerType, key: string, tx?: any) => {
|
||||
const uniqueTx = tx || DrizzleClient;
|
||||
|
||||
return await uniqueTx.query.userTimers.findFirst({
|
||||
where: and(
|
||||
eq(userTimers.userId, BigInt(userId)),
|
||||
eq(userTimers.type, type),
|
||||
eq(userTimers.key, key)
|
||||
),
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* Manually clear a timer.
|
||||
*/
|
||||
clearTimer: async (userId: string, type: TimerType, key: string, tx?: any) => {
|
||||
const execute = async (txFn: any) => {
|
||||
await txFn.delete(userTimers)
|
||||
.where(and(
|
||||
eq(userTimers.userId, BigInt(userId)),
|
||||
eq(userTimers.type, type),
|
||||
eq(userTimers.key, key)
|
||||
));
|
||||
};
|
||||
|
||||
if (tx) {
|
||||
return await execute(tx);
|
||||
} else {
|
||||
return await DrizzleClient.transaction(async (t) => {
|
||||
return await execute(t);
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
Reference in New Issue
Block a user