🎥 Make videos programmatically with React
deploy site working, readme wip
Matt Mcgillivray83a0fc79abd0
diff --git a/.gitignore b/.gitignoreindex eadbbbfd3a..d14d1832a6 100644--- a/.gitignore+++ b/.gitignore@@ -14,4 +14,4 @@ packages/example/out.vercelpackages/renderer/targetpackages/gcp/src/remotion-lambda-gcp.code-workspace-sa-key.json+sa-key*.jsondiff --git a/packages/gcp/readme.md b/packages/gcp/readme.mdindex edb760141c..af32a1b48d 100644--- a/packages/gcp/readme.md+++ b/packages/gcp/readme.md@@ -4,15 +4,73 @@ The /container folder contains a package.json that lists functions-framework asThis can be built and deployed to Cloud Run. Cloud Run is a serverless container platform that allows you to run containers in a managed environment.-### Push images to Google Container Registry-To start, you need to create a project in the Google Cloud Console, and create a repository in the Google Container Registry, and push the container to the registry using;-`gcloud builds submit --tag australia-southeast1-docker.pkg.dev/remotion-lambda/repo1/render-on-cloud-run:0.1.0`-### Deploy to Cloud Run-Navigate to Cloud Run, and click "Create Service". Select "Container Registry", and select the image you just pushed. You can select `Allow unauthenticated invocations` to ignore security for now. Click "Create".-To update the image running on Cloud Run, you can click "Edit & Deploy new revision" and select the new image.+## Deploying new artifact repo in GCP for new Remotion versions+Public artifact registry that contains the container images+ us-docker.pkg.dev/remotion-dev/cloud-run/render+Image is tagged with the same semver as the remotion packages+ us-docker.pkg.dev/remotion-dev/cloud-run/render:3.3.36-alpha+Part of the CI/CD pipeline should be to push a new container image to the artifact registry, with the right version:+`gcloud builds submit --tag us-docker.pkg.dev/remotion-dev/cloud-run/render:${version}`++++# How to use the GCP CLI commands+### 1. Create a project in the Google Cloud Console+Navigate to the [Manage Resources](https://console.cloud.google.com/cloud-resource-manager?walkthrough_id=resource-manager--create-project&start_index=1#step_index=1) screen in Google Cloud Console.+- On the Select organization drop-down list at the top of the page, select the organization resource in which you want to create a project. If you are a free trial user, skip this step, as this list does not appear.+- Click Create Project.+- In the New Project window that appears, enter a project name and select a billing account as applicable. A project name can contain only letters, numbers, single quotes, hyphens, spaces, or exclamation points, and must be between 4 and 30 characters.+- Enter the parent organization or folder resource in the Location box. That resource will be the hierarchical parent of the new project. If No organization is an option, you can select it to create your new project as the top level of its own resource hierarchy.+- When you're finished entering new project details, click Create.++### 2. Create a service account in the Google Cloud Console+Navigate to the [Service Accounts](https://console.cloud.google.com/projectselector2/iam-admin/serviceaccounts/create) screen in Google Cloud Console, within IAM.+- Select the Cloud project created in the previous step.+- Enter a service account name to display in the Google Cloud console.+- The Google Cloud console generates a service account ID based on this name. Edit the ID if necessary. You cannot change the ID later.+- Optional: Enter a description of the service account.+- Click 'Create and continue' and continue to the next step.+- Give the Service Account the Owner role. Note - this grants full admin rights and should be refined before the GCP option is live.++- Click Done to finish creating the service account.++### 3. Save a key for the Service Account+- Navigate to the [Service Accounts](https://console.cloud.google.com/iam-admin/serviceaccounts) screen in Google Cloud Console, within IAM.+- Select the Cloud project created in the previous step.+- Click on the ellipsis under 'Actions', in the final column, and click 'Manage keys'.+- On the next screen, click ADD KEY, and then Create new key.+- select JSON, and click Create.+- Save the JSON file to your computer, with the filename `sa-key.json`.+- Place the key in the root of the Remotion project you wish to deploy to GCP. For now, this will have to be somewhere that `npx remotion gcp ...` is able to run, as this package is not deploy to npm yet.++### 3. Enable required APIs in the project+- Enable the Cloud Run API. Navigate to the [Cloud Run API](https://console.cloud.google.com/apis/library/run.googleapis.com) screen in Google Cloud Console, and click ENABLE. Make sure the correct project is selected in the dropdown in the top left.++# Available commands from the CLI:+This command will deploy a cloud-run service, and return the URL of the service. This cloud run service is what will be invoked to render media.+## `npx remotion gcp cloud-run deploy`+options:+- --project-id (required):+ - The project-id is the name of the project in which to deploy the service. The ID can be retrieved by navigating to the [Dashboard](https://console.cloud.google.com/home/dashboard?project=new-remotion-project&supportedpurview=project) screen in Google Cloud Console, and selecting the project from the drop-down menu in the top left corner. The ID is under Project Info in the top left corner.+- --service-name (required):+ - the name of the Cloud Run service to deploy or update. Service names must be 49 characters or less and must be unique per region and project. A service name cannot be changed later and is publicly visible. The service does not need to exist yet. If it does exist, a new revision will be deployed.+- --region: the region of the service+- --remotion-version (required for now): the version of the remotion package to use+ - the version of Remotion to deploy on the service. Behind the scenes, this is selecting the container image from a publicly readable repository `us-docker.pkg.dev/remotion-dev/cloud-run/render`. Part of the build step for the monorepo will be to deploy a new container image to this repository, with the remotion version as a tag.+ - for now, the remotion version must be set to `3.3.36-alpha`+- --allow-unauthenticated (optional, default to false):+ - whether to allow unauthenticated requests to the service. For now, I would suggest setting this to true, to avoid having to create a service account and grant it access to the service. In the future, it would be recommended to not set this tru.+- --overwrite-service (optional, default to false):+ - if an existing service is found with the same name, a prompt will come up asking if a new revision should be deployed. If this flag is set to true, the prompt will be skipped and a new revision will be deployed automatically.++Taking the above into account, a valid command would be:+`npx remotion gcp cloud-run deploy --service-name=cloud-run-render --project-id=new-remotion-project --remotion-version=3.3.36-alpha --allow-unauthenticated`-### Run the services+## `npx remotion gcp sites create`+t.b.c++### Render media on GCPWithin the Cloud Run service, you can see the URL of the service. You can run the service by sending a POST request to the URL with the following body example:#### Body to render media:@@ -41,27 +99,4 @@ Within the Cloud Run service, you can see the URL of the service. You can run th"outputBucket": "remotionlambda-test","outputFile": "outFolder/stillOutput.png"}-```---### NEXT STEPS-> let's work towards making user facing APIs for deploying the container and invoke it.-> aka make equivalent functions for deployFunction() and renderMediaOnLambda()-> as far as I understand it right now, one would have to clone the monorepo to deploy it--Add firestore option for storing progress-https://www.remotion.dev/docs/renderer/render-media#onprogress--# To investigate-How can people get the :latest version from artifact registry?-How to program a CLI command that will deploy the container to Cloud Run?--## Created public artifact repo in GCP-Public artifact registry that contains the container images- us-docker.pkg.dev/remotion-dev/cloud-run/render-Image is tagged with the same semver as the remotion packages- us-docker.pkg.dev/remotion-dev/cloud-run/render:3.3.36-alpha-Part of the CI/CD pipeline should be to push a new container image to the artifact registry, with the right version:-`gcloud builds submit --tag us-docker.pkg.dev/remotion-dev/cloud-run/render:${version}`--## deployCloudRun()+```\ No newline at end of filediff --git a/packages/gcp/readmeImages/createSA.png b/packages/gcp/readmeImages/createSA.pngnew file mode 100644index 0000000000..95b2f14008Binary files /dev/null and b/packages/gcp/readmeImages/createSA.png differdiff --git a/packages/gcp/remotion-gcp-cli.mjs b/packages/gcp/remotion-gcp-cli.mjsindex d21247709d..8f7c3cd4f9 100755--- a/packages/gcp/remotion-gcp-cli.mjs+++ b/packages/gcp/remotion-gcp-cli.mjs@@ -105,28 +105,11 @@ 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 = [];++const uploadPromises = [];+const paths = [firstFilePath, secondFilePath]++async function uploadInParallel() {for (const index in paths) {const path = paths[index];const fileSizeInBytes = fs.statSync(path).size;@@ -142,8 +125,27 @@ async function uploadInParallel(}));}- await Promise.all(uploadPromises).catch(console.error);}---await uploadInParallel(bucket, [firstFilePath, secondFilePath]);+// const promise = Promise.all(uploadPromises).catch(console.error);++// uploadInParallel()+// console.log('before')+// await promise+// console.log('after')++const uploads = paths.map(async (path) => {+ const fileSizeInBytes = fs.statSync(path).size;+ return new Promise((resolve, reject) => {+ fs.createReadStream(path)+ .pipe(bucket.file(`new/${path}`).createWriteStream())+ .on("error", error => reject(error))+ .on('progress', function (p) {+ console.log(path, `${Math.floor(p.bytesWritten / fileSizeInBytes * 100)}%`);+ })+ .on('finish', () => resolve("done"))+ });+})+console.log('before')+const promise = Promise.all(uploads);+await promise;+console.log('after')\ No newline at end of filediff --git a/packages/gcp/src/api/deploy-site.ts b/packages/gcp/src/api/deploy-site.tsindex 5999fc244c..3cd16248c4 100644--- a/packages/gcp/src/api/deploy-site.ts+++ b/packages/gcp/src/api/deploy-site.ts@@ -56,19 +56,11 @@ export const deploySite = async ({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 existsawait cloudStorageClient.bucket(bucketName).get()const subFolder = getSitesKey(siteId);-+// gcpLs is a function that lists all files in a bucketconst [files, bundled] = await Promise.all([gcpLs({diff --git a/packages/gcp/src/api/get-or-create-bucket.ts b/packages/gcp/src/api/get-or-create-bucket.tsindex eabf3d606a..e007c18153 100644--- a/packages/gcp/src/api/get-or-create-bucket.ts+++ b/packages/gcp/src/api/get-or-create-bucket.ts@@ -35,7 +35,7 @@ export const getOrCreateBucket = async (return {bucketName: remotionBuckets[0].name};}- const bucketName = makeBucketName(options.region); // TODO: pretty sure I can remove the region here+ const bucketName = makeBucketName();await createBucket({bucketName,diff --git a/packages/gcp/src/api/upload-dir.ts b/packages/gcp/src/api/upload-dir.tsindex 86513202c6..d3ff9816aa 100644--- a/packages/gcp/src/api/upload-dir.ts+++ b/packages/gcp/src/api/upload-dir.ts@@ -1,9 +1,8 @@import type { Dirent } from 'fs';-import { createReadStream, promises as fs } from 'fs';+import { createReadStream, promises as fs, statSync } 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;@@ -87,42 +86,22 @@ export const uploadDir = async ({}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 (file) => {+ const path = file.name;+ const destination = makeStorageKey( keyPrefix, localDir, path )+ return new Promise((resolve, reject) => {+ createReadStream(path)+ .pipe(cloudStorageClient.bucket(bucket).file(destination).createWriteStream())+ .on("error", error => reject(error))+ .on('progress', function (p) {+ progresses[path] = p.bytesWritten ?? 0;+ })+ .on('finish', () => resolve("done"))+ });})-- // 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 promise = Promise.all(uploads);const interval = setInterval(() => {onProgress({diff --git a/packages/gcp/src/shared/validate-bucketname.ts b/packages/gcp/src/shared/validate-bucketname.tsindex d879169d29..273e62f4ba 100644--- a/packages/gcp/src/shared/validate-bucketname.ts+++ b/packages/gcp/src/shared/validate-bucketname.ts@@ -54,8 +54,8 @@ export const parseBucketName = (return {region: realRegionFound ?? null};};-export const makeBucketName = (region: GcpRegion) => {- return `${REMOTION_BUCKET_PREFIX}${region.replace(/-/g, '')}-${randomHash({+export const makeBucketName = () => {+ return `${REMOTION_BUCKET_PREFIX}${randomHash({randomInTests: false,})}`;};