From d5c278ae066ba260f629d958d07685a888437823 Mon Sep 17 00:00:00 2001 From: alikia2x Date: Thu, 27 Mar 2025 01:48:10 +0800 Subject: [PATCH] improve: cache result for adjustSnapshotTime --- lib/db/snapshotSchedule.ts | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/lib/db/snapshotSchedule.ts b/lib/db/snapshotSchedule.ts index 9e8a893..1aa2d06 100644 --- a/lib/db/snapshotSchedule.ts +++ b/lib/db/snapshotSchedule.ts @@ -9,6 +9,7 @@ import { Redis } from "ioredis"; const WINDOW_SIZE = 2880; const REDIS_KEY = "cvsa:snapshot_window_counts"; +let lastAvailableWindow: { offset: number; count: number } | null = null; function getCurrentWindowIndex(): number { const now = new Date(); @@ -43,6 +44,8 @@ export async function refreshSnapshotWindowCounts(client: Client, redisClient: R await redisClient.hset(REDIS_KEY, offset.toString(), Number(row.count)); } } + + lastAvailableWindow = null; } export async function initSnapshotWindowCounts(client: Client, redisClient: Redis) { @@ -57,10 +60,6 @@ async function getWindowCount(redisClient: Redis, offset: number): Promise { - await redisClient.hincrby(REDIS_KEY, offset.toString(), increment); -} - export async function snapshotScheduleExists(client: Client, id: number) { const res = await client.queryObject<{ id: number }>( `SELECT id FROM snapshot_schedule WHERE id = $1`, @@ -203,17 +202,23 @@ export async function adjustSnapshotTime( redisClient: Redis, ): Promise { const currentWindow = getCurrentWindowIndex(); - const targetOffset = Math.floor((expectedStartTime.getTime() - Date.now()) / (5 * MINUTE)); + let initialOffset = 0; + + if (lastAvailableWindow && lastAvailableWindow.count < allowedCounts) { + initialOffset = lastAvailableWindow.offset; + } + let timePerIteration = 0; const t = performance.now(); - for (let i = 0; i < WINDOW_SIZE; i++) { + for (let i = initialOffset; i < WINDOW_SIZE; i++) { const offset = (currentWindow + targetOffset + i) % WINDOW_SIZE; const count = await getWindowCount(redisClient, offset); if (count < allowedCounts) { - await updateWindowCount(redisClient, offset, 1); + const newCount = await redisClient.hincrby(REDIS_KEY, offset.toString(), 1); + lastAvailableWindow = { offset, count: newCount }; const startPoint = new Date(); startPoint.setHours(0, 0, 0, 0);