Skip to content

🎥 Make videos programmatically with React

don't reupload assets already on S3

Jonny Burger79067b1a7fee
diff --git a/packages/lambda/src/api/deploy-site.ts b/packages/lambda/src/api/deploy-site.ts
index 255d5a53a8..963c6c6258 100644
--- a/packages/lambda/src/api/deploy-site.ts
+++ b/packages/lambda/src/api/deploy-site.ts
@@ -1,9 +1,10 @@
import type {WebpackOverrideFn} from 'remotion';
-import {deleteSite} from '../api/delete-site';
+import {lambdaDeleteFile, lambdaLs} from '../functions/helpers/io';
import type {AwsRegion} from '../pricing/aws-regions';
import {bundleSite} from '../shared/bundle-site';
import {getSitesKey} from '../shared/constants';
import {getAccountId} from '../shared/get-account-id';
+import {getS3DiffOperations} from '../shared/get-s3-operations';
import {makeS3ServeUrl} from '../shared/make-s3-url';
import {randomHash} from '../shared/random-hash';
import {validateAwsRegion} from '../shared/validate-aws-region';
@@ -66,12 +67,14 @@ export const deploySite = async ({
}
const subFolder = getSitesKey(siteId);
- await deleteSite({
+
+ const files = await lambdaLs({
bucketName,
- onAfterItemDeleted: () => undefined,
+ expectedBucketOwner: await getAccountId({region}),
region,
- siteName: siteId,
+ prefix: subFolder,
});
+
const bundled = await bundleSite(
entryPoint,
options?.onBundleProgress ?? (() => undefined),
@@ -83,16 +86,32 @@ export const deploySite = async ({
rootDir: options?.rootDir,
}
);
+ const {toDelete, toUpload} = await getS3DiffOperations({
+ objects: files,
+ bundle: bundled,
+ prefix: subFolder,
+ });
await Promise.all([
uploadDir({
bucket: bucketName,
region,
- dir: bundled,
+ localDir: bundled,
onProgress: options?.onUploadProgress ?? (() => undefined),
- folder: subFolder,
+ keyPrefix: subFolder,
privacy: 'public',
+ toUpload,
}),
+ Promise.all(
+ toDelete.map((d) => {
+ return lambdaDeleteFile({
+ bucketName,
+ customCredentials: null,
+ key: d.Key as string,
+ region,
+ });
+ })
+ ),
enableS3Website({
region,
bucketName,
diff --git a/packages/lambda/src/api/upload-dir.ts b/packages/lambda/src/api/upload-dir.ts
index 2fba3420fa..41277dcbba 100644
--- a/packages/lambda/src/api/upload-dir.ts
+++ b/packages/lambda/src/api/upload-dir.ts
@@ -1,5 +1,6 @@
import {PutObjectCommand} from '@aws-sdk/client-s3';
import {Upload} from '@aws-sdk/lib-storage';
+import type {Dirent} from 'fs';
import {createReadStream, promises as fs} from 'fs';
import mimeTypes from 'mime-types';
import path from 'path';
@@ -31,29 +32,34 @@ export const getDirFiles = (entry: string): MockFile[] => {
);
};
-export const uploadDir = async ({
- bucket,
- region,
- dir,
- onProgress,
- folder,
- privacy,
-}: {
- bucket: string;
- region: AwsRegion;
- dir: string;
- folder: string;
- onProgress: (progress: UploadDirProgress) => void;
- privacy: Privacy;
-}) => {
- async function getFiles(directory: string): Promise<FileInfo[]> {
- const dirents = await fs.readdir(directory, {withFileTypes: true});
- const _files = await Promise.all(
- dirents.map(async (dirent) => {
+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)
+ ? getFiles(res, originalDirectory, toUpload)
: [
{
name: res,
@@ -61,11 +67,28 @@ export const uploadDir = async ({
},
];
})
- );
- return _files.flat(1);
- }
+ );
+ return _files.flat(1);
+}
- const files = await getFiles(dir);
+export const uploadDir = async ({
+ bucket,
+ region,
+ localDir: dir,
+ onProgress,
+ keyPrefix: folder,
+ privacy,
+ toUpload,
+}: {
+ bucket: string;
+ region: AwsRegion;
+ localDir: string;
+ keyPrefix: string;
+ onProgress: (progress: UploadDirProgress) => void;
+ privacy: Privacy;
+ toUpload: string[];
+}) => {
+ const files = await getFiles(dir, dir, toUpload);
const progresses: {[key: string]: number} = {};
for (const file of files) {
progresses[file.name] = 0;
diff --git a/packages/lambda/src/shared/get-etag.ts b/packages/lambda/src/shared/get-etag.ts
new file mode 100644
index 0000000000..aa23c64d02
--- /dev/null
+++ b/packages/lambda/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/lambda/src/shared/get-s3-operations.ts b/packages/lambda/src/shared/get-s3-operations.ts
new file mode 100644
index 0000000000..37a2a07fab
--- /dev/null
+++ b/packages/lambda/src/shared/get-s3-operations.ts
@@ -0,0 +1,34 @@
+import type {_Object} from '@aws-sdk/client-s3';
+import {readDirectory} from './read-dir';
+
+export const getS3DiffOperations = async ({
+ objects,
+ bundle,
+ prefix,
+}: {
+ objects: _Object[];
+ bundle: string;
+ prefix: string;
+}) => {
+ const dir = await readDirectory({
+ dir: bundle,
+ etags: {},
+ originalDir: bundle,
+ });
+
+ const filesOnS3ButNotLocal = objects.filter((fileOnS3) => {
+ const key = fileOnS3.Key?.substring(prefix.length + 1) as string;
+ return !dir[key];
+ });
+ const localFilesNotOnS3 = Object.keys(dir).filter((d) => {
+ return !objects.find((o) => {
+ const key = o.Key?.substring(prefix.length + 1) as string;
+ return key === d && o.ETag === dir[d];
+ });
+ });
+
+ return {
+ toDelete: filesOnS3ButNotLocal,
+ toUpload: localFilesNotOnS3,
+ };
+};
diff --git a/packages/lambda/src/shared/read-dir.ts b/packages/lambda/src/shared/read-dir.ts
new file mode 100644
index 0000000000..c66e8a2edd
--- /dev/null
+++ b/packages/lambda/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;
+}