Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat(web): wait for media server completion via upload state

Richie McIlroy4d1168462dda
diff --git a/apps/web/workflows/process-video.ts b/apps/web/workflows/process-video.ts
index 4701ab60f..e516b6586 100644
--- a/apps/web/workflows/process-video.ts
+++ b/apps/web/workflows/process-video.ts
@@ -111,6 +111,14 @@ interface MediaServerProcessResult {
const MEDIA_SERVER_START_MAX_ATTEMPTS = 6;
const MEDIA_SERVER_START_RETRY_BASE_MS = 2000;
+const MEDIA_SERVER_COMPLETION_MAX_ATTEMPTS = 720;
+const MEDIA_SERVER_COMPLETION_POLL_INTERVAL_MS = 5000;
+const MEDIA_SERVER_PRESIGNED_GET_EXPIRES_SECONDS = 3 * 60 * 60;
+const MEDIA_SERVER_PRESIGNED_PUT_EXPIRES_SECONDS = 3 * 60 * 60;
+
+function isPositiveNumber(value: number | null): value is number {
+ return typeof value === "number" && Number.isFinite(value) && value > 0;
+}
function getInputExtension(rawFileKey: string): string {
const parts = rawFileKey.split(".");
@@ -238,28 +246,38 @@ async function processVideoOnMediaServer(
await Storage.getAccessForVideo(videoDomain).pipe(runPromise);
const rawVideoUrl = await bucket
- .getInternalSignedObjectUrl(rawFileKey)
+ .getInternalSignedObjectUrl(rawFileKey, {
+ expiresIn: MEDIA_SERVER_PRESIGNED_GET_EXPIRES_SECONDS,
+ })
.pipe(runPromise);
const outputKey = `${userId}/${videoId}/result.mp4`;
const thumbnailKey = `${userId}/${videoId}/screenshot/screen-capture.jpg`;
const outputPresignedUrl = await bucket
- .getInternalPresignedPutUrl(outputKey, {
- ContentType: "video/mp4",
- })
+ .getInternalPresignedPutUrl(
+ outputKey,
+ {
+ ContentType: "video/mp4",
+ },
+ { expiresIn: MEDIA_SERVER_PRESIGNED_PUT_EXPIRES_SECONDS },
+ )
.pipe(runPromise);
const thumbnailPresignedUrl = await bucket
- .getInternalPresignedPutUrl(thumbnailKey, {
- ContentType: "image/jpeg",
- })
+ .getInternalPresignedPutUrl(
+ thumbnailKey,
+ {
+ ContentType: "image/jpeg",
+ },
+ { expiresIn: MEDIA_SERVER_PRESIGNED_PUT_EXPIRES_SECONDS },
+ )
.pipe(runPromise);
const webhookUrl = `${webhookBaseUrl}/api/webhooks/media-server/progress`;
const webhookSecret = serverEnv().MEDIA_SERVER_WEBHOOK_SECRET;
- const jobId = await startMediaServerProcessJob(mediaServerUrl, {
+ await startMediaServerProcessJob(mediaServerUrl, {
videoId,
userId,
videoUrl: rawVideoUrl,
@@ -270,65 +288,103 @@ async function processVideoOnMediaServer(
inputExtension: getInputExtension(rawFileKey),
});
- const result = await pollForCompletion(mediaServerUrl, jobId);
-
- return result;
+ return await waitForProcessingCompletion(videoId);
}
-async function pollForCompletion(
- mediaServerUrl: string,
- jobId: string,
-): Promise<MediaServerProcessResult> {
- const maxAttempts = 360;
- const pollIntervalMs = 5000;
-
- for (let attempt = 0; attempt < maxAttempts; attempt++) {
- await new Promise((resolve) => setTimeout(resolve, pollIntervalMs));
+function getMetadataFromVideoRow(
+ video:
+ | {
+ duration: number | null;
+ width: number | null;
+ height: number | null;
+ fps: number | null;
+ }
+ | undefined,
+): MediaServerProcessResult["metadata"] | null {
+ if (
+ !video ||
+ !isPositiveNumber(video.width) ||
+ !isPositiveNumber(video.height) ||
+ !isPositiveNumber(video.fps)
+ ) {
+ return null;
+ }
- const response = await fetch(
- `${mediaServerUrl}/video/process/${jobId}/status`,
- {
- method: "GET",
- headers: { Accept: "application/json" },
- },
- );
+ return {
+ duration: isPositiveNumber(video.duration) ? video.duration : 0,
+ width: video.width,
+ height: video.height,
+ fps: video.fps,
+ };
+}
- if (!response.ok) {
- console.warn(
- `[process-video] Failed to get job status: ${response.status}`,
- );
- continue;
- }
+async function getCompletedMetadata(
+ videoId: string,
+): Promise<MediaServerProcessResult["metadata"] | null> {
+ const [video] = await db()
+ .select({
+ duration: videos.duration,
+ width: videos.width,
+ height: videos.height,
+ fps: videos.fps,
+ })
+ .from(videos)
+ .where(eq(videos.id, videoId as Video.VideoId));
- const status = (await response.json()) as {
- phase: string;
- progress: number;
- error?: string;
- metadata?: {
- duration: number;
- width: number;
- height: number;
- fps: number;
- };
- };
+ return getMetadataFromVideoRow(video);
+}
- if (status.phase === "complete") {
- if (!status.metadata) {
- throw new Error("Processing completed but no metadata returned");
+async function waitForProcessingCompletion(
+ videoId: string,
+): Promise<MediaServerProcessResult> {
+ let lastStatus = "processing";
+
+ for (
+ let attempt = 0;
+ attempt < MEDIA_SERVER_COMPLETION_MAX_ATTEMPTS;
+ attempt++
+ ) {
+ await waitForRetry(MEDIA_SERVER_COMPLETION_POLL_INTERVAL_MS);
+
+ const [upload] = await db()
+ .select({
+ phase: videoUploads.phase,
+ processingProgress: videoUploads.processingProgress,
+ processingMessage: videoUploads.processingMessage,
+ processingError: videoUploads.processingError,
+ })
+ .from(videoUploads)
+ .where(eq(videoUploads.videoId, videoId as Video.VideoId));
+
+ if (!upload || upload.phase === "complete") {
+ const metadata = await getCompletedMetadata(videoId);
+ if (!metadata) {
+ throw new Error("Processing completed but video metadata is missing");
}
- return { metadata: status.metadata };
- }
- if (status.phase === "error") {
- throw new Error(status.error || "Video processing failed");
+ return { metadata };
}
- if (status.phase === "cancelled") {
- throw new Error("Video processing was cancelled");
+ if (upload.phase === "error") {
+ throw new Error(
+ upload.processingError ||
+ upload.processingMessage ||
+ "Video processing failed",
+ );
}
+
+ lastStatus = [
+ upload.phase,
+ typeof upload.processingProgress === "number"
+ ? `${upload.processingProgress}%`
+ : null,
+ upload.processingMessage,
+ ]
+ .filter(Boolean)
+ .join(" ");
}
- throw new Error("Video processing timed out");
+ throw new Error(`Video processing timed out while ${lastStatus}`);
}
async function saveMetadataAndComplete(