Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

fix(recorder): align streamed multipart uploads for R2

Richie McIlroyb215b9bc2d37
diff --git a/packages/recorder-core/__tests__/instant-recording-uploader.test.ts b/packages/recorder-core/__tests__/instant-recording-uploader.test.ts
index 0a07cccd6..7951064e8 100644
--- a/packages/recorder-core/__tests__/instant-recording-uploader.test.ts
+++ b/packages/recorder-core/__tests__/instant-recording-uploader.test.ts
@@ -1,3 +1,4 @@
+import { createHash } from "node:crypto";
import {
InstantRecordingUploader,
MultipartCompletionUncertainError,
@@ -5,9 +6,9 @@ import {
import type { VideoId } from "@cap/recorder-core/recorder-types";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-const STREAMED_PART_BYTES = 5 * 1024 * 1024 + 128;
+const STREAMED_PART_BYTES = 5 * 1024 * 1024;
const DRIVE_PART_BYTES = 16 * 1024 * 1024;
-const OVERFLOW_PART_BYTES = 129 * 1024 * 1024;
+const OVERFLOW_PART_BYTES = 130 * 1024 * 1024;
const FINALIZED_BLOB_BYTES = 129 * 1024 * 1024;
type UploadOutcome =
@@ -19,6 +20,7 @@ class MockXMLHttpRequest {
static outcomes: UploadOutcome[] = [];
static abortedCount = 0;
static recordedHeaders: Array<Map<string, string>> = [];
+ static recordedParts: Blob[] = [];
upload = {
onprogress: null as ((event: ProgressEvent<EventTarget>) => void) | null,
@@ -37,6 +39,7 @@ class MockXMLHttpRequest {
MockXMLHttpRequest.outcomes = [...outcomes];
MockXMLHttpRequest.abortedCount = 0;
MockXMLHttpRequest.recordedHeaders = [];
+ MockXMLHttpRequest.recordedParts = [];
}
open() {}
@@ -51,6 +54,7 @@ class MockXMLHttpRequest {
send(part: Blob) {
MockXMLHttpRequest.recordedHeaders.push(new Map(this.headers));
+ MockXMLHttpRequest.recordedParts.push(part);
const outcome = MockXMLHttpRequest.outcomes.shift();
if (!outcome) {
@@ -115,6 +119,91 @@ describe("InstantRecordingUploader", () => {
vi.useRealTimers();
});
+ it.each([
+ [
+ STREAMED_PART_BYTES + 128,
+ STREAMED_PART_BYTES + 333,
+ 11 * 1024 * 1024 + 777,
+ ],
+ [STREAMED_PART_BYTES - 100, 100, STREAMED_PART_BYTES],
+ [123, 456],
+ ])(
+ "preserves bytes while aligning variable capture chunks %j for R2",
+ async (...sizes) => {
+ const chunks = sizes.map(
+ (size, index) =>
+ new Blob([new Uint8Array(size).fill(index + 1)], {
+ type: "video/webm",
+ }),
+ );
+ const totalBytes = sizes.reduce((total, size) => total + size, 0);
+ const expectedSizes = Array.from(
+ { length: Math.ceil(totalBytes / STREAMED_PART_BYTES) },
+ (_, index) =>
+ Math.min(
+ STREAMED_PART_BYTES,
+ totalBytes - index * STREAMED_PART_BYTES,
+ ),
+ );
+ let completedParts: unknown;
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
+ const body = JSON.parse(String(init?.body));
+ if (input.toString().endsWith("/presign-part")) {
+ return makeJsonResponse({
+ presignedUrl: `https://uploads.example/part-${body.partNumber}`,
+ });
+ }
+ expect(input.toString()).toBe("/api/upload/multipart/complete");
+ completedParts = body.parts;
+ return makeJsonResponse({ success: true });
+ }),
+ );
+ MockXMLHttpRequest.setOutcomes(
+ expectedSizes.map((_, index) => ({
+ type: "success",
+ etag: `etag-${index + 1}`,
+ })),
+ );
+ const uploader = new InstantRecordingUploader({
+ videoId,
+ uploadId: "upload-r2",
+ provider: "s3",
+ mimeType: "video/webm",
+ subpath: "raw-upload.webm",
+ setUploadStatus: vi.fn(),
+ sendProgressUpdate: vi.fn().mockResolvedValue(undefined),
+ });
+ let recordedBytes = 0;
+ for (const chunk of chunks) {
+ recordedBytes += chunk.size;
+ uploader.handleChunk(chunk, recordedBytes);
+ }
+ await uploader.finalize({
+ durationSeconds: 50 * 60,
+ subpath: "raw-upload.webm",
+ });
+ expect(completedParts).toEqual(
+ expectedSizes.map((size, index) => ({
+ partNumber: index + 1,
+ etag: `etag-${index + 1}`,
+ size,
+ })),
+ );
+ expect(MockXMLHttpRequest.recordedParts.map((part) => part.size)).toEqual(
+ expectedSizes,
+ );
+ const digest = async (parts: Blob[]) =>
+ createHash("sha256")
+ .update(new Uint8Array(await new Blob(parts).arrayBuffer()))
+ .digest("hex");
+ expect(await digest(MockXMLHttpRequest.recordedParts)).toBe(
+ await digest(chunks),
+ );
+ },
+ );
+
it("uploads streamed chunks and completes multipart with the raw subpath", async () => {
const fetchMock = vi.fn(
async (input: RequestInfo | URL, init?: RequestInit) => {
diff --git a/packages/recorder-core/src/instant-mp4-uploader.ts b/packages/recorder-core/src/instant-mp4-uploader.ts
index f4646a5ae..6ed7fcaf7 100644
--- a/packages/recorder-core/src/instant-mp4-uploader.ts
+++ b/packages/recorder-core/src/instant-mp4-uploader.ts
@@ -489,29 +489,14 @@ export class InstantRecordingUploader {
}
private flushBuffer(force = false) {
- if (this.provider === "googleDrive") {
- this.flushDriveBuffer(force);
- return;
- }
-
- if (this.bufferedBytes === 0) return;
- if (!force && this.bufferedBytes < MIN_PART_SIZE_BYTES) return;
-
- const chunk = new Blob(this.bufferedChunks, { type: this.mimeType });
- this.bufferedChunks = [];
- this.bufferedBytes = 0;
-
- this.enqueueUpload(chunk);
- }
-
- private flushDriveBuffer(force = false) {
+ const targetPartSize =
+ this.provider === "googleDrive"
+ ? DRIVE_PART_SIZE_BYTES
+ : MIN_PART_SIZE_BYTES;
while (this.bufferedBytes > 0) {
- if (!force && this.bufferedBytes < DRIVE_PART_SIZE_BYTES) return;
+ if (!force && this.bufferedBytes < targetPartSize) return;
- const partSize =
- force && this.bufferedBytes <= DRIVE_PART_SIZE_BYTES
- ? this.bufferedBytes
- : DRIVE_PART_SIZE_BYTES;
+ const partSize = Math.min(this.bufferedBytes, targetPartSize);
const { part, remainingChunks, remainingBytes } =
this.takeBufferedPart(partSize);
@@ -519,7 +504,7 @@ export class InstantRecordingUploader {
this.bufferedBytes = remainingBytes;
this.enqueueUpload(part);
- if (partSize < DRIVE_PART_SIZE_BYTES) return;
+ if (partSize < targetPartSize) return;
}
}