Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat(web api): route multipart uploads through Storage access layer

Richie McIlroy65fac13e2549
diff --git a/apps/web/app/api/upload/[...route]/multipart.ts b/apps/web/app/api/upload/[...route]/multipart.ts
index 65871e752..e4bfd05d1 100644
--- a/apps/web/app/api/upload/[...route]/multipart.ts
+++ b/apps/web/app/api/upload/[...route]/multipart.ts
@@ -5,7 +5,7 @@ import {
Database,
makeCurrentUserLayer,
provideOptionalAuth,
- S3Buckets,
+ Storage,
VideosPolicy,
VideosRepo,
} from "@cap/web-backend";
@@ -16,6 +16,7 @@ import { Effect, Option, Schedule } from "effect";
import { Hono, type MiddlewareHandler } from "hono";
import { z } from "zod";
import { withAuth } from "@/app/api/utils";
+import { invalidateGoogleDriveStorageQuotaCache } from "@/lib/google-drive-storage-quota";
import { runPromise } from "@/lib/server";
import { startVideoProcessingWorkflow } from "@/lib/video-processing";
import { stringOrNumberOptional } from "@/utils/zod";
@@ -121,7 +122,16 @@ app.post(
try {
try {
const uploadId = await Effect.gen(function* () {
- const [bucket] = yield* S3Buckets.getBucketAccessForUser(user.id);
+ const repo = yield* VideosRepo;
+ const policy = yield* VideosPolicy;
+ const maybeVideo = yield* repo
+ .getById(videoId)
+ .pipe(Policy.withPolicy(policy.isOwner(videoId)));
+ if (Option.isNone(maybeVideo)) {
+ return yield* new Video.NotFoundError();
+ }
+ const [video] = maybeVideo.value;
+ const [bucket] = yield* Storage.getAccessForVideo(video);
const finalContentType = contentType || "video/mp4";
console.log(
@@ -148,10 +158,14 @@ app.post(
`Upload details: Bucket=${bucket.bucketName}, Key=${fileKey}, ContentType=${finalContentType}`,
);
- return UploadId;
- }).pipe(provideOptionalAuth, runPromiseAnyEnv);
+ return { uploadId: UploadId, provider: bucket.provider };
+ }).pipe(
+ Effect.provide(makeCurrentUserLayer(user)),
+ provideOptionalAuth,
+ runPromiseAnyEnv,
+ );
- return c.json({ uploadId: uploadId });
+ return c.json(uploadId);
} catch (s3Error) {
console.error("S3 operation failed:", s3Error);
throw new Error(
@@ -201,7 +215,21 @@ app.post(
try {
try {
const presignedUrl = await Effect.gen(function* () {
- const [bucket] = yield* S3Buckets.getBucketAccessForUser(user.id);
+ const videoIdFromFileKey = fileKey.split("/")[1];
+ const videoIdRaw =
+ "videoId" in body ? body.videoId : videoIdFromFileKey;
+ if (!videoIdRaw) throw new Error("Video id not found");
+ const videoId = Video.VideoId.make(videoIdRaw);
+ const repo = yield* VideosRepo;
+ const policy = yield* VideosPolicy;
+ const maybeVideo = yield* repo
+ .getById(videoId)
+ .pipe(Policy.withPolicy(policy.isOwner(videoId)));
+ if (Option.isNone(maybeVideo)) {
+ return yield* new Video.NotFoundError();
+ }
+ const [video] = maybeVideo.value;
+ const [bucket] = yield* Storage.getAccessForVideo(video);
console.log(
`Getting presigned URL for part ${partNumber} of upload ${uploadId}`,
@@ -215,10 +243,14 @@ app.post(
{ ContentMD5: body.md5Sum },
);
- return presignedUrl;
- }).pipe(provideOptionalAuth, runPromiseAnyEnv);
+ return { presignedUrl, provider: bucket.provider };
+ }).pipe(
+ Effect.provide(makeCurrentUserLayer(user)),
+ provideOptionalAuth,
+ runPromiseAnyEnv,
+ );
- return c.json({ presignedUrl });
+ return c.json(presignedUrl);
} catch (s3Error) {
console.error("S3 operation failed:", s3Error);
throw new Error(
@@ -294,7 +326,7 @@ app.post(
const [video] = maybeVideo.value;
return yield* Effect.gen(function* () {
- const [bucket] = yield* S3Buckets.getBucketAccess(video.bucketId);
+ const [bucket] = yield* Storage.getAccessForVideo(video);
const { result, formattedParts } = yield* Effect.gen(function* () {
console.log(
@@ -342,6 +374,11 @@ app.post(
Parts: formattedParts,
},
});
+ yield* Effect.promise(() =>
+ invalidateGoogleDriveStorageQuotaCache(
+ Option.getOrNull(video.storageIntegrationId),
+ ),
+ );
return { result, formattedParts };
});
@@ -419,30 +456,32 @@ app.post(
});
}
- console.log(
- "Performing metadata fix by copying the object to itself...",
- );
+ if (bucket.provider === "s3") {
+ console.log(
+ "Performing metadata fix by copying the object to itself...",
+ );
- yield* bucket
- .copyObject(`${bucket.bucketName}/${fileKey}`, fileKey, {
- ContentType: "video/mp4",
- MetadataDirective: "REPLACE",
- })
- .pipe(
- Effect.tap((result) =>
- Effect.log("Copy for metadata fix successful:", result),
- ),
- Effect.catchAll((e) =>
- Effect.logError(
- "Warning: Failed to copy object to fix metadata:",
- e,
+ yield* bucket
+ .copyObject(`${bucket.bucketName}/${fileKey}`, fileKey, {
+ ContentType: "video/mp4",
+ MetadataDirective: "REPLACE",
+ })
+ .pipe(
+ Effect.tap((result) =>
+ Effect.log("Copy for metadata fix successful:", result),
),
- ),
- Effect.retry({
- times: 3,
- schedule: Schedule.exponential("50 millis"),
- }),
- );
+ Effect.catchAll((e) =>
+ Effect.logError(
+ "Warning: Failed to copy object to fix metadata:",
+ e,
+ ),
+ ),
+ Effect.retry({
+ times: 3,
+ schedule: Schedule.exponential("50 millis"),
+ }),
+ );
+ }
yield* db.use((db) =>
db.transaction(() =>
@@ -474,7 +513,11 @@ app.post(
);
const mediaServerUrl = serverEnv().MEDIA_SERVER_URL;
- if (video.source.type === "webMP4" && mediaServerUrl) {
+ if (
+ bucket.provider === "s3" &&
+ video.source.type === "webMP4" &&
+ mediaServerUrl
+ ) {
const inputUrl = yield* bucket.getInternalSignedObjectUrl(fileKey);
const outputPresignedUrl = yield* bucket.getInternalPresignedPutUrl(
fileKey,
@@ -598,7 +641,7 @@ app.post("/abort", abortRequestValidator, (c) => {
}
const [video] = maybeVideo.value;
- const [bucket] = yield* S3Buckets.getBucketAccess(video.bucketId);
+ const [bucket] = yield* Storage.getAccessForVideo(video);
type MultipartWithAbort = typeof bucket.multipart & {
abort: (
...args: Parameters<typeof bucket.multipart.complete>
diff --git a/apps/web/app/api/upload/[...route]/recording-complete.ts b/apps/web/app/api/upload/[...route]/recording-complete.ts
index ce5515b9a..d8e8afd8c 100644
--- a/apps/web/app/api/upload/[...route]/recording-complete.ts
+++ b/apps/web/app/api/upload/[...route]/recording-complete.ts
@@ -1,14 +1,16 @@
import { db } from "@cap/database";
import * as Db from "@cap/database/schema";
import { serverEnv } from "@cap/env";
-import { S3Buckets } from "@cap/web-backend";
-import { S3Bucket, Video } from "@cap/web-domain";
+import { Storage } from "@cap/web-backend";
+import { Video } from "@cap/web-domain";
import { zValidator } from "@hono/zod-validator";
import { and, eq, notInArray } from "drizzle-orm";
import { Effect, Option, Schema } from "effect";
import { Hono } from "hono";
import { z } from "zod";
+import { invalidateGoogleDriveStorageQuotaCache } from "@/lib/google-drive-storage-quota";
import { runPromise } from "@/lib/server";
+import { decodeStorageVideo } from "@/lib/video-storage";
import { withAuth } from "../../utils";
export const app = new Hono().post(
@@ -48,16 +50,16 @@ export const app = new Hono().post(
await db()
.delete(Db.videoUploads)
.where(eq(Db.videoUploads.videoId, videoId));
+ await invalidateGoogleDriveStorageQuotaCache(video.storageIntegrationId);
return c.json({ success: true });
}
try {
const muxPayload = await Effect.gen(function* () {
- const bucketId = Option.fromNullable(video.bucket).pipe(
- Option.map(S3Bucket.S3BucketId.make),
+ const [bucket] = yield* Storage.getAccessForVideo(
+ decodeStorageVideo(video),
);
- const [bucket] = yield* S3Buckets.getBucketAccess(bucketId);
const segSource = new Video.SegmentsSource({
videoId: videoIdRaw,
@@ -70,7 +72,7 @@ export const app = new Hono().post(
Effect.andThen(
Option.match({
onNone: () =>
- Effect.fail(new Error("Segment manifest not found on S3")),
+ Effect.fail(new Error("Segment manifest not found")),
onSome: (c) => Effect.succeed(c),
}),
),
@@ -164,6 +166,7 @@ export const app = new Hono().post(
audioSegmentUrls,
};
}).pipe(runPromise);
+ await invalidateGoogleDriveStorageQuotaCache(video.storageIntegrationId);
const claimResult = await db()
.update(Db.videoUploads)
diff --git a/apps/web/app/api/upload/[...route]/signed.ts b/apps/web/app/api/upload/[...route]/signed.ts
index 420ef1e11..31d58562b 100644
--- a/apps/web/app/api/upload/[...route]/signed.ts
+++ b/apps/web/app/api/upload/[...route]/signed.ts
@@ -1,20 +1,23 @@
-import type { PresignedPost } from "@aws-sdk/s3-presigned-post";
import { db, updateIfDefined } from "@cap/database";
import * as Db from "@cap/database/schema";
-import { S3Buckets } from "@cap/web-backend";
+import { Storage } from "@cap/web-backend";
import { Video } from "@cap/web-domain";
import { zValidator } from "@hono/zod-validator";
import { and, eq } from "drizzle-orm";
-import { Effect, Option } from "effect";
+import { Effect } from "effect";
import { Hono } from "hono";
import { z } from "zod";
import { runPromise } from "@/lib/server";
+import { decodeStorageVideo } from "@/lib/video-storage";
import { isFromDesktopSemver, UPLOAD_PROGRESS_VERSION } from "@/utils/desktop";
import { stringOrNumberOptional } from "@/utils/zod";
import { withAuth } from "../../utils";
import { parseVideoIdOrFileKey } from "../utils";
+const decodeVideo = (video: typeof Db.videos.$inferSelect) =>
+ decodeStorageVideo(video);
+
function contentTypeForSubpath(subpath: string): string {
if (subpath.endsWith(".json")) return "application/json";
if (subpath.endsWith(".mp4") || subpath.endsWith(".m4s")) return "video/mp4";
@@ -52,31 +55,34 @@ app.post(
const { videoId, subpaths } = c.req.valid("json");
try {
- const [customBucket] = await db()
+ const [video] = await db()
.select()
- .from(Db.s3Buckets)
- .where(eq(Db.s3Buckets.ownerId, user.id));
+ .from(Db.videos)
+ .where(eq(Db.videos.id, Video.VideoId.make(videoId)));
+
+ if (!video) return c.json({ error: "Video not found" }, 404);
+ if (video.ownerId !== user.id) return c.json({ error: "Forbidden" }, 403);
+ const videoDomain = decodeVideo(video);
const urls = await Effect.gen(function* () {
- const [bucket] = yield* S3Buckets.getBucketAccess(
- Option.fromNullable(customBucket?.id),
- );
+ const [bucket] = yield* Storage.getAccessForVideo(videoDomain);
const entries = yield* Effect.all(
subpaths.map((subpath) => {
const fileKey = `${user.id}/${videoId}/${subpath}`;
return bucket
- .getPresignedPutUrl(
- fileKey,
- { ContentType: contentTypeForSubpath(subpath) },
- { expiresIn: 1800 },
- )
+ .createUploadTarget(fileKey, {
+ contentType: contentTypeForSubpath(subpath),
+ method: "put",
+ })
.pipe(Effect.map((url) => [subpath, url] as const));
}),
{ concurrency: "unbounded" },
);
- return Object.fromEntries(entries);
+ return Object.fromEntries(
+ entries.map(([subpath, upload]) => [subpath, upload.url]),
+ );
}).pipe(runPromise);
return c.json({ urls });
@@ -113,12 +119,19 @@ app.post(
c.req.valid("json");
const fileKey = parseVideoIdOrFileKey(user.id, body);
+ const videoIdFromKey = fileKey.split("/")[1];
+ const videoIdToUse = "videoId" in body ? body.videoId : videoIdFromKey;
+ if (!videoIdToUse) return c.json({ error: "Video id not found" }, 400);
try {
- const [customBucket] = await db()
+ const [video] = await db()
.select()
- .from(Db.s3Buckets)
- .where(eq(Db.s3Buckets.ownerId, user.id));
+ .from(Db.videos)
+ .where(eq(Db.videos.id, Video.VideoId.make(videoIdToUse)));
+
+ if (!video) return c.json({ error: "Video not found" }, 404);
+ if (video.ownerId !== user.id) return c.json({ error: "Forbidden" }, 403);
+ const videoDomain = decodeVideo(video);
const contentType = fileKey.endsWith(".aac")
? "audio/aac"
@@ -133,45 +146,24 @@ app.post(
: "video/mp2t";
const data = await Effect.gen(function* () {
- const [bucket] = yield* S3Buckets.getBucketAccess(
- Option.fromNullable(customBucket?.id),
- );
-
- if (method === "post") {
- const Fields = {
- "Content-Type": contentType,
- "x-amz-meta-userid": user.id,
- "x-amz-meta-duration": durationInSecs
- ? durationInSecs.toString()
- : "",
- };
-
- return yield* bucket.getPresignedPostUrl(fileKey, {
- Fields,
- Expires: 1800,
- });
- }
-
- const presignedUrl = yield* bucket.getPresignedPutUrl(
- fileKey,
- {
- ContentType: contentType,
- Metadata: {
- userid: user.id,
- duration: durationInSecs ? durationInSecs.toString() : "",
- },
- },
- { expiresIn: 1800 },
- );
-
- return { url: presignedUrl, fields: {} } satisfies PresignedPost;
+ const [bucket] = yield* Storage.getAccessForVideo(videoDomain);
+
+ const Fields = {
+ "x-amz-meta-userid": user.id,
+ "x-amz-meta-duration": durationInSecs
+ ? durationInSecs.toString()
+ : "",
+ };
+
+ return yield* bucket.createUploadTarget(fileKey, {
+ contentType,
+ fields: Fields,
+ method,
+ });
}).pipe(runPromise);
console.log("Presigned URL created successfully");
- const videoIdFromKey = fileKey.split("/")[1];
-
- const videoIdToUse = "videoId" in body ? body.videoId : videoIdFromKey;
if (videoIdToUse) {
const videoId = Video.VideoId.make(videoIdToUse);
await db()
@@ -197,8 +189,19 @@ app.post(
.where(eq(Db.videoUploads.videoId, videoId));
}
- if (method === "post") return c.json({ presignedPostData: data });
- else return c.json({ presignedPutData: data });
+ if (data.type === "s3Post") {
+ return c.json({
+ presignedPostData: { url: data.url, fields: data.fields },
+ });
+ }
+ return c.json({
+ presignedPutData: {
+ url: data.url,
+ fields: {},
+ headers: data.headers,
+ type: data.type,
+ },
+ });
} catch (s3Error) {
console.error("S3 operation failed:", s3Error);
throw new Error(