perf: batch recent play counts for gallery lists

This commit is contained in:
2026-05-12 10:59:51 +08:00
parent 612d105a23
commit 183e78d475
3 changed files with 213 additions and 26 deletions

View File

@@ -1,5 +1,5 @@
use crate::*;
use std::collections::HashSet;
use std::collections::{HashMap, HashSet};
#[spacetimedb::table(
accessor = custom_world_profile,
@@ -1549,11 +1549,26 @@ fn list_custom_world_gallery_snapshots(
) -> Result<Vec<CustomWorldGalleryEntrySnapshot>, String> {
sync_missing_custom_world_gallery_entries(ctx)?;
let mut entries = ctx
let entries = ctx
.db
.custom_world_gallery_entry()
.iter()
.map(|row| build_custom_world_gallery_entry_snapshot(ctx, &row))
.collect::<Vec<_>>();
let profile_ids = entries
.iter()
.map(|row| row.profile_id.clone())
.collect::<Vec<_>>();
let recent_play_counts = count_recent_public_work_plays_for_profiles(
ctx,
"custom-world",
&profile_ids,
ctx.timestamp.to_micros_since_unix_epoch(),
);
let mut entries = entries
.iter()
.map(|row| {
build_custom_world_gallery_entry_snapshot_with_recent_counts(row, &recent_play_counts)
})
.collect::<Vec<_>>();
entries.sort_by(|left, right| {
@@ -5078,6 +5093,19 @@ fn build_custom_world_draft_card_snapshot(
fn build_custom_world_gallery_entry_snapshot(
ctx: &ReducerContext,
row: &CustomWorldGalleryEntry,
) -> CustomWorldGalleryEntrySnapshot {
let recent_play_counts = count_recent_public_work_plays_for_profiles(
ctx,
"custom-world",
&[row.profile_id.clone()],
ctx.timestamp.to_micros_since_unix_epoch(),
);
build_custom_world_gallery_entry_snapshot_with_recent_counts(row, &recent_play_counts)
}
fn build_custom_world_gallery_entry_snapshot_with_recent_counts(
row: &CustomWorldGalleryEntry,
recent_play_counts: &HashMap<String, u32>,
) -> CustomWorldGalleryEntrySnapshot {
CustomWorldGalleryEntrySnapshot {
profile_id: row.profile_id.clone(),
@@ -5095,12 +5123,10 @@ fn build_custom_world_gallery_entry_snapshot(
play_count: row.play_count,
remix_count: row.remix_count,
like_count: row.like_count,
recent_play_count_7d: count_recent_public_work_plays(
ctx,
"custom-world",
&row.profile_id,
ctx.timestamp.to_micros_since_unix_epoch(),
),
recent_play_count_7d: recent_play_counts
.get(&row.profile_id)
.copied()
.unwrap_or(0),
published_at_micros: row.published_at.to_micros_since_unix_epoch(),
updated_at_micros: row.updated_at.to_micros_since_unix_epoch(),
}