Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

use rpc and dataloader for fetching video thumbnails (#1170)

Brendan Allan31df4330d21a
diff --git a/apps/web/app/(org)/dashboard/caps/components/UploadCapButton.tsx b/apps/web/app/(org)/dashboard/caps/components/UploadCapButton.tsx
index 638f54652..ba7c33a92 100644
--- a/apps/web/app/(org)/dashboard/caps/components/UploadCapButton.tsx
+++ b/apps/web/app/(org)/dashboard/caps/components/UploadCapButton.tsx
@@ -17,7 +17,7 @@ import {
useUploadingContext,
} from "@/app/(org)/dashboard/caps/UploadingContext";
import { UpgradeModal } from "@/components/UpgradeModal";
-import { imageUrlQuery } from "@/components/VideoThumbnail";
+import { ThumbnailRequest } from "@/lib/ThumbnailRequest";
export const UploadCapButton = ({
size = "md",
@@ -495,7 +495,9 @@ async function legacyUploadCap(
xhr.onload = () => {
if (xhr.status >= 200 && xhr.status < 300) {
resolve();
- queryClient.refetchQueries(imageUrlQuery(uploadId));
+ queryClient.refetchQueries({
+ queryKey: ThumbnailRequest.queryKey(uploadId),
+ });
} else {
reject(
new Error(`Screenshot upload failed with status ${xhr.status}`),
diff --git a/apps/web/components/VideoThumbnail.tsx b/apps/web/components/VideoThumbnail.tsx
index 605da0e46..01a18bad7 100644
--- a/apps/web/components/VideoThumbnail.tsx
+++ b/apps/web/components/VideoThumbnail.tsx
@@ -1,14 +1,17 @@
import { LogoSpinner } from "@cap/ui";
-import { queryOptions, useQuery } from "@tanstack/react-query";
+import type { Video } from "@cap/web-domain";
import clsx from "clsx";
+import { Effect } from "effect";
import moment from "moment";
import Image from "next/image";
import { memo, useEffect, useRef } from "react";
+import { useEffectQuery } from "@/lib/EffectRuntime";
+import { ThumbnailRequest } from "@/lib/ThumbnailRequest";
export type ImageLoadingStatus = "loading" | "success" | "error";
interface VideoThumbnailProps {
- videoId: string;
+ videoId: Video.VideoId;
alt: string;
imageClass?: string;
objectFit?: string;
@@ -45,17 +48,17 @@ function generateRandomGrayScaleColor() {
return `rgb(${grayScaleValue}, ${grayScaleValue}, ${grayScaleValue})`;
}
-export const imageUrlQuery = (videoId: string) =>
- queryOptions({
- queryKey: ["thumbnail", videoId],
- queryFn: async () => {
- const response = await fetch(`/api/thumbnail?videoId=${videoId}`);
- if (response.ok) {
- const data = await response.json();
- return data.screen;
- } else throw new Error("Failed to fetch pre-signed URLs");
- },
+export const useThumnailQuery = (videoId: Video.VideoId) => {
+ return useEffectQuery({
+ queryKey: ThumbnailRequest.queryKey(videoId),
+ queryFn: Effect.fn(function* () {
+ return yield* Effect.request(
+ new ThumbnailRequest.ThumbnailRequest({ videoId }),
+ yield* ThumbnailRequest.DataLoaderResolver,
+ );
+ }),
});
+};
export const VideoThumbnail: React.FC<VideoThumbnailProps> = memo(
({
@@ -68,7 +71,7 @@ export const VideoThumbnail: React.FC<VideoThumbnailProps> = memo(
imageStatus,
setImageStatus,
}) => {
- const imageUrl = useQuery(imageUrlQuery(videoId));
+ const thumbnailUrl = useThumnailQuery(videoId);
const imageRef = useRef<HTMLImageElement>(null);
const randomGradient = `linear-gradient(to right, ${generateRandomGrayScaleColor()}, ${generateRandomGrayScaleColor()})`;
@@ -87,26 +90,21 @@ export const VideoThumbnail: React.FC<VideoThumbnailProps> = memo(
)}
>
<div className="flex absolute inset-0 z-10 justify-center items-center">
- {imageUrl.isError || imageStatus === "error" ? (
+ {thumbnailUrl.isError || imageStatus === "error" ? (
<div
className="w-full h-full"
style={{ backgroundImage: randomGradient }}
/>
) : (
- (imageUrl.isPending || imageStatus === "loading") && (
+ (thumbnailUrl.isPending || imageStatus === "loading") && (
<LogoSpinner className="w-5 h-auto animate-spin md:w-8" />
)
)}
</div>
- {videoDuration && (
- <p className="text-white leading-0 px-2 left-3 rounded-full backdrop-blur-sm absolute z-10 bottom-3 bg-black/50 text-[11px]">
- {formatDuration(videoDuration)}
- </p>
- )}
- {imageUrl.data && (
+ {thumbnailUrl.data && (
<Image
ref={imageRef}
- src={imageUrl.data}
+ src={thumbnailUrl.data}
fill={true}
sizes="(max-width: 768px) 100vw, 33vw"
alt={alt}
@@ -121,6 +119,11 @@ export const VideoThumbnail: React.FC<VideoThumbnailProps> = memo(
onError={() => setImageStatus("error")}
/>
)}
+ {videoDuration && (
+ <p className="text-white leading-0 px-2 left-3 rounded-full backdrop-blur-sm absolute z-10 bottom-3 bg-black/50 text-[11px]">
+ {formatDuration(videoDuration)}
+ </p>
+ )}
</div>
);
},
diff --git a/apps/web/lib/EffectRuntime.ts b/apps/web/lib/EffectRuntime.ts
index e9c8bccdf..ba6957b01 100644
--- a/apps/web/lib/EffectRuntime.ts
+++ b/apps/web/lib/EffectRuntime.ts
@@ -5,8 +5,13 @@ import {
makeUseEffectQuery,
} from "./effect-react-query";
import { Rpc } from "./Rpcs";
+import { ThumbnailRequest } from "./ThumbnailRequest";
-const RuntimeLayer = Layer.mergeAll(Rpc.Default, FetchHttpClient.layer);
+export const RuntimeLayer = Layer.mergeAll(
+ ThumbnailRequest.DataLoaderResolver.Default,
+ Rpc.Default,
+ FetchHttpClient.layer,
+);
export type RuntimeLayer = typeof RuntimeLayer;
diff --git a/apps/web/lib/ThumbnailRequest.ts b/apps/web/lib/ThumbnailRequest.ts
new file mode 100644
index 000000000..4e8386f64
--- /dev/null
+++ b/apps/web/lib/ThumbnailRequest.ts
@@ -0,0 +1,54 @@
+import type { Video } from "@cap/web-domain";
+import { dataLoader } from "@effect/experimental/RequestResolver";
+import { Effect, Request, RequestResolver } from "effect";
+import type { NonEmptyArray } from "effect/Array";
+import { Rpc } from "@/lib/Rpcs";
+
+export namespace ThumbnailRequest {
+ export const queryKey = (videoId: string) => ["thumbnail", videoId] as const;
+
+ export class ThumbnailRequest extends Request.Class<
+ string,
+ unknown,
+ { videoId: Video.VideoId }
+ > {}
+
+ export class DataLoaderResolver extends Effect.Service<DataLoaderResolver>()(
+ "ThumbnailRequest/DataLoaderResolver",
+ {
+ scoped: Effect.gen(function* () {
+ const rpc = yield* Rpc;
+
+ const requestResolver = RequestResolver.makeBatched(
+ (requests: NonEmptyArray<ThumbnailRequest>) => {
+ return rpc.VideosGetThumbnails(requests.map((r) => r.videoId)).pipe(
+ Effect.flatMap(
+ // biome-ignore lint/suspicious/useIterableCallbackReturn: effect
+ Effect.forEach((result, index) =>
+ Effect.matchEffect(Effect.flatten(result), {
+ onSuccess: (v) => Request.succeed(requests[index]!, v),
+ onFailure: (e) => Request.fail(requests[index]!, e),
+ }),
+ ),
+ ),
+ Effect.catchAll((error) =>
+ Effect.forEach(
+ requests,
+ (request) => Request.fail(request, error),
+ {
+ discard: true,
+ },
+ ),
+ ),
+ );
+ },
+ );
+
+ return yield* dataLoader(requestResolver, {
+ window: "10 millis",
+ });
+ }),
+ dependencies: [Rpc.Default],
+ },
+ ) {}
+}
diff --git a/apps/web/package.json b/apps/web/package.json
index 15c0625b0..0cb40ac87 100644
--- a/apps/web/package.json
+++ b/apps/web/package.json
@@ -28,6 +28,7 @@
"@deepgram/sdk": "^3.3.4",
"@dub/analytics": "^0.0.27",
"@effect/cluster": "^0.50.4",
+ "@effect/experimental": "^0.56.0",
"@effect/opentelemetry": "^0.58.0",
"@effect/platform": "^0.92.1",
"@effect/platform-node": "^0.98.3",
diff --git a/apps/web/utils/helpers.ts b/apps/web/utils/helpers.ts
index 4a7c174f9..6433d1105 100644
--- a/apps/web/utils/helpers.ts
+++ b/apps/web/utils/helpers.ts
@@ -1,4 +1,4 @@
-import { buildEnv, serverEnv } from "@cap/env";
+import { buildEnv } from "@cap/env";
import { type ClassValue, clsx } from "clsx";
import type { ReadonlyHeaders } from "next/dist/server/web/spec-extension/adapters/headers";
import type { NextRequest } from "next/server";
diff --git a/packages/web-backend/src/Videos/VideosRpcs.ts b/packages/web-backend/src/Videos/VideosRpcs.ts
index c54a3a53c..f27239ea1 100644
--- a/packages/web-backend/src/Videos/VideosRpcs.ts
+++ b/packages/web-backend/src/Videos/VideosRpcs.ts
@@ -1,5 +1,5 @@
import { InternalError, Video } from "@cap/web-domain";
-import { Effect } from "effect";
+import { Effect, Exit, Schema, Unify } from "effect";
import { provideOptionalAuth } from "../Auth.ts";
import { Videos } from "./index.ts";
@@ -43,6 +43,33 @@ export const VideosRpcsLive = Video.VideoRpcs.toLayer(
S3Error: () => new InternalError({ type: "s3" }),
}),
),
+
+ VideosGetThumbnails: (videoIds) =>
+ Effect.all(
+ videoIds.map((id) =>
+ videos.getThumbnailURL(id).pipe(
+ Effect.catchTags({
+ DatabaseError: () => new InternalError({ type: "database" }),
+ S3Error: () => new InternalError({ type: "s3" }),
+ }),
+ Effect.matchEffect({
+ onSuccess: (v) => Effect.succeed(Exit.succeed(v)),
+ onFailure: (e) =>
+ Schema.is(InternalError)(e)
+ ? Effect.fail(e)
+ : Effect.succeed(Exit.fail(e)),
+ }),
+ Effect.map((v) => Unify.unify(v)),
+ ),
+ ),
+ { concurrency: 10 },
+ ).pipe(
+ provideOptionalAuth,
+ Effect.catchTags({
+ DatabaseError: () => new InternalError({ type: "database" }),
+ UnknownException: () => new InternalError({ type: "unknown" }),
+ }),
+ ),
};
}),
);
diff --git a/packages/web-backend/src/Videos/index.ts b/packages/web-backend/src/Videos/index.ts
index 85767cfff..523fd64ff 100644
--- a/packages/web-backend/src/Videos/index.ts
+++ b/packages/web-backend/src/Videos/index.ts
@@ -160,6 +160,38 @@ export class Videos extends Effect.Service<Videos>()("Videos", {
Effect.transposeOption,
);
}),
+
+ getThumbnailURL: Effect.fn("Videos.getThumbnailURL")(function* (
+ videoId: Video.VideoId,
+ ) {
+ const videoOpt = yield* repo
+ .getById(videoId)
+ .pipe(Policy.withPublicPolicy(policy.canView(videoId)));
+
+ return yield* videoOpt.pipe(
+ Effect.transposeMapOption(
+ Effect.fn(function* ([video]) {
+ const [bucket] = yield* S3Buckets.getBucketAccess(video.bucketId);
+
+ const listResponse = yield* bucket.listObjects({
+ prefix: `${video.ownerId}/${video.id}/`,
+ });
+ const contents = listResponse.Contents || [];
+
+ const thumbnailKey = contents.find((item) =>
+ item.Key?.endsWith("screen-capture.jpg"),
+ )?.Key;
+
+ if (!thumbnailKey) return Option.none();
+
+ return Option.some(
+ yield* bucket.getSignedObjectUrl(thumbnailKey),
+ );
+ }),
+ ),
+ Effect.map(Option.flatten),
+ );
+ }),
};
}),
dependencies: [
diff --git a/packages/web-domain/src/Policy.ts b/packages/web-domain/src/Policy.ts
index 05acb769b..bfa3f628a 100644
--- a/packages/web-domain/src/Policy.ts
+++ b/packages/web-domain/src/Policy.ts
@@ -1,7 +1,7 @@
// shoutout https://lucas-barake.github.io/building-a-composable-policy-system/
import { HttpApiSchema } from "@effect/platform";
-import { type Brand, Context, Data, Effect, type Option, Schema } from "effect";
+import { Context, Data, Effect, type Option, Schema } from "effect";
import type { NonEmptyReadonlyArray } from "effect/Array";
import { CurrentUser } from "./Authentication.ts";
diff --git a/packages/web-domain/src/Video.ts b/packages/web-domain/src/Video.ts
index 13b1a402c..cd3fda5df 100644
--- a/packages/web-domain/src/Video.ts
+++ b/packages/web-domain/src/Video.ts
@@ -169,4 +169,21 @@ export class VideoRpcs extends RpcGroup.make(
VerifyVideoPasswordError,
),
}),
+ Rpc.make("VideosGetThumbnails", {
+ payload: Schema.Array(VideoId).pipe(
+ Schema.filter((a) => a.length <= 50 || "Maximum of 50 videos at a time"),
+ ),
+ success: Schema.Array(
+ Schema.Exit({
+ success: Schema.Option(Schema.String),
+ failure: Schema.Union(
+ NotFoundError,
+ PolicyDeniedError,
+ VerifyVideoPasswordError,
+ ),
+ defect: Schema.Unknown,
+ }),
+ ),
+ error: InternalError,
+ }),
) {}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 8f1eaa6e3..f2b39ec0a 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -473,7 +473,10 @@ importers:
version: 0.0.27
'@effect/cluster':
specifier: ^0.50.4
+ '@effect/experimental':
+ specifier: ^0.56.0
'@effect/opentelemetry':
specifier: ^0.58.0
version: 0.58.0(@effect/[email protected]([email protected]))(@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected])([email protected])
@@ -482,13 +485,13 @@ importers:
version: 0.92.1([email protected])
'@effect/platform-node':
specifier: ^0.98.3
'@effect/rpc':
specifier: ^0.71.0
'@effect/sql-mysql2':
specifier: ^0.47.0
'@effect/workflow':
specifier: ^0.11.3
@@ -698,7 +701,7 @@ importers:
next-auth:
specifier: ^4.24.5
next-contentlayer2:
specifier: ^0.5.3
@@ -840,7 +843,7 @@ importers:
version: link:../../packages/web-domain
'@effect/cluster':
specifier: ^0.50.4
'@effect/opentelemetry':
specifier: ^0.58.0
version: 0.58.0(@effect/[email protected]([email protected]))(@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected])([email protected])
@@ -849,16 +852,16 @@ importers:
version: 0.92.1([email protected])
'@effect/platform-node':
specifier: ^0.98.3
'@effect/platform-node-shared':
specifier: ^0.51.4
'@effect/rpc':
specifier: ^0.71.0
'@effect/sql-mysql2':
specifier: ^0.47.0
'@effect/workflow':
specifier: ^0.11.3
@@ -969,7 +972,7 @@ importers:
version: link:../web-domain
'@effect/sql-mysql2':
specifier: ^0.47.0
'@kubiks/otel-drizzle':
specifier: ^2.1.0
version: 2.1.0(@opentelemetry/[email protected])([email protected](@cloudflare/[email protected])(@opentelemetry/[email protected])(@planetscale/[email protected])([email protected]))
@@ -1008,7 +1011,7 @@ importers:
next-auth:
specifier: ^4.24.5
react-email:
specifier: ^4.0.16
@@ -1329,7 +1332,7 @@ importers:
version: link:../web-domain
'@effect/cluster':
specifier: ^0.50.4
'@effect/platform':
specifier: ^0.92.1
version: 0.92.1([email protected])
@@ -1375,7 +1378,7 @@ importers:
devDependencies:
'@effect/platform-node':
specifier: ^0.98.3
packages:
@@ -2143,11 +2146,11 @@ packages:
'@effect/workflow': ^0.11.3
effect: ^3.18.4
- '@effect/[email protected]':
- resolution: {integrity: sha512-UqHMvCQmrZT6kUVoUC0lqyno4Yad+j9hBGCdUjW84zkLwAq08tPqySiZUKRwY+Ae5B2Ab8rISYJH7nQvct9DMQ==}
+ '@effect/[email protected]':
+ resolution: {integrity: sha512-ZT9wTUVyDptzdkW4Tfvz5fNzygW9vt5jWcFmKI9SlhZMu9unVJgsBhxWCNYCyfPnxw3n/Z6SEKsqgt8iKQc4MA==}
peerDependencies:
- '@effect/platform': ^0.90.2
- effect: ^3.17.7
+ '@effect/platform': ^0.92.0
+ effect: ^3.18.0
ioredis: ^5
lmdb: ^3
peerDependenciesMeta:
@@ -15921,15 +15924,15 @@ snapshots:
'@effect-ts/[email protected]': {}
dependencies:
'@effect/platform': 0.92.1([email protected])
'@effect/rpc': 0.71.0(@effect/[email protected]([email protected]))([email protected])
effect: 3.18.4
dependencies:
'@effect/platform': 0.92.1([email protected])
effect: 3.18.4
@@ -15967,12 +15970,12 @@ snapshots:
'@opentelemetry/sdk-trace-node': 2.1.0(@opentelemetry/[email protected])
'@opentelemetry/sdk-trace-web': 2.1.0(@opentelemetry/[email protected])
dependencies:
'@effect/platform': 0.92.1([email protected])
'@effect/rpc': 0.71.0(@effect/[email protected]([email protected]))([email protected])
'@parcel/watcher': 2.5.1
effect: 3.18.4
multipasta: 0.2.7
@@ -15981,13 +15984,13 @@ snapshots:
- bufferutil
- utf-8-validate
dependencies:
'@effect/platform': 0.92.1([email protected])
'@effect/rpc': 0.71.0(@effect/[email protected]([email protected]))([email protected])
effect: 3.18.4
mime: 3.0.0
undici: 7.16.0
@@ -16009,17 +16012,17 @@ snapshots:
effect: 3.18.4
msgpackr: 1.11.5
dependencies:
- '@effect/experimental': 0.54.6(@effect/[email protected]([email protected]))([email protected])([email protected])
+ '@effect/experimental': 0.56.0(@effect/[email protected]([email protected]))([email protected])([email protected])
'@effect/platform': 0.92.1([email protected])
effect: 3.18.4
mysql2: 3.15.2
dependencies:
- '@effect/experimental': 0.54.6(@effect/[email protected]([email protected]))([email protected])([email protected])
+ '@effect/experimental': 0.56.0(@effect/[email protected]([email protected]))([email protected])([email protected])
'@effect/platform': 0.92.1([email protected])
effect: 3.18.4
uuid: 11.1.0
@@ -26488,7 +26491,7 @@ snapshots:
p-wait-for: 5.0.2
qs: 6.14.0
dependencies:
'@babel/runtime': 7.27.1
'@panva/hkdf': 1.2.1