/
render-still-on-cloudrun.ts
241 lines (216 loc) · 7.56 KB
/
render-still-on-cloudrun.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
import type {
ChromiumOptions,
StillImageFormat,
ToOptions,
} from '@remotion/renderer';
import {BrowserSafeApis} from '@remotion/renderer/client';
import {NoReactAPIs} from '@remotion/renderer/pure';
import {NoReactInternals} from 'remotion/no-react';
import {VERSION} from 'remotion/version';
import type {
CloudRunCrashResponse,
CloudRunPayloadType,
ErrorResponsePayload,
RenderStillOnCloudrunOutput,
} from '../functions/helpers/payloads';
import type {GcpRegion} from '../pricing/gcp-regions';
import {validatePrivacy} from '../shared/validate-privacy';
import {validateServeUrl} from '../shared/validate-serveurl';
import {getOrCreateBucket} from './get-or-create-bucket';
import {getAuthClientForUrl} from './helpers/get-auth-client-for-url';
import {getCloudrunEndpoint} from './helpers/get-cloudrun-endpoint';
type MandatoryParameters = {
region: GcpRegion;
serveUrl: string;
composition: string;
imageFormat: StillImageFormat;
};
type OptionalParameters = {
cloudRunUrl: string | null;
serviceName: string | null;
inputProps: Record<string, unknown>;
privacy: 'public' | 'private';
forceBucketName: string | null;
outName: string | null;
envVariables: Record<string, string>;
frame: number;
chromiumOptions: ChromiumOptions;
forceWidth: number | null;
forceHeight: number | null;
indent: boolean;
} & ToOptions<typeof BrowserSafeApis.optionsMap.renderStillOnCloudRun>;
export type RenderStillOnCloudrunInput = Partial<OptionalParameters> &
MandatoryParameters;
/**
* @description Triggers a render on a GCP Cloud Run service given a composition and a Cloud Run URL.
* @see [Documentation](https://remotion.dev/docs/cloudrun/renderstilloncloudrun)
* @param params.cloudRunUrl The URL of the Cloud Run service that should be used. Use either this or serviceName.
* @param params.serviceName The name of the Cloud Run service that should be used. Use either this or cloudRunUrl.
* @param params.region The region that the Cloud Run service is deployed in.
* @param params.serveUrl The URL of the deployed project
* @param params.composition The ID of the composition which should be rendered.
* @param params.inputProps The input props that should be passed to the composition.
* @param params.forceBucketName The name of the bucket that the output file should be uploaded to.
* @param params.privacy Whether the output file should be public or private.
* @param params.outName The name of the output file.
* @param params.imageFormat Which image format the frame should be rendered in.
* @param params.envVariables Object containing environment variables to be injected in your project.
* @param params.frame Which frame of the composition should be rendered. Frames are zero-indexed.
* @param params.jpegQuality JPEG quality if JPEG was selected as the image format.
* @param params.chromiumOptions Allows you to set certain Chromium / Google Chrome flags.
* @param params.scale Scales the output dimensions by a factor.
* @param params.forceWidth Overrides default composition width.
* @param params.forceHeight Overrides default composition height.
* @param params.logLevel Level of logging that Cloud Run service should perform. Default "info".
* @param params.delayRenderTimeoutInMilliseconds A number describing how long the render may take to resolve all delayRender() calls before it times out.
* @returns {Promise<RenderStillOnCloudrunOutput>} See documentation for detailed structure
*/
const internalRenderStillOnCloudRun = async ({
cloudRunUrl,
serviceName,
region,
serveUrl,
composition,
inputProps,
forceBucketName,
privacy,
outName,
imageFormat,
envVariables,
frame,
jpegQuality,
chromiumOptions,
scale,
forceWidth,
forceHeight,
logLevel,
delayRenderTimeoutInMilliseconds,
offthreadVideoCacheSizeInBytes,
}: OptionalParameters & MandatoryParameters): Promise<
RenderStillOnCloudrunOutput | ErrorResponsePayload | CloudRunCrashResponse
> => {
validateServeUrl(serveUrl);
if (privacy) validatePrivacy(privacy);
const outputBucket =
forceBucketName ?? (await getOrCreateBucket({region})).bucketName;
const cloudRunEndpoint = await getCloudrunEndpoint({
cloudRunUrl,
serviceName,
region,
});
const data: CloudRunPayloadType = {
composition,
serveUrl,
serializedInputPropsWithCustomSchema:
NoReactInternals.serializeJSONWithDate({
indent: undefined,
staticBase: null,
data: inputProps ?? {},
}).serializedString,
outputBucket,
outName,
privacy,
imageFormat,
envVariables,
jpegQuality,
chromiumOptions,
scale,
forceWidth,
forceHeight,
frame,
type: 'still',
logLevel,
delayRenderTimeoutInMilliseconds,
offthreadVideoCacheSizeInBytes,
clientVersion: VERSION,
};
const client = await getAuthClientForUrl(cloudRunEndpoint);
const postResponse = await client.request({
url: cloudRunEndpoint,
method: 'POST',
data,
responseType: 'stream',
});
const renderResponse = await new Promise<
RenderStillOnCloudrunOutput | CloudRunCrashResponse
>((resolve, reject) => {
let response:
| RenderStillOnCloudrunOutput
| ErrorResponsePayload
| CloudRunCrashResponse;
const startTime = Date.now();
const formattedStartTime = new Date().toISOString();
const stream: any = postResponse.data;
let accumulatedChunks = ''; // A buffer to accumulate chunks.
stream.on('data', (chunk: Buffer) => {
accumulatedChunks += chunk.toString(); // Add the new chunk to the buffer.
let parsedData;
try {
parsedData = JSON.parse(accumulatedChunks.trim());
accumulatedChunks = ''; // Clear the buffer after successful parsing.
} catch (e) {
// If parsing fails, it means we don't have a complete JSON string yet.
// We'll wait for more chunks.
return;
}
if (parsedData.response) {
response = parsedData.response;
}
if (parsedData.type === 'error') {
reject(parsedData);
}
});
stream.on('end', () => {
if (!response) {
const crashTime = Date.now();
const formattedCrashTime = new Date().toISOString();
resolve({
type: 'crash',
cloudRunEndpoint,
message:
'Service crashed without sending a response. Check the logs in GCP console.',
requestStartTime: formattedStartTime,
requestCrashTime: formattedCrashTime,
requestElapsedTimeInSeconds: (crashTime - startTime) / 1000,
});
} else if (response.type !== 'success' && response.type !== 'crash') {
throw response;
}
resolve(response);
});
stream.on('error', (error: Error) => {
reject(error);
});
});
return renderResponse;
};
const errorHandled = NoReactAPIs.wrapWithErrorHandling(
internalRenderStillOnCloudRun,
);
export const renderStillOnCloudrun = (options: RenderStillOnCloudrunInput) => {
return errorHandled({
chromiumOptions: options.chromiumOptions ?? {},
cloudRunUrl: options.cloudRunUrl ?? null,
composition: options.composition,
delayRenderTimeoutInMilliseconds:
options.delayRenderTimeoutInMilliseconds ?? 30000,
envVariables: options.envVariables ?? {},
forceBucketName: options.forceBucketName ?? null,
forceHeight: options.forceHeight ?? null,
forceWidth: options.forceWidth ?? null,
frame: options.frame ?? 0,
imageFormat: options.imageFormat,
indent: options.indent ?? false,
inputProps: options.inputProps ?? {},
jpegQuality: options.jpegQuality ?? BrowserSafeApis.DEFAULT_JPEG_QUALITY,
logLevel: options.logLevel ?? 'info',
offthreadVideoCacheSizeInBytes:
options.offthreadVideoCacheSizeInBytes ?? null,
outName: options.outName ?? null,
privacy: options.privacy ?? 'public',
region: options.region,
scale: options.scale ?? 1,
serveUrl: options.serveUrl,
serviceName: options.serviceName ?? null,
});
};