Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

Limit feed video preloads and cancel abandoned downloads

Anand Baburajan50348da02f42
diff --git a/rust/bindings/wasm/space/src/space.rs b/rust/bindings/wasm/space/src/space.rs
index 0c27b49c61..778ca08415 100644
--- a/rust/bindings/wasm/space/src/space.rs
+++ b/rust/bindings/wasm/space/src/space.rs
@@ -984,12 +984,10 @@ impl SpaceLinkCtxHandle {
pub async fn download_post_asset(
&self,
asset: <PostAsset as Tsify>::JsType,
- ) -> Result<Vec<u8>, Error> {
- let asset = PostAsset::from_js(asset)?;
- self.inner
- .download_post_asset(&asset.into())
- .await
- .map_err(Into::into)
+ signal: Option<AbortSignal>,
+ ) -> Result<Vec<u8>, JsValue> {
+ let asset = PostAsset::from_js(asset).map_err(Error::from)?;
+ with_abort_signal(self.inner.download_post_asset(&asset.into()), signal).await
}
#[wasm_bindgen(js_name = downloadAvatar)]
@@ -1397,12 +1395,15 @@ impl SpaceAccountCtxHandle {
&self,
asset: <PostAsset as Tsify>::JsType,
viewer_space_id: Option<String>,
- ) -> Result<Vec<u8>, Error> {
- let asset = PostAsset::from_js(asset)?;
- self.inner
- .download_post_asset(&asset.into(), viewer_space_id.as_deref())
- .await
- .map_err(Into::into)
+ signal: Option<AbortSignal>,
+ ) -> Result<Vec<u8>, JsValue> {
+ let asset = PostAsset::from_js(asset).map_err(Error::from)?;
+ with_abort_signal(
+ self.inner
+ .download_post_asset(&asset.into(), viewer_space_id.as_deref()),
+ signal,
+ )
+ .await
}
#[wasm_bindgen(js_name = downloadSpaceAvatar)]
diff --git a/web/apps/space/src/components/InlinePostVideo.tsx b/web/apps/space/src/components/InlinePostVideo.tsx
index 73d8267132..acda39a533 100644
--- a/web/apps/space/src/components/InlinePostVideo.tsx
+++ b/web/apps/space/src/components/InlinePostVideo.tsx
@@ -10,33 +10,35 @@ export const SpaceInlinePostVideo: React.FC<{
imageUrl?: string;
video: SpacePostVideo;
isActive: boolean;
+ shouldPreload: boolean;
muted: boolean;
onLoadVideo?: SpacePostAssetURLLoader;
-}> = ({ imageUrl, video, isActive, muted, onLoadVideo }) => {
+}> = ({ imageUrl, video, isActive, shouldPreload, muted, onLoadVideo }) => {
const root = useRef<HTMLDivElement>(null);
const player = useRef<
ReturnType<typeof createSpaceVideoContent> | undefined
>(undefined);
const playback = useRef<ReturnType<typeof registerFeedVideo>>(undefined);
+ const queuedLoad = useRef<ReturnType<typeof queueFeedVideoLoad>>(undefined);
useEffect(() => {
const container = root.current!;
- let queuedLoad: ReturnType<typeof queueFeedVideoLoad> | undefined;
const content = createSpaceVideoContent(
{ video },
onLoadVideo
? (asset) => {
- queuedLoad?.cancel();
- queuedLoad = queueFeedVideoLoad(container, () =>
- onLoadVideo(asset),
+ queuedLoad.current?.cancel();
+ queuedLoad.current = queueFeedVideoLoad(
+ container,
+ (signal) => onLoadVideo(asset, signal),
);
- return queuedLoad.promise;
+ return queuedLoad.current.promise;
}
: undefined,
{
inline: true,
- onPlay: () => queuedLoad?.prioritize(),
- onPause: () => queuedLoad?.deprioritize(),
+ onPlay: () => queuedLoad.current?.prioritize(),
+ onPause: () => queuedLoad.current?.deprioritize(),
onTogglePlayback: (play) => {
if (play) registration.play();
else registration.pause();
@@ -47,20 +49,28 @@ export const SpaceInlinePostVideo: React.FC<{
playback.current = registration;
player.current = content;
container.append(content.element);
- void content.preload().catch((error: unknown) => {
- if (!(error instanceof DOMException && error.name == "AbortError"))
- log.warn("Failed to preload feed video", error);
- });
return () => {
registration.unregister();
content.destroy();
- queuedLoad?.cancel();
+ queuedLoad.current?.cancel();
content.element.remove();
player.current = undefined;
playback.current = undefined;
+ queuedLoad.current = undefined;
};
}, [onLoadVideo, video]);
+ useEffect(() => {
+ queuedLoad.current?.setPreloading(shouldPreload);
+ if (shouldPreload)
+ void player.current!.preload().catch((error: unknown) => {
+ if (!(
+ error instanceof DOMException && error.name == "AbortError"
+ ))
+ log.warn("Failed to preload feed video", error);
+ });
+ }, [shouldPreload, onLoadVideo, video]);
+
useEffect(() => {
const element = player.current!.video;
if (imageUrl) element.poster = imageUrl;
diff --git a/web/apps/space/src/components/feed-video-preloading.ts b/web/apps/space/src/components/feed-video-preloading.ts
index c799ed4073..b2cd263a81 100644
--- a/web/apps/space/src/components/feed-video-preloading.ts
+++ b/web/apps/space/src/components/feed-video-preloading.ts
@@ -1,6 +1,20 @@
+import type { SpacePostPhoto } from "services/space";
+
+export const feedVideoPreloadIndices = (
+ photos: SpacePostPhoto[],
+ photoIndex: number,
+) =>
+ photos
+ .flatMap((photo, index) =>
+ index >= photoIndex && photo.video ? [index] : [],
+ )
+ .slice(0, 2);
+
interface VideoLoad {
element: HTMLElement;
- load: () => Promise<string>;
+ load: (signal: AbortSignal) => Promise<string>;
+ controller: AbortController;
+ preloading: boolean;
start: () => void;
resolve: (url: string) => void;
reject: (error: unknown) => void;
@@ -39,13 +53,16 @@ const schedule = () => {
distance(a) - distance(b),
);
for (const request of next) {
+ if (!request.preloading && request != foreground) continue;
if (inFlight >= (request == foreground ? 3 : 2)) continue;
queued.delete(request);
inFlight++;
request.start();
void (async () => {
try {
- request.resolve(await request.load());
+ request.resolve(
+ await request.load(request.controller.signal),
+ );
} catch (error) {
request.reject(error);
} finally {
@@ -62,18 +79,41 @@ export const queueFeedVideoLoad = (
element: HTMLElement,
load: VideoLoad["load"],
) => {
+ const controller = new AbortController();
let start: () => void;
const started = new Promise<void>((resolve) => {
start = resolve;
});
let request: VideoLoad;
const promise = new Promise<string>((resolve, reject) => {
- request = { element, load, start, resolve, reject };
+ request = {
+ element,
+ load,
+ controller,
+ preloading: true,
+ start,
+ resolve,
+ reject,
+ };
queued.add(request);
schedule();
});
+ const cancel = () => {
+ controller.abort();
+ if (foreground == request) foreground = undefined;
+ if (!queued.delete(request)) return;
+ request.reject(controller.signal.reason);
+ if (!queued.size && frame != undefined) {
+ cancelAnimationFrame(frame);
+ frame = undefined;
+ }
+ };
return {
promise,
+ setPreloading: (preloading: boolean) => {
+ request.preloading = preloading;
+ if (preloading) schedule();
+ },
prioritize: () => {
if (queued.has(request)) {
foreground = request;
@@ -84,16 +124,6 @@ export const queueFeedVideoLoad = (
deprioritize: () => {
if (foreground == request) foreground = undefined;
},
- cancel: () => {
- if (foreground == request) foreground = undefined;
- if (!queued.delete(request)) return;
- request.reject(
- new DOMException("Video preload canceled", "AbortError"),
- );
- if (!queued.size && frame != undefined) {
- cancelAnimationFrame(frame);
- frame = undefined;
- }
- },
+ cancel,
};
};
diff --git a/web/apps/space/src/screens/HomeScreen.tsx b/web/apps/space/src/screens/HomeScreen.tsx
index a523f35df3..6032145e84 100644
--- a/web/apps/space/src/screens/HomeScreen.tsx
+++ b/web/apps/space/src/screens/HomeScreen.tsx
@@ -15,6 +15,7 @@ import {
focusFeedPost,
registerFeedPost,
} from "components/feed-video-playback";
+import { feedVideoPreloadIndices } from "components/feed-video-preloading";
import {
SpaceFileViewer,
type SpaceFileViewerController,
@@ -671,6 +672,7 @@ const FeedPhoto: React.FC<{
onLoadVideo?: SpacePostAssetURLLoader;
onOpenPhoto?: () => void;
shouldLoad: boolean;
+ shouldMountVideo: boolean;
shouldPreloadVideo: boolean;
thumbHash?: string;
viewerOrigin?: string;
@@ -684,6 +686,7 @@ const FeedPhoto: React.FC<{
onLoadVideo,
onOpenPhoto,
shouldLoad,
+ shouldMountVideo,
shouldPreloadVideo,
thumbHash,
video,
@@ -820,11 +823,12 @@ const FeedPhoto: React.FC<{
}}
/>
)}
- {!isPostUnavailable && video && shouldPreloadVideo && (
+ {!isPostUnavailable && video && shouldMountVideo && (
<SpaceInlinePostVideo
imageUrl={displayImageUrl}
video={video}
isActive={isActive}
+ shouldPreload={shouldPreloadVideo}
muted={muted}
onLoadVideo={onLoadVideo}
/>
@@ -902,6 +906,7 @@ const FeedItem: React.FC<FeedItemProps> = ({
const feedPhotos = photos ?? [{ imageUrl, thumbHash }];
const hasVideo = feedPhotos.some((photo) => Boolean(photo.video));
const activePhoto = feedPhotos[photoIndex]!;
+ const videoPreloadIndices = feedVideoPreloadIndices(feedPhotos, photoIndex);
const carouselRef = React.useRef<HTMLDivElement | null>(null);
React.useEffect(() => registerFeedPost(carouselRef.current!), []);
const photoAnimationRef = React.useRef<number | null>(null);
@@ -1500,11 +1505,16 @@ const FeedItem: React.FC<FeedItemProps> = ({
onOpenPhoto ? () => openPhoto(index) : undefined
}
shouldLoad={
- (shouldPreloadVideo && Boolean(photo.video)) ||
+ (shouldPreloadVideo &&
+ videoPreloadIndices.includes(index)) ||
(shouldLoadMedia &&
Math.abs(index - photoIndex) <= 1)
}
- shouldPreloadVideo={shouldPreloadVideo}
+ shouldMountVideo={shouldPreloadVideo}
+ shouldPreloadVideo={
+ shouldPreloadVideo &&
+ videoPreloadIndices.includes(index)
+ }
thumbHash={photo.thumbHash}
video={photo.video}
viewerOrigin={
diff --git a/web/apps/space/src/services/media-cache.ts b/web/apps/space/src/services/media-cache.ts
index 8ea7c33866..57fe7f9819 100644
--- a/web/apps/space/src/services/media-cache.ts
+++ b/web/apps/space/src/services/media-cache.ts
@@ -99,16 +99,25 @@ const blobURLForSpaceMedia = async (
export const cachedSpaceMediaBlobURL = async (
cacheKey: string,
- load: () => Promise<Uint8Array>,
+ load: (signal?: AbortSignal) => Promise<Uint8Array>,
mediaType?: string,
+ signal?: AbortSignal,
) => {
const storageKey = await spaceMediaStorageKey(cacheKey);
- if (mediaType?.startsWith("video/"))
- return URL.createObjectURL(
- await cachedSpaceVideoBlob(storageKey, async () =>
- blobForBytes(await loadSpaceMedia(load), mediaType),
- ),
+ signal?.throwIfAborted();
+ if (mediaType?.startsWith("video/")) {
+ const blob = await cachedSpaceVideoBlob(
+ storageKey,
+ async (signal) =>
+ blobForBytes(
+ await loadSpaceMedia(() => load(signal)),
+ mediaType,
+ ),
+ signal,
);
+ signal?.throwIfAborted();
+ return URL.createObjectURL(blob);
+ }
const cached = spaceMediaURLCache.get(storageKey);
if (cached) {
spaceMediaURLCache.delete(storageKey);
@@ -131,10 +140,13 @@ export const cachedSpaceMediaBlobURL = async (
export const cachedSpaceMediaBlobURLIfPresent = async (
cacheKey: string,
mediaType?: string,
+ signal?: AbortSignal,
) => {
const storageKey = await spaceMediaStorageKey(cacheKey);
+ signal?.throwIfAborted();
if (mediaType?.startsWith("video/")) {
- const blob = await cachedSpaceVideoBlobIfPresent(storageKey);
+ const blob = await cachedSpaceVideoBlobIfPresent(storageKey, signal);
+ signal?.throwIfAborted();
return blob ? URL.createObjectURL(blob) : undefined;
}
const cached = spaceMediaURLCache.get(storageKey);
diff --git a/web/apps/space/src/services/space.ts b/web/apps/space/src/services/space.ts
index 435c3edd6d..752245cf11 100644
--- a/web/apps/space/src/services/space.ts
+++ b/web/apps/space/src/services/space.ts
@@ -137,6 +137,7 @@ export interface PublicSpaceLinkSession {
export type SpacePostAssetURLLoader = (
asset: SpacePostAsset,
+ signal?: AbortSignal,
) => Promise<string>;
export type SpacePostAvatarURLLoader = (
@@ -414,11 +415,13 @@ const accountPostAssetURLFromAsset = (
ctx: SpaceAccountCtxHandle,
asset: SpacePostAsset,
viewerSpaceId?: string,
+ signal?: AbortSignal,
) =>
cachedSpaceMediaBlobURL(
postAssetCacheKey(asset),
- () => ctx.downloadPostAsset(asset, viewerSpaceId ?? null),
+ (signal) => ctx.downloadPostAsset(asset, viewerSpaceId ?? null, signal),
asset.mediaType,
+ signal,
);
const accountPostAssetURL = (
@@ -586,11 +589,12 @@ export const openPublicSpaceLink = async (
const profile = profileFromSpaceProfile(response);
return {
close: () => ctx.free(),
- loadPostImage: (asset) =>
+ loadPostImage: (asset, signal) =>
cachedSpaceMediaBlobURL(
postAssetCacheKey(asset),
- () => ctx.downloadPostAsset(asset),
+ (signal) => ctx.downloadPostAsset(asset, signal),
asset.mediaType,
+ signal,
),
loadProfileMedia: async () => {
const [avatarUrl, coverUrl] = await Promise.all([
@@ -1166,17 +1170,24 @@ export const loadCurrentSpacePost = async (
export const loadCurrentSpacePostAssetURL: SpacePostAssetURLLoader = async (
asset,
+ signal,
) => {
const cachedURL = await cachedSpaceMediaBlobURLIfPresent(
postAssetCacheKey(asset),
asset.mediaType,
+ signal,
);
if (cachedURL) return cachedURL;
const profile = await loadExistingSpaceProfile();
const ctx = await ensureCurrentSpaceContext();
try {
- return await accountPostAssetURLFromAsset(ctx, asset, profile?.spaceId);
+ return await accountPostAssetURLFromAsset(
+ ctx,
+ asset,
+ profile?.spaceId,
+ signal,
+ );
} finally {
releaseCurrentSpaceContext(ctx);
}
diff --git a/web/apps/space/src/services/video-cache.ts b/web/apps/space/src/services/video-cache.ts
index 08c7caa63b..6236d26ba8 100644
--- a/web/apps/space/src/services/video-cache.ts
+++ b/web/apps/space/src/services/video-cache.ts
@@ -2,13 +2,47 @@ import log from "ente-base/log";
const cacheName = "space-videos";
const maxCacheBytes = 100 * 1024 * 1024;
-const loads = new Map<string, Promise<Blob>>();
+interface VideoLoad {
+ promise: Promise<Blob>;
+ controller: AbortController;
+ consumers: number;
+}
+
+const loads = new Map<string, VideoLoad>();
let writes = Promise.resolve();
let generation = 0;
-export const cachedSpaceVideoBlobIfPresent = async (key: string) => {
+const consumeVideoLoad = async (
+ key: string,
+ pending: VideoLoad,
+ signal?: AbortSignal,
+) => {
+ signal?.throwIfAborted();
+ pending.consumers++;
+ let abort: () => void;
+ try {
+ return await new Promise<Blob>((resolve, reject) => {
+ abort = () => reject(signal!.reason as Error);
+ signal?.addEventListener("abort", abort, { once: true });
+ pending.promise.then(resolve, reject);
+ });
+ } finally {
+ signal?.removeEventListener("abort", abort!);
+ pending.consumers--;
+ if (!pending.consumers && loads.get(key) == pending) {
+ loads.delete(key);
+ pending.controller.abort();
+ }
+ }
+};
+
+export const cachedSpaceVideoBlobIfPresent = async (
+ key: string,
+ signal?: AbortSignal,
+) => {
+ signal?.throwIfAborted();
const pending = loads.get(key);
- if (pending) return pending;
+ if (pending) return consumeVideoLoad(key, pending, signal);
try {
await writes;
const response = await (await caches.open(cacheName)).match(`/${key}`);
@@ -58,22 +92,28 @@ export const rememberSpaceVideoBlob = (key: string, blob: Blob) => {
export const cachedSpaceVideoBlob = (
key: string,
- load: () => Promise<Blob>,
+ load: (signal: AbortSignal) => Promise<Blob>,
+ signal?: AbortSignal,
) => {
+ signal?.throwIfAborted();
const pending = loads.get(key);
- if (pending) return pending;
+ if (pending) return consumeVideoLoad(key, pending, signal);
const current = generation;
+ const controller = new AbortController();
const promise = (async () => {
const cached = await cachedSpaceVideoBlobIfPresent(key);
+ controller.signal.throwIfAborted();
if (cached) return cached;
- const blob = await load();
+ const blob = await load(controller.signal);
+ controller.signal.throwIfAborted();
if (current == generation) await rememberSpaceVideoBlob(key, blob);
return blob;
})().finally(() => {
- if (loads.get(key) == promise) loads.delete(key);
+ if (loads.get(key) == request) loads.delete(key);
});
- loads.set(key, promise);
- return promise;
+ const request = { promise, controller, consumers: 0 };
+ loads.set(key, request);
+ return consumeVideoLoad(key, request, signal);
};
export const clearSpaceVideoLoads = () => {
diff --git a/web/apps/space/tests/feed-video-preloading.test.ts b/web/apps/space/tests/feed-video-preloading.test.ts
index a81930b0cc..1fc4f35a5b 100644
--- a/web/apps/space/tests/feed-video-preloading.test.ts
+++ b/web/apps/space/tests/feed-video-preloading.test.ts
@@ -1,5 +1,8 @@
import { afterEach, beforeEach, expect, test, vi } from "vitest";
-import { queueFeedVideoLoad } from "../src/components/feed-video-preloading";
+import {
+ feedVideoPreloadIndices,
+ queueFeedVideoLoad,
+} from "../src/components/feed-video-preloading";
let viewport: { innerHeight: number; scrollY: number };
let frames: Map<number, FrameRequestCallback>;
@@ -54,8 +57,11 @@ const enqueue = (name: string, top: number, slideOffset = 0) => {
: null,
} as unknown as HTMLElement;
const download = Promise.withResolvers<string>();
- const load = vi.fn(() => {
+ const load = vi.fn((signal: AbortSignal) => {
started.push(name);
+ signal.addEventListener("abort", () => download.reject(signal.reason), {
+ once: true,
+ });
return download.promise;
});
const control = queueFeedVideoLoad(element, load);
@@ -65,6 +71,26 @@ const enqueue = (name: string, top: number, slideOffset = 0) => {
return request;
};
+test.each([
+ [0, [1, 3]],
+ [1, [1, 3]],
+ [2, [3, 4]],
+ [3, [3, 4]],
+ [4, [4]],
+ [5, []],
+] as const)(
+ "prepares two videos ahead of slide %i, skipping photos",
+ (index, expected) => {
+ const video = { durationMs: 1000 };
+ const photos = [{}, { video }, {}, { video }, { video }, {}];
+ expect(feedVideoPreloadIndices(photos, index)).toEqual(expected);
+ },
+);
+
+test("a carousel of photos does not request video preloads", () => {
+ expect(feedVideoPreloadIndices([{}, {}, {}], 0)).toEqual([]);
+});
+
test("downloads the nearest videos first and limits simultaneous loads to two", async () => {
const far = enqueue("far", 2400);
const next = enqueue("next", 1000);
@@ -205,20 +231,61 @@ test("a detached video is canceled even when it is the only queued request", asy
});
});
-test("an in-flight download retains its slot when its post is unmounted", async () => {
+test("unmounting a post aborts its download and releases its slot", async () => {
const first = enqueue("first", 100);
enqueue("second", 500);
enqueue("third", 900);
flush();
first.cancel();
+ expect(first.load.mock.calls[0]![0].aborted).toBe(true);
flush();
expect(started).toEqual(["first", "second"]);
- first.download.resolve("blob:first");
- await expect(first.promise).resolves.toBe("blob:first");
+ await expect(first.promise).rejects.toMatchObject({ name: "AbortError" });
flush();
expect(started).toEqual(["first", "second", "third"]);
});
+test("swiping away from a queued video defers it until it is needed again", async () => {
+ const previous = enqueue("previous", 100);
+ const current = enqueue("current", 100);
+ const nextPost = enqueue("next post", 900);
+ previous.setPreloading(false);
+ flush();
+ expect(started).toEqual(["current", "next post"]);
+ current.download.resolve("blob:current");
+ nextPost.download.resolve("blob:next");
+ await Promise.all([current.promise, nextPost.promise]);
+ flush();
+ expect(previous.load).not.toHaveBeenCalled();
+ previous.setPreloading(true);
+ flush();
+ expect(started).toEqual(["current", "next post", "previous"]);
+ expect(previous.load).toHaveBeenCalledOnce();
+});
+
+test("swiping away lets an already-started download finish without restarting it", async () => {
+ const previous = enqueue("previous", 100);
+ flush();
+ previous.setPreloading(false);
+ expect(previous.load.mock.calls[0]![0].aborted).toBe(false);
+ previous.download.resolve("blob:previous");
+ await expect(previous.promise).resolves.toBe("blob:previous");
+ previous.setPreloading(true);
+ flush();
+ expect(previous.load).toHaveBeenCalledOnce();
+});
+
+test("leaving the post cancels a deferred preload", async () => {
+ const previous = enqueue("previous", 100);
+ previous.setPreloading(false);
+ flush();
+ previous.cancel();
+ await expect(previous.promise).rejects.toMatchObject({
+ name: "AbortError",
+ });
+ expect(previous.load).not.toHaveBeenCalled();
+});
+
test("a failed download releases its slot for the next video", async () => {
const first = enqueue("first", 100);
enqueue("second", 500);
diff --git a/web/apps/space/tests/inline-post-video.test.tsx b/web/apps/space/tests/inline-post-video.test.tsx
new file mode 100644
index 0000000000..43a554a501
--- /dev/null
+++ b/web/apps/space/tests/inline-post-video.test.tsx
@@ -0,0 +1,162 @@
+import type {
+ DependencyList,
+ EffectCallback,
+ ReactElement,
+ RefObject,
+} from "react";
+import { afterEach, beforeEach, expect, test, vi } from "vitest";
+import { SpaceInlinePostVideo } from "../src/components/InlinePostVideo";
+import type {
+ SpacePostAsset,
+ SpacePostAssetURLLoader,
+} from "../src/services/space";
+
+const mocks = vi.hoisted(() => ({
+ refs: [] as { current: unknown }[],
+ effects: [] as {
+ dependencies: DependencyList;
+ cleanup: ReturnType<EffectCallback>;
+ }[],
+ pendingEffects: [] as (() => void)[],
+ refIndex: 0,
+ effectIndex: 0,
+ create: vi.fn(),
+ register: vi.fn(),
+ queue: vi.fn(),
+}));
+
+vi.mock("react", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("react")>()),
+ useRef: (current: unknown) => {
+ const index = mocks.refIndex++;
+ return (mocks.refs[index] ??= { current });
+ },
+ useEffect: (effect: EffectCallback, dependencies: DependencyList) => {
+ const index = mocks.effectIndex++;
+ const previous = mocks.effects[index];
+ if (
+ !previous ||
+ dependencies.some(
+ (value, i) => !Object.is(value, previous.dependencies[i]),
+ )
+ )
+ mocks.pendingEffects.push(() => {
+ previous?.cleanup?.();
+ mocks.effects[index] = { dependencies, cleanup: effect() };
+ });
+ },
+}));
+vi.mock("@mui/material", () => ({ Box: () => null }));
+vi.mock("components/PostVideoContent", () => ({
+ createSpaceVideoContent: mocks.create,
+}));
+vi.mock("components/feed-video-playback", () => ({
+ registerFeedVideo: mocks.register,
+}));
+vi.mock("components/feed-video-preloading", () => ({
+ queueFeedVideoLoad: mocks.queue,
+}));
+vi.mock("ente-base/log", () => ({ default: { warn: vi.fn() } }));
+
+const asset = { objectKey: "video" } as SpacePostAsset;
+const video = { asset, durationMs: 1000 };
+const onLoadVideo = vi.fn<SpacePostAssetURLLoader>();
+const container = { append: vi.fn() };
+const button = { tabIndex: -1 };
+const content = {
+ element: { querySelector: () => button, remove: vi.fn() },
+ video: {
+ tabIndex: -1,
+ muted: true,
+ currentTime: 0,
+ removeAttribute: vi.fn(),
+ },
+ preload: vi.fn<() => Promise<void>>(),
+ destroy: vi.fn(),
+};
+const registration = { setActive: vi.fn(), unregister: vi.fn() };
+const request = {
+ promise: Promise.resolve("blob:video"),
+ setPreloading: vi.fn(),
+ prioritize: vi.fn(),
+ deprioritize: vi.fn(),
+ cancel: vi.fn(),
+};
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.refs = [];
+ mocks.effects = [];
+ mocks.pendingEffects = [];
+ content.video.currentTime = 0;
+ mocks.create.mockImplementation((_, load: SpacePostAssetURLLoader) => {
+ content.preload.mockImplementation(() =>
+ load(asset).then(() => undefined),
+ );
+ return content;
+ });
+ mocks.register.mockReturnValue(registration);
+ mocks.queue.mockReturnValue(request);
+});
+
+const unmount = () => {
+ mocks.effects.splice(0).forEach(({ cleanup }) => cleanup?.());
+};
+
+afterEach(unmount);
+
+const render = (shouldPreload: boolean, isActive = false) => {
+ mocks.refIndex = 0;
+ mocks.effectIndex = 0;
+ const element = SpaceInlinePostVideo({
+ video,
+ onLoadVideo,
+ shouldPreload,
+ isActive,
+ muted: true,
+ }) as ReactElement<{ ref: RefObject<unknown> }>;
+ element.props.ref.current = container;
+ mocks.pendingEffects.splice(0).forEach((effect) => effect());
+};
+
+test("mounting a hidden slide outside the preload pair does not queue its video", () => {
+ render(false);
+ expect(mocks.create).toHaveBeenCalledOnce();
+ expect(content.preload).not.toHaveBeenCalled();
+ expect(mocks.queue).not.toHaveBeenCalled();
+ render(true);
+ expect(content.preload).toHaveBeenCalledOnce();
+ expect(mocks.queue).toHaveBeenCalledOnce();
+});
+
+test("swiping away and back preserves the player and playback position", () => {
+ render(true, true);
+ content.video.currentTime = 0.5;
+ render(false);
+ expect(request.setPreloading).toHaveBeenLastCalledWith(false);
+ expect(registration.setActive).toHaveBeenLastCalledWith(false);
+ expect(request.cancel).not.toHaveBeenCalled();
+ expect(content.destroy).not.toHaveBeenCalled();
+ render(true, true);
+ expect(request.setPreloading).toHaveBeenLastCalledWith(true);
+ expect(mocks.create).toHaveBeenCalledOnce();
+ expect(content.video.currentTime).toBe(0.5);
+ expect(registration.setActive).toHaveBeenLastCalledWith(true);
+});
+
+test("activating the preloaded next slide reuses its player and load", () => {
+ render(true);
+ render(true, true);
+ expect(mocks.create).toHaveBeenCalledOnce();
+ expect(content.preload).toHaveBeenCalledOnce();
+ expect(mocks.queue).toHaveBeenCalledOnce();
+});
+
+test("leaving the post releases its player and cancels its load", () => {
+ render(true, true);
+ render(false);
+ unmount();
+ expect(content.destroy).toHaveBeenCalledOnce();
+ expect(request.cancel).toHaveBeenCalledOnce();
+ expect(registration.unregister).toHaveBeenCalledOnce();
+});
diff --git a/web/apps/space/tests/media-cache.test.ts b/web/apps/space/tests/media-cache.test.ts
index 12b921b6be..be6398b422 100644
--- a/web/apps/space/tests/media-cache.test.ts
+++ b/web/apps/space/tests/media-cache.test.ts
@@ -165,6 +165,103 @@ test("concurrent players share a download and receive their own playback URLs",
expect(createURL.mock.calls[0]![0]).toBe(createURL.mock.calls[1]![0]);
});
+test("canceling one player preserves a download joined through the cache lookup", async () => {
+ const firstController = new AbortController();
+ const secondController = new AbortController();
+ const joined = vi.spyOn(secondController.signal, "addEventListener");
+ const bytes = Promise.withResolvers<Uint8Array>();
+ const download = vi.fn((signal?: AbortSignal) => {
+ signal!.addEventListener("abort", () => bytes.reject(signal!.reason), {
+ once: true,
+ });
+ return bytes.promise;
+ });
+ const first = cachedSpaceMediaBlobURL(
+ "video",
+ download,
+ "video/mp4",
+ firstController.signal,
+ );
+ const canceled = expect(first).rejects.toMatchObject({
+ name: "AbortError",
+ });
+ await vi.waitFor(() => expect(download).toHaveBeenCalledOnce());
+ const second = cachedSpaceMediaBlobURLIfPresent(
+ "video",
+ "video/mp4",
+ secondController.signal,
+ );
+ await vi.waitFor(() => expect(joined).toHaveBeenCalled());
+ firstController.abort();
+ await canceled;
+ expect(download.mock.calls[0]![0]!.aborted).toBe(false);
+ bytes.resolve(new Uint8Array([7]));
+ await expect(second).resolves.toBe("blob:media");
+ expect(createURL).toHaveBeenCalledOnce();
+});
+
+test("leaving the last player aborts the shared download and permits a fresh load", async () => {
+ const firstController = new AbortController();
+ const secondController = new AbortController();
+ const download = vi.fn(
+ (signal?: AbortSignal) =>
+ new Promise<Uint8Array>((_, reject) => {
+ signal!.addEventListener(
+ "abort",
+ () => reject(signal!.reason as Error),
+ { once: true },
+ );
+ }),
+ );
+ const first = cachedSpaceMediaBlobURL(
+ "video",
+ download,
+ "video/mp4",
+ firstController.signal,
+ );
+ const second = cachedSpaceMediaBlobURL(
+ "video",
+ download,
+ "video/mp4",
+ secondController.signal,
+ );
+ const firstCanceled = expect(first).rejects.toMatchObject({
+ name: "AbortError",
+ });
+ const secondCanceled = expect(second).rejects.toMatchObject({
+ name: "AbortError",
+ });
+ await vi.waitFor(() => expect(download).toHaveBeenCalledOnce());
+ firstController.abort();
+ await firstCanceled;
+ expect(download.mock.calls[0]![0]!.aborted).toBe(false);
+ secondController.abort();
+ await secondCanceled;
+ expect(download.mock.calls[0]![0]!.aborted).toBe(true);
+ expect(stored.size).toBe(0);
+ expect(createURL).not.toHaveBeenCalled();
+ download.mockResolvedValueOnce(new Uint8Array([9]));
+ await expect(
+ cachedSpaceMediaBlobURL("video", download, "video/mp4"),
+ ).resolves.toBe("blob:media");
+ expect(download).toHaveBeenCalledTimes(2);
+});
+
+test("canceling before a video starts loading avoids its network request", async () => {
+ const controller = new AbortController();
+ const download = vi.fn();
+ const pending = cachedSpaceMediaBlobURL(
+ "video",
+ download,
+ "video/mp4",
+ controller.signal,
+ );
+ controller.abort();
+ await expect(pending).rejects.toMatchObject({ name: "AbortError" });
+ expect(download).not.toHaveBeenCalled();
+ expect(createURL).not.toHaveBeenCalled();
+});
+
test("a published video is available from the cache without downloading", async () => {
const blob = new Blob(["published video"], { type: "video/mp4" });
await rememberCachedSpaceVideoBlob("video", blob);
diff --git a/web/apps/space/tests/post-upload.test.ts b/web/apps/space/tests/post-upload.test.ts
index 0b87ddd328..2007758510 100644
--- a/web/apps/space/tests/post-upload.test.ts
+++ b/web/apps/space/tests/post-upload.test.ts
@@ -459,6 +459,76 @@ const videoBytes = new Uint8Array([
0, 0, 0, 24, 102, 116, 121, 112, 109, 112, 52, 50,
]);
+test.each(["redirect", "headers", "body"])(
+ "cancels a post asset download during %s and allows another download",
+ async (stage) => {
+ const started = Promise.withResolvers<Request>();
+ let stalled = false;
+ const { ctx, createPhotoPost } = await uploadFixture(
+ false,
+ (request) => {
+ const path = new URL(request.url).pathname;
+ if (
+ !stalled ||
+ !(stage == "redirect"
+ ? path.endsWith("/assets/redirect")
+ : path.startsWith("/assets/"))
+ )
+ return;
+ if (stage == "body") {
+ return Promise.resolve(
+ new Response(
+ new ReadableStream({
+ start(controller) {
+ request.signal.addEventListener(
+ "abort",
+ () =>
+ controller.error(
+ request.signal.reason,
+ ),
+ { once: true },
+ );
+ controller.enqueue(new Uint8Array([1]));
+ },
+ pull() {
+ started.resolve(request);
+ },
+ }),
+ ),
+ );
+ }
+ started.resolve(request);
+ return new Promise((_, reject) => {
+ request.signal.addEventListener(
+ "abort",
+ () => reject(request.signal.reason as Error),
+ { once: true },
+ );
+ });
+ },
+ );
+ try {
+ const post = await createPhotoPost("test-space", [photo(0)], "");
+ const asset = post.photos[0]!.asset;
+ stalled = true;
+ const controller = new AbortController();
+ const canceled = expect(
+ ctx.downloadPostAsset(asset, "test-space", controller.signal),
+ ).rejects.toMatchObject({ name: "AbortError" });
+ const request = await started.promise;
+ controller.abort();
+ await canceled;
+ expect(request.signal.aborted).toBe(true);
+ stalled = false;
+ await expect(
+ ctx.downloadPostAsset(asset, "test-space"),
+ ).resolves.toEqual(photo(0).bytes);
+ } finally {
+ ctx.free();
+ }
+ },
+);
+
test.each([
["photo", "POST"],
["photo", "PUT"],
diff --git a/web/apps/space/tests/post-video-content.test.ts b/web/apps/space/tests/post-video-content.test.ts
index eff1520e25..c72ba77765 100644
--- a/web/apps/space/tests/post-video-content.test.ts
+++ b/web/apps/space/tests/post-video-content.test.ts
@@ -164,6 +164,7 @@ test("switching carousel slides preserves the loaded video for its next activati
const content = create();
content.play();
await vi.advanceTimersByTimeAsync(0);
+ content.video.currentTime = 0.5;
content.deactivate();
expect(content.video.paused).toBe(true);
expect(revokeURL).not.toHaveBeenCalled();
@@ -171,6 +172,7 @@ test("switching carousel slides preserves the loaded video for its next activati
await vi.advanceTimersByTimeAsync(0);
expect(load).toHaveBeenCalledTimes(1);
expect(content.video.play).toHaveBeenCalledTimes(2);
+ expect(content.video.currentTime).toBe(0.5);
});
test("deactivating during a download keeps the preload without starting playback", async () => {