Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
feat(web-backend): add Storage Effect service for S3 and Google Drive
Richie McIlroyb1ab930630e5
diff --git a/packages/web-backend/src/Storage/GoogleDrive.ts b/packages/web-backend/src/Storage/GoogleDrive.tsnew file mode 100644index 000000000..6e1f2662c--- /dev/null+++ b/packages/web-backend/src/Storage/GoogleDrive.ts@@ -0,0 +1,733 @@+import { serverEnv } from "@cap/env";+import { Storage, type User, type Video } from "@cap/web-domain";+import { Effect, Option, Schedule } from "effect";+import type {+ GoogleDriveIntegrationConfig,+ GoogleDriveStorageQuota,+ StorageRepo,+} from "./StorageRepo.ts";++const DRIVE_FILE_SCOPE = "https://www.googleapis.com/auth/drive.file";+const DRIVE_API_BASE = "https://www.googleapis.com/drive/v3";+const DRIVE_UPLOAD_BASE = "https://www.googleapis.com/upload/drive/v3";+export const GOOGLE_DRIVE_FOLDER_MIME_TYPE =+ "application/vnd.google-apps.folder";+const DRIVE_FOLDER_OBJECT_PREFIX = ".cap-folders";+const DRIVE_WARNING_OBJECT_PREFIX = ".cap-warnings";+const DRIVE_WARNING_FILE_NAME = "DO_NOT_EDIT_OR_DELETE.txt";+const DRIVE_WARNING_TEXT =+ "Cap uses this folder to store and serve your video files. Do not rename, move, edit, or delete files or folders here. Changing anything in this folder can break playback, downloads, thumbnails, captions, and processing.";++type GoogleDriveFile = {+ id: string;+ name?: string;+ mimeType?: string;+ size?: string;+};++type GoogleDriveListResponse = {+ files?: GoogleDriveFile[];+};++type GoogleDriveTokenResponse = {+ access_token?: string;+ expires_in?: number;+ scope?: string;+ token_type?: string;+ refresh_token?: string;+};++export type CreateGoogleDriveUploadInput = {+ integrationId: Storage.StorageIntegrationId;+ ownerId: User.UserId;+ videoId: Video.VideoId | null;+ key: string;+ contentType: string;+ contentLength?: number;+};++const normalizeContentType = (contentType?: string | null) =>+ contentType?.trim() ? contentType : "application/octet-stream";++const parseDriveJson = async <T>(response: Response) => {+ const text = await response.text();+ if (!text) return {} as T;+ return JSON.parse(text) as T;+};++const assertDriveResponse = async (response: Response) => {+ if (response.ok || response.status === 308) return;+ const text = await response.text().catch(() => "");+ throw new Error(`Google Drive request failed: ${response.status} ${text}`);+};++const escapeDriveQueryValue = (value: string) =>+ value.replace(/\\/g, "\\\\").replace(/'/g, "\\'");++export const getGoogleDriveAuthUrl = ({ state }: { state: string }) => {+ const env = serverEnv();+ if (!env.GOOGLE_CLIENT_ID) {+ throw new Error("GOOGLE_CLIENT_ID is not configured");+ }++ const params = new URLSearchParams({+ client_id: env.GOOGLE_CLIENT_ID,+ redirect_uri: `${env.WEB_URL}/api/desktop/storage/google-drive/callback`,+ response_type: "code",+ access_type: "offline",+ prompt: "consent",+ scope: DRIVE_FILE_SCOPE,+ state,+ include_granted_scopes: "true",+ });++ return `https://accounts.google.com/o/oauth2/v2/auth?${params.toString()}`;+};++export const exchangeGoogleDriveCode = (code: string) =>+ Effect.tryPromise({+ try: async () => {+ const env = serverEnv();+ if (!env.GOOGLE_CLIENT_ID || !env.GOOGLE_CLIENT_SECRET) {+ throw new Error("Google OAuth is not configured");+ }++ const response = await fetch("https://oauth2.googleapis.com/token", {+ method: "POST",+ headers: { "Content-Type": "application/x-www-form-urlencoded" },+ body: new URLSearchParams({+ code,+ client_id: env.GOOGLE_CLIENT_ID,+ client_secret: env.GOOGLE_CLIENT_SECRET,+ redirect_uri: `${env.WEB_URL}/api/desktop/storage/google-drive/callback`,+ grant_type: "authorization_code",+ }),+ });++ await assertDriveResponse(response);+ const tokens = await parseDriveJson<GoogleDriveTokenResponse>(response);+ if (!tokens.refresh_token) {+ throw new Error("Google did not return a refresh token");+ }+ return tokens;+ },+ catch: (cause) => new Storage.StorageError({ cause }),+ });++export const refreshGoogleDriveAccessToken = (+ config: GoogleDriveIntegrationConfig,+) =>+ Effect.tryPromise({+ try: async () => {+ const env = serverEnv();+ if (!env.GOOGLE_CLIENT_ID || !env.GOOGLE_CLIENT_SECRET) {+ throw new Error("Google OAuth is not configured");+ }++ const response = await fetch("https://oauth2.googleapis.com/token", {+ method: "POST",+ headers: { "Content-Type": "application/x-www-form-urlencoded" },+ body: new URLSearchParams({+ client_id: env.GOOGLE_CLIENT_ID,+ client_secret: env.GOOGLE_CLIENT_SECRET,+ refresh_token: config.refreshToken,+ grant_type: "refresh_token",+ }),+ });++ await assertDriveResponse(response);+ const token = await parseDriveJson<GoogleDriveTokenResponse>(response);+ if (!token.access_token) {+ throw new Error("Google did not return an access token");+ }+ return token.access_token;+ },+ catch: (cause) => new Storage.StorageError({ cause }),+ });++const driveFetch = (+ config: GoogleDriveIntegrationConfig,+ url: string,+ init?: RequestInit,+) =>+ Effect.gen(function* () {+ const accessToken = yield* refreshGoogleDriveAccessToken(config);+ return yield* Effect.tryPromise({+ try: async () => {+ const headers = new Headers(init?.headers);+ headers.set("Authorization", `Bearer ${accessToken}`);+ const response = await fetch(url, { ...init, headers });+ await assertDriveResponse(response);+ return response;+ },+ catch: (cause) => new Storage.StorageError({ cause }),+ });+ });++const getDriveFileName = (key: string) => {+ const parts = key.split("/").filter(Boolean);+ if (parts[2] === "segments") return parts.slice(3).join("__") || "file";+ if (parts.length > 2) return parts.slice(2).join("__");+ return parts.at(-1) ?? "file";+};++const getDriveFolderParts = (key: string) => {+ const parts = key.split("/").filter(Boolean);+ if (parts.length < 2) return [];+ return parts[2] === "segments"+ ? [parts[1] as string, "segments"]+ : [parts[1] as string];+};++const getDriveFolderObjectKey = (folderPath: string) =>+ `${DRIVE_FOLDER_OBJECT_PREFIX}/${folderPath}`;++const getDriveWarningObjectKey = (folderPath: string) =>+ `${DRIVE_WARNING_OBJECT_PREFIX}/${folderPath}/${DRIVE_WARNING_FILE_NAME}`;++export const getGoogleDriveUserEmail = (config: GoogleDriveIntegrationConfig) =>+ driveFetch(config, `${DRIVE_API_BASE}/about?fields=user(emailAddress)`).pipe(+ Effect.flatMap((response) =>+ Effect.tryPromise({+ try: async () => {+ const body = (await parseDriveJson<{+ user?: { emailAddress?: string };+ }>(response)) as { user?: { emailAddress?: string } };+ return body.user?.emailAddress;+ },+ catch: (cause) => new Storage.StorageError({ cause }),+ }),+ ),+ );++export const getGoogleDriveStorageQuota = (+ config: GoogleDriveIntegrationConfig,+) =>+ driveFetch(+ config,+ `${DRIVE_API_BASE}/about?fields=storageQuota(limit,usage,usageInDrive,usageInDriveTrash)`,+ ).pipe(+ Effect.flatMap((response) =>+ Effect.tryPromise({+ try: async () => {+ const body = await parseDriveJson<{+ storageQuota?: GoogleDriveStorageQuota;+ }>(response);+ return body.storageQuota ?? {};+ },+ catch: (cause) => new Storage.StorageError({ cause }),+ }),+ ),+ );++export const ensureGoogleDriveFolder = (+ config: GoogleDriveIntegrationConfig,+ name: string,+ parentId?: string,+) =>+ Effect.gen(function* () {+ const query = [+ `name='${escapeDriveQueryValue(name)}'`,+ "mimeType='application/vnd.google-apps.folder'",+ "trashed=false",+ ...(parentId ? [`'${escapeDriveQueryValue(parentId)}' in parents`] : []),+ ].join(" and ");+ const listUrl = `${DRIVE_API_BASE}/files?q=${encodeURIComponent(query)}&fields=files(id,name)&spaces=drive`;+ const listResponse = yield* driveFetch(config, listUrl);+ const listBody = yield* Effect.tryPromise({+ try: () => parseDriveJson<GoogleDriveListResponse>(listResponse),+ catch: (cause) => new Storage.StorageError({ cause }),+ });+ const existingId = listBody.files?.[0]?.id;+ if (existingId) return existingId;++ const createResponse = yield* driveFetch(+ config,+ `${DRIVE_API_BASE}/files`,+ {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ name,+ mimeType: GOOGLE_DRIVE_FOLDER_MIME_TYPE,+ ...(parentId ? { parents: [parentId] } : {}),+ }),+ },+ );++ const created = yield* Effect.tryPromise({+ try: () => parseDriveJson<GoogleDriveFile>(createResponse),+ catch: (cause) => new Storage.StorageError({ cause }),+ });+ if (!created.id) {+ return yield* Effect.fail(+ new Storage.StorageError({+ cause: new Error("Google Drive folder creation did not return an id"),+ }),+ );+ }+ return created.id;+ });++const createGoogleDriveFolderWithId = (+ config: GoogleDriveIntegrationConfig,+ id: string,+ name: string,+ parentId: string,+) =>+ driveFetch(config, `${DRIVE_API_BASE}/files?fields=id,name`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ id,+ name,+ mimeType: GOOGLE_DRIVE_FOLDER_MIME_TYPE,+ parents: [parentId],+ }),+ }).pipe(Effect.asVoid);++const createGoogleDriveTextFileWithId = ({+ config,+ id,+ name,+ parentId,+ content,+}: {+ config: GoogleDriveIntegrationConfig;+ id: string;+ name: string;+ parentId: string;+ content: string;+}) => {+ const boundary = `cap_drive_boundary_${id}`;+ const metadata = JSON.stringify({+ id,+ name,+ mimeType: "text/plain",+ parents: [parentId],+ });+ const body = [+ `--${boundary}`,+ "Content-Type: application/json; charset=UTF-8",+ "",+ metadata,+ `--${boundary}`,+ "Content-Type: text/plain; charset=UTF-8",+ "",+ content,+ `--${boundary}--`,+ "",+ ].join("\r\n");++ return driveFetch(+ config,+ `${DRIVE_UPLOAD_BASE}/files?uploadType=multipart&fields=id,name,mimeType,size`,+ {+ method: "POST",+ headers: { "Content-Type": `multipart/related; boundary=${boundary}` },+ body,+ },+ ).pipe(Effect.asVoid);+};++const waitForReservedGoogleDriveObject = (+ repo: StorageRepo,+ integrationId: Storage.StorageIntegrationId,+ objectKey: string,+) =>+ repo.getObjectByKey(integrationId, objectKey).pipe(+ Effect.flatMap(+ Option.match({+ onNone: () =>+ Effect.fail(+ new Storage.StorageError({+ cause: new Error("Google Drive object reservation not found"),+ }),+ ),+ onSome: (object) =>+ object.uploadStatus === "complete"+ ? Effect.succeed(object.providerObjectId)+ : Effect.fail(+ new Storage.StorageError({+ cause: new Error("Google Drive object reservation pending"),+ }),+ ),+ }),+ ),+ Effect.retry({+ times: 150,+ schedule: Schedule.spaced("100 millis"),+ }),+ );++const getOrCreateGoogleDriveFolder = ({+ repo,+ config,+ input,+ folderPath,+ name,+ parentId,+}: {+ repo: StorageRepo;+ config: GoogleDriveIntegrationConfig;+ input: CreateGoogleDriveUploadInput;+ folderPath: string;+ name: string;+ parentId: string;+}) =>+ Effect.gen(function* () {+ const folderObjectKey = getDriveFolderObjectKey(folderPath);+ const existing = yield* repo.getObjectByKey(+ input.integrationId,+ folderObjectKey,+ );+ if (Option.isSome(existing)) {+ if (existing.value.uploadStatus === "complete") {+ return existing.value.providerObjectId;+ }+ return yield* waitForReservedGoogleDriveObject(+ repo,+ input.integrationId,+ folderObjectKey,+ );+ }++ const folderId = yield* generateGoogleDriveFileId(config);+ const reserved = yield* repo.reserveObject({+ integrationId: input.integrationId,+ ownerId: input.ownerId,+ videoId: input.videoId,+ objectKey: folderObjectKey,+ providerObjectId: folderId,+ uploadStatus: "pending",+ contentType: GOOGLE_DRIVE_FOLDER_MIME_TYPE,+ metadata: {+ videoId: input.videoId ?? undefined,+ fileName: name,+ contentType: GOOGLE_DRIVE_FOLDER_MIME_TYPE,+ },+ });++ if (reserved.providerObjectId !== folderId) {+ return yield* waitForReservedGoogleDriveObject(+ repo,+ input.integrationId,+ folderObjectKey,+ );+ }++ yield* createGoogleDriveFolderWithId(config, folderId, name, parentId).pipe(+ Effect.tapError(() =>+ repo.deleteObjectByKey(input.integrationId, folderObjectKey),+ ),+ );+ yield* repo.markObjectComplete(input.integrationId, folderObjectKey);+ return folderId;+ });++const ensureGoogleDriveWarningFile = ({+ repo,+ config,+ input,+ folderPath,+ parentId,+}: {+ repo: StorageRepo;+ config: GoogleDriveIntegrationConfig;+ input: CreateGoogleDriveUploadInput;+ folderPath: string;+ parentId: string;+}) =>+ Effect.gen(function* () {+ const warningObjectKey = getDriveWarningObjectKey(folderPath);+ const existing = yield* repo.getObjectByKey(+ input.integrationId,+ warningObjectKey,+ );+ if (Option.isSome(existing)) {+ if (existing.value.uploadStatus === "complete") return;+ yield* waitForReservedGoogleDriveObject(+ repo,+ input.integrationId,+ warningObjectKey,+ );+ return;+ }++ const warningFileId = yield* generateGoogleDriveFileId(config);+ const reserved = yield* repo.reserveObject({+ integrationId: input.integrationId,+ ownerId: input.ownerId,+ videoId: input.videoId,+ objectKey: warningObjectKey,+ providerObjectId: warningFileId,+ uploadStatus: "pending",+ contentType: "text/plain",+ contentLength: DRIVE_WARNING_TEXT.length,+ metadata: {+ videoId: input.videoId ?? undefined,+ fileName: DRIVE_WARNING_FILE_NAME,+ contentType: "text/plain",+ },+ });++ if (reserved.providerObjectId !== warningFileId) {+ yield* waitForReservedGoogleDriveObject(+ repo,+ input.integrationId,+ warningObjectKey,+ );+ return;+ }++ yield* createGoogleDriveTextFileWithId({+ config,+ id: warningFileId,+ name: DRIVE_WARNING_FILE_NAME,+ parentId,+ content: DRIVE_WARNING_TEXT,+ }).pipe(+ Effect.tapError(() =>+ repo.deleteObjectByKey(input.integrationId, warningObjectKey),+ ),+ );+ yield* repo.markObjectComplete(+ input.integrationId,+ warningObjectKey,+ DRIVE_WARNING_TEXT.length,+ );+ });++const getGoogleDriveUploadParentId = (+ repo: StorageRepo,+ config: GoogleDriveIntegrationConfig,+ input: CreateGoogleDriveUploadInput,+) =>+ Effect.gen(function* () {+ const folderParts = getDriveFolderParts(input.key);+ let parentId = config.folderId;+ const pathParts: string[] = [];+ let videoFolderId: string | null = null;+ let videoFolderPath: string | null = null;++ for (const folderName of folderParts) {+ pathParts.push(folderName);+ parentId = yield* getOrCreateGoogleDriveFolder({+ repo,+ config,+ input,+ folderPath: pathParts.join("/"),+ name: folderName,+ parentId,+ });+ if (pathParts.length === 1) {+ videoFolderId = parentId;+ videoFolderPath = pathParts.join("/");+ }+ }++ if (videoFolderId && videoFolderPath) {+ yield* ensureGoogleDriveWarningFile({+ repo,+ config,+ input,+ folderPath: videoFolderPath,+ parentId: videoFolderId,+ });+ }++ return parentId;+ });++const generateGoogleDriveFileId = (config: GoogleDriveIntegrationConfig) =>+ driveFetch(+ config,+ `${DRIVE_API_BASE}/files/generateIds?count=1&space=drive&type=files`,+ ).pipe(+ Effect.flatMap((response) =>+ Effect.tryPromise({+ try: async () => {+ const body = await parseDriveJson<{ ids?: string[] }>(response);+ const id = body.ids?.[0];+ if (!id) throw new Error("Google Drive did not return a file id");+ return id;+ },+ catch: (cause) => new Storage.StorageError({ cause }),+ }),+ ),+ );++export const createGoogleDriveResumableUpload = (+ repo: StorageRepo,+ config: GoogleDriveIntegrationConfig,+ input: CreateGoogleDriveUploadInput,+) =>+ Effect.gen(function* () {+ const contentType = normalizeContentType(input.contentType);+ const [parentId, fileId] = yield* Effect.all([+ getGoogleDriveUploadParentId(repo, config, input),+ generateGoogleDriveFileId(config),+ ]);+ const headers: Record<string, string> = {+ "Content-Type": "application/json; charset=UTF-8",+ "X-Upload-Content-Type": contentType,+ };+ if (input.contentLength !== undefined) {+ headers["X-Upload-Content-Length"] = input.contentLength.toString();+ }++ const response = yield* driveFetch(+ config,+ `${DRIVE_UPLOAD_BASE}/files?uploadType=resumable&fields=id,name,mimeType,size`,+ {+ method: "POST",+ headers,+ body: JSON.stringify({+ id: fileId,+ name: getDriveFileName(input.key),+ mimeType: contentType,+ parents: [parentId],+ appProperties: {+ capObjectKey: input.key,+ },+ }),+ },+ );+ const uploadUrl = response.headers.get("Location");+ if (!uploadUrl) {+ return yield* Effect.fail(+ new Storage.StorageError({+ cause: new Error("Google Drive did not return an upload URL"),+ }),+ );+ }++ yield* repo.upsertObject({+ integrationId: input.integrationId,+ ownerId: input.ownerId,+ videoId: input.videoId,+ objectKey: input.key,+ providerObjectId: fileId,+ uploadSessionUrl: uploadUrl,+ uploadStatus: "pending",+ contentType,+ contentLength: input.contentLength ?? null,+ metadata: {+ videoId: input.videoId ?? undefined,+ fileName: getDriveFileName(input.key),+ contentType,+ },+ });++ return uploadUrl;+ });++export const getGoogleDriveFileMetadata = (+ config: GoogleDriveIntegrationConfig,+ fileId: string,+) =>+ driveFetch(+ config,+ `${DRIVE_API_BASE}/files/${encodeURIComponent(fileId)}?fields=id,name,mimeType,size`,+ ).pipe(+ Effect.flatMap((response) =>+ Effect.tryPromise({+ try: () => parseDriveJson<GoogleDriveFile>(response),+ catch: (cause) => new Storage.StorageError({ cause }),+ }),+ ),+ );++export const getGoogleDriveObjectText = (+ config: GoogleDriveIntegrationConfig,+ fileId: string,+) =>+ driveFetch(+ config,+ `${DRIVE_API_BASE}/files/${encodeURIComponent(fileId)}?alt=media`,+ ).pipe(+ Effect.flatMap((response) =>+ Effect.tryPromise({+ try: () => response.text(),+ catch: (cause) => new Storage.StorageError({ cause }),+ }),+ ),+ );++export const getGoogleDriveObjectResponse = (+ config: GoogleDriveIntegrationConfig,+ fileId: string,+ range?: string | null,+) =>+ Effect.gen(function* () {+ const headers: Record<string, string> = {};+ if (range) headers.Range = range;+ const response = yield* driveFetch(+ config,+ `${DRIVE_API_BASE}/files/${encodeURIComponent(fileId)}?alt=media`,+ { headers },+ );+ return response;+ });++export const deleteGoogleDriveFile = (+ config: GoogleDriveIntegrationConfig,+ fileId: string,+) =>+ driveFetch(config, `${DRIVE_API_BASE}/files/${encodeURIComponent(fileId)}`, {+ method: "DELETE",+ }).pipe(Effect.asVoid);++export const copyGoogleDriveFile = ({+ repo,+ config,+ sourceFileId,+ input,+}: {+ repo: StorageRepo;+ config: GoogleDriveIntegrationConfig;+ sourceFileId: string;+ input: CreateGoogleDriveUploadInput;+}) =>+ Effect.gen(function* () {+ const parentId = yield* getGoogleDriveUploadParentId(repo, config, input);+ const response = yield* driveFetch(+ config,+ `${DRIVE_API_BASE}/files/${encodeURIComponent(sourceFileId)}/copy?fields=id,name,mimeType,size`,+ {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ name: getDriveFileName(input.key),+ parents: [parentId],+ appProperties: {+ capObjectKey: input.key,+ },+ }),+ },+ );+ const copied = yield* Effect.tryPromise({+ try: () => parseDriveJson<GoogleDriveFile>(response),+ catch: (cause) => new Storage.StorageError({ cause }),+ });+ if (!copied.id) {+ return yield* Effect.fail(+ new Storage.StorageError({+ cause: new Error("Google Drive copy did not return an id"),+ }),+ );+ }+ yield* repo.upsertObject({+ integrationId: input.integrationId,+ ownerId: input.ownerId,+ videoId: input.videoId,+ objectKey: input.key,+ providerObjectId: copied.id,+ uploadStatus: "complete",+ contentType: copied.mimeType ?? input.contentType,+ contentLength: copied.size ? Number(copied.size) : null,+ });+ });++export const parseVideoIdFromObjectKey = (key: string) =>+ Option.fromNullable(key.split("/")[1]).pipe(Option.filter((id) => id !== ""));diff --git a/packages/web-backend/src/Storage/SignedObject.ts b/packages/web-backend/src/Storage/SignedObject.tsnew file mode 100644index 000000000..44f3033db--- /dev/null+++ b/packages/web-backend/src/Storage/SignedObject.ts@@ -0,0 +1,45 @@+import { createHmac, timingSafeEqual } from "node:crypto";+import { serverEnv } from "@cap/env";++type StorageObjectTokenPayload = {+ videoId: string;+ key: string;+ expiresAt: number;+};++const encode = (value: unknown) =>+ Buffer.from(JSON.stringify(value), "utf8").toString("base64url");++const sign = (payload: string) =>+ createHmac("sha256", serverEnv().NEXTAUTH_SECRET)+ .update(payload)+ .digest("base64url");++export function createStorageObjectToken(+ payload: Omit<StorageObjectTokenPayload, "expiresAt">,+ ttlSeconds = 3600,+) {+ const encodedPayload = encode({+ ...payload,+ expiresAt: Date.now() + ttlSeconds * 1000,+ });+ return `${encodedPayload}.${sign(encodedPayload)}`;+}++export function verifyStorageObjectToken(token: string) {+ const [encodedPayload, signature] = token.split(".");+ if (!encodedPayload || !signature) return null;++ const expected = sign(encodedPayload);+ const signatureBuffer = Buffer.from(signature);+ const expectedBuffer = Buffer.from(expected);+ if (signatureBuffer.length !== expectedBuffer.length) return null;+ if (!timingSafeEqual(signatureBuffer, expectedBuffer)) return null;++ const payload = JSON.parse(+ Buffer.from(encodedPayload, "base64url").toString("utf8"),+ ) as StorageObjectTokenPayload;++ if (payload.expiresAt < Date.now()) return null;+ return payload;+}diff --git a/packages/web-backend/src/Storage/StorageRepo.ts b/packages/web-backend/src/Storage/StorageRepo.tsnew file mode 100644index 000000000..d2ec302d0--- /dev/null+++ b/packages/web-backend/src/Storage/StorageRepo.ts@@ -0,0 +1,300 @@+import { createHash } from "node:crypto";+import { decrypt, encrypt } from "@cap/database/crypto";+import { nanoId } from "@cap/database/helpers";+import * as Db from "@cap/database/schema";+import { Storage, type User, type Video } from "@cap/web-domain";+import * as Dz from "drizzle-orm";+import { Effect, Option } from "effect";++import { Database } from "../Database.ts";++export const getObjectKeyHash = (key: string) =>+ createHash("sha256").update(key).digest("hex");++const escapeLikePattern = (value: string) =>+ value.replace(/[\\%_]/g, (match) => `\\${match}`);++export type GoogleDriveIntegrationConfig = {+ refreshToken: string;+ folderId: string;+ email?: string;+ scope?: string;+ storageQuotaCache?: GoogleDriveStorageQuotaCache;+};++export type GoogleDriveStorageQuota = {+ limit?: string | null;+ usage?: string | null;+ usageInDrive?: string | null;+ usageInDriveTrash?: string | null;+};++export type GoogleDriveStorageQuotaCache = GoogleDriveStorageQuota & {+ fetchedAt: string;+};++export type StorageObjectInput = {+ integrationId: Storage.StorageIntegrationId;+ ownerId: User.UserId;+ videoId: Video.VideoId | null;+ objectKey: string;+ providerObjectId: string;+ uploadSessionUrl?: string | null;+ uploadStatus?: "pending" | "complete" | "error";+ contentType?: string | null;+ contentLength?: number | null;+ metadata?: Storage.StorageObjectMetadata | null;+};++export class StorageRepo extends Effect.Service<StorageRepo>()("StorageRepo", {+ effect: Effect.gen(function* () {+ const db = yield* Database;++ const getActiveIntegrationForUser = Effect.fn(+ "StorageRepo.getActiveIntegrationForUser",+ )((userId: User.UserId) =>+ Effect.gen(function* () {+ const [integration] = yield* db.use((db) =>+ db+ .select()+ .from(Db.storageIntegrations)+ .where(+ Dz.and(+ Dz.eq(Db.storageIntegrations.ownerId, userId),+ Dz.eq(Db.storageIntegrations.active, true),+ Dz.eq(Db.storageIntegrations.status, "active"),+ ),+ ),+ );++ return Option.fromNullable(integration);+ }),+ );++ const getIntegrationById = Effect.fn("StorageRepo.getIntegrationById")(+ (id: Storage.StorageIntegrationId) =>+ Effect.gen(function* () {+ const [integration] = yield* db.use((db) =>+ db+ .select()+ .from(Db.storageIntegrations)+ .where(Dz.eq(Db.storageIntegrations.id, id)),+ );++ return Option.fromNullable(integration);+ }),+ );++ const getGoogleDriveConfig = Effect.fn("StorageRepo.getGoogleDriveConfig")(+ (integration: typeof Db.storageIntegrations.$inferSelect) =>+ Effect.tryPromise({+ try: async () =>+ JSON.parse(+ await decrypt(integration.encryptedConfig),+ ) as GoogleDriveIntegrationConfig,+ catch: (cause) => new Storage.StorageError({ cause }),+ }),+ );++ const upsertObject = Effect.fn("StorageRepo.upsertObject")(+ (input: StorageObjectInput) =>+ Effect.gen(function* () {+ const objectKeyHash = getObjectKeyHash(input.objectKey);+ const uploadSessionUrl = input.uploadSessionUrl+ ? yield* Effect.tryPromise({+ try: () => encrypt(input.uploadSessionUrl as string),+ catch: (cause) => new Storage.StorageError({ cause }),+ })+ : null;++ const value = {+ id: Storage.StorageObjectId.make(nanoId()),+ integrationId: input.integrationId,+ ownerId: input.ownerId,+ videoId: input.videoId,+ objectKey: input.objectKey,+ objectKeyHash,+ providerObjectId: input.providerObjectId,+ uploadSessionUrl,+ uploadStatus: input.uploadStatus ?? "pending",+ contentType: input.contentType ?? null,+ contentLength: input.contentLength ?? null,+ metadata: input.metadata ?? null,+ };++ yield* db.use((db) =>+ db+ .insert(Db.storageObjects)+ .values(value)+ .onDuplicateKeyUpdate({+ set: {+ providerObjectId: value.providerObjectId,+ uploadSessionUrl: value.uploadSessionUrl,+ uploadStatus: value.uploadStatus,+ contentType: value.contentType,+ contentLength: value.contentLength,+ metadata: value.metadata,+ updatedAt: new Date(),+ },+ }),+ );+ }),+ );++ const reserveObject = Effect.fn("StorageRepo.reserveObject")(+ (input: StorageObjectInput) =>+ Effect.gen(function* () {+ const objectKeyHash = getObjectKeyHash(input.objectKey);+ const uploadSessionUrl = input.uploadSessionUrl+ ? yield* Effect.tryPromise({+ try: () => encrypt(input.uploadSessionUrl as string),+ catch: (cause) => new Storage.StorageError({ cause }),+ })+ : null;++ yield* db.use((db) =>+ db+ .insert(Db.storageObjects)+ .values({+ id: Storage.StorageObjectId.make(nanoId()),+ integrationId: input.integrationId,+ ownerId: input.ownerId,+ videoId: input.videoId,+ objectKey: input.objectKey,+ objectKeyHash,+ providerObjectId: input.providerObjectId,+ uploadSessionUrl,+ uploadStatus: input.uploadStatus ?? "pending",+ contentType: input.contentType ?? null,+ contentLength: input.contentLength ?? null,+ metadata: input.metadata ?? null,+ })+ .onDuplicateKeyUpdate({+ set: {+ id: Dz.sql`${Db.storageObjects.id}`,+ },+ }),+ );++ const object = yield* getObjectByKey(+ input.integrationId,+ input.objectKey,+ );+ return yield* Option.match(object, {+ onNone: () =>+ Effect.fail(+ new Storage.StorageError({+ cause: new Error("Storage object reservation failed"),+ }),+ ),+ onSome: Effect.succeed,+ });+ }),+ );++ const getObjectByKey = Effect.fn("StorageRepo.getObjectByKey")(+ (integrationId: Storage.StorageIntegrationId, key: string) =>+ Effect.gen(function* () {+ const [object] = yield* db.use((db) =>+ db+ .select()+ .from(Db.storageObjects)+ .where(+ Dz.and(+ Dz.eq(Db.storageObjects.integrationId, integrationId),+ Dz.eq(Db.storageObjects.objectKeyHash, getObjectKeyHash(key)),+ ),+ ),+ );++ return Option.fromNullable(object).pipe(+ Option.filter((object) => object.objectKey === key),+ );+ }),+ );++ const listObjectsByPrefix = Effect.fn("StorageRepo.listObjectsByPrefix")(+ (+ integrationId: Storage.StorageIntegrationId,+ prefix: string | undefined,+ maxKeys: number | undefined,+ ) =>+ db+ .use((db) => {+ const where = prefix+ ? Dz.and(+ Dz.eq(Db.storageObjects.integrationId, integrationId),+ Dz.like(+ Db.storageObjects.objectKey,+ `${escapeLikePattern(prefix)}%`,+ ),+ )+ : Dz.eq(Db.storageObjects.integrationId, integrationId);++ return db+ .select()+ .from(Db.storageObjects)+ .where(where)+ .orderBy(Db.storageObjects.objectKey)+ .limit(maxKeys ?? 1000);+ })+ .pipe(+ Effect.map((objects) =>+ objects.filter((object) =>+ prefix ? object.objectKey.startsWith(prefix) : true,+ ),+ ),+ ),+ );++ const markObjectComplete = Effect.fn("StorageRepo.markObjectComplete")(+ (+ integrationId: Storage.StorageIntegrationId,+ key: string,+ contentLength?: number | null,+ ) =>+ db.use((db) =>+ db+ .update(Db.storageObjects)+ .set({+ uploadStatus: "complete",+ contentLength: contentLength ?? undefined,+ updatedAt: new Date(),+ })+ .where(+ Dz.and(+ Dz.eq(Db.storageObjects.integrationId, integrationId),+ Dz.eq(Db.storageObjects.objectKeyHash, getObjectKeyHash(key)),+ ),+ ),+ ),+ );++ const deleteObjectByKey = Effect.fn("StorageRepo.deleteObjectByKey")(+ (integrationId: Storage.StorageIntegrationId, key: string) =>+ db.use((db) =>+ db+ .delete(Db.storageObjects)+ .where(+ Dz.and(+ Dz.eq(Db.storageObjects.integrationId, integrationId),+ Dz.eq(Db.storageObjects.objectKeyHash, getObjectKeyHash(key)),+ ),+ ),+ ),+ );++ return {+ getActiveIntegrationForUser,+ getIntegrationById,+ getGoogleDriveConfig,+ upsertObject,+ reserveObject,+ getObjectByKey,+ listObjectsByPrefix,+ markObjectComplete,+ deleteObjectByKey,+ };+ }),+ dependencies: [Database.Default],+}) {}diff --git a/packages/web-backend/src/Storage/index.ts b/packages/web-backend/src/Storage/index.tsnew file mode 100644index 000000000..b1749bee8--- /dev/null+++ b/packages/web-backend/src/Storage/index.ts@@ -0,0 +1,677 @@+import type * as S3 from "@aws-sdk/client-s3";+import type * as Db from "@cap/database/schema";+import { serverEnv } from "@cap/env";+import {+ Storage as StorageDomain,+ type User,+ type Video,+} from "@cap/web-domain";+import { Effect, Option } from "effect";++import { S3Buckets } from "../S3Buckets/index.ts";+import type { S3BucketAccess } from "../S3Buckets/S3BucketAccess.ts";+import {+ copyGoogleDriveFile,+ createGoogleDriveResumableUpload,+ deleteGoogleDriveFile,+ GOOGLE_DRIVE_FOLDER_MIME_TYPE,+ getGoogleDriveFileMetadata,+ getGoogleDriveObjectResponse,+ getGoogleDriveObjectText,+ parseVideoIdFromObjectKey,+} from "./GoogleDrive.ts";+import { createStorageObjectToken } from "./SignedObject.ts";+import type { GoogleDriveIntegrationConfig } from "./StorageRepo.ts";+import { StorageRepo } from "./StorageRepo.ts";++type UploadTargetInput = {+ contentType: string;+ contentLength?: number;+ fields?: Record<string, string>;+ method?: "post" | "put";+};++const toS3UploadTarget = (data: {+ url: string;+ fields: Record<string, string>;+}): StorageDomain.UploadTarget => ({+ type: "s3Post",+ url: data.url,+ fields: data.fields,+});++const toPutUploadTarget = (+ url: string,+ contentType: string,+): StorageDomain.UploadTarget => ({+ type: "put",+ url,+ headers: {+ "Content-Type": contentType,+ },+});++const toDriveUploadTarget = (+ url: string,+ contentType: string,+): StorageDomain.UploadTarget => ({+ type: "driveResumable",+ url,+ headers: {+ "Content-Type": contentType,+ },+});++const getGoogleDriveUploadHeaders = (+ contentType: string,+ contentLength: number,+) => ({+ "Content-Type": contentType,+ "Content-Length": contentLength.toString(),+ ...(contentLength > 0+ ? {+ "Content-Range": `bytes 0-${contentLength - 1}/${contentLength}`,+ }+ : {}),+});++const parseSourceKey = (source: string) => {+ const parts = source.split("/");+ return parts.length > 1 ? parts.slice(1).join("/") : source;+};++const requireDriveObject = (+ repo: StorageRepo,+ integrationId: StorageDomain.StorageIntegrationId,+ key: string,+) =>+ repo.getObjectByKey(integrationId, key).pipe(+ Effect.flatMap(+ Option.match({+ onNone: () =>+ Effect.fail(+ new StorageDomain.StorageError({+ cause: new Error(`Storage object not found: ${key}`),+ }),+ ),+ onSome: Effect.succeed,+ }),+ ),+ );++const createDriveObjectUrl = (key: string, ttlSeconds = 3600) =>+ parseVideoIdFromObjectKey(key).pipe(+ Option.match({+ onNone: () =>+ Effect.fail(+ new StorageDomain.StorageError({+ cause: new Error(`Could not resolve video id from key: ${key}`),+ }),+ ),+ onSome: (videoId) =>+ Effect.sync(() => {+ const token = createStorageObjectToken({ videoId, key }, ttlSeconds);+ const params = new URLSearchParams({ videoId, key, token });+ return `${serverEnv().WEB_URL}/api/storage/object?${params.toString()}`;+ }),+ }),+ );++const mapStorageError = <A, E, R>(effect: Effect.Effect<A, E, R>) =>+ effect.pipe(+ Effect.mapError((cause) => new StorageDomain.StorageError({ cause })),+ );++const makeS3Access = (s3: S3BucketAccess) => ({+ provider: "s3" as const,+ bucketName: s3.bucketName,+ isPathStyle: s3.isPathStyle,+ getSignedObjectUrl: (key: string) =>+ mapStorageError(s3.getSignedObjectUrl(key)),+ getInternalSignedObjectUrl: (key: string) =>+ mapStorageError(s3.getInternalSignedObjectUrl(key)),+ getObject: (key: string) => mapStorageError(s3.getObject(key)),+ listObjects: (input: {+ prefix?: string;+ maxKeys?: number;+ continuationToken?: string;+ }) =>+ mapStorageError(s3.listObjects(input)).pipe(+ Effect.map((result) => ({+ Contents: result.Contents?.map((object) => ({+ Key: object.Key,+ Size: object.Size,+ })),+ KeyCount: result.KeyCount,+ IsTruncated: result.IsTruncated,+ NextContinuationToken: result.NextContinuationToken,+ })),+ ),+ headObject: (key: string) =>+ mapStorageError(s3.headObject(key)).pipe(+ Effect.map((result) => ({+ ContentLength: result.ContentLength,+ ContentType: result.ContentType,+ Metadata: result.Metadata,+ })),+ ),+ putObject: (+ key: string,+ body: Parameters<S3BucketAccess["putObject"]>[1],+ fields?: Parameters<S3BucketAccess["putObject"]>[2],+ ) => mapStorageError(s3.putObject(key, body, fields)).pipe(Effect.asVoid),+ copyObject: (+ source: string,+ key: string,+ args?: Omit<S3.CopyObjectCommandInput, "Bucket" | "CopySource" | "Key">,+ ) => mapStorageError(s3.copyObject(source, key, args)).pipe(Effect.asVoid),+ deleteObject: (key: string) =>+ mapStorageError(s3.deleteObject(key)).pipe(Effect.asVoid),+ deleteObjects: (objects: Array<{ Key?: string }>) =>+ mapStorageError(+ s3.deleteObjects(+ objects+ .filter((object): object is { Key: string } => Boolean(object.Key))+ .map((object) => ({ Key: object.Key })),+ ),+ ).pipe(Effect.asVoid),+ getPresignedPutUrl: (+ key: string,+ args?: Omit<S3.PutObjectRequest, "Key" | "Bucket">,+ signingArgs?: Parameters<S3BucketAccess["getPresignedPutUrl"]>[2],+ ) => mapStorageError(s3.getPresignedPutUrl(key, args, signingArgs)),+ getInternalPresignedPutUrl: (+ key: string,+ args?: Omit<S3.PutObjectRequest, "Key" | "Bucket">,+ signingArgs?: Parameters<S3BucketAccess["getInternalPresignedPutUrl"]>[2],+ ) => mapStorageError(s3.getInternalPresignedPutUrl(key, args, signingArgs)),+ getPresignedPostUrl: (+ key: string,+ args: Parameters<S3BucketAccess["getPresignedPostUrl"]>[1],+ ) => mapStorageError(s3.getPresignedPostUrl(key, args)),+ multipart: {+ create: (+ key: string,+ args?: Omit<S3.CreateMultipartUploadCommandInput, "Bucket" | "Key">,+ ) => mapStorageError(s3.multipart.create(key, args)),+ getPresignedUploadPartUrl: (+ key: string,+ uploadId: string,+ partNumber: number,+ args?: Omit<+ S3.UploadPartCommandInput,+ "Key" | "Bucket" | "PartNumber" | "UploadId"+ >,+ ) =>+ mapStorageError(+ s3.multipart.getPresignedUploadPartUrl(key, uploadId, partNumber, args),+ ),+ complete: (+ key: string,+ uploadId: string,+ args?: Omit<+ S3.CompleteMultipartUploadCommandInput,+ "Key" | "Bucket" | "UploadId"+ >,+ ) => mapStorageError(s3.multipart.complete(key, uploadId, args)),+ abort: (+ key: string,+ uploadId: string,+ args?: Omit<+ S3.AbortMultipartUploadCommandInput,+ "Key" | "Bucket" | "UploadId"+ >,+ ) => mapStorageError(s3.multipart.abort(key, uploadId, args)),+ },+ createUploadTarget: (key: string, input: UploadTargetInput) =>+ Effect.gen(function* () {+ if (input.method === "put") {+ const url = yield* s3+ .getPresignedPutUrl(+ key,+ { ContentType: input.contentType },+ { expiresIn: 1800 },+ )+ .pipe(mapStorageError);+ return toPutUploadTarget(url, input.contentType);+ }++ const data = yield* s3+ .getPresignedPostUrl(key, {+ Fields: {+ "Content-Type": input.contentType,+ ...(input.fields ?? {}),+ },+ Expires: 1800,+ })+ .pipe(mapStorageError);+ return toS3UploadTarget(data);+ }),+});++const makeGoogleDriveAccess = ({+ repo,+ integration,+ config,+}: {+ repo: StorageRepo;+ integration: typeof Db.storageIntegrations.$inferSelect;+ config: GoogleDriveIntegrationConfig;+}) => {+ const integrationId = integration.id;+ const ownerId = integration.ownerId;++ const getObjectRecord = (key: string) =>+ mapStorageError(requireDriveObject(repo, integrationId, key));++ return {+ provider: "googleDrive" as const,+ bucketName: "google-drive",+ isPathStyle: false,+ getSignedObjectUrl: (key: string) => createDriveObjectUrl(key),+ getInternalSignedObjectUrl: (key: string) =>+ createDriveObjectUrl(key, 7200),+ getObject: (key: string) =>+ getObjectRecord(key).pipe(+ Effect.flatMap((object) =>+ getGoogleDriveObjectText(config, object.providerObjectId),+ ),+ Effect.map(Option.some),+ Effect.catchTag("StorageError", () => Effect.succeed(Option.none())),+ ),+ listObjects: (input: {+ prefix?: string;+ maxKeys?: number;+ continuationToken?: string;+ }) =>+ mapStorageError(+ repo.listObjectsByPrefix(integrationId, input.prefix, input.maxKeys),+ ).pipe(+ Effect.map((objects) => ({+ Contents: objects+ .filter(+ (object) =>+ object.contentType !== GOOGLE_DRIVE_FOLDER_MIME_TYPE &&+ !object.objectKey.startsWith(".cap-folders/") &&+ !object.objectKey.startsWith(".cap-warnings/"),+ )+ .map((object) => ({+ Key: object.objectKey,+ Size: object.contentLength ?? undefined,+ })),+ KeyCount: objects.filter(+ (object) =>+ object.contentType !== GOOGLE_DRIVE_FOLDER_MIME_TYPE &&+ !object.objectKey.startsWith(".cap-folders/") &&+ !object.objectKey.startsWith(".cap-warnings/"),+ ).length,+ IsTruncated: false,+ NextContinuationToken: undefined,+ })),+ ),+ headObject: (key: string) =>+ getObjectRecord(key).pipe(+ Effect.flatMap((object) =>+ getGoogleDriveFileMetadata(config, object.providerObjectId).pipe(+ Effect.map((metadata) => ({+ ContentLength: metadata.size+ ? Number(metadata.size)+ : (object.contentLength ?? undefined),+ ContentType: metadata.mimeType ?? object.contentType ?? undefined,+ Metadata: object.metadata ?? undefined,+ })),+ ),+ ),+ ),+ putObject: (+ key: string,+ body: string | Uint8Array | ArrayBuffer,+ fields?: { contentType?: string; contentLength?: number },+ ) =>+ Effect.gen(function* () {+ const contentType = fields?.contentType ?? "application/octet-stream";+ const contentLength =+ fields?.contentLength ??+ (typeof body === "string"+ ? new TextEncoder().encode(body).byteLength+ : body.byteLength);+ const uploadUrl = yield* createGoogleDriveResumableUpload(+ repo,+ config,+ {+ integrationId,+ ownerId,+ videoId: parseVideoIdFromObjectKey(key).pipe(+ Option.map((id) => id as Video.VideoId),+ Option.getOrNull,+ ),+ key,+ contentType,+ contentLength,+ },+ ).pipe(mapStorageError);+ const response = yield* Effect.tryPromise({+ try: () =>+ fetch(uploadUrl, {+ method: "PUT",+ headers: getGoogleDriveUploadHeaders(contentType, contentLength),+ body,+ }),+ catch: (cause) => new StorageDomain.StorageError({ cause }),+ });+ if (!response.ok) {+ return yield* Effect.fail(+ new StorageDomain.StorageError({+ cause: new Error(+ `Google Drive upload failed: ${response.status}`,+ ),+ }),+ );+ }+ yield* mapStorageError(+ repo.markObjectComplete(integrationId, key, contentLength),+ );+ }),+ copyObject: (+ source: string,+ key: string,+ args?: Omit<S3.CopyObjectCommandInput, "Bucket" | "CopySource" | "Key">,+ ) =>+ getObjectRecord(parseSourceKey(source)).pipe(+ Effect.flatMap((sourceObject) =>+ copyGoogleDriveFile({+ repo,+ config,+ sourceFileId: sourceObject.providerObjectId,+ input: {+ integrationId,+ ownerId,+ videoId: parseVideoIdFromObjectKey(key).pipe(+ Option.map((id) => id as Video.VideoId),+ Option.getOrNull,+ ),+ key,+ contentType:+ (args?.ContentType as string | undefined) ??+ sourceObject.contentType ??+ "application/octet-stream",+ },+ }).pipe(mapStorageError),+ ),+ ),+ deleteObject: (key: string) =>+ getObjectRecord(key).pipe(+ Effect.flatMap((object) =>+ deleteGoogleDriveFile(config, object.providerObjectId).pipe(+ Effect.catchAll(() => Effect.void),+ Effect.flatMap(() =>+ mapStorageError(repo.deleteObjectByKey(integrationId, key)),+ ),+ ),+ ),+ Effect.catchAll(() => Effect.void),+ ),+ deleteObjects: (objects: Array<{ Key?: string }>) =>+ Effect.forEach(+ objects,+ (object) =>+ object.Key+ ? getObjectRecord(object.Key).pipe(+ Effect.flatMap((record) =>+ deleteGoogleDriveFile(config, record.providerObjectId).pipe(+ Effect.catchAll(() => Effect.void),+ Effect.flatMap(() =>+ mapStorageError(+ repo.deleteObjectByKey(+ integrationId,+ object.Key as string,+ ),+ ),+ ),+ ),+ ),+ Effect.catchAll(() => Effect.void),+ )+ : Effect.void,+ { concurrency: 3 },+ ),+ getPresignedPutUrl: (+ key: string,+ args?: Omit<S3.PutObjectRequest, "Key" | "Bucket">,+ ) =>+ createGoogleDriveResumableUpload(repo, config, {+ integrationId,+ ownerId,+ videoId: parseVideoIdFromObjectKey(key).pipe(+ Option.map((id) => id as Video.VideoId),+ Option.getOrNull,+ ),+ key,+ contentType: args?.ContentType ?? "application/octet-stream",+ contentLength: args?.ContentLength,+ }).pipe(mapStorageError),+ getInternalPresignedPutUrl: (+ key: string,+ args?: Omit<S3.PutObjectRequest, "Key" | "Bucket">,+ ) =>+ createGoogleDriveResumableUpload(repo, config, {+ integrationId,+ ownerId,+ videoId: parseVideoIdFromObjectKey(key).pipe(+ Option.map((id) => id as Video.VideoId),+ Option.getOrNull,+ ),+ key,+ contentType: args?.ContentType ?? "application/octet-stream",+ contentLength: args?.ContentLength,+ }).pipe(mapStorageError),+ getPresignedPostUrl: (key: string) =>+ Effect.fail(+ new StorageDomain.StorageError({+ cause: new Error(+ `Google Drive does not support POST uploads: ${key}`,+ ),+ }),+ ),+ multipart: {+ create: (+ key: string,+ args?: Omit<S3.CreateMultipartUploadCommandInput, "Bucket" | "Key">,+ ) =>+ createGoogleDriveResumableUpload(repo, config, {+ integrationId,+ ownerId,+ videoId: parseVideoIdFromObjectKey(key).pipe(+ Option.map((id) => id as Video.VideoId),+ Option.getOrNull,+ ),+ key,+ contentType: args?.ContentType ?? "application/octet-stream",+ }).pipe(+ mapStorageError,+ Effect.map((UploadId) => ({ UploadId })),+ ),+ getPresignedUploadPartUrl: (+ _key: string,+ uploadId: string,+ _partNumber: number,+ _args?: Omit<+ S3.UploadPartCommandInput,+ "Key" | "Bucket" | "PartNumber" | "UploadId"+ >,+ ) => Effect.succeed(uploadId),+ complete: (+ key: string,+ _uploadId?: string,+ _args?: Omit<+ S3.CompleteMultipartUploadCommandInput,+ "Key" | "Bucket" | "UploadId"+ >,+ ) =>+ getObjectRecord(key).pipe(+ Effect.flatMap((object) =>+ getGoogleDriveFileMetadata(config, object.providerObjectId),+ ),+ Effect.flatMap((metadata) =>+ mapStorageError(+ repo.markObjectComplete(+ integrationId,+ key,+ metadata.size ? Number(metadata.size) : undefined,+ ),+ ),+ ),+ Effect.flatMap(() => createDriveObjectUrl(key)),+ Effect.map((Location) => ({ Location })),+ ),+ abort: (+ key: string,+ _uploadId?: string,+ _args?: Omit<+ S3.AbortMultipartUploadCommandInput,+ "Key" | "Bucket" | "UploadId"+ >,+ ) =>+ mapStorageError(repo.deleteObjectByKey(integrationId, key)).pipe(+ Effect.as({}),+ ),+ },+ createUploadTarget: (key: string, input: UploadTargetInput) =>+ createGoogleDriveResumableUpload(repo, config, {+ integrationId,+ ownerId,+ videoId: parseVideoIdFromObjectKey(key).pipe(+ Option.map((id) => id as Video.VideoId),+ Option.getOrNull,+ ),+ key,+ contentType: input.contentType,+ contentLength: input.contentLength,+ }).pipe(+ mapStorageError,+ Effect.map((url) => toDriveUploadTarget(url, input.contentType)),+ ),+ getObjectResponse: (key: string, range?: string | null) =>+ getObjectRecord(key).pipe(+ Effect.flatMap((object) =>+ getGoogleDriveObjectResponse(config, object.providerObjectId, range),+ ),+ ),+ };+};++export class Storage extends Effect.Service<Storage>()("Storage", {+ effect: Effect.gen(function* () {+ const repo = yield* StorageRepo;+ const s3Buckets = yield* S3Buckets;++ const getDriveAccess = Effect.fn("Storage.getDriveAccess")(function* (+ integrationId: StorageDomain.StorageIntegrationId,+ ) {+ const integration = yield* mapStorageError(+ repo.getIntegrationById(integrationId),+ ).pipe(+ Effect.flatMap(+ Option.match({+ onNone: () =>+ Effect.fail(+ new StorageDomain.StorageError({+ cause: new Error("Storage integration not found"),+ }),+ ),+ onSome: Effect.succeed,+ }),+ ),+ );+ const config = yield* mapStorageError(+ repo.getGoogleDriveConfig(integration),+ );+ return makeGoogleDriveAccess({ repo, integration, config });+ });++ const getWritableAccessForUser = Effect.fn(+ "Storage.getWritableAccessForUser",+ )(function* (userId: User.UserId) {+ const activeIntegration = yield* mapStorageError(+ repo.getActiveIntegrationForUser(userId),+ );+ if (Option.isSome(activeIntegration)) {+ const access = yield* getDriveAccess(activeIntegration.value.id);+ return {+ access,+ bucketId: Option.none(),+ storageIntegrationId: Option.some(activeIntegration.value.id),+ };+ }++ const [s3, customBucket] = yield* mapStorageError(+ s3Buckets.getBucketAccessForUser(userId),+ );+ return {+ access: makeS3Access(s3),+ bucketId: Option.map(customBucket, (bucket) => bucket.id),+ storageIntegrationId: Option.none(),+ };+ });++ const getAccessForVideo = Effect.fn("Storage.getAccessForVideo")(function* (+ video: Video.Video,+ ) {+ if (Option.isSome(video.storageIntegrationId)) {+ const access = yield* getDriveAccess(video.storageIntegrationId.value);+ return [access, Option.none()] as const;+ }++ const [s3, customBucket] = yield* mapStorageError(+ s3Buckets.getBucketAccess(video.bucketId),+ );+ return [makeS3Access(s3), customBucket] as const;+ });++ const createUploadTargetForUser = Effect.fn(+ "Storage.createUploadTargetForUser",+ )(function* (userId: User.UserId, key: string, input: UploadTargetInput) {+ const writable = yield* getWritableAccessForUser(userId);+ const upload = yield* writable.access.createUploadTarget(key, input);+ return { ...writable, upload };+ });++ const createUploadTargetForVideo = Effect.fn(+ "Storage.createUploadTargetForVideo",+ )(function* (video: Video.Video, key: string, input: UploadTargetInput) {+ const [access] = yield* getAccessForVideo(video);+ return yield* access.createUploadTarget(key, input);+ });++ return {+ getWritableAccessForUser,+ getAccessForVideo,+ createUploadTargetForUser,+ createUploadTargetForVideo,+ };+ }),+ dependencies: [StorageRepo.Default, S3Buckets.Default],+}) {+ static getWritableAccessForUser = (userId: User.UserId) =>+ Effect.flatMap(Storage, (storage) =>+ storage.getWritableAccessForUser(userId),+ );+ static getAccessForVideo = (video: Video.Video) =>+ Effect.flatMap(Storage, (storage) => storage.getAccessForVideo(video));+ static createUploadTargetForUser = (+ userId: User.UserId,+ key: string,+ input: UploadTargetInput,+ ) =>+ Effect.flatMap(Storage, (storage) =>+ storage.createUploadTargetForUser(userId, key, input),+ );+ static createUploadTargetForVideo = (+ video: Video.Video,+ key: string,+ input: UploadTargetInput,+ ) =>+ Effect.flatMap(Storage, (storage) =>+ storage.createUploadTargetForVideo(video, key, input),+ );+}