update: use findSnapshotBefore instead of findClosetSnapshot in regular snapshot scheduling

This commit is contained in:
alikia2x (寒寒) 2025-03-26 22:59:52 +08:00
parent cabb360a16
commit b286a9d7b1
Signed by: alikia2x
GPG Key ID: 56209E0CCD8420C6
2 changed files with 27 additions and 1 deletions

View File

@ -114,6 +114,31 @@ export async function findClosestSnapshot(
}; };
} }
export async function findSnapshotBefore(
client: Client,
aid: number,
targetTime: Date,
): Promise<Snapshot | null> {
const query = `
SELECT created_at, views
FROM video_snapshot
WHERE aid = $1
AND created_at <= $2::timestamptz
ORDER BY created_at DESC
LIMIT 1
`;
const result = await client.queryObject<{ created_at: string; views: number }>(
query,
[aid, targetTime.toISOString()],
);
if (result.rows.length === 0) return null;
const row = result.rows[0];
return {
created_at: new Date(row.created_at).getTime(),
views: row.views,
};
}
export async function hasAtLeast2Snapshots(client: Client, aid: number) { export async function hasAtLeast2Snapshots(client: Client, aid: number) {
const res = await client.queryObject<{ count: number }>( const res = await client.queryObject<{ count: number }>(
`SELECT COUNT(*) FROM video_snapshot WHERE aid = $1`, `SELECT COUNT(*) FROM video_snapshot WHERE aid = $1`,

View File

@ -3,6 +3,7 @@ import { db } from "lib/db/init.ts";
import { getLatestVideoSnapshot, getVideosNearMilestone } from "lib/db/snapshot.ts"; import { getLatestVideoSnapshot, getVideosNearMilestone } from "lib/db/snapshot.ts";
import { import {
findClosestSnapshot, findClosestSnapshot,
findSnapshotBefore,
getLatestSnapshot, getLatestSnapshot,
getSnapshotsInNextSecond, getSnapshotsInNextSecond,
getVideosWithoutActiveSnapshotSchedule, getVideosWithoutActiveSnapshotSchedule,
@ -139,7 +140,7 @@ export const collectMilestoneSnapshotsWorker = async (_job: Job) => {
const getRegularSnapshotInterval = async (client: Client, aid: number) => { const getRegularSnapshotInterval = async (client: Client, aid: number) => {
const now = Date.now(); const now = Date.now();
const date = new Date(now - 24 * HOUR); const date = new Date(now - 24 * HOUR);
const oldSnapshot = await findClosestSnapshot(client, aid, date); const oldSnapshot = await findSnapshotBefore(client, aid, date);
const latestSnapshot = await getLatestSnapshot(client, aid); const latestSnapshot = await getLatestSnapshot(client, aid);
if (!oldSnapshot || !latestSnapshot) return 0; if (!oldSnapshot || !latestSnapshot) return 0;
if (oldSnapshot.created_at === latestSnapshot.created_at) return 0; if (oldSnapshot.created_at === latestSnapshot.created_at) return 0;