Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
do cloudfront invalidation in multipart upload complete
Brendan Allanb67f94f419b7
diff --git a/apps/web/app/api/upload/[...route]/multipart.ts b/apps/web/app/api/upload/[...route]/multipart.tsindex 9130c82fd..f2b455264 100644--- a/apps/web/app/api/upload/[...route]/multipart.ts+++ b/apps/web/app/api/upload/[...route]/multipart.ts@@ -1,11 +1,15 @@+import {+ CloudFrontClient,+ CreateInvalidationCommand,+} from "@aws-sdk/client-cloudfront";import { db, updateIfDefined } from "@cap/database";-import { videos, videoUploads } from "@cap/database/schema";+import * as Db from "@cap/database/schema";import { serverEnv } from "@cap/env";-import { S3Buckets } from "@cap/web-backend";+import { AwsCredentials, Database, S3Buckets, Videos } from "@cap/web-backend";import { Video } from "@cap/web-domain";import { zValidator } from "@hono/zod-validator";import { and, eq } from "drizzle-orm";-import { Effect } from "effect";+import { Effect, Option, Schedule } from "effect";import { Hono } from "hono";import { z } from "zod";import { withAuth } from "@/app/api/utils";@@ -187,22 +191,36 @@ app.post(]),),),- async (c) => {- const { uploadId, parts, ...body } = c.req.valid("json");- const user = c.get("user");-- const fileKey = parseVideoIdOrFileKey(user.id, {- ...body,- subpath: "result.mp4",- });+ (c) =>+ Effect.gen(function* () {+ const videos = yield* Videos;+ const db = yield* Database;++ const { uploadId, parts, ...body } = c.req.valid("json");+ const user = c.get("user");++ const fileKey = parseVideoIdOrFileKey(user.id, {+ ...body,+ subpath: "result.mp4",+ });++ const videoIdFromFileKey = fileKey.split("/")[1];+ const videoId = "videoId" in body ? body.videoId : videoIdFromFileKey;+ if (!videoId) throw new Error("Video ID is required");++ const maybeVideo = yield* videos.getById(Video.VideoId.make(videoId));+ if (Option.isNone(maybeVideo)) {+ c.status(404);+ return c.text("Video not found");+ }+ const [video] = maybeVideo.value;- try {- try {- const [bucket] = await S3Buckets.getBucketAccessForUser(user.id).pipe(- runPromise,+ return yield* Effect.gen(function* () {+ const [bucket, customBucket] = yield* S3Buckets.getBucketAccess(+ video.bucketId,);- const { result, formattedParts } = await Effect.gen(function* () {+ const { result, formattedParts } = yield* Effect.gen(function* () {console.log(`Completing multipart upload ${uploadId} with ${parts.length} parts for key: ${fileKey}`,);@@ -250,9 +268,9 @@ app.post(});return { result, formattedParts };- }).pipe(runPromise);+ });- try {+ return yield* Effect.gen(function* () {console.log(`Multipart upload completed successfully: ${result.Location || "no location"@@ -260,66 +278,111 @@ app.post();console.log(`Complete response: ${JSON.stringify(result, null, 2)}`);- await Effect.gen(function* () {- console.log(- "Performing metadata fix by copying the object to itself...",+ 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,+ ),+ ),+ Effect.retry({+ times: 3,+ schedule: Schedule.exponential("50 millis"),+ }),);- yield* bucket- .copyObject(`${bucket.bucketName}/${fileKey}`, fileKey, {- ContentType: "video/mp4",- MetadataDirective: "REPLACE",- })- .pipe(- Effect.tap((result) =>- Effect.log("Copy for metadata fix successful:", result),+ yield* bucket.headObject(fileKey).pipe(+ Effect.tap((headResult) =>+ Effect.log(+ `Object verification successful: ContentType=${headResult.ContentType}, ContentLength=${headResult.ContentLength}`,+ ),+ ),+ Effect.catchAll((headError) =>+ Effect.logError(`Warning: Unable to verify object: ${headError}`),+ ),+ Effect.retry({+ times: 3,+ schedule: Schedule.exponential("50 millis"),+ }),+ );++ yield* db.use((db) =>+ db.transaction(() =>+ Promise.all([+ db+ .update(Db.videos)+ .set({+ duration: updateIfDefined(+ body.durationInSecs,+ Db.videos.duration,+ ),+ width: updateIfDefined(body.width, Db.videos.width),+ height: updateIfDefined(body.height, Db.videos.height),+ fps: updateIfDefined(body.fps, Db.videos.fps),+ })+ .where(+ and(+ eq(Db.videos.id, Video.VideoId.make(videoId)),+ eq(Db.videos.ownerId, user.id),+ ),+ ),+ db+ .delete(Db.videoUploads)+ .where(+ eq(Db.videoUploads.videoId, Video.VideoId.make(videoId)),+ ),+ ]),+ ),+ );++ if (Option.isNone(customBucket)) {+ const distributionId = serverEnv().CAP_CLOUDFRONT_DISTRIBUTION_ID;+ if (distributionId) {+ const cloudfront = new CloudFrontClient({+ region: serverEnv().CAP_AWS_REGION || "us-east-1",+ credentials: yield* Effect.map(+ AwsCredentials,+ (c) => c.credentials,),+ });++ const pathToInvalidate = "/" + fileKey;++ yield* Effect.promise(() =>+ cloudfront.send(+ new CreateInvalidationCommand({+ DistributionId: distributionId,+ InvalidationBatch: {+ CallerReference: `${Date.now()}`,+ Paths: {+ Quantity: 1,+ Items: [pathToInvalidate],+ },+ },+ }),+ ),+ ).pipe(Effect.catchAll((e) =>Effect.logError(- "Warning: Failed to copy object to fix metadata:",+ "Failed to create CloudFront invalidation:",e,),),+ Effect.withSpan("CloudFrontInvalidation"),);-- yield* bucket.headObject(fileKey).pipe(- Effect.tap((headResult) =>- Effect.log(- `Object verification successful: ContentType=${headResult.ContentType}, ContentLength=${headResult.ContentLength}`,- ),- ),- Effect.catchAll((headError) =>- Effect.logError(- `Warning: Unable to verify object: ${headError}`,- ),- ),- );- }).pipe(runPromise);-- const videoIdFromFileKey = fileKey.split("/")[1];-- const videoId = "videoId" in body ? body.videoId : videoIdFromFileKey;- if (videoId) {- const [result] = await db()- .update(videos)- .set({- duration: updateIfDefined(body.durationInSecs, videos.duration),- width: updateIfDefined(body.width, videos.width),- height: updateIfDefined(body.height, videos.height),- fps: updateIfDefined(body.fps, videos.fps),- })- .where(- and(- eq(videos.id, Video.VideoId.make(videoId)),- eq(videos.ownerId, user.id),- ),- );-- // This proves authentication- if (result.affectedRows > 0)- await db()- .delete(videoUploads)- .where(eq(videoUploads.videoId, Video.VideoId.make(videoId)));+ }}return c.json({@@ -327,39 +390,43 @@ app.post(success: true,fileKey,});- } catch (completeError) {- console.error("Failed to complete multipart upload:", completeError);- return c.json(- {- error: "Failed to complete multipart upload",- details:- completeError instanceof Error- ? completeError.message- : String(completeError),- uploadId,- fileKey,- parts: formattedParts.length,- },- 500,- );- }- } catch (s3Error) {- console.error("S3 operation failed:", s3Error);- throw new Error(- `S3 operation failed: ${- s3Error instanceof Error ? s3Error.message : "Unknown error"- }`,+ }).pipe(+ Effect.catchAllCause((completeError) => {+ console.error(+ "Failed to complete multipart upload:",+ completeError,+ );+ return Effect.succeed(+ c.json(+ {+ error: "Failed to complete multipart upload",+ details:+ completeError instanceof Error+ ? completeError.message+ : String(completeError),+ uploadId,+ fileKey,+ parts: formattedParts.length,+ },+ 500,+ ),+ );+ }),);- }- } catch (error) {- console.error("Error completing multipart upload", error);- return c.json(- {- error: "Error completing multipart upload",- details: error instanceof Error ? error.message : String(error),- },- 500,+ }).pipe(+ Effect.catchAll((error) => {+ console.error("Multipart upload failed:", error);++ return Effect.succeed(+ c.json(+ {+ error: "Error completing multipart upload",+ details: error instanceof Error ? error.message : String(error),+ },+ 500,+ ),+ );+ }),);- }- },+ }).pipe(runPromise),);