Skip to content

🎥 Make videos programmatically with React

wip gcp sites deploy

Matt Mcgillivrayb123c51cca19
diff --git a/packages/gcp/haloInf.mp4 b/packages/gcp/haloInf.mp4
new file mode 100644
index 0000000000..93e42edad0
Binary files /dev/null and b/packages/gcp/haloInf.mp4 differ
diff --git a/packages/gcp/remotion-gcp-cli.mjs b/packages/gcp/remotion-gcp-cli.mjs
index c44ec68ca2..d21247709d 100755
--- a/packages/gcp/remotion-gcp-cli.mjs
+++ b/packages/gcp/remotion-gcp-cli.mjs
@@ -1,63 +1,149 @@
#!/usr/bin/env node
import { v2 } from '@google-cloud/run';
import fs from 'fs';
+import { Storage, TransferManager } from '@google-cloud/storage';
// npx remotion-gcp --remotion-version=3.3.36-alpha --project=remotion-lambda --service-name=hello --region=australia-southeast1
-const { ServicesClient } = v2;
+// const { ServicesClient } = v2;
const sa_data = fs.readFileSync('./sa-key.json', 'utf8');
const sa_json = JSON.parse(sa_data)
-const runClient = new ServicesClient({
+// const runClient = new ServicesClient({
+// credentials: sa_json
+// });
+
+// const newService = await createService()
+
+// // TODO: Check input for whether to allow unauthenticated access
+// allowUnauthenticatedAccess(newService)
+
+
+// async function createService() {
+// const project = 'remotion-lambda' // TODO: get from args
+// const location = 'australia-southeast1' // TODO: get from args
+
+// const parent = `projects/${project}/locations/${location}`
+// const serviceId = 'remotionCloudRun' // TODO: get from args, or use a default name
+
+// // service structure: https://googleapis.dev/nodejs/run/latest/google.cloud.run.v2.IService.html
+// const service = {
+// template: {
+// containers: [
+// { image: 'us-docker.pkg.dev/remotion-dev/cloud-run/render:3.3.36-alpha' }
+// ]
+// }
+// }
+// // Construct request
+// const request = {
+// parent,
+// service,
+// serviceId,
+// };
+
+// // Run request
+// const [operation] = await runClient.createService(request);
+// const [response] = await operation.promise();
+// return response.name
+// }
+
+// async function allowUnauthenticatedAccess(newService) {
+// await runClient.setIamPolicy(
+// {
+// resource: newService,
+// policy: {
+// bindings: [
+// {
+// role: 'roles/run.invoker',
+// members: ['allUsers']
+// }
+// ]
+// }
+// });
+// }
+
+
+const cloudStorageClient = new Storage({
credentials: sa_json
});
-const newService = await createService()
+// cloudStorageClient.bucket('remotionlambda-testy').get()
+
+// const result = await cloudStorageClient.bucket('remotionlambda-testc').get();
+const bucketName = 'remotionlambda-test'
+const prefix = 'sites/xmycbufjs3/'
+// const [files] = await cloudStorageClient.bucket(bucketName).getFiles({ prefix });
+// // const [files, nextContinuationToken] = await cloudStorageClient.bucket('gcp-public-data-landsat').getFiles({ prefix: 'LC08/01/001' });
+
+// const dir = [
+// 'bundle.js', 'bundle.js.map'
+// ]
-// TODO: Check input for whether to allow unauthenticated access
-allowUnauthenticatedAccess(newService)
+// const filesOnStorageButNotLocal = files.filter((fileOnStorage) => {
+// const key = fileOnStorage.name?.substring(prefix.length);
+// return !dir[key];
+// });
+// filesOnStorageButNotLocal.map((d) => [
+// console.log('d', d.name)
+// ])
+// const key = 'sites/xmycbufjs3/LibraryMock.png'
+// await cloudStorageClient.bucket(bucketName).file(key).delete();
+// https://storage.googleapis.com/remotionlambda-test/sites/xmycbufjs3/LibraryMock.png
+const firstFilePath = 'haloInf.mp4'
+const secondFilePath = 'zoomJump.mp4'
-async function createService() {
- const project = 'remotion-lambda' // TODO: get from args
- const location = 'australia-southeast1' // TODO: get from args
+// const transferManager = new TransferManager(cloudStorageClient.bucket(bucketName));
+// await transferManager.uploadManyFiles([firstFilePath, secondFilePath], { prefix });
- const parent = `projects/${project}/locations/${location}`
- const serviceId = 'remotionCloudRun' // TODO: get from args, or use a default name
+// for (const filePath of [firstFilePath, secondFilePath]) {
+// console.log(`${filePath} uploaded to ${bucketName}.`);
+// }
- // service structure: https://googleapis.dev/nodejs/run/latest/google.cloud.run.v2.IService.html
- const service = {
- template: {
- containers: [
- { image: 'us-docker.pkg.dev/remotion-dev/cloud-run/render:3.3.36-alpha' }
- ]
- }
+const bucket = cloudStorageClient.bucket(bucketName)
+const remote_file = bucket.file("new/haloInf.mp4")
+
+console.log('test message')
+// var stats = fs.statSync(firstFilePath)
+// var fileSizeInBytes = stats.size;
+
+// fs.createReadStream(firstFilePath)
+// .pipe(remote_file.createWriteStream())
+// .on('error', function (err) { })
+// .on('progress', function (p) {
+// console.log(p, '/', fileSizeInBytes);
+// // as percentage
+// console.log('percentage progress: ', p.bytesWritten / fileSizeInBytes * 100);
+// // { bytesWritten: 67371008, contentLength: '*' }
+// })
+// .on('finish', function () {
+// console.log('completed');
+// // The file upload is complete.
+// });
+
+async function uploadInParallel(
+ bucket,
+ paths
+) {
+ const uploadPromises = [];
+ for (const index in paths) {
+ const path = paths[index];
+ const fileSizeInBytes = fs.statSync(path).size;
+ uploadPromises.push(
+ fs.createReadStream(path)
+ .pipe(bucket.file(`new/${path}`).createWriteStream())
+ .on('error', function (err) { })
+ .on('progress', function (p) {
+ console.log(path, `${Math.floor(p.bytesWritten / fileSizeInBytes * 100)}%`);
+ })
+ .on('finish', function () {
+ console.log(path, ' completed');
+ })
+ );
}
- // Construct request
- const request = {
- parent,
- service,
- serviceId,
- };
-
- // Run request
- const [operation] = await runClient.createService(request);
- const [response] = await operation.promise();
- return response.name
+ await Promise.all(uploadPromises).catch(console.error);
}
-async function allowUnauthenticatedAccess(newService) {
- await runClient.setIamPolicy(
- {
- resource: newService,
- policy: {
- bindings: [
- {
- role: 'roles/run.invoker',
- members: ['allUsers']
- }
- ]
- }
- });
-}
\ No newline at end of file
+
+await uploadInParallel(bucket, [firstFilePath, secondFilePath]);
diff --git a/packages/gcp/src/api/cloud-run-allow-unauthenticated-access.ts b/packages/gcp/src/api/cloud-run-allow-unauthenticated-access.ts
index a8cd0ecceb..510c99a817 100644
--- a/packages/gcp/src/api/cloud-run-allow-unauthenticated-access.ts
+++ b/packages/gcp/src/api/cloud-run-allow-unauthenticated-access.ts
@@ -1,4 +1,4 @@
-import { getCloudRunClient } from './get-cloud-run-client';
+import { getCloudRunClient } from './helpers/get-cloud-run-client';
/**
* @description Allow unauthenticated access to the Cloud Run service.
diff --git a/packages/gcp/src/api/create-bucket.ts b/packages/gcp/src/api/create-bucket.ts
new file mode 100644
index 0000000000..80b2a62fa6
--- /dev/null
+++ b/packages/gcp/src/api/create-bucket.ts
@@ -0,0 +1,17 @@
+import type {GcpRegion} from '../pricing/gcp-regions';
+import {getCloudStorageClient} from './helpers/get-cloud-storage-client';
+
+export const createBucket = async ({
+ region,
+ bucketName,
+}: {
+ region: GcpRegion;
+ bucketName: string;
+}) => {
+ const cloudStorageClient = getCloudStorageClient()
+
+ // metadata: https://googleapis.dev/nodejs/storage/latest/global.html#CreateBucketRequest
+ await cloudStorageClient.createBucket(bucketName, {
+ location: region
+ });
+};
diff --git a/packages/gcp/src/api/deploy-cloud-run-revision.ts b/packages/gcp/src/api/deploy-cloud-run-revision.ts
index f6d1957237..f9c32bab05 100644
--- a/packages/gcp/src/api/deploy-cloud-run-revision.ts
+++ b/packages/gcp/src/api/deploy-cloud-run-revision.ts
@@ -2,7 +2,7 @@ import { IService } from './helpers/IService';
import { validateGcpRegion } from '../shared/validate-gcp-region';
import { validateProjectID } from '../shared/validate-project-id';
import { validateRemotionVersion } from '../shared/validate-remotion-version';
-import { getCloudRunClient } from './get-cloud-run-client';
+import { getCloudRunClient } from './helpers/get-cloud-run-client';
export type DeployCloudRunRevisionInput = {
remotionVersion: string;
diff --git a/packages/gcp/src/api/deploy-new-cloud-run.ts b/packages/gcp/src/api/deploy-new-cloud-run.ts
index 87661790b2..f2ca4c0824 100644
--- a/packages/gcp/src/api/deploy-new-cloud-run.ts
+++ b/packages/gcp/src/api/deploy-new-cloud-run.ts
@@ -2,7 +2,7 @@ import { IService } from './helpers/IService';
import { validateGcpRegion } from '../shared/validate-gcp-region';
import { validateServiceName } from '../shared/validate-service-name';
import { validateProjectID } from '../shared/validate-project-id';
-import { getCloudRunClient } from './get-cloud-run-client';
+import { getCloudRunClient } from './helpers/get-cloud-run-client';
import { validateRemotionVersion } from '../shared/validate-remotion-version';
export type DeployCloudRunInput = {
diff --git a/packages/gcp/src/api/deploy-site.ts b/packages/gcp/src/api/deploy-site.ts
new file mode 100644
index 0000000000..5999fc244c
--- /dev/null
+++ b/packages/gcp/src/api/deploy-site.ts
@@ -0,0 +1,120 @@
+import type { WebpackOverrideFn } from 'remotion';
+import { gcpLs, gcpDeleteFile } from '../functions/helpers/io';
+import { bundleSite } from '../shared/bundle-site';
+import { getSitesKey } from '../shared/constants';
+import { getStorageDiffOperations } from '../shared/get-storage-operations';
+import { makeStorageServeUrl } from '../shared/make-storage-url';
+import { randomHash } from '../shared/random-hash';
+import { validateBucketName } from '../shared/validate-bucketname';
+import { validateSiteName } from '../shared/validate-site-name';
+import type { UploadDirProgress } from './upload-dir';
+import { uploadDir } from './upload-dir';
+import { getCloudStorageClient } from './helpers/get-cloud-storage-client';
+
+export type DeploySiteInput = {
+ entryPoint: string;
+ bucketName: string;
+ siteName?: string;
+ options?: {
+ onBundleProgress?: (progress: number) => void;
+ onUploadProgress?: (upload: UploadDirProgress) => void;
+ webpackOverride?: WebpackOverrideFn;
+ enableCaching?: boolean;
+ publicDir?: string | null;
+ rootDir?: string;
+ };
+};
+
+export type DeploySiteOutput = Promise<{
+ serveUrl: string;
+ siteName: string;
+ stats: {
+ uploadedFiles: number;
+ deletedFiles: number;
+ untouchedFiles: number;
+ };
+}>;
+
+/**
+ * @description Deploys a Remotion project to a GCP storage bucket to prepare it for rendering on Cloud Run.
+ * @link https://remotion.dev/docs/lambda/deploysite
+ * @param {string} params.entryPoint An absolute path to the entry file of your Remotion project.
+ * @param {string} params.bucketName The name of the bucket to deploy your project into.
+ * @param {string} params.siteName The name of the folder in which the project gets deployed to.
+ * @param {object} params.options Further options, see documentation page for this function.
+ */
+export const deploySite = async ({
+ bucketName,
+ entryPoint,
+ siteName,
+ options,
+}: DeploySiteInput): DeploySiteOutput => {
+ validateBucketName(bucketName, { mustStartWithRemotion: true });
+
+ const siteId = siteName ?? randomHash();
+ validateSiteName(siteId);
+
+ const cloudStorageClient = getCloudStorageClient()
+
+ // const filePath = 'path/to/your/file'
+ // const destFileName = 'your-new-file-name';
+ // const uploadOptions = {
+ // destination: destFileName
+ // }
+
+ // await cloudStorageClient.bucket(bucketName).upload(entryPoint, uploadOptions);
+
+ // check if bucket exists
+ await cloudStorageClient.bucket(bucketName).get()
+
+ const subFolder = getSitesKey(siteId);
+
+ // gcpLs is a function that lists all files in a bucket
+ const [files, bundled] = await Promise.all([
+ gcpLs({
+ bucketName,
+ prefix: subFolder
+ }),
+ bundleSite(entryPoint, options?.onBundleProgress ?? (() => undefined), {
+ publicPath: `/${subFolder}/`,
+ webpackOverride: options?.webpackOverride ?? ((f) => f),
+ enableCaching: options?.enableCaching ?? true,
+ publicDir: options?.publicDir,
+ rootDir: options?.rootDir,
+ }),
+ ]);
+
+ const { toDelete, toUpload, existingCount } = await getStorageDiffOperations({
+ objects: files,
+ bundle: bundled,
+ prefix: subFolder,
+ });
+
+ await Promise.all([
+ uploadDir({
+ bucket: bucketName,
+ localDir: bundled,
+ onProgress: options?.onUploadProgress ?? (() => undefined),
+ keyPrefix: subFolder,
+ toUpload,
+ }),
+ Promise.all(
+ toDelete.map((d) => {
+ return gcpDeleteFile({
+ bucketName,
+ key: d.name as string,
+ });
+ })
+ ),
+ ]);
+
+ return {
+ serveUrl: makeStorageServeUrl({ bucketName, subFolder }),
+ siteName: siteId,
+ stats: {
+ uploadedFiles: toUpload.length,
+ deletedFiles: toDelete.length,
+ untouchedFiles: existingCount,
+ },
+ };
+};
diff --git a/packages/gcp/src/api/get-buckets.ts b/packages/gcp/src/api/get-buckets.ts
new file mode 100644
index 0000000000..43d2fb01e2
--- /dev/null
+++ b/packages/gcp/src/api/get-buckets.ts
@@ -0,0 +1,23 @@
+import { Bucket } from '@google-cloud/storage';
+import {REMOTION_BUCKET_PREFIX} from '../shared/constants';
+import { getCloudStorageClient } from './helpers/get-cloud-storage-client';
+
+export const getRemotionStorageBuckets = async (): Promise<{
+ remotionBuckets: Bucket[];
+}> => {
+ // List buckets in this project
+ const cloudStorageClient = getCloudStorageClient()
+ const [buckets] = await cloudStorageClient.getBuckets();
+ if (!buckets) {
+ return {remotionBuckets: []};
+ }
+
+ // Lambda equivalent code was filtering buckets by region.
+ // Instead, I am just returning all buckets that get listed.
+ // Not sure if I need to filter them by project ID.
+
+ const remotionBuckets = buckets.filter((b) =>
+ b.name?.startsWith(REMOTION_BUCKET_PREFIX)
+ );
+ return {remotionBuckets: remotionBuckets};
+};
diff --git a/packages/gcp/src/api/get-or-create-bucket.ts b/packages/gcp/src/api/get-or-create-bucket.ts
new file mode 100644
index 0000000000..eabf3d606a
--- /dev/null
+++ b/packages/gcp/src/api/get-or-create-bucket.ts
@@ -0,0 +1,47 @@
+import type {GcpRegion} from '../pricing/gcp-regions';
+import {REMOTION_BUCKET_PREFIX} from '../shared/constants';
+import {makeBucketName} from '../shared/validate-bucketname';
+import {createBucket} from './create-bucket';
+import {getRemotionStorageBuckets} from './get-buckets';
+
+export type GetOrCreateBucketInput = {
+ region: GcpRegion;
+ onBucketEnsured?: () => void;
+};
+
+export type GetOrCreateBucketOutput = {
+ bucketName: string;
+};
+/**
+ * @description Creates a bucket for Remotion Cloud Run in your GCP Project. If one already exists, it will get returned instead.
+ * @link https://remotion.dev/docs/lambda/getorcreatebucket
+ * @param options.region The region in which you want your Storage bucket to reside in.
+ * @returns {Promise<GetOrCreateBucketOutput>} An object containing the `bucketName`.
+ */
+export const getOrCreateBucket = async (
+ options: GetOrCreateBucketInput
+): Promise<GetOrCreateBucketOutput> => {
+ const {remotionBuckets} = await getRemotionStorageBuckets();
+ if (remotionBuckets.length > 1) {
+ throw new Error(
+ `You have multiple buckets (${remotionBuckets.map(
+ (b) => b.name
+ )}) starting with "${REMOTION_BUCKET_PREFIX}". This is an error, please delete buckets so that you have one maximum.`
+ );
+ }
+
+ if (remotionBuckets.length === 1) {
+ options.onBucketEnsured?.();
+ return {bucketName: remotionBuckets[0].name};
+ }
+
+ const bucketName = makeBucketName(options.region); // TODO: pretty sure I can remove the region here
+
+ await createBucket({
+ bucketName,
+ region: options.region,
+ });
+ options.onBucketEnsured?.();
+
+ return {bucketName};
+};
diff --git a/packages/gcp/src/api/get-cloud-run-client.ts b/packages/gcp/src/api/helpers/get-cloud-run-client.ts
similarity index 100%
rename from packages/gcp/src/api/get-cloud-run-client.ts
rename to packages/gcp/src/api/helpers/get-cloud-run-client.ts
diff --git a/packages/gcp/src/api/helpers/get-cloud-storage-client.ts b/packages/gcp/src/api/helpers/get-cloud-storage-client.ts
new file mode 100644
index 0000000000..ad456669b5
--- /dev/null
+++ b/packages/gcp/src/api/helpers/get-cloud-storage-client.ts
@@ -0,0 +1,11 @@
+import { Storage } from '@google-cloud/storage';
+import fs from 'fs';
+
+const sa_data = fs.readFileSync('./sa-key.json', 'utf8');
+const sa_json = JSON.parse(sa_data)
+
+export const getCloudStorageClient = () => {
+ return new Storage({
+ credentials: sa_json
+ })
+};
\ No newline at end of file
diff --git a/packages/gcp/src/api/upload-dir.ts b/packages/gcp/src/api/upload-dir.ts
new file mode 100644
index 0000000000..86513202c6
--- /dev/null
+++ b/packages/gcp/src/api/upload-dir.ts
@@ -0,0 +1,137 @@
+import type { Dirent } from 'fs';
+import { createReadStream, promises as fs } from 'fs';
+import { makeStorageKey } from '../shared/make-storage-key';
+import { getCloudStorageClient } from './helpers/get-cloud-storage-client';
+import path from 'path';
+import { Log } from '../cli/log';
+
+type FileInfo = {
+ name: string;
+ size: number;
+};
+
+export type UploadDirProgress = {
+ totalFiles: number;
+ filesUploaded: number;
+ totalSize: number;
+ sizeUploaded: number;
+};
+
+export type MockFile = {
+ name: string;
+ content: string;
+};
+
+export const getDirFiles = (entry: string): MockFile[] => {
+ throw new TypeError(
+ 'should only be executed in test ' + JSON.stringify(entry)
+ );
+};
+
+export const uploadDir = async ({
+ bucket,
+ localDir,
+ onProgress,
+ keyPrefix,
+ toUpload,
+}: {
+ bucket: string;
+ localDir: string;
+ keyPrefix: string;
+ onProgress: (progress: UploadDirProgress) => void;
+ toUpload: string[];
+}) => {
+ const files = await getFiles(localDir, localDir, toUpload);
+ const progresses: { [key: string]: number } = {};
+ for (const file of files) {
+ progresses[file.name] = 0;
+ }
+
+ async function getFiles(
+ directory: string,
+ originalDirectory: string,
+ toUpload: string[]
+ ): Promise<FileInfo[]> {
+ const dirents = await fs.readdir(directory, { withFileTypes: true });
+ const _files = await Promise.all(
+ dirents
+ .map((dirent): [Dirent, string] => {
+ const res = path.resolve(directory, dirent.name);
+ return [dirent, res];
+ })
+ .filter(([dirent, res]) => {
+ const relative = path.relative(originalDirectory, res);
+ if (dirent.isDirectory()) {
+ return true;
+ }
+
+ if (!toUpload.includes(relative)) {
+ return false;
+ }
+
+ return true;
+ })
+ .map(async ([dirent, res]) => {
+ const { size } = await fs.stat(res);
+ return dirent.isDirectory()
+ ? getFiles(res, originalDirectory, toUpload)
+ : [
+ {
+ name: res,
+ size,
+ },
+ ];
+ })
+ );
+ return _files.flat(1);
+ }
+
+ const cloudStorageClient = getCloudStorageClient()
+
+ const uploadPromises:any[] = [];
+
+ files.map(async (filePath) => {
+ const uploadDestination = makeStorageKey(keyPrefix, localDir, filePath.name);
+ Log.verbose('uploadDestination:', uploadDestination);
+ uploadPromises.push(createReadStream(path.relative(localDir, filePath.name).split(path.sep).join('/'))
+ .pipe(cloudStorageClient.bucket(bucket).file(uploadDestination).createWriteStream())
+ .on('error', function (err: any) {Log.verbose('Upload error: ', err) })
+ .on('progress', function (p: any) {
+ Log.verbose('in Progress:', filePath.name, p.bytesWritten);
+ progresses[filePath.name] = p.bytesWritten ?? 0;
+ })
+ .on('finish', function () {
+ progresses[filePath.name] = filePath.size;
+ }))
+ })
+
+
+ // const uploads = files.map(async (filePath) => {
+ // const uploadDestination = makeStorageKey(keyPrefix, localDir, filePath.name);
+ // createReadStream(path.relative(localDir, filePath.name).split(path.sep).join('/'))
+ // .pipe(cloudStorageClient.bucket(bucket).file(uploadDestination).createWriteStream())
+ // .on('error', function (err: any) { })
+ // .on('progress', function (p: any) {
+ // Log.verbose('in Progress:', filePath.name, p.bytesWritten);
+ // progresses[filePath.name] = p.bytesWritten ?? 0;
+ // })
+ // .on('finish', function () {
+ // progresses[filePath.name] = filePath.size;
+ // })
+ // })
+
+ // const promise = Promise.all(uploads);
+ const promise = Promise.all(uploadPromises).catch(console.error);
+
+
+ const interval = setInterval(() => {
+ onProgress({
+ totalSize: files.map((f) => f.size).reduce((a, b) => a + b, 0),
+ sizeUploaded: Object.values(progresses).reduce((a, b) => a + b, 0),
+ totalFiles: files.length,
+ filesUploaded: files.filter((f) => progresses[f.name] === f.size).length,
+ });
+ }, 1000);
+ await promise;
+ clearInterval(interval);
+};
diff --git a/packages/gcp/src/cli/commands/sites/create.ts b/packages/gcp/src/cli/commands/sites/create.ts
new file mode 100644
index 0000000000..9a2a0e6ca6
--- /dev/null
+++ b/packages/gcp/src/cli/commands/sites/create.ts
@@ -0,0 +1,175 @@
+import { CliInternals, ConfigInternals } from '@remotion/cli';
+import { quit } from '../../helpers/quit';
+import { Log } from '../../log';
+import { BINARY_NAME } from '../../../shared/constants';
+import { existsSync, lstatSync } from 'fs';
+import path from 'path';
+import { Internals } from 'remotion';
+import { parsedGcpCli } from '../../args';
+import { validateSiteName } from '../../../shared/validate-site-name';
+import { getGcpRegion } from '../../get-gcp-region';
+import { getOrCreateBucket } from '../../../api/get-or-create-bucket';
+import {
+ BucketCreationProgress,
+ BundleProgress,
+ DeployToStorageProgress,
+} from '../../helpers/progress-bar';
+import {
+ makeBucketProgress,
+ makeBundleProgress,
+ makeDeployProgressBar,
+} from '../../helpers/progress-bar';
+import { deploySite } from '../../../api/deploy-site';
+
+export const SITES_CREATE_SUBCOMMAND = 'create';
+
+export const sitesCreateSubcommand = async (
+ args: string[],
+ remotionRoot: string) => {
+ const { file, reason } = CliInternals.findEntryPoint(args, remotionRoot);
+ if (!file) {
+ Log.error('No entry file passed.');
+ Log.info(
+ 'Pass an additional argument specifying the entry file of your Remotion project:'
+ );
+ Log.info();
+ Log.info(`${BINARY_NAME} deploy <entry-file.ts>`);
+ quit(1);
+ return;
+ }
+
+ Log.verbose('Entry point:', file, 'Reason:', reason);
+
+ const absoluteFile = path.join(process.cwd(), file);
+ if (!existsSync(absoluteFile)) {
+ Log.error(
+ `No file exists at ${absoluteFile}. Make sure the path exists and try again.`
+ );
+ quit(1);
+ }
+
+ if (lstatSync(absoluteFile).isDirectory()) {
+ Log.error(
+ `You passed a path ${absoluteFile} but it is a directory. Pass a file instead.`
+ );
+ quit(1);
+ }
+
+ const desiredSiteName = parsedGcpCli['site-name'] ?? undefined;
+ if (desiredSiteName !== undefined) {
+ validateSiteName(desiredSiteName);
+ }
+
+ const progressBar = CliInternals.createOverwriteableCliOutput(
+ CliInternals.quietFlagProvided()
+ );
+
+ const multiProgress: {
+ bundleProgress: BundleProgress;
+ bucketProgress: BucketCreationProgress;
+ deployProgress: DeployToStorageProgress;
+ } = {
+ bundleProgress: {
+ doneIn: null,
+ progress: 0,
+ },
+ bucketProgress: {
+ bucketCreated: false,
+ doneIn: null,
+ },
+ deployProgress: {
+ doneIn: null,
+ totalSize: null,
+ sizeUploaded: 0,
+ stats: null,
+ },
+ };
+
+ const updateProgress = () => {
+ progressBar.update(
+ [
+ makeBundleProgress(multiProgress.bundleProgress),
+ makeBucketProgress(multiProgress.bucketProgress),
+ makeDeployProgressBar(multiProgress.deployProgress),
+ ].join('\n')
+ );
+ };
+
+ const bucketStart = Date.now();
+
+ const { bucketName } = await getOrCreateBucket({
+ region: getGcpRegion(),
+ onBucketEnsured: () => {
+ multiProgress.bucketProgress.bucketCreated = true;
+ updateProgress();
+ },
+ });
+
+ multiProgress.bucketProgress.doneIn = Date.now() - bucketStart;
+ updateProgress();
+
+ const bundleStart = Date.now();
+
+ const { serveUrl, siteName, stats } = await deploySite({
+ entryPoint: absoluteFile,
+ siteName: desiredSiteName,
+ bucketName,
+ options: {
+ onBundleProgress: (progress: number) => {
+ multiProgress.bundleProgress = {
+ progress,
+ doneIn: progress === 100 ? Date.now() - bundleStart : null,
+ };
+ },
+ onUploadProgress: (p) => {
+ multiProgress.deployProgress = {
+ sizeUploaded: p.sizeUploaded,
+ totalSize: p.totalSize,
+ doneIn: null,
+ stats: null,
+ };
+ updateProgress();
+ },
+ enableCaching: ConfigInternals.getWebpackCaching(),
+ webpackOverride: ConfigInternals.getWebpackOverrideFn() ?? ((f) => f),
+ },
+ });
+
+ updateProgress();
+
+ const uploadStart = Date.now();
+
+ const uploadDuration = Date.now() - uploadStart;
+ multiProgress.deployProgress = {
+ sizeUploaded: 1,
+ totalSize: 1,
+ doneIn: uploadDuration,
+ stats: {
+ addedFiles: stats.uploadedFiles,
+ removedFiles: stats.deletedFiles,
+ untouchedFiles: stats.untouchedFiles,
+ },
+ };
+ updateProgress();
+
+ Log.info();
+ Log.info();
+ Log.info('Deployed to GCP Storage!');
+
+ Log.info(`Serve URL: ${serveUrl}`);
+ Log.info(`Site Name: ${siteName}`);
+
+ Log.info();
+ Log.info(
+ CliInternals.chalk.blueBright(
+ 'ℹ️ If you make changes to your code, you need to redeploy the site. You can overwrite the existing site by running:'
+ )
+ );
+ Log.info(
+ CliInternals.chalk.blueBright(
+ ['npx remotion gcp sites create', args[0], `--site-name=${siteName}`]
+ .filter(Internals.truthy)
+ .join(' ')
+ )
+ );
+}
\ No newline at end of file
diff --git a/packages/gcp/src/cli/commands/sites/index.ts b/packages/gcp/src/cli/commands/sites/index.ts
new file mode 100644
index 0000000000..04fd2d1ce4
--- /dev/null
+++ b/packages/gcp/src/cli/commands/sites/index.ts
@@ -0,0 +1,23 @@
+import {Log} from '@remotion/cli/dist/log';
+import {quit} from '../../helpers/quit';
+import {sitesCreateSubcommand, SITES_CREATE_SUBCOMMAND} from './create';
+
+export const SITES_COMMAND = 'sites';
+
+const printSitesHelp = () => {
+ // TODO: Add help text
+};
+
+export const sitesCommand = (args: string[], remotionRoot: string) => {
+ if (args[0] === SITES_CREATE_SUBCOMMAND) {
+ return sitesCreateSubcommand(args.slice(1), remotionRoot);
+ }
+
+ if (args[0]) {
+ Log.error(`Subcommand ${args[0]} not found.`);
+ printSitesHelp();
+ quit(1);
+ }
+
+ printSitesHelp();
+};
diff --git a/packages/gcp/src/cli/helpers/progress-bar.ts b/packages/gcp/src/cli/helpers/progress-bar.ts
new file mode 100644
index 0000000000..dfb35362d9
--- /dev/null
+++ b/packages/gcp/src/cli/helpers/progress-bar.ts
@@ -0,0 +1,101 @@
+import {CliInternals} from '@remotion/cli';
+import {Internals} from 'remotion';
+
+export type BundleProgress = {
+ progress: number;
+ doneIn: number | null;
+};
+
+export const makeBundleProgress = ({progress, doneIn}: BundleProgress) => {
+ return [
+ '📦',
+ `(1/3)`,
+ CliInternals.makeProgressBar(progress / 100),
+ `${doneIn === null ? 'Bundling' : 'Bundled'} video`,
+ doneIn === null
+ ? `${Math.round(progress)}%`
+ : CliInternals.chalk.gray(`${doneIn}ms`),
+ ].join(' ');
+};
+
+export type BucketCreationProgress = {
+ bucketCreated: boolean;
+ doneIn: number | null;
+};
+
+export const makeBucketProgress = ({
+ bucketCreated,
+ doneIn,
+}: BucketCreationProgress) => {
+ const states = [bucketCreated];
+ const statesFinished = states.filter(Boolean).map((p) => p).length;
+ const progress = statesFinished / states.length;
+
+ return [
+ '🪣',
+ `(2/3)`,
+ CliInternals.makeProgressBar(progress),
+ `${doneIn === null ? 'Creating' : 'Created'} bucket`,
+ doneIn === null
+ ? `${statesFinished} / ${states.length}`
+ : CliInternals.chalk.gray(`${doneIn}ms`),
+ ].join(' ');
+};
+
+type UploadStats = {
+ addedFiles: number;
+ removedFiles: number;
+ untouchedFiles: number;
+};
+
+export type DeployToStorageProgress = {
+ sizeUploaded: number;
+ totalSize: number | null;
+ doneIn: number | null;
+ stats: UploadStats | null;
+};
+
+const makeUploadDiff = ({stats}: {stats: UploadStats | null}) => {
+ if (!stats) {
+ return null;
+ }
+
+ if (stats.addedFiles === 0 && stats.removedFiles === 0) {
+ return CliInternals.chalk.gray(`(Unchanged)`);
+ }
+
+ const total = stats.addedFiles + stats.removedFiles;
+ return CliInternals.chalk.gray(
+ `(${[
+ stats.addedFiles ? `+${stats.addedFiles}` : null,
+ stats.removedFiles ? `-${stats.removedFiles}` : null,
+ ]
+ .filter(Internals.truthy)
+ .join(',')} ${total === 1 ? 'file' : 'files'})`
+ );
+};
+
+export const makeDeployProgressBar = ({
+ sizeUploaded,
+ totalSize,
+ doneIn,
+ stats,
+}: DeployToStorageProgress) => {
+ const progress = totalSize === null ? 0 : sizeUploaded / totalSize;
+ return [
+ '☁️ ',
+ `(3/3)`,
+ CliInternals.makeProgressBar(progress),
+ `${doneIn === null ? 'Uploading' : 'Uploaded'} to GCP Storage Bucket`,
+ doneIn === null
+ ? typeof totalSize === 'number'
+ ? `${CliInternals.formatBytes(sizeUploaded)}/${CliInternals.formatBytes(
+ totalSize
+ )}`
+ : ''
+ : CliInternals.chalk.gray(`${doneIn}ms`),
+ makeUploadDiff({stats}),
+ ]
+ .filter(Internals.truthy)
+ .join(' ');
+};
diff --git a/packages/gcp/src/cli/index.ts b/packages/gcp/src/cli/index.ts
index 11b8ad84cd..1dc0628ce6 100644
--- a/packages/gcp/src/cli/index.ts
+++ b/packages/gcp/src/cli/index.ts
@@ -2,6 +2,7 @@ import {Log} from './log';
import {quit} from './helpers/quit';
import {parsedGcpCli} from './args';
import {cloudRunCommand, CLOUD_RUN_COMMAND} from './commands/cloud-run';
+import {sitesCommand, SITES_COMMAND} from './commands/sites';
const matchCommand = (args: string[], remotionRoot: string) => {
if (parsedGcpCli.help || args.length === 0) {
@@ -13,6 +14,10 @@ const matchCommand = (args: string[], remotionRoot: string) => {
return cloudRunCommand(args.slice(1));
}
+ if (args[0] === SITES_COMMAND) {
+ return sitesCommand(args.slice(1), remotionRoot);
+ }
+
if (args[0] === 'deploy') {
Log.info(`The "deploy" command does not exist.`);
Log.info(`Did you mean "cloud-run deploy"?`);
diff --git a/packages/gcp/src/client.ts b/packages/gcp/src/client.ts
new file mode 100644
index 0000000000..9f1a7f16e9
--- /dev/null
+++ b/packages/gcp/src/client.ts
@@ -0,0 +1,3 @@
+import type {GcpRegion} from './pricing/gcp-regions';
+
+export type {GcpRegion};
diff --git a/packages/gcp/src/functions/helpers/io.ts b/packages/gcp/src/functions/helpers/io.ts
new file mode 100644
index 0000000000..eb3945eb49
--- /dev/null
+++ b/packages/gcp/src/functions/helpers/io.ts
@@ -0,0 +1,37 @@
+import { getCloudStorageClient } from '../../api/helpers/get-cloud-storage-client';
+import { File } from '@google-cloud/storage';
+
+export type GcpLSInput = {
+ bucketName: string;
+ prefix: string;
+};
+export type GcpLsReturnType = Promise<File[]>;
+
+export const gcpLs = async ({
+ bucketName,
+ prefix
+}: GcpLSInput): GcpLsReturnType => {
+ try {
+ const cloudStorageClient = getCloudStorageClient()
+ const [files] = await cloudStorageClient.bucket(bucketName).getFiles({ prefix, autoPaginate: true });
+ return files;
+ } catch (err) {
+ throw err;
+ }
+};
+
+export const gcpDeleteFile = async ({
+ bucketName,
+ key
+}: {
+ bucketName: string;
+ key: string;
+}) => {
+ try {
+ const cloudStorageClient = getCloudStorageClient()
+ await cloudStorageClient.bucket(bucketName).file(key).delete();
+ } catch (err) {
+ throw err;
+ }
+}
+
diff --git a/packages/gcp/src/regions.ts b/packages/gcp/src/regions.ts
new file mode 100644
index 0000000000..8f8a611967
--- /dev/null
+++ b/packages/gcp/src/regions.ts
@@ -0,0 +1,3 @@
+import {GCP_REGIONS} from './pricing/gcp-regions';
+
+export {GCP_REGIONS};
diff --git a/packages/gcp/src/shared/bundle-site.ts b/packages/gcp/src/shared/bundle-site.ts
new file mode 100644
index 0000000000..c9a0d71ac2
--- /dev/null
+++ b/packages/gcp/src/shared/bundle-site.ts
@@ -0,0 +1,3 @@
+import {bundle} from '@remotion/bundler';
+
+export const bundleSite = bundle;
diff --git a/packages/gcp/src/shared/constants.ts b/packages/gcp/src/shared/constants.ts
index cf4d325804..5dcf18fcba 100644
--- a/packages/gcp/src/shared/constants.ts
+++ b/packages/gcp/src/shared/constants.ts
@@ -1,3 +1,8 @@
import type {GcpRegion} from '../pricing/gcp-regions';
-export const DEFAULT_REGION: GcpRegion = 'us-east1';
\ No newline at end of file
+export const DEFAULT_REGION: GcpRegion = 'us-east1';
+export const BINARY_NAME = 'remotion gcp';
+
+export const REMOTION_BUCKET_PREFIX = 'remotioncloudrun-';
+
+export const getSitesKey = (siteId: string) => `sites/${siteId}`;
\ No newline at end of file
diff --git a/packages/gcp/src/shared/get-etag.ts b/packages/gcp/src/shared/get-etag.ts
new file mode 100644
index 0000000000..aa23c64d02
--- /dev/null
+++ b/packages/gcp/src/shared/get-etag.ts
@@ -0,0 +1,23 @@
+import fs from 'fs';
+import crypto from 'crypto';
+
+const chunk = 1024 * 1024 * 5; // 5MB
+
+const md5 = (data: Buffer) =>
+ crypto.createHash('md5').update(data).digest('hex');
+
+export const getEtagOfFile = async (filePath: string) => {
+ const stream = await fs.promises.readFile(filePath);
+ if (stream.length <= chunk) {
+ return `"${md5(stream)}"`;
+ }
+
+ const md5Chunks = [];
+ const chunksNumber = Math.ceil(stream.length / chunk);
+ for (let i = 0; i < chunksNumber; i++) {
+ const chunkStream = stream.slice(i * chunk, (i + 1) * chunk);
+ md5Chunks.push(md5(chunkStream));
+ }
+
+ return `"${md5(Buffer.from(md5Chunks.join(''), 'hex'))}-${chunksNumber}"`;
+};
diff --git a/packages/gcp/src/shared/get-storage-operations.ts b/packages/gcp/src/shared/get-storage-operations.ts
new file mode 100644
index 0000000000..3744409f4e
--- /dev/null
+++ b/packages/gcp/src/shared/get-storage-operations.ts
@@ -0,0 +1,41 @@
+import { File } from '@google-cloud/storage';
+import {readDirectory} from './read-dir';
+
+export const getStorageDiffOperations = async ({
+ objects,
+ bundle,
+ prefix,
+}: {
+ objects: File[];
+ bundle: string;
+ prefix: string;
+}) => {
+ const dir = await readDirectory({
+ dir: bundle,
+ etags: {},
+ originalDir: bundle,
+ });
+
+ const filesOnStorageButNotLocal = objects.filter((fileOnStorage) => {
+ const key = fileOnStorage.name?.substring(prefix.length) as string;
+ return !dir[key];
+ });
+ const localFilesNotOnStorage = Object.keys(dir).filter((d) => {
+ return !objects.find((o) => {
+ const key = o.name?.substring(prefix.length) as string;
+ return key === d && o.metadata.etag === dir[d];
+ });
+ });
+ const existing = Object.keys(dir).filter((d) => {
+ return objects.find((o) => {
+ const key = o.name?.substring(prefix.length) as string;
+ return key === d && o.metadata.etag === dir[d];
+ });
+ });
+
+ return {
+ toDelete: filesOnStorageButNotLocal,
+ toUpload: localFilesNotOnStorage,
+ existingCount: existing.length,
+ };
+};
diff --git a/packages/gcp/src/shared/make-storage-key.ts b/packages/gcp/src/shared/make-storage-key.ts
new file mode 100644
index 0000000000..14cbf78d58
--- /dev/null
+++ b/packages/gcp/src/shared/make-storage-key.ts
@@ -0,0 +1,5 @@
+import path from 'path';
+
+export const makeStorageKey = (folder: string, dir: string, filePath: string) => {
+ return `${folder}/${path.relative(dir, filePath).split(path.sep).join('/')}`;
+};
diff --git a/packages/gcp/src/shared/make-storage-url.ts b/packages/gcp/src/shared/make-storage-url.ts
new file mode 100644
index 0000000000..a7df532826
--- /dev/null
+++ b/packages/gcp/src/shared/make-storage-url.ts
@@ -0,0 +1,11 @@
+import crypto from 'crypto';
+
+export const makeStorageServeUrl = ({
+ bucketName,
+ subFolder,
+}: {
+ bucketName: string;
+ subFolder: string;
+}): string => {
+ return `https://storage.googleapis.com/${bucketName}/${subFolder}/index.html`;
+};
diff --git a/packages/gcp/src/shared/random-hash.ts b/packages/gcp/src/shared/random-hash.ts
new file mode 100644
index 0000000000..de476d38f6
--- /dev/null
+++ b/packages/gcp/src/shared/random-hash.ts
@@ -0,0 +1,11 @@
+const alphabet = 'abcdefghijklmnopqrstuvwxyz0123456789';
+
+// eslint-disable-next-line @typescript-eslint/no-unused-vars
+export const randomHash = (_options?: {randomInTests: boolean}): string => {
+ return new Array(10)
+ .fill(1)
+ .map(() => {
+ return alphabet[Math.floor(Math.random() * alphabet.length)];
+ })
+ .join('');
+};
diff --git a/packages/gcp/src/shared/read-dir.ts b/packages/gcp/src/shared/read-dir.ts
new file mode 100644
index 0000000000..c66e8a2edd
--- /dev/null
+++ b/packages/gcp/src/shared/read-dir.ts
@@ -0,0 +1,47 @@
+import * as fs from 'fs';
+import * as path from 'path';
+import {getEtagOfFile} from './get-etag';
+
+// Function to recursively read a directory and return a list of files
+// with their etags and file names
+export async function readDirectory({
+ dir,
+ etags,
+ originalDir,
+}: {
+ dir: string;
+ etags: {[key: string]: string};
+ originalDir: string;
+}) {
+ const files = fs.readdirSync(dir);
+
+ for (const file of files) {
+ if (file.startsWith('.DS_Store')) continue;
+
+ const filePath = path.join(dir, file);
+
+ if (fs.lstatSync(filePath).isDirectory()) {
+ etags = {
+ ...etags,
+ ...(await readDirectory({dir: filePath, etags, originalDir})),
+ };
+ continue;
+ }
+
+ // eslint-disable-next-line no-lonely-if
+ if (fs.lstatSync(filePath).isSymbolicLink()) {
+ const realPath = fs.realpathSync(filePath);
+
+ etags[path.relative(originalDir, filePath)] = await getEtagOfFile(
+ realPath
+ );
+ } else {
+ etags[path.relative(originalDir, filePath)] = await getEtagOfFile(
+ filePath
+ );
+ }
+ }
+
+ // Return the list of files with their etags and file names
+ return etags;
+}
diff --git a/packages/gcp/src/shared/validate-bucketname.ts b/packages/gcp/src/shared/validate-bucketname.ts
new file mode 100644
index 0000000000..d879169d29
--- /dev/null
+++ b/packages/gcp/src/shared/validate-bucketname.ts
@@ -0,0 +1,61 @@
+import type {GcpRegion} from '../client';
+import {GCP_REGIONS} from '../regions';
+import {REMOTION_BUCKET_PREFIX} from './constants';
+import {randomHash} from './random-hash';
+
+export const validateBucketName = (
+ bucketName: unknown,
+ options: {
+ mustStartWithRemotion: boolean;
+ }
+) => {
+ if (typeof bucketName !== 'string') {
+ throw new TypeError(
+ `'bucketName' must be a string, but is ${JSON.stringify(bucketName)}`
+ );
+ }
+
+ if (
+ options.mustStartWithRemotion &&
+ !bucketName.startsWith(REMOTION_BUCKET_PREFIX)
+ ) {
+ throw new Error(
+ `The bucketName parameter must start with ${REMOTION_BUCKET_PREFIX}.`
+ );
+ }
+
+ if (
+ !bucketName.match(
+ /^(?=^.{3,63}$)(?!^(\d+\.)+\d+$)(^(([a-z0-9]|[a-z0-9][a-z0-9-]*[a-z0-9])\.)*([a-z0-9]|[a-z0-9][a-z0-9-]*[a-z0-9])$)/
+ )
+ ) {
+ throw new Error(`The bucket ${bucketName} `);
+ }
+};
+
+export const parseBucketName = (
+ name: string
+): {
+ region: GcpRegion | null;
+} => {
+ const parsed = name.match(
+ new RegExp(`^${REMOTION_BUCKET_PREFIX}(.*)-([a-z0-9A-Z]+)$`)
+ );
+ const region = parsed?.[1] as GcpRegion;
+
+ if (!region) {
+ return {region: null};
+ }
+
+ const realRegionFound = GCP_REGIONS.find(
+ (r) => r.replace(/-/g, '') === region
+ );
+
+ return {region: realRegionFound ?? null};
+};
+
+export const makeBucketName = (region: GcpRegion) => {
+ return `${REMOTION_BUCKET_PREFIX}${region.replace(/-/g, '')}-${randomHash({
+ randomInTests: false,
+ })}`;
+};
diff --git a/packages/gcp/src/shared/validate-site-name.ts b/packages/gcp/src/shared/validate-site-name.ts
new file mode 100644
index 0000000000..4d4c1406e8
--- /dev/null
+++ b/packages/gcp/src/shared/validate-site-name.ts
@@ -0,0 +1,21 @@
+export const validateSiteName = (siteName: unknown) => {
+ if (typeof siteName === 'undefined') {
+ return;
+ }
+
+ if (typeof siteName !== 'string') {
+ throw new TypeError(
+ `The 'projectName' argument must be a string if provided, but is ${JSON.stringify(
+ siteName
+ )}`
+ );
+ }
+
+ if (!siteName.match(/([0-9a-zA-Z-!_.*'()]+)/g)) {
+ throw new Error(
+ "The `siteName` must match the RegExp `/([0-9a-zA-Z-!_.*'()]+)/g`. You passed: " +
+ siteName +
+ '. Check for invalid characters.'
+ );
+ }
+};
diff --git a/packages/gcp/zoomJump.mp4 b/packages/gcp/zoomJump.mp4
new file mode 100644
index 0000000000..4c2bfa1585
Binary files /dev/null and b/packages/gcp/zoomJump.mp4 differ