feat: 优化接口速度

This commit is contained in:
2026-04-24 22:02:53 +08:00
parent fd20a4411b
commit d1c5b818d9
5 changed files with 148 additions and 60 deletions
+41 -26
View File
@@ -2,6 +2,7 @@ import { NextRequest, NextResponse } from 'next/server'
import { win32 } from 'path'
import { prisma } from '@/lib/prisma'
import { withCors } from '@/lib/middleware'
import { Prisma } from '@prisma/client'
const MAX_GAP_MS = 5 * 60 * 1000
const DEFAULT_SAMPLE_MS = 30 * 1000
@@ -36,6 +37,12 @@ interface HourBucket {
appDurations: Map<string, number>
}
interface ScreenTimeRecordRow {
timestamp: Date
title: string | null
path: string | null
}
const cleanTitle = (title: string) => title.replace(/\s+/g, ' ').trim()
const trimLabelSeparators = (label: string) => label
@@ -304,27 +311,36 @@ async function handleScreenTime(req: NextRequest) {
const aggregateEndMs = unit === 'week' ? weekEndMs : selectedDayEndMs
const aggregateEndDate = addDays(aggregateStartDate, unit === 'week' ? 7 : 1)
const records = await prisma.record.findMany({
where: {
hostname,
timestamp: {
gte: new Date(weekStartMs - MAX_GAP_MS),
lte: new Date(weekEndMs + MAX_GAP_MS)
}
},
select: {
timestamp: true,
windows: {
select: {
title: true,
path: true
}
}
},
orderBy: {
timestamp: 'asc'
}
})
const rangeStart = new Date(weekStartMs - MAX_GAP_MS)
const rangeEnd = new Date(weekEndMs + MAX_GAP_MS)
const records = await prisma.$queryRaw<ScreenTimeRecordRow[]>(Prisma.sql`
WITH scoped_records AS (
SELECT "id", "timestamp"
FROM "records"
WHERE "hostname" = ${hostname}
AND "timestamp" >= ${rangeStart}
AND "timestamp" <= ${rangeEnd}
),
ranked_windows AS (
SELECT
w."recordId",
w."title",
w."path",
ROW_NUMBER() OVER (PARTITION BY w."recordId" ORDER BY w."id") AS row_number
FROM "windows" w
INNER JOIN scoped_records r ON r."id" = w."recordId"
)
SELECT
r."timestamp",
w."title",
w."path"
FROM scoped_records r
LEFT JOIN ranked_windows w
ON w."recordId" = r."id"
AND w.row_number = 1
ORDER BY r."timestamp" ASC
`)
const validDiffs = records
.slice(0, -1)
@@ -346,8 +362,7 @@ async function handleScreenTime(req: NextRequest) {
}))
records.forEach((record, index) => {
const activeWindow = record.windows[0]
if (!activeWindow) return
if (record.title === null && record.path === null) return
const currentMs = record.timestamp.getTime()
const nextMs = records[index + 1]?.timestamp.getTime()
@@ -359,10 +374,10 @@ async function handleScreenTime(req: NextRequest) {
const intervalStartMs = currentMs
const intervalEndMs = currentMs + intervalMs
const title = cleanTitle(activeWindow.title)
|| stripExtension(win32.basename(activeWindow.path || ''))
const title = cleanTitle(record.title ?? '')
|| stripExtension(win32.basename(record.path ?? ''))
|| '未知窗口'
const process = normalizeProcess(activeWindow.path, title)
const process = normalizeProcess(record.path ?? '', title)
const aggregateContributionMs = Math.max(0, Math.min(intervalEndMs, aggregateEndMs) - Math.max(intervalStartMs, aggregateStartMs))
addDurationToUsageMap(