Track traffic by game month

This commit is contained in:
2026-07-27 11:32:48 +00:00
parent 9f402a3d67
commit 2b15410c5c
9 changed files with 595 additions and 146 deletions
+92 -61
View File
@@ -173,26 +173,6 @@ const readFiniteMetaNumber = (meta: Record<string, unknown>, key: string): numbe
return typeof value === 'number' && Number.isFinite(value) ? value : 0;
};
const parseTrafficHistory = (value: unknown): TrafficHistoryItem[] => {
if (!Array.isArray(value)) {
return [];
}
const result: TrafficHistoryItem[] = [];
for (const item of value) {
const row = asRecord(item);
const year = readFiniteMetaNumber(row, 'year');
const month = readFiniteMetaNumber(row, 'month');
const refresh = readFiniteMetaNumber(row, 'refresh');
const online = readFiniteMetaNumber(row, 'online');
const date = typeof row.date === 'string' ? row.date : '';
if (year > 0 && month > 0 && date) {
result.push({ year, month, refresh, online, date });
}
}
return result;
};
const compareString = (left: string, right: string): number => {
if (left === right) {
return 0;
@@ -298,69 +278,120 @@ export const publicRouter = router({
}
const meta = asRecord(worldState.meta);
const rawOnlineSince = meta.lastTurnTime ?? meta.turntime;
const parsedOnlineSince =
typeof rawOnlineSince === 'string' || rawOnlineSince instanceof Date
? new Date(rawOnlineSince)
: null;
const onlineSince =
parsedOnlineSince && Number.isFinite(parsedOnlineSince.getTime())
? parsedOnlineSince
: new Date(Date.now() - worldState.tickSeconds * 1_000);
const [accessTotal, currentOnline, topAccess] = await Promise.all([
ctx.db.generalAccessLog.aggregate({
_sum: {
refresh: true,
refreshScoreTotal: true,
},
}),
ctx.db.generalAccessLog.count({
const [currentPeriod, previousPeriods, periodMaximums, accessTotal] = await Promise.all([
ctx.db.trafficPeriod.findUnique({
where: {
lastRefresh: {
gte: onlineSince,
worldStateId_year_month: {
worldStateId: worldState.id,
year: worldState.currentYear,
month: worldState.currentMonth,
},
},
include: {
_count: {
select: { generals: true },
},
},
}),
ctx.db.generalAccessLog.findMany({
orderBy: [{ refresh: 'desc' }, { generalId: 'asc' }],
ctx.db.trafficPeriod.findMany({
where: {
worldStateId: worldState.id,
NOT: {
year: worldState.currentYear,
month: worldState.currentMonth,
},
},
orderBy: [{ startedAt: 'desc' }, { id: 'desc' }],
take: 5,
select: {
generalId: true,
include: {
_count: {
select: { generals: true },
},
},
}),
ctx.db.trafficPeriod.aggregate({
where: { worldStateId: worldState.id },
_max: {
refresh: true,
online: true,
},
}),
ctx.db.generalAccessLog.aggregate({
_sum: {
refreshScoreTotal: true,
},
}),
]);
const topAccess = currentPeriod
? await ctx.db.trafficPeriodGeneral.findMany({
where: { periodId: currentPeriod.id },
orderBy: [{ refresh: 'desc' }, { generalId: 'asc' }],
take: 5,
select: {
generalId: true,
refresh: true,
},
})
: [];
const generalIds = topAccess.map((entry) => entry.generalId);
const generalRows =
const [generalRows, generalAccessRows] =
generalIds.length > 0
? await ctx.db.general.findMany({
where: { id: { in: generalIds } },
select: { id: true, name: true },
})
: [];
? await Promise.all([
ctx.db.general.findMany({
where: { id: { in: generalIds } },
select: { id: true, name: true },
}),
ctx.db.generalAccessLog.findMany({
where: { generalId: { in: generalIds } },
select: { generalId: true, refreshScoreTotal: true },
}),
])
: [[], []];
const generalName = new Map(generalRows.map((general) => [general.id, general.name]));
const totalRefresh = accessTotal._sum.refresh ?? 0;
const accessScore = new Map(generalAccessRows.map((entry) => [entry.generalId, entry.refreshScoreTotal]));
const totalRefresh = currentPeriod?.refresh ?? 0;
const totalRefreshScore = accessTotal._sum.refreshScoreTotal ?? 0;
const currentRefresh = Math.max(readFiniteMetaNumber(meta, 'refresh'), totalRefresh);
const history = parseTrafficHistory(meta.recentTraffic);
history.push({
year: worldState.currentYear,
month: worldState.currentMonth,
refresh: currentRefresh,
online: currentOnline,
date: new Date().toISOString(),
});
const currentOnline = currentPeriod ? Math.max(currentPeriod.online, currentPeriod._count.generals) : 0;
const history: TrafficHistoryItem[] = previousPeriods.reverse().map((period) => ({
year: period.year,
month: period.month,
refresh: period.refresh,
online: Math.max(period.online, period._count.generals),
date: period.lastRefresh.toISOString(),
}));
history.push(
currentPeriod
? {
year: currentPeriod.year,
month: currentPeriod.month,
refresh: currentPeriod.refresh,
online: currentOnline,
date: currentPeriod.lastRefresh.toISOString(),
}
: {
year: worldState.currentYear,
month: worldState.currentMonth,
refresh: 0,
online: 0,
date: new Date().toISOString(),
}
);
return {
history,
maxRefresh: Math.max(
1,
readFiniteMetaNumber(meta, 'maxrefresh'),
periodMaximums._max.refresh ?? 0,
...history.map((entry) => entry.refresh)
),
maxOnline: Math.max(1, readFiniteMetaNumber(meta, 'maxonline'), ...history.map((entry) => entry.online)),
maxOnline: Math.max(
1,
readFiniteMetaNumber(meta, 'maxonline'),
periodMaximums._max.online ?? 0,
...history.map((entry) => entry.online)
),
suspects: [
{
generalId: null,
@@ -372,7 +403,7 @@ export const publicRouter = router({
generalId: entry.generalId,
name: generalName.get(entry.generalId) ?? `장수 ${entry.generalId}`,
refresh: entry.refresh,
refreshScoreTotal: entry.refreshScoreTotal,
refreshScoreTotal: accessScore.get(entry.generalId) ?? 0,
})),
],
};
+136 -48
View File
@@ -76,8 +76,7 @@ export const resolveAccessWindows = (
now: Date,
tickSeconds: number,
worldMeta: unknown
): { dayStartedAt: Date; scoreStartedAt: Date } => {
const dayStartedAt = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()));
): { periodStartedAt: Date; scoreStartedAt: Date } => {
const meta = asRecord(worldMeta);
const tickStartedAt = readDate(meta.lastTurnTime) ?? readDate(meta.turntime);
const fallbackTickMs = Math.max(1, Math.floor(tickSeconds)) * 1_000;
@@ -85,60 +84,140 @@ export const resolveAccessWindows = (
tickStartedAt && tickStartedAt.getTime() <= now.getTime()
? tickStartedAt
: new Date(now.getTime() - fallbackTickMs);
return { dayStartedAt, scoreStartedAt };
return { periodStartedAt: scoreStartedAt, scoreStartedAt };
};
export const upsertGeneralAccess = async (
db: Pick<GameApiContext['db'], '$executeRaw'>,
db: Pick<GameApiContext['db'], '$transaction'>,
input: {
worldStateId: number;
year: number;
month: number;
generalId: number;
userId: string;
weight: number;
now: Date;
dayStartedAt: Date;
periodStartedAt: Date;
scoreStartedAt: Date;
}
): Promise<void> => {
await db.$executeRaw(
GamePrisma.sql`
INSERT INTO general_access_log (
general_id,
user_id,
last_refresh,
refresh,
refresh_total,
refresh_score,
refresh_score_total
)
VALUES (
${input.generalId},
${input.userId},
${input.now},
${input.weight},
${input.weight},
${input.weight},
${input.weight}
)
ON CONFLICT (general_id) DO UPDATE SET
user_id = EXCLUDED.user_id,
last_refresh = EXCLUDED.last_refresh,
refresh = CASE
WHEN general_access_log.last_refresh IS NULL
OR general_access_log.last_refresh < ${input.dayStartedAt}
THEN EXCLUDED.refresh
ELSE general_access_log.refresh + EXCLUDED.refresh
END,
refresh_total = general_access_log.refresh_total + EXCLUDED.refresh_total,
refresh_score = CASE
WHEN general_access_log.last_refresh IS NULL
OR general_access_log.last_refresh < ${input.scoreStartedAt}
THEN EXCLUDED.refresh_score
ELSE general_access_log.refresh_score + EXCLUDED.refresh_score
END,
refresh_score_total =
general_access_log.refresh_score_total + EXCLUDED.refresh_score_total
`
);
if (!db.$transaction) {
throw new Error('Traffic access persistence requires transaction support.');
}
await db.$transaction(async (transaction) => {
const periodRows = await transaction.$queryRaw<Array<{ id: number }>>(
GamePrisma.sql`
INSERT INTO traffic_period (
world_state_id,
year,
month,
started_at,
last_refresh,
refresh
)
VALUES (
${input.worldStateId},
${input.year},
${input.month},
${input.periodStartedAt},
${input.now},
${input.weight}
)
ON CONFLICT (world_state_id, year, month) DO UPDATE SET
started_at = LEAST(traffic_period.started_at, EXCLUDED.started_at),
last_refresh = GREATEST(traffic_period.last_refresh, EXCLUDED.last_refresh),
refresh = traffic_period.refresh + EXCLUDED.refresh
RETURNING id
`
);
const periodId = periodRows[0]?.id;
if (periodId === undefined) {
throw new Error('Failed to resolve the traffic period.');
}
await transaction.$executeRaw(
GamePrisma.sql`
WITH inserted_general AS (
INSERT INTO traffic_period_general (
period_id,
general_id,
user_id,
refresh,
last_refresh
)
VALUES (
${periodId},
${input.generalId},
${input.userId},
${input.weight},
${input.now}
)
ON CONFLICT (period_id, general_id) DO NOTHING
RETURNING period_id
),
updated_general AS (
UPDATE traffic_period_general
SET
user_id = ${input.userId},
refresh = traffic_period_general.refresh + ${input.weight},
last_refresh = GREATEST(
traffic_period_general.last_refresh,
${input.now}
)
WHERE period_id = ${periodId}
AND general_id = ${input.generalId}
AND NOT EXISTS (SELECT 1 FROM inserted_general)
RETURNING period_id
)
UPDATE traffic_period
SET online = traffic_period.online + (
SELECT COUNT(*)::INTEGER FROM inserted_general
)
WHERE id = ${periodId}
`
);
await transaction.$executeRaw(
GamePrisma.sql`
INSERT INTO general_access_log (
general_id,
user_id,
last_refresh,
refresh,
refresh_total,
refresh_score,
refresh_score_total
)
VALUES (
${input.generalId},
${input.userId},
${input.now},
${input.weight},
${input.weight},
${input.weight},
${input.weight}
)
ON CONFLICT (general_id) DO UPDATE SET
user_id = EXCLUDED.user_id,
last_refresh = EXCLUDED.last_refresh,
refresh = CASE
WHEN general_access_log.last_refresh IS NULL
OR general_access_log.last_refresh < ${input.periodStartedAt}
THEN EXCLUDED.refresh
ELSE general_access_log.refresh + EXCLUDED.refresh
END,
refresh_total = general_access_log.refresh_total + EXCLUDED.refresh_total,
refresh_score = CASE
WHEN general_access_log.last_refresh IS NULL
OR general_access_log.last_refresh < ${input.scoreStartedAt}
THEN EXCLUDED.refresh_score
ELSE general_access_log.refresh_score + EXCLUDED.refresh_score
END,
refresh_score_total =
general_access_log.refresh_score_total + EXCLUDED.refresh_score_total
`
);
});
};
export const recordGeneralAccess = async (
@@ -159,7 +238,13 @@ export const recordGeneralAccess = async (
}),
ctx.db.worldState.findFirst({
orderBy: { id: 'asc' },
select: { tickSeconds: true, meta: true },
select: {
id: true,
currentYear: true,
currentMonth: true,
tickSeconds: true,
meta: true,
},
}),
]);
if (!general || !worldState) {
@@ -174,14 +259,17 @@ export const recordGeneralAccess = async (
}
const weight = accessPageWeights[page];
const { dayStartedAt, scoreStartedAt } = resolveAccessWindows(now, worldState.tickSeconds, meta);
const { periodStartedAt, scoreStartedAt } = resolveAccessWindows(now, worldState.tickSeconds, meta);
await upsertGeneralAccess(ctx.db, {
worldStateId: worldState.id,
year: worldState.currentYear,
month: worldState.currentMonth,
generalId: general.id,
userId: user.id,
weight,
now,
dayStartedAt,
periodStartedAt,
scoreStartedAt,
});
return true;