FPI 사용자·국가 랭킹 서버 집계 · YouTube 스밍 · Music Shake 참여
This commit is contained in:
@@ -13,7 +13,7 @@ import { rankWithTies } from '../ledger/fpi.js';
|
||||
import { txIdOf } from '../core/ids.js';
|
||||
import { dayKey } from '../core/time.js';
|
||||
import { notifyEclipseWarning } from '../notify/push.js';
|
||||
import { publicNameOf } from '../core/names.js';
|
||||
import { PUBLIC_NAME_FALLBACK, publicNameOf } from '../core/names.js';
|
||||
|
||||
/**
|
||||
* 티커 이벤트 보존 창.
|
||||
@@ -885,39 +885,101 @@ export async function closeDay(now: Date = new Date()): Promise<{ day: string; f
|
||||
}
|
||||
|
||||
/**
|
||||
* `fn-ranking-country` — 국가별 지표 랭킹 사전 집계(설계서 §10).
|
||||
* `fn-ranking-country` — **사용자 지표 랭킹 + 국가별 지표 랭킹** 사전 집계 · 5 분 주기(설계서 §2.6 · §4.4).
|
||||
*
|
||||
* 랭킹 화면은 `rankings/{rankingId}` 문서 1건만 읽는다. 축마다 문서를 따로 두어
|
||||
* 축을 바꾸면 다른 문서를 읽게 한다 — 한 문서에 다섯 축을 담으면 화면이 어느 축을
|
||||
* 그리는지 다시 분기해야 하고, 그 분기가 「지표를 바꿔도 같은 Ranking」의 자리다.
|
||||
* 1 분 FPI 집계(`fnFpiAggregate`)는 행성 단위만 적는다. 멤버 단위 값은 멤버 전수를 훑어야
|
||||
* 해서 국가 집계와 같은 5 분 배치에서 한 번에 낸다(설계서 §2.6 「멤버 전수 스캔이라 5 분」).
|
||||
*
|
||||
* 국가는 멤버 문서에 비정규화된 `countryCode`(사용자 프로필 기준)이며, 없으면
|
||||
* `ZZ`(미지정) 버킷으로 모은다.
|
||||
* 1. **멤버별 축 값** — 행성 FPI 와 같은 원천(최근 `fpiWindowDays` 일 · verified `fpiEvents`)을
|
||||
* `uid` 별로 합산해 `members/{uid}.fpiAxes` 에 적는다. Eclipse 차감은 행성 총점만 깎으므로
|
||||
* 개인 값에 넣지 않는다.
|
||||
* 2. **멤버 축별 순위** `rankByAxis` (C-19 1·1·3, 동점 내부 uid 오름차순) · 직전 순위
|
||||
* `rankPrevByAxis` (= 직전 배치의 `rankByAxis`, 행성 `fpiRanksPrev` 와 같은 정의) ·
|
||||
* 「내 상위 %」 `topPercentByAxis` = ⌈순위 ÷ 멤버 수 × 100⌉ — 그 축 기여가 0 이면 적지 않는다
|
||||
* (「상위 100%」는 최하위라는 사실 주장이 된다).
|
||||
* 3. **국가 합** — 위 멤버 값을 사용자 프로필 `users/{uid}.countryCode` 로 묶는다(없으면 `ZZ`).
|
||||
* 멤버 문서에도 `countryCode` · 공개 닉네임(`nickname`, M-7)을 비정규화해 앱이 「내 국가」 행과
|
||||
* 사용자 랭킹 이름을 멤버 문서 한 건으로 그리게 한다.
|
||||
*
|
||||
* 모집단은 행성 랭킹과 같다 — 별첨 B 「정식 행성 중 최근 7 일 유효 활동 존재 행성」.
|
||||
* 여기만 전수로 세면 국가 합이 행성 랭킹의 합보다 커져 두 화면이 어긋난다.
|
||||
* 모집단은 행성 랭킹과 같다 — 별첨 B 「정식 행성 중 최근 7 일 유효 활동 존재 행성」(B-17,
|
||||
* `rankingEligible`). 모집단에서 빠진 행성은 멤버 랭킹 필드를 지워 지난 순위가 남지 않게 한다.
|
||||
* 바뀐 멤버 문서만 쓴다.
|
||||
*
|
||||
* ponytail: 대상 행성의 멤버 전수 스캔이다. 멤버가 늘면 실행 시간을 넘으므로
|
||||
* 9주차 부하 설계에서 국가 카운터 샤드로 옮긴다. 지금은 화면이 실데이터로 도는
|
||||
* 것이 우선이다.
|
||||
* ponytail: 대상 행성의 멤버 · 7 일 이벤트 전수 스캔이다. 멤버가 늘어 실행 시간을 넘으면
|
||||
* 행성별 샤드 배치(Cloud Tasks)로 쪼갠다.
|
||||
*/
|
||||
export const fnRankingCountryAggregate = onSchedule('every 5 minutes', async () => {
|
||||
export const fnRankingCountryAggregate = onSchedule(
|
||||
{ schedule: 'every 5 minutes', timeoutSeconds: 280 },
|
||||
async () => { await aggregateRankings(); },
|
||||
);
|
||||
|
||||
const MEMBER_RANK_FIELDS = ['fpiAxes', 'rankByAxis', 'rankPrevByAxis', 'topPercentByAxis'] as const;
|
||||
|
||||
export async function aggregateRankings(now = Date.now()): Promise<{ fandoms: number; members: number; countries: number }> {
|
||||
const db = getFirestore();
|
||||
const eligible = await db.collection('fandoms')
|
||||
.where('rankingEligible', '==', true).select().get();
|
||||
const members = (await Promise.all(
|
||||
eligible.docs.map((f) => f.ref.collection('members').get()),
|
||||
)).flatMap((snap) => snap.docs);
|
||||
const policy = await loadPolicy();
|
||||
const since = Timestamp.fromMillis(now - policy.fpiWindowDays * 24 * 60 * 60 * 1000);
|
||||
const [eligible, ranked] = await Promise.all([
|
||||
db.collection('fandoms').where('rankingEligible', '==', true).select().get(),
|
||||
db.collection('fandoms').where('memberRanked', '==', true).select('rankingEligible').get(),
|
||||
]);
|
||||
const writer = db.bulkWriter();
|
||||
|
||||
// 모집단에서 빠진 행성 — 지난 순위를 지운다. 남겨 두면 활동 없는 행성에 옛 순위 · 상위 % 가 뜬다.
|
||||
for (const fandom of ranked.docs) {
|
||||
if (fandom.get('rankingEligible') === true) continue;
|
||||
const members = await fandom.ref.collection('members').select(...MEMBER_RANK_FIELDS).get();
|
||||
for (const m of members.docs) {
|
||||
if (MEMBER_RANK_FIELDS.some((f) => m.get(f) !== undefined)) {
|
||||
void writer.update(m.ref, Object.fromEntries(MEMBER_RANK_FIELDS.map((f) => [f, FieldValue.delete()])));
|
||||
}
|
||||
}
|
||||
void writer.update(fandom.ref, { memberRanked: false });
|
||||
}
|
||||
|
||||
const totals = new Map<string, Record<FpiAxis, number>>();
|
||||
for (const member of members) {
|
||||
const code = (member.get('countryCode') as string | undefined) || 'ZZ';
|
||||
const axes = (member.get('fpiAxes') as Record<FpiAxis, number> | undefined) ?? {} as Record<FpiAxis, number>;
|
||||
const bucket = totals.get(code)
|
||||
?? Object.fromEntries(FPI_AXES.map((a) => [a, 0])) as Record<FpiAxis, number>;
|
||||
for (const axis of FPI_AXES) bucket[axis] += axes[axis] ?? 0;
|
||||
totals.set(code, bucket);
|
||||
let memberTotal = 0;
|
||||
for (const fandom of eligible.docs) {
|
||||
const [members, events] = await Promise.all([
|
||||
fandom.ref.collection('members').get(),
|
||||
fandom.ref.collection('fpiEvents').where('verified', '==', true).where('occurredAt', '>=', since).get(),
|
||||
]);
|
||||
const values = new Map<string, Record<FpiAxis, number>>(
|
||||
members.docs.map((m) => [m.id, zeroAxes()]));
|
||||
for (const ev of events.docs) {
|
||||
const bucket = values.get(ev.get('uid') as string);
|
||||
const axis = ev.get('axis') as FpiAxis;
|
||||
const value = ev.get('value');
|
||||
// 차감 이벤트(uid · axis 없음)와 탈퇴한 사용자의 이벤트는 개인 값에 넣지 않는다.
|
||||
if (bucket && axis in bucket && typeof value === 'number' && Number.isFinite(value)) bucket[axis] += value;
|
||||
}
|
||||
const patches = memberRankPatches(values);
|
||||
const profiles = await profilesOf(members.docs.map((m) => m.id));
|
||||
for (const member of members.docs) {
|
||||
const patch = patches.get(member.id)!;
|
||||
const profile = profiles.get(member.id);
|
||||
const code = profile?.countryCode ?? 'ZZ';
|
||||
const next = {
|
||||
fpiAxes: patch.fpiAxes,
|
||||
rankByAxis: patch.rankByAxis,
|
||||
// 직전 순위 = 직전 배치의 순위. 첫 배치는 현재 순위(변동 0)로 둔다.
|
||||
rankPrevByAxis: (member.get('rankByAxis') as Record<string, number> | undefined) ?? patch.rankByAxis,
|
||||
topPercentByAxis: patch.topPercentByAxis,
|
||||
countryCode: code,
|
||||
// 사용자 랭킹의 이름 칸 — 공개 닉네임만(M-7). 프로필이 없으면 「팬」.
|
||||
nickname: profile?.nickname ?? PUBLIC_NAME_FALLBACK,
|
||||
};
|
||||
if (Object.entries(next).some(([k, v]) => stable(member.get(k)) !== stable(v))) {
|
||||
void writer.update(member.ref, next);
|
||||
}
|
||||
const total = totals.get(code) ?? zeroAxes();
|
||||
for (const axis of FPI_AXES) total[axis] += patch.fpiAxes[axis];
|
||||
totals.set(code, total);
|
||||
}
|
||||
void writer.update(fandom.ref, { memberRanked: true });
|
||||
memberTotal += members.size;
|
||||
}
|
||||
await writer.close();
|
||||
|
||||
for (const axis of FPI_AXES) {
|
||||
const doc = db.doc(`rankings/country-${axis}`);
|
||||
@@ -938,10 +1000,63 @@ export const fnRankingCountryAggregate = onSchedule('every 5 minutes', async ()
|
||||
}));
|
||||
await doc.set({ axis, rows, updatedAt: FieldValue.serverTimestamp() });
|
||||
}
|
||||
logger.info('[ranking] 국가 집계 완료', {
|
||||
countries: totals.size, fandoms: eligible.size, members: members.length,
|
||||
});
|
||||
});
|
||||
const result = { fandoms: eligible.size, members: memberTotal, countries: totals.size };
|
||||
logger.info('[ranking] 사용자 · 국가 집계 완료', result);
|
||||
return result;
|
||||
}
|
||||
|
||||
/** 키 순서와 무관한 비교용 직렬화 — Firestore 가 돌려주는 맵의 키 순서는 쓴 순서와 다를 수 있다. */
|
||||
function stable(value: unknown): string {
|
||||
return JSON.stringify(value, (_, v: unknown) => v && typeof v === 'object' && !Array.isArray(v)
|
||||
? Object.fromEntries(Object.entries(v).sort(([a], [b]) => (a < b ? -1 : 1))) : v) ?? 'undefined';
|
||||
}
|
||||
|
||||
function zeroAxes(): Record<FpiAxis, number> {
|
||||
return Object.fromEntries(FPI_AXES.map((a) => [a, 0])) as Record<FpiAxis, number>;
|
||||
}
|
||||
|
||||
/** 사용자 프로필의 국가 코드 · 공개 닉네임. 한 번에 읽는 수는 300건씩 자른다. */
|
||||
async function profilesOf(uids: string[]): Promise<Map<string, { countryCode: string | undefined; nickname: string }>> {
|
||||
const db = getFirestore();
|
||||
const out = new Map<string, { countryCode: string | undefined; nickname: string }>();
|
||||
for (let i = 0; i < uids.length; i += 300) {
|
||||
const refs = uids.slice(i, i + 300).map((uid) => db.doc(`users/${uid}`));
|
||||
if (refs.length === 0) continue;
|
||||
for (const snap of await db.getAll(...refs, { fieldMask: ['countryCode', 'nickname'] })) {
|
||||
if (!snap.exists) continue;
|
||||
const code = snap.get('countryCode');
|
||||
out.set(snap.id, {
|
||||
countryCode: typeof code === 'string' && /^[A-Z]{2}$/.test(code) ? code : undefined,
|
||||
nickname: publicNameOf(snap),
|
||||
});
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* 한 행성 멤버의 축별 순위 · 「내 상위 %」(순수 계산). 순위는 C-19 공동 순위 — 실값 내림차순,
|
||||
* 동점은 같은 순위, 동점 내부는 uid 오름차순. 상위 % 는 ⌈순위 ÷ 멤버 수 × 100⌉(최소 1),
|
||||
* 그 축 값이 0 이면 비운다.
|
||||
*/
|
||||
export function memberRankPatches(values: ReadonlyMap<string, Record<FpiAxis, number>>): Map<string, {
|
||||
fpiAxes: Record<FpiAxis, number>;
|
||||
rankByAxis: Partial<Record<FpiAxis, number>>;
|
||||
topPercentByAxis: Partial<Record<FpiAxis, number>>;
|
||||
}> {
|
||||
const out = new Map([...values].map(([uid, fpiAxes]) => [uid, {
|
||||
fpiAxes, rankByAxis: {} as Partial<Record<FpiAxis, number>>, topPercentByAxis: {} as Partial<Record<FpiAxis, number>>,
|
||||
}]));
|
||||
const n = values.size;
|
||||
for (const axis of FPI_AXES) {
|
||||
for (const { item: [uid, axes], rank } of rankWithTies([...values], ([, a]) => a[axis], ([uid]) => uid)) {
|
||||
const row = out.get(uid)!;
|
||||
row.rankByAxis[axis] = rank;
|
||||
if (axes[axis] > 0) row.topPercentByAxis[axis] = Math.max(1, Math.ceil(rank / n * 100));
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* `fn-campaign-fund` — 캠페인 후원.
|
||||
|
||||
Reference in New Issue
Block a user