feat(diashow): guarantee all eligible photos shown + 2048px display derivative
Diashow completeness rewrite so every eligible upload is shown regardless of
bursts, disconnects, or library size:
- queue.ts: SlideQueue with live/shuffle queues, allKnown map, recentlyShown
ring; merge(dedup, live-first), remove/removeByUser (prunes recentlyShown),
knownIds for reconcile-eviction. Adds queue.test.ts (burst/completeness/race).
- diashow/+page.svelte: reconcile (full paginate + evict, pre-scan snapshot to
spare concurrent uploads) on mount/reconnect/periodic; catchUpNew paginate-
until-known for bursts with debounced maxWait; hard-cut removals; decode
timeout + candidate fallback + bounded skip so a broken image never stalls.
New ~2048px "display" derivative for big-screen sharpness, decoupled from the
data-saver preview (800px) used on phones:
- migration 016: upload.display_path + v_feed rebuilt (DROP+CREATE, not REPLACE,
to slot the column beside preview/thumbnail).
- compression: generate_image_derivatives emits preview+display (downscale-only
guard, no upscaling); backfill_missing_display regenerates on startup (safe:
logs on error, never soft-deletes).
- upload.rs/main.rs: GET /upload/{id}/display (mirrors preview auth/cache),
/media/displays direct-serve blocked.
- feed.rs + types.ts: display_url in feed/delta DTOs.
- diashow candidate chain: display -> original -> preview.
Verified on the running stack: migration applied, 10/10 existing images
backfilled (2048px cap honoured, small images not upscaled), /display serves
200, /feed returns display_url, diashow cycles.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
141
frontend/src/lib/diashow/queue.test.ts
Normal file
141
frontend/src/lib/diashow/queue.test.ts
Normal file
@@ -0,0 +1,141 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { SlideQueue } from './queue';
|
||||
import type { FeedUpload } from '$lib/types';
|
||||
|
||||
// Minimal FeedUpload factory — the queue only reads id, user_id, preview_url, thumbnail_url.
|
||||
const up = (
|
||||
id: string,
|
||||
opts: { user?: string; preview?: boolean; thumb?: boolean } = {}
|
||||
): FeedUpload =>
|
||||
({
|
||||
id,
|
||||
user_id: opts.user ?? 'u1',
|
||||
preview_url: opts.preview === false ? null : `/p/${id}`,
|
||||
thumbnail_url: opts.thumb ? `/t/${id}` : null
|
||||
}) as unknown as FeedUpload;
|
||||
|
||||
const drain = (q: SlideQueue, n: number): string[] => {
|
||||
const out: string[] = [];
|
||||
for (let i = 0; i < n; i++) {
|
||||
const s = q.next();
|
||||
if (!s) break;
|
||||
out.push(s.id);
|
||||
}
|
||||
return out;
|
||||
};
|
||||
|
||||
describe('SlideQueue.merge', () => {
|
||||
it('dedups by id and reports the count actually added', () => {
|
||||
const q = new SlideQueue();
|
||||
expect(q.merge([up('a'), up('b')], { live: false })).toBe(2);
|
||||
expect(q.merge([up('b'), up('c')], { live: false })).toBe(1); // b already known
|
||||
expect(q.stats().known).toBe(3);
|
||||
});
|
||||
|
||||
it('skips uploads with no preview or thumbnail (still compressing)', () => {
|
||||
const q = new SlideQueue();
|
||||
const added = q.merge([up('a'), up('pending', { preview: false }), up('t', { thumb: true })], {
|
||||
live: false
|
||||
});
|
||||
expect(added).toBe(2); // a + t; pending has neither preview nor thumb
|
||||
expect(q.has('pending')).toBe(false);
|
||||
});
|
||||
|
||||
it('live items drain before the shuffle pool', () => {
|
||||
const q = new SlideQueue();
|
||||
q.merge([up('s1'), up('s2')], { live: false });
|
||||
q.merge([up('L1'), up('L2')], { live: true });
|
||||
// Live first, in FIFO order, then the pool.
|
||||
expect(drain(q, 2)).toEqual(['L1', 'L2']);
|
||||
expect(drain(q, 2).sort()).toEqual(['s1', 's2']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('SlideQueue completeness', () => {
|
||||
it('eventually shows every merged item across one full cycle (500 items, paged)', () => {
|
||||
const q = new SlideQueue();
|
||||
const all = new Set<string>();
|
||||
// Simulate a paginated load of 500 across 5 pages of 100.
|
||||
for (let page = 0; page < 5; page++) {
|
||||
const batch = Array.from({ length: 100 }, (_, i) => {
|
||||
const id = `img-${page * 100 + i}`;
|
||||
all.add(id);
|
||||
return up(id);
|
||||
});
|
||||
q.merge(batch, { live: false });
|
||||
}
|
||||
q.reshuffle();
|
||||
expect(q.stats().known).toBe(500);
|
||||
|
||||
// Drain generously more than the set size; every id must appear at least once.
|
||||
const shown = new Set(drain(q, 500 + 50));
|
||||
for (const id of all) expect(shown.has(id)).toBe(true);
|
||||
});
|
||||
|
||||
it('a burst of live items are all shown before falling back to the pool', () => {
|
||||
const q = new SlideQueue();
|
||||
q.merge([up('old1'), up('old2')], { live: false });
|
||||
const burst = Array.from({ length: 250 }, (_, i) => up(`burst-${i}`));
|
||||
q.merge(burst, { live: true });
|
||||
const firstBurst = drain(q, 250);
|
||||
expect(new Set(firstBurst).size).toBe(250);
|
||||
expect(firstBurst.every((id) => id.startsWith('burst-'))).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('SlideQueue removals', () => {
|
||||
it('remove() reports whether the removed id was current', () => {
|
||||
const q = new SlideQueue();
|
||||
q.merge([up('a'), up('b')], { live: false });
|
||||
expect(q.remove('a', 'a').wasCurrent).toBe(true);
|
||||
expect(q.remove('b', 'a').wasCurrent).toBe(false);
|
||||
expect(q.stats().known).toBe(0);
|
||||
});
|
||||
|
||||
it('removeByUser() evicts a whole user and flags current', () => {
|
||||
const q = new SlideQueue();
|
||||
q.merge([up('a', { user: 'x' }), up('b', { user: 'y' }), up('c', { user: 'x' })], {
|
||||
live: false
|
||||
});
|
||||
const res = q.removeByUser('x', 'c');
|
||||
expect(res.wasCurrent).toBe(true);
|
||||
expect(q.has('a')).toBe(false);
|
||||
expect(q.has('c')).toBe(false);
|
||||
expect(q.has('b')).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('SlideQueue.knownIds + reconcile eviction', () => {
|
||||
it('knownIds snapshots exactly the current set', () => {
|
||||
const q = new SlideQueue();
|
||||
q.merge([up('a'), up('b')], { live: false });
|
||||
expect(new Set(q.knownIds())).toEqual(new Set(['a', 'b']));
|
||||
});
|
||||
|
||||
// Mirrors the page's reconcile: evict only pre-scan ids the feed no longer lists, so an
|
||||
// upload that lands mid-scan survives.
|
||||
const reconcileEvict = (q: SlideQueue, before: Set<string>, seen: Set<string>) => {
|
||||
for (const id of before) if (!seen.has(id)) q.remove(id, null);
|
||||
};
|
||||
|
||||
it('drops a slide the server no longer lists (deleted/banned we missed)', () => {
|
||||
const q = new SlideQueue();
|
||||
q.merge([up('a'), up('b'), up('c')], { live: false });
|
||||
const before = new Set(q.knownIds());
|
||||
reconcileEvict(q, before, new Set(['a', 'c'])); // feed no longer has b
|
||||
expect(q.has('b')).toBe(false);
|
||||
expect(q.has('a')).toBe(true);
|
||||
expect(q.has('c')).toBe(true);
|
||||
});
|
||||
|
||||
it('never evicts an upload that arrived mid-scan (not in the pre-scan snapshot)', () => {
|
||||
const q = new SlideQueue();
|
||||
q.merge([up('a'), up('b')], { live: false });
|
||||
const before = new Set(q.knownIds()); // {a, b}
|
||||
// A live upload lands during the scan; the scan's `seen` predates it.
|
||||
q.merge([up('fresh')], { live: true });
|
||||
reconcileEvict(q, before, new Set(['a', 'b']));
|
||||
expect(q.has('fresh')).toBe(true); // survives — not an eviction candidate
|
||||
expect(q.has('a')).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -5,13 +5,18 @@
|
||||
// (minus the most recent N items) once it empties. A new live post pushes onto the
|
||||
// live queue and waits for the next slide transition — it never interrupts the
|
||||
// current slide.
|
||||
//
|
||||
// Completeness is the whole point: `allKnown` is meant to converge to the server's full
|
||||
// set of eligible uploads. The page feeds it via `merge` (incremental / paginated) and
|
||||
// `retainOnly` (evict anything the server no longer returns — deletions, bans, hides),
|
||||
// so every eligible image is eventually shown and no ineligible one lingers.
|
||||
|
||||
import type { FeedUpload } from '$lib/types';
|
||||
|
||||
const RECENT_RING_SIZE = 5;
|
||||
|
||||
export class SlideQueue {
|
||||
/** Live queue — FIFO. New uploads land here via `pushLive`. */
|
||||
/** Live queue — FIFO. New uploads land here via `merge(_, { live: true })`. */
|
||||
private liveQueue: FeedUpload[] = [];
|
||||
/** Shuffle queue — refilled from `allKnown` minus `recentlyShown` when emptied. */
|
||||
private shuffleQueue: FeedUpload[] = [];
|
||||
@@ -20,19 +25,35 @@ export class SlideQueue {
|
||||
/** Ring buffer of the last N shown ids — excluded from the next shuffle pool. */
|
||||
private recentlyShown: string[] = [];
|
||||
|
||||
/** Seed the shuffle pool from an initial fetch of the feed. */
|
||||
seed(initial: FeedUpload[]): void {
|
||||
for (const slide of initial) {
|
||||
this.allKnown.set(slide.id, slide);
|
||||
/**
|
||||
* Add uploads, de-duplicated by id. Only *displayable* items (preview- or
|
||||
* thumbnail-ready) are kept — a still-compressing upload has no image yet, so it's
|
||||
* skipped until a later sync brings it with a preview. `live` items jump onto the live
|
||||
* queue (shown next); otherwise they join the shuffle pool. Returns the count newly added.
|
||||
*/
|
||||
merge(uploads: FeedUpload[], opts: { live: boolean }): number {
|
||||
let added = 0;
|
||||
for (const u of uploads) {
|
||||
if (!u.preview_url && !u.thumbnail_url) continue;
|
||||
if (this.allKnown.has(u.id)) continue;
|
||||
this.allKnown.set(u.id, u);
|
||||
if (opts.live) this.liveQueue.push(u);
|
||||
else this.shuffleQueue.push(u);
|
||||
added++;
|
||||
}
|
||||
this.shuffleQueue = shuffle(Array.from(this.allKnown.values()));
|
||||
return added;
|
||||
}
|
||||
|
||||
/** Add a slide pushed by a new SSE upload-processed event. */
|
||||
pushLive(slide: FeedUpload): void {
|
||||
if (this.allKnown.has(slide.id)) return;
|
||||
this.allKnown.set(slide.id, slide);
|
||||
this.liveQueue.push(slide);
|
||||
/** True if this id is already in the known set — used to stop a catch-up scan once it
|
||||
* reaches territory we've already ingested. */
|
||||
has(id: string): boolean {
|
||||
return this.allKnown.has(id);
|
||||
}
|
||||
|
||||
/** Re-randomise the not-yet-shown shuffle pool. Called once after the initial paginated
|
||||
* load so the first cycle isn't just newest-first (merge appends in feed order). */
|
||||
reshuffle(): void {
|
||||
this.shuffleQueue = shuffle(this.shuffleQueue);
|
||||
}
|
||||
|
||||
/** Pop the next slide. Returns null while both queues are empty (event has no posts). */
|
||||
@@ -85,9 +106,21 @@ export class SlideQueue {
|
||||
}
|
||||
this.liveQueue = this.liveQueue.filter((s) => s.user_id !== userId);
|
||||
this.shuffleQueue = this.shuffleQueue.filter((s) => s.user_id !== userId);
|
||||
this.recentlyShown = this.recentlyShown.filter((sid) => this.allKnown.has(sid));
|
||||
return { wasCurrent };
|
||||
}
|
||||
|
||||
/**
|
||||
* Snapshot of all currently-known ids. The page captures this BEFORE a reconcile scan,
|
||||
* then evicts only ids that were known before AND the server no longer lists — the
|
||||
* reconciliation half of `merge`. Snapshotting first means an upload that lands *during*
|
||||
* the scan (not in the snapshot) is never wrongly evicted, so a busy event doesn't
|
||||
* flicker freshly-added slides out and back in.
|
||||
*/
|
||||
knownIds(): string[] {
|
||||
return Array.from(this.allKnown.keys());
|
||||
}
|
||||
|
||||
/** Look up a slide by id — for the diashow page to render the current slide. */
|
||||
get(id: string): FeedUpload | undefined {
|
||||
return this.allKnown.get(id);
|
||||
|
||||
@@ -9,6 +9,8 @@ export interface FeedUpload {
|
||||
uploader_name: string;
|
||||
preview_url: string | null;
|
||||
thumbnail_url: string | null;
|
||||
/** Big-screen (~2048px) variant for the diashow; null until the derivative exists. */
|
||||
display_url: string | null;
|
||||
mime_type: string;
|
||||
caption: string | null;
|
||||
like_count: number;
|
||||
|
||||
@@ -4,7 +4,6 @@
|
||||
import { api } from '$lib/api';
|
||||
import { getToken } from '$lib/auth';
|
||||
import { showBottomNav } from '$lib/ui-store';
|
||||
import { dataMode, pickMediaUrl } from '$lib/data-mode-store';
|
||||
import { connectSse, disconnectSse, onSseEvent } from '$lib/sse';
|
||||
import { SlideQueue } from '$lib/diashow/queue';
|
||||
import { transitions, findTransition } from '$lib/diashow/transitions';
|
||||
@@ -12,6 +11,17 @@
|
||||
import type { FeedUpload, FeedResponse, DeltaResponse } from '$lib/types';
|
||||
|
||||
const DWELL_OPTIONS = [3000, 6000, 10000];
|
||||
// Cap on how long we wait for the next image to decode before showing it anyway.
|
||||
const PRELOAD_TIMEOUT_MS = 4000;
|
||||
// If every source for a slide is unreadable we skip it — but bail out of skipping after
|
||||
// this many in a row so a total media outage can't hot-loop the show.
|
||||
const MAX_CONSECUTIVE_SKIPS = 5;
|
||||
// Feed pagination: the server caps `limit` at 100, so we page to cover larger events.
|
||||
const FEED_PAGE = 100;
|
||||
const MAX_PAGES = 100; // safety bound (~10k images) against a runaway pagination loop
|
||||
// Periodic full reconcile — the completeness backstop for anything a live event missed
|
||||
// (dropped SSE, rate-limited fetch, an add/remove that never arrived).
|
||||
const RECONCILE_INTERVAL_MS = 120_000;
|
||||
|
||||
let queue = new SlideQueue();
|
||||
let current = $state<FeedUpload | null>(null);
|
||||
@@ -25,8 +35,11 @@
|
||||
type SlideLayer = { key: string; src: string; isVideo: boolean; phase: 'enter' | 'exit' };
|
||||
let layers = $state<SlideLayer[]>([]);
|
||||
let dropPrevTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
let reconcileInterval: ReturnType<typeof setInterval> | null = null;
|
||||
// Guards the async (decode-gated) layer commit against a newer advance superseding it.
|
||||
let slideToken = 0;
|
||||
// Consecutive slides skipped because no source decoded — reset the moment one shows.
|
||||
let consecutiveSkips = 0;
|
||||
let dwellMs = $state(6000);
|
||||
let transitionId = $state('crossfade');
|
||||
let paused = $state(false);
|
||||
@@ -66,18 +79,31 @@
|
||||
}
|
||||
}
|
||||
|
||||
function advance() {
|
||||
// `immediate` = hard-cut with no exiting layer, used when the outgoing slide was just
|
||||
// removed (deleted / banned): it must vanish at once, not linger through the transition.
|
||||
function advance(immediate = false) {
|
||||
const next = queue.next();
|
||||
showSlide(next);
|
||||
showSlide(next, immediate);
|
||||
if (current) scheduleNext();
|
||||
}
|
||||
|
||||
// Swap in the next slide as the top layer while holding the outgoing one beneath it
|
||||
// for the length of the transition. For images we decode the incoming frame first so
|
||||
// the fade reveals a painted picture rather than a blank one; the outgoing slide stays
|
||||
// visible until then, so there's never a black gap. Videos can't be pre-decoded, so
|
||||
// they swap in immediately.
|
||||
function showSlide(next: FeedUpload | null) {
|
||||
// The diashow is a big screen (usually on good connectivity), so it ALWAYS prefers the
|
||||
// crisp ~2048px `display` derivative — decoupled from the per-device data-saver mode,
|
||||
// which is about a guest's phone data plan and irrelevant here. It falls back to the
|
||||
// original (uploads without a display yet) and then the 800px preview.
|
||||
function imageCandidates(u: FeedUpload): string[] {
|
||||
const displayOrOriginal = u.display_url ?? `/api/v1/upload/${u.id}/original`;
|
||||
const list = [displayOrOriginal];
|
||||
if (u.preview_url && u.preview_url !== displayOrOriginal) list.push(u.preview_url);
|
||||
return list;
|
||||
}
|
||||
|
||||
// Swap in the next slide as the top layer while holding the outgoing one beneath it for
|
||||
// the length of the transition. Images are decode-gated (the fade reveals a painted
|
||||
// frame, not a blank one) and try each source in turn; the outgoing slide stays visible
|
||||
// until one commits, so there's never a black gap. Videos can't be pre-decoded, so they
|
||||
// swap in immediately.
|
||||
function showSlide(next: FeedUpload | null, immediate = false) {
|
||||
const token = ++slideToken;
|
||||
if (dropPrevTimer) {
|
||||
clearTimeout(dropPrevTimer);
|
||||
@@ -88,21 +114,26 @@
|
||||
layers = [];
|
||||
return;
|
||||
}
|
||||
const slide: SlideLayer = {
|
||||
key: next.id,
|
||||
src: pickMediaUrl($dataMode, next),
|
||||
isVideo: next.mime_type.startsWith('video/'),
|
||||
phase: 'enter'
|
||||
};
|
||||
const isVid = next.mime_type.startsWith('video/');
|
||||
const prev = layers.length ? layers[layers.length - 1] : null;
|
||||
// Re-showing the same slide (e.g. a feed re-fetch resolved to the current head) —
|
||||
// just replace it; never stack a slide on top of itself.
|
||||
if (prev && prev.key === slide.key) {
|
||||
layers = [slide];
|
||||
return;
|
||||
}
|
||||
const commit = () => {
|
||||
|
||||
const commit = (src: string) => {
|
||||
if (token !== slideToken) return; // superseded by a newer advance — drop this frame
|
||||
consecutiveSkips = 0; // a slide actually reached the screen — reset the skip guard
|
||||
const slide: SlideLayer = { key: next.id, src, isVideo: isVid, phase: 'enter' };
|
||||
// Re-showing the same slide id (e.g. a re-fetch resolved to the current head) —
|
||||
// just replace it; never stack a slide on itself.
|
||||
if (prev && prev.key === slide.key) {
|
||||
layers = [slide];
|
||||
return;
|
||||
}
|
||||
// Removal-driven advance: drop the outgoing (removed) frame instantly — no exiting
|
||||
// layer. A brief blank over black beats showing a just-deleted/banned photo for
|
||||
// another second while it slides away.
|
||||
if (immediate) {
|
||||
layers = [slide];
|
||||
return;
|
||||
}
|
||||
// Mark the outgoing frame as exiting so slide transitions push it off in step with
|
||||
// the incoming one. Crossfade/Ken Burns ignore `phase` and just hold it opaque.
|
||||
const exiting = prev ? { ...prev, phase: 'exit' as const } : null;
|
||||
@@ -114,43 +145,141 @@
|
||||
}, transitionDef.defaultDurationMs + 80);
|
||||
}
|
||||
};
|
||||
if (slide.isVideo) {
|
||||
commit();
|
||||
|
||||
// Videos play the original file directly (can't be pre-decoded) — show immediately.
|
||||
if (isVid) {
|
||||
commit(`/api/v1/upload/${next.id}/original`);
|
||||
return;
|
||||
}
|
||||
const pre = new Image();
|
||||
pre.src = slide.src;
|
||||
// decode() resolves once the bitmap is ready to paint; on failure just commit anyway
|
||||
// (a broken image should still advance the show rather than stall it).
|
||||
pre.decode().then(commit).catch(commit);
|
||||
|
||||
// Try each image source in order. A decoded one is shown; a SLOW one is shown after
|
||||
// the timeout (don't stall the wall); a BROKEN one (fast decode reject) falls through
|
||||
// to the next source. If every source is unreadable, skip to a different slide rather
|
||||
// than parking a broken frame — guarded so a full media outage can't hot-loop.
|
||||
const candidates = imageCandidates(next);
|
||||
const tryCandidate = (i: number) => {
|
||||
if (token !== slideToken) return;
|
||||
if (i >= candidates.length) {
|
||||
if (consecutiveSkips < MAX_CONSECUTIVE_SKIPS) {
|
||||
consecutiveSkips++;
|
||||
advance();
|
||||
} else {
|
||||
consecutiveSkips = 0;
|
||||
commit(candidates[candidates.length - 1]); // give up skipping; show last try
|
||||
}
|
||||
return;
|
||||
}
|
||||
let settled = false;
|
||||
let timer: ReturnType<typeof setTimeout>;
|
||||
const done = (action: () => void) => {
|
||||
if (settled || token !== slideToken) return;
|
||||
settled = true;
|
||||
clearTimeout(timer);
|
||||
action();
|
||||
};
|
||||
timer = setTimeout(() => done(() => commit(candidates[i])), PRELOAD_TIMEOUT_MS);
|
||||
const pre = new Image();
|
||||
pre.src = candidates[i];
|
||||
pre.decode().then(
|
||||
() => done(() => commit(candidates[i])),
|
||||
() => done(() => tryCandidate(i + 1))
|
||||
);
|
||||
};
|
||||
tryCandidate(0);
|
||||
}
|
||||
|
||||
// A video finished before its dwell/12s cap — advance immediately (unless paused).
|
||||
// The {#key current.id} block destroys the old <video> on advance, so a fallback
|
||||
// timer that already fired can't trigger this handler for a stale slide.
|
||||
// `onended` is only wired to the layer whose key === current.id (see the template), so a
|
||||
// stale/exiting <video> that ends mid-transition can't trigger an advance.
|
||||
function handleVideoEnded() {
|
||||
if (!paused) advance();
|
||||
}
|
||||
|
||||
async function loadInitial() {
|
||||
// Full reconcile: page the ENTIRE eligible feed, merge everything, then evict anything
|
||||
// the server no longer returns. v_feed already excludes deleted/banned/hidden, so the
|
||||
// feed's id-set IS the eligible set — retaining exactly those ids converges the show to
|
||||
// the server truth in both directions, catching any add/remove a live event missed.
|
||||
// Runs on mount (initial fill), on reconnect deltas, and periodically as the backstop.
|
||||
// `initial` reshuffles once the whole set is in, so the first cycle isn't newest-first.
|
||||
async function reconcile(initial = false) {
|
||||
// Ids known BEFORE the scan — only these are eviction candidates, so an upload that
|
||||
// arrives mid-scan (not in this snapshot) is never wrongly pruned.
|
||||
const before = new Set(queue.knownIds());
|
||||
const seen = new Set<string>();
|
||||
let cursor: string | null = null;
|
||||
let complete = false;
|
||||
try {
|
||||
const feed = await api.get<FeedResponse>('/feed?limit=200');
|
||||
queue.seed(feed.uploads);
|
||||
advance();
|
||||
for (let page = 0; page < MAX_PAGES; page++) {
|
||||
const qs: string = cursor ? `?limit=${FEED_PAGE}&cursor=${cursor}` : `?limit=${FEED_PAGE}`;
|
||||
const feed: FeedResponse = await api.get<FeedResponse>(`/feed${qs}`);
|
||||
for (const u of feed.uploads) seen.add(u.id);
|
||||
queue.merge(feed.uploads, { live: false });
|
||||
if (!current) advance(); // start the show the moment the first page lands
|
||||
if (feed.next_cursor == null) {
|
||||
complete = true;
|
||||
break;
|
||||
}
|
||||
cursor = feed.next_cursor;
|
||||
}
|
||||
} catch {
|
||||
// Silent — placeholder stays shown
|
||||
// Partial fetch (network / rate-limit): keep what we merged but DON'T prune — a
|
||||
// truncated `seen` set must never evict valid slides. The next reconcile retries.
|
||||
complete = false;
|
||||
}
|
||||
if (complete) {
|
||||
if (initial) queue.reshuffle();
|
||||
// Evict only pre-existing slides the server no longer lists (deletions/bans/hides
|
||||
// we missed a live event for). Hard-cut if the current slide was one of them.
|
||||
let removedCurrent = false;
|
||||
for (const id of before) {
|
||||
if (!seen.has(id) && queue.remove(id, current?.id ?? null).wasCurrent) {
|
||||
removedCurrent = true;
|
||||
}
|
||||
}
|
||||
if (removedCurrent) advance(true);
|
||||
}
|
||||
if (!current) advance();
|
||||
}
|
||||
|
||||
// Live catch-up after `upload-processed`. Pages from the newest downward, merging onto
|
||||
// the live queue (shown soon), and stops at the first page overlapping what we already
|
||||
// know — so a burst larger than one 100-item page is fully captured, while a steady
|
||||
// trickle costs a single request. We deliberately ignore `new-upload` (fires before
|
||||
// compression, so preview_url is still null and the item isn't displayable yet).
|
||||
async function catchUpNew() {
|
||||
let cursor: string | null = null;
|
||||
try {
|
||||
for (let page = 0; page < MAX_PAGES; page++) {
|
||||
const qs: string = cursor ? `?limit=${FEED_PAGE}&cursor=${cursor}` : `?limit=${FEED_PAGE}`;
|
||||
const feed: FeedResponse = await api.get<FeedResponse>(`/feed${qs}`);
|
||||
// A known id marks the boundary: everything below it we already have.
|
||||
const reachedKnown = feed.uploads.some((u) => queue.has(u.id));
|
||||
queue.merge(feed.uploads, { live: true });
|
||||
if (!current) advance();
|
||||
if (feed.next_cursor == null || reachedKnown) break;
|
||||
cursor = feed.next_cursor;
|
||||
}
|
||||
} catch {
|
||||
// transient — the max-wait debounce re-fires and the periodic reconcile backstops
|
||||
}
|
||||
}
|
||||
|
||||
// `upload-processed` carries only `{ upload_id }`; we re-fetch from /feed to get the
|
||||
// preview/thumbnail URLs that just became available. We deliberately do NOT listen
|
||||
// to `new-upload` here — its payload arrives before compression finishes
|
||||
// (preview_url is still null), and `SlideQueue.pushLive` dedupes by id, so the
|
||||
// preview would never be picked up if we enqueued the pre-processed version first.
|
||||
// COALESCE the fetch: a host bulk-uploading fires dozens of `upload-processed` events in
|
||||
// seconds; one `/feed` fetch per event trips the per-user feed rate limit (429) and drops
|
||||
// slides. Debounce into a single fetch of the newest slice instead.
|
||||
// Debounce `upload-processed` into a single catch-up, BUT with a max-wait: a sustained
|
||||
// burst (every guest uploading at once) would otherwise keep resetting a plain trailing
|
||||
// debounce and never fire. The max-wait forces a catch-up at least every 2s mid-burst.
|
||||
let processedDebounce: ReturnType<typeof setTimeout> | null = null;
|
||||
let processedMaxWait: ReturnType<typeof setTimeout> | null = null;
|
||||
function fireCatchUp() {
|
||||
if (processedDebounce) {
|
||||
clearTimeout(processedDebounce);
|
||||
processedDebounce = null;
|
||||
}
|
||||
if (processedMaxWait) {
|
||||
clearTimeout(processedMaxWait);
|
||||
processedMaxWait = null;
|
||||
}
|
||||
void catchUpNew();
|
||||
}
|
||||
function handleUploadProcessed(data: string) {
|
||||
try {
|
||||
const { upload_id } = JSON.parse(data) as { upload_id: string };
|
||||
@@ -159,97 +288,55 @@
|
||||
return;
|
||||
}
|
||||
if (processedDebounce) clearTimeout(processedDebounce);
|
||||
processedDebounce = setTimeout(() => {
|
||||
processedDebounce = null;
|
||||
void refreshRecentFromFeed();
|
||||
}, 500);
|
||||
}
|
||||
|
||||
async function refreshRecentFromFeed() {
|
||||
try {
|
||||
const feed = await api.get<FeedResponse>('/feed?limit=50');
|
||||
for (const upload of feed.uploads) {
|
||||
if (upload.preview_url || upload.thumbnail_url) queue.pushLive(upload);
|
||||
}
|
||||
if (!current) advance();
|
||||
} catch {
|
||||
// ignore — silent recovery; the next event or reconnect delta retries
|
||||
}
|
||||
processedDebounce = setTimeout(fireCatchUp, 500);
|
||||
if (!processedMaxWait) processedMaxWait = setTimeout(fireCatchUp, 2000);
|
||||
}
|
||||
|
||||
function handleUploadDeleted(data: string) {
|
||||
try {
|
||||
const payload = JSON.parse(data) as { upload_id: string };
|
||||
const result = queue.remove(payload.upload_id, current?.id ?? null);
|
||||
if (result.wasCurrent) advance();
|
||||
const { upload_id } = JSON.parse(data) as { upload_id: string };
|
||||
// Hard-cut: a just-deleted photo must not linger through the exit transition.
|
||||
if (queue.remove(upload_id, current?.id ?? null).wasCurrent) advance(true);
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
|
||||
// After an all-night projector reconnects (SSE drop, network blip), the live events
|
||||
// it missed are gone. The SSE client fans out a `feed-delta` of everything since the
|
||||
// last seen timestamp — merge it so the show backfills the gap instead of silently
|
||||
// stalling on a stale set.
|
||||
function handleFeedDelta(data: string) {
|
||||
try {
|
||||
const delta = JSON.parse(data) as DeltaResponse;
|
||||
// Apply deletions + ban-hides FIRST and unconditionally: both are explicit, uncapped
|
||||
// lists, so a moderated/removed photo (or a banned user's whole set) must leave the
|
||||
// rotation even when the delta is truncated. This replays a `user-hidden`/delete the
|
||||
// projector missed while disconnected — the reason a banned guest's slides used to
|
||||
// keep cycling all night. (We can't infer removals by absence from a capped /feed
|
||||
// backfill — older slides beyond the newest 200 would be falsely dropped.)
|
||||
for (const id of delta.deleted_ids) {
|
||||
const result = queue.remove(id, current?.id ?? null);
|
||||
if (result.wasCurrent) advance();
|
||||
}
|
||||
for (const userId of delta.hidden_user_ids) {
|
||||
const result = queue.removeByUser(userId, current?.id ?? null);
|
||||
if (result.wasCurrent) advance();
|
||||
}
|
||||
// A truncated delta's `uploads` is only the newest slice of a larger gap; merging it
|
||||
// alone would skip the older-but-still-new items in between. Backfill new uploads from
|
||||
// a full feed fetch (pushLive dedupes by id, so the current slide isn't disturbed).
|
||||
if (delta.truncated) {
|
||||
void backfillFromFeed();
|
||||
return;
|
||||
}
|
||||
for (const upload of delta.uploads) {
|
||||
// Only enqueue displayable (processed) items; pushLive dedupes by id, so a
|
||||
// later `upload-processed` still refines anything that arrives raw.
|
||||
if (upload.preview_url || upload.thumbnail_url) queue.pushLive(upload);
|
||||
}
|
||||
if (!current) advance();
|
||||
} catch {
|
||||
// ignore — non-fatal; the next live event keeps the show moving
|
||||
}
|
||||
}
|
||||
|
||||
// Full-feed backfill used when a reconnect delta overflows the cap. Merges via
|
||||
// pushLive (id-deduped) so a long-running projector recovers the whole gap.
|
||||
async function backfillFromFeed() {
|
||||
try {
|
||||
const feed = await api.get<FeedResponse>('/feed?limit=200');
|
||||
for (const upload of feed.uploads) {
|
||||
if (upload.preview_url || upload.thumbnail_url) queue.pushLive(upload);
|
||||
}
|
||||
if (!current) advance();
|
||||
} catch {
|
||||
// ignore — the next live event keeps the show moving
|
||||
}
|
||||
}
|
||||
|
||||
function handleUserHidden(data: string) {
|
||||
try {
|
||||
const payload = JSON.parse(data) as { user_id: string };
|
||||
const result = queue.removeByUser(payload.user_id, current?.id ?? null);
|
||||
if (result.wasCurrent) advance();
|
||||
const { user_id } = JSON.parse(data) as { user_id: string };
|
||||
if (queue.removeByUser(user_id, current?.id ?? null).wasCurrent) advance(true);
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
|
||||
// Reconnect after an SSE drop: the client fans out a delta of everything since the last
|
||||
// seen timestamp. Apply removals first (hard-cut off the current slide if affected),
|
||||
// then merge additions; a truncated delta means the gap overflowed the cap, so fall back
|
||||
// to a full catch-up scan.
|
||||
function handleFeedDelta(data: string) {
|
||||
try {
|
||||
const delta = JSON.parse(data) as DeltaResponse;
|
||||
let removedCurrent = false;
|
||||
for (const id of delta.deleted_ids) {
|
||||
if (queue.remove(id, current?.id ?? null).wasCurrent) removedCurrent = true;
|
||||
}
|
||||
for (const userId of delta.hidden_user_ids) {
|
||||
if (queue.removeByUser(userId, current?.id ?? null).wasCurrent) removedCurrent = true;
|
||||
}
|
||||
if (removedCurrent) advance(true); // one advance regardless of how many were removed
|
||||
if (delta.truncated) {
|
||||
void catchUpNew();
|
||||
return;
|
||||
}
|
||||
queue.merge(delta.uploads, { live: true });
|
||||
if (!current) advance();
|
||||
} catch {
|
||||
// ignore — non-fatal; the periodic reconcile backstops anything dropped here
|
||||
}
|
||||
}
|
||||
|
||||
// Reveal the control cluster on any pointer/keyboard activity and re-arm the idle timer.
|
||||
// Controls stay up while the settings panel is open so it can't vanish mid-interaction.
|
||||
function showControls() {
|
||||
@@ -340,7 +427,10 @@
|
||||
// (no-ops if the feed page already opened it). Subscriptions are registered above
|
||||
// first so no early event is missed.
|
||||
connectSse();
|
||||
void loadInitial();
|
||||
void reconcile(true); // initial full load
|
||||
// Completeness backstop: periodically re-sync the whole eligible set, so a dropped
|
||||
// SSE event, a rate-limited catch-up, or any missed add/remove self-heals.
|
||||
reconcileInterval = setInterval(() => void reconcile(), RECONCILE_INTERVAL_MS);
|
||||
});
|
||||
|
||||
onDestroy(() => {
|
||||
@@ -348,6 +438,8 @@
|
||||
clearTimer();
|
||||
if (controlsHideTimer) clearTimeout(controlsHideTimer);
|
||||
if (processedDebounce) clearTimeout(processedDebounce);
|
||||
if (processedMaxWait) clearTimeout(processedMaxWait);
|
||||
if (reconcileInterval) clearInterval(reconcileInterval);
|
||||
if (dropPrevTimer) clearTimeout(dropPrevTimer);
|
||||
document.removeEventListener('fullscreenchange', handleFullscreenChange);
|
||||
// Leave fullscreen when exiting the show, so /feed isn't stuck fullscreen.
|
||||
@@ -426,7 +518,13 @@
|
||||
>
|
||||
{#if isFullscreen}
|
||||
<!-- arrows pointing in -->
|
||||
<svg class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8">
|
||||
<svg
|
||||
class="h-5 w-5"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke="currentColor"
|
||||
stroke-width="1.8"
|
||||
>
|
||||
<path
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
@@ -435,7 +533,13 @@
|
||||
</svg>
|
||||
{:else}
|
||||
<!-- arrows pointing out -->
|
||||
<svg class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8">
|
||||
<svg
|
||||
class="h-5 w-5"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke="currentColor"
|
||||
stroke-width="1.8"
|
||||
>
|
||||
<path
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
|
||||
Reference in New Issue
Block a user