π₯ Make videos programmatically with React
merged service deploy into one function
Matt McGillivray405ce9eba9e5
diff --git a/packages/cloudrun/gcpInstaller/gcpInstaller.tar b/packages/cloudrun/gcpInstaller/gcpInstaller.tarindex 51bbfcd8a0..1f4e9ee53b 100644Binary files a/packages/cloudrun/gcpInstaller/gcpInstaller.tar and b/packages/cloudrun/gcpInstaller/gcpInstaller.tar differdiff --git a/packages/cloudrun/src/api/check-if-service-exists.ts b/packages/cloudrun/src/api/check-if-service-exists.tsindex 734f5ccb7a..ad455a1708 100644--- a/packages/cloudrun/src/api/check-if-service-exists.ts+++ b/packages/cloudrun/src/api/check-if-service-exists.ts@@ -1,13 +1,14 @@import type {protos} from '@google-cloud/run';import {CliInternals} from '@remotion/cli';import {Log} from '../cli/log';+import {generateServiceName} from '../shared/generate-service-name';import {validateGcpRegion} from '../shared/validate-gcp-region';import {validateProjectID} from '../shared/validate-project-id';-import {validateServiceName} from '../shared/validate-service-name';import {getCloudRunClient} from './helpers/get-cloud-run-client';export type CheckIfServiceExistsInput = {- serviceNameToCheck: string;+ memory: string;+ cpu: string;projectID: string;region: string;};@@ -24,11 +25,15 @@ export const checkIfServiceExists = async (options: CheckIfServiceExistsInput): Promise<protos.google.cloud.run.v2.IService | undefined> => {validateGcpRegion(options.region);- validateServiceName(options.serviceNameToCheck);validateProjectID(options.projectID);const parent = `projects/${options.projectID}/locations/${options.region}`;+ const serviceName = generateServiceName({+ memory: options.memory,+ cpu: options.cpu,+ });+const cloudRunClient = getCloudRunClient();// Construct request@@ -40,9 +45,7 @@ export const checkIfServiceExists = async (try {const iterable = cloudRunClient.listServicesAsync(request);for await (const response of iterable) {- if (- response.name === `${parent}/services/${options.serviceNameToCheck}`- ) {+ if (response.name === `${parent}/services/${serviceName}`) {return response;}}diff --git a/packages/cloudrun/src/api/deploy-cloud-run-revision.ts b/packages/cloudrun/src/api/deploy-cloud-run-revision.tsdeleted file mode 100644index 51468d9ad0..0000000000--- a/packages/cloudrun/src/api/deploy-cloud-run-revision.ts+++ /dev/null@@ -1,51 +0,0 @@-import {validateGcpRegion} from '../shared/validate-gcp-region';-import {validateProjectID} from '../shared/validate-project-id';-import {validateRemotionVersion} from '../shared/validate-remotion-version';-import {constructServiceTemplate} from './helpers/construct-service-deploy-request';-import {getCloudRunClient} from './helpers/get-cloud-run-client';-import type {IService} from './helpers/IService';--export type DeployCloudRunRevisionInput = {- remotionVersion: string;- existingService: IService;- memory: string;- cpu: string;- projectID: string;- region: string;-};--/**- * @description Creates a Cloud Run service in your project that will be able to render a video in GCP.- * @link https://remotion.dev/docs/lambda/deployfunction- * @param options.remotionVersion Which version of Remotion to use within the Cloud Run service.- * @param options.projectID GCP Project ID to deploy the Cloud Run service to.- * @param options.existingService The Cloud Run service to receive a new revision.- * @param options.region The region you want to deploy your Cloud Run service to.- * @returns {Promise<IService>} An object that contains the `functionName` property- */-export const deployCloudRunRevision = async (- options: DeployCloudRunRevisionInput-): Promise<IService> => {- validateGcpRegion(options.region);- validateProjectID(options.projectID);- validateRemotionVersion(options.remotionVersion);-- const cloudRunClient = getCloudRunClient();-- // Construct request- const request = {- service: {- name: options.existingService.name,- template: constructServiceTemplate({- remotionVersion: options.remotionVersion,- memory: options.memory,- cpu: options.cpu,- }),- },- };- // Run request- const [operation] = await cloudRunClient.updateService(request);- const [response] = await operation.promise();-- return response;-};diff --git a/packages/cloudrun/src/api/deploy-new-cloud-run.ts b/packages/cloudrun/src/api/deploy-service.tssimilarity index 83%rename from packages/cloudrun/src/api/deploy-new-cloud-run.tsrename to packages/cloudrun/src/api/deploy-service.tsindex 2b572e2671..697cf65c7f 100644--- a/packages/cloudrun/src/api/deploy-new-cloud-run.ts+++ b/packages/cloudrun/src/api/deploy-service.ts@@ -1,19 +1,17 @@+import {generateServiceName} from '../shared/generate-service-name';import {validateGcpRegion} from '../shared/validate-gcp-region';import {validateProjectID} from '../shared/validate-project-id';import {validateRemotionVersion} from '../shared/validate-remotion-version';-import {validateServiceName} from '../shared/validate-service-name';import {constructServiceTemplate} from './helpers/construct-service-deploy-request';import {getCloudRunClient} from './helpers/get-cloud-run-client';import type {IService} from './helpers/IService';-export type DeployCloudRunInput = {+export type DeployServiceInput = {remotionVersion: string;- serviceName: string;memory: string;cpu: string;projectID: string;region: string;- overwriteService: boolean;};/**@@ -21,16 +19,14 @@ export type DeployCloudRunInput = {* @link https://remotion.dev/docs/lambda/deployfunction* @param options.remotionVersion Which version of Remotion to use within the Cloud Run service.* @param options.projectID GCP Project ID to deploy the Cloud Run service to.- * @param options.serviceName The name of the Cloud Run service.* @param options.region The region you want to deploy your Cloud Run service to.* @returns {Promise<IService>} An object that contains the `functionName` property*/-export const deployNewCloudRun = async (- options: DeployCloudRunInput+export const deployService = async (+ options: DeployServiceInput): Promise<IService> => {// ToDo: This needs to allow for defaults for use of the node API without CLIvalidateGcpRegion(options.region);- validateServiceName(options.serviceName);validateProjectID(options.projectID);validateRemotionVersion(options.remotionVersion);@@ -38,6 +34,11 @@ export const deployNewCloudRun = async (const cloudRunClient = getCloudRunClient();+ const serviceName = generateServiceName({+ memory: options.memory,+ cpu: options.cpu,+ });+const request = {parent,service: {@@ -48,7 +49,7 @@ export const deployNewCloudRun = async (cpu: options.cpu,}),},- serviceId: options.serviceName,+ serviceId: serviceName,};// Run requestdiff --git a/packages/cloudrun/src/cli/commands/services/deploy.ts b/packages/cloudrun/src/cli/commands/services/deploy.tsindex f40222ba30..2d4eabf157 100644--- a/packages/cloudrun/src/cli/commands/services/deploy.ts+++ b/packages/cloudrun/src/cli/commands/services/deploy.ts@@ -2,12 +2,10 @@ import {CliInternals} from '@remotion/cli';import {VERSION} from 'remotion/version';import {checkIfServiceExists} from '../../../api/check-if-service-exists';import {allowUnauthenticatedAccess} from '../../../api/cloud-run-allow-unauthenticated-access';-import {deployCloudRunRevision} from '../../../api/deploy-cloud-run-revision';-import {deployNewCloudRun} from '../../../api/deploy-new-cloud-run';+import {deployService} from '../../../api/deploy-service';+import {generateServiceName} from '../../../shared/generate-service-name';import {validateGcpRegion} from '../../../shared/validate-gcp-region';-import {validateOverwrite} from '../../../shared/validate-overwrite';import {validateRemotionVersion} from '../../../shared/validate-remotion-version';-import {validateServiceName} from '../../../shared/validate-service-name';import {parsedCloudrunCli} from '../../args';import {getGcpRegion} from '../../get-gcp-region';import {confirmCli} from '../../helpers/confirm';@@ -18,12 +16,10 @@ export const CLOUD_RUN_DEPLOY_SUBCOMMAND = 'deploy';export const cloudRunDeploySubcommand = async () => {const region = getGcpRegion();- const serviceName = parsedCloudrunCli['service-name'];const projectID = process.env.REMOTION_GCP_PROJECT_ID as string;const remotionVersion = VERSION;const allowUnauthenticated =parsedCloudrunCli['allow-unauthenticated'] ?? false;- const overwriteService = parsedCloudrunCli['overwrite-service'] ?? false;const memory = parsedCloudrunCli.memory ?? '512Mi';const cpu = parsedCloudrunCli.cpu ?? '1.0';@@ -34,13 +30,11 @@ export const cloudRunDeploySubcommand = async () => {Validating Deployment of Cloud Run Service:Remotion Version = ${remotionVersion}- Service Name = ${serviceName}Service Memory Limit = ${memory}Service CPU Limit = ${cpu}Project Name = ${projectID}Region = ${region}Allow Unauthenticated Access = ${allowUnauthenticated}- Overwrite existing service = ${overwriteService}`.trim()));@@ -49,9 +43,7 @@ Validating Deployment of Cloud Run Service:Log.info();validateGcpRegion(region);- validateServiceName(serviceName);validateRemotionVersion(remotionVersion);- validateOverwrite(overwriteService);if (projectID === undefined) {Log.error(`REMOTION_GCP_PROJECT_ID not found in the .env file.`);@@ -59,121 +51,82 @@ Validating Deployment of Cloud Run Service:}const existingService = await checkIfServiceExists({- serviceNameToCheck: serviceName,+ memory,+ cpu,projectID,region,});if (existingService) {- const shouldDeployNewRevision =- overwriteService ||- (await confirmCli({- delMessage: `Existing service found in ${projectID} project. Deploy new revision? (Y/n)`,- allowForceFlag: true,- }));-- if (shouldDeployNewRevision) {- Log.info(CliInternals.chalk.white('Deploying Cloud Run Revision...'));- const deployRevisionResult = await deployCloudRunRevision({- remotionVersion,- existingService,- memory,- cpu,- projectID,- region,- });- // TODO: should somehow check if the new revision was identical to the previous one, and therefore not actually revised-- if (!deployRevisionResult.name || !deployRevisionResult.uri) {- throw new Error(- `Failed to deploy revision. Invalid response from Cloud Run π ${deployRevisionResult}`- );- }-- Log.info();-- Log.info(- CliInternals.chalk.blueBright(- `-π Cloud Run Revision Deployed! π+ const answer = await confirmCli({+ delMessage:+ 'A Cloud Run service with the same Remotion Version, Memory, and CPU already exists. Do you want to re-deploy? (Y/n)',+ allowForceFlag: true,+ });++ if (answer === false) {+ Log.info(CliInternals.chalk.white('\nService deployment cancelled.'));+ quit(1);+ }+ }- Full Service Name = ${deployRevisionResult.name}- Cloud Run URL = ${deployRevisionResult.uri}- Project = ${projectID}- GCP Console URL = https://console.cloud.google.com/run/detail/${region}/${serviceName}/revisions- `.trim()- )- );+ // if no existing service, deploy new service+ Log.info(CliInternals.chalk.white('\nDeploying Cloud Run Service...'));+ try {+ const deployResult = await deployService({+ remotionVersion,+ memory,+ cpu,+ projectID,+ region,+ });++ if (!deployResult.name) {+ Log.error('service name not returned from Cloud Run API.');+ throw new Error(JSON.stringify(deployResult));+ }- await allowUnauthenticatedAccessToService(- deployRevisionResult.name,- allowUnauthenticated- );- } else {- Log.info(CliInternals.chalk.gray('deploy cancelled'));- quit(1); // TODO: Check with Jonny what to pass to quit - 0 or 1?+ if (!deployResult.uri) {+ Log.error('service uri not returned from Cloud Run API.');+ throw new Error(JSON.stringify(deployResult));}- } else {- // if no existing service, deploy new service- Log.info(CliInternals.chalk.white('\nDeploying Cloud Run Service...'));- try {- const deployResult = await deployNewCloudRun({- remotionVersion,- serviceName,- memory,- cpu,- projectID,- region,- overwriteService,- });-- if (!deployResult.name) {- Log.error('service name not returned from Cloud Run API.');- throw new Error(JSON.stringify(deployResult));- }-- if (!deployResult.uri) {- Log.error('service uri not returned from Cloud Run API.');- throw new Error(JSON.stringify(deployResult));- }- Log.info();+ Log.info();- Log.info(- CliInternals.chalk.blueBright(- `+ Log.info(+ CliInternals.chalk.blueBright(+ `π Cloud Run Deployed! πFull Service Name = ${deployResult.name}Cloud Run URL = ${deployResult.uri}Project = ${projectID}- GCP Console URL = https://console.cloud.google.com/run/detail/${region}/${serviceName}/revisions+ GCP Console URL = https://console.cloud.google.com/run/detail/${region}/${deployResult.name}/revisions`.trim()- )- );-- await allowUnauthenticatedAccessToService(- deployResult.name,- allowUnauthenticated- );- } catch (e: any) {- if (e.code === 6) {- Log.error(- CliInternals.chalk.red(- `Failed to deploy service - ${serviceName} already exists in ${parent}.`- )- );- } else {- throw e;- }- }- }+ )+ );- if (CliInternals.quietFlagProvided()) {- // Log.info(functionName);+ await allowUnauthenticatedAccessToService(+ deployResult.name,+ allowUnauthenticated+ );+ } catch (e: any) {+ Log.error(+ CliInternals.chalk.red(+ `Failed to deploy service - ${generateServiceName({+ memory,+ cpu,+ })}.`+ )+ );+ throw e;}};+if (CliInternals.quietFlagProvided()) {+ // Log.info(functionName);+}+async function allowUnauthenticatedAccessToService(serviceName: string,allowUnauthenticated: booleandiff --git a/packages/cloudrun/src/index.ts b/packages/cloudrun/src/index.tsindex bfbcc66f17..f5a7f994b3 100644--- a/packages/cloudrun/src/index.ts+++ b/packages/cloudrun/src/index.ts@@ -1,13 +1,6 @@-import {deployCloudRunRevision} from './api/deploy-cloud-run-revision';-import {deployNewCloudRun} from './api/deploy-new-cloud-run';+import {deployService} from './api/deploy-service';import {deploySite} from './api/deploy-site';import {getOrCreateBucket} from './api/get-or-create-bucket';import {CloudrunInternals} from './internals';-export {- CloudrunInternals,- deployNewCloudRun,- deployCloudRunRevision,- deploySite,- getOrCreateBucket,-};+export {CloudrunInternals, deployService, deploySite, getOrCreateBucket};diff --git a/packages/cloudrun/src/shared/generate-service-name.ts b/packages/cloudrun/src/shared/generate-service-name.tsnew file mode 100644index 0000000000..03257b38b9--- /dev/null+++ b/packages/cloudrun/src/shared/generate-service-name.ts@@ -0,0 +1,23 @@+import {SERVICE_VERSION_STRING} from './service-version-string';++export const generateServiceName = ({+ memory,+ cpu,+}: {+ memory: string;+ cpu: string;+}): string => {+ const sanitisedCPU = cpu.replace(/\./g, '-').substring(0, 10);++ const sanitisedMem = memory+ .replace(/\./g, '-')+ .substring(0, 10)+ .toLowerCase();++ return [+ 'remotion',+ `${SERVICE_VERSION_STRING}`,+ `mem${sanitisedMem}`,+ `cpu${sanitisedCPU}`,+ ].join('--');+};diff --git a/packages/cloudrun/src/shared/service-version-string.ts b/packages/cloudrun/src/shared/service-version-string.tsnew file mode 100644index 0000000000..446999f06c--- /dev/null+++ b/packages/cloudrun/src/shared/service-version-string.ts@@ -0,0 +1,5 @@+import {VERSION} from 'remotion/version';++export const SERVICE_VERSION_STRING = VERSION.replace(/\./g, '-')+ .replace(/\+/g, '-')+ .substring(0, 10);diff --git a/packages/cloudrun/src/shared/validate-overwrite.ts b/packages/cloudrun/src/shared/validate-overwrite.tsdeleted file mode 100644index 26bb3b7a4b..0000000000--- a/packages/cloudrun/src/shared/validate-overwrite.ts+++ /dev/null@@ -1,13 +0,0 @@-export const validateOverwrite = (overwriteService: unknown) => {- if (- overwriteService !== true &&- overwriteService !== false &&- overwriteService !== 'undefined'- ) {- throw new TypeError(- `The 'overwrite-service' argument must be either true or false, or not included, but is ${JSON.stringify(- overwriteService- )}`- );- }-};diff --git a/packages/cloudrun/src/shared/validate-service-name.ts b/packages/cloudrun/src/shared/validate-service-name.tsdeleted file mode 100644index 4fb68148f6..0000000000--- a/packages/cloudrun/src/shared/validate-service-name.ts+++ /dev/null@@ -1,25 +0,0 @@-export const validateServiceName = (serviceName: unknown) => {- if (typeof serviceName === 'undefined') {- // TODO - have a default service name, but also check GCP to see if it's already taken, and iterate- // `gcloud run services list --project=projectID` can be used, but then this function needs to be aware of the project ID also- throw new TypeError(- `The 'serviceName' argument must be provided, but is missing.`- );- }-- if (typeof serviceName !== 'string') {- throw new TypeError(- `The 'serviceName' argument must be a string, but is ${JSON.stringify(- serviceName- )}`- );- }-- if (!serviceName.match(/^[a-zA-Z][a-zA-Z0-9-]{0,48}[a-zA-Z0-9]$/g)) {- throw new Error(- 'The `serviceName` must match the RegExp `/^[a-zA-Z][a-zA-Z0-9-]{0,48}[a-zA-Z0-9]$/g`. This means it may only start with a letter, end with a letter or number, and contain up to 49 lowercase letters, numbers or hyphens. You passed: ' +- serviceName +- '. Check for invalid characters.'- );- }-};