-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
223 lines (192 loc) · 6.81 KB
/
Copy pathindex.js
File metadata and controls
223 lines (192 loc) · 6.81 KB
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
#!/usr/bin/env node
import 'dotenv/config'
import { list } from '@vercel/blob';
import { S3Client, PutObjectCommand, HeadObjectCommand } from '@aws-sdk/client-s3';
import { Command } from 'commander';
function createS3Client(options) {
return new S3Client({
region: options.region || process.env.AWS_REGION,
credentials: {
accessKeyId: options.accessKeyId || process.env.AWS_ACCESS_KEY_ID,
secretAccessKey: options.secretKey || process.env.AWS_SECRET_ACCESS_KEY,
},
});
}
async function fileExistsInS3(s3Client, bucketName, key) {
try {
await s3Client.send(new HeadObjectCommand({
Bucket: bucketName,
Key: key,
}));
return true;
} catch (error) {
if (error.name === 'NotFound') return false;
if (error.$metadata?.httpStatusCode === 404) return false;
// Log specific S3 errors
if (error.name === 'NoSuchBucket') {
throw new Error(`Bucket ${bucketName} does not exist`);
}
if (error.name === 'AccessDenied') {
throw new Error('Access denied to S3 bucket - check your credentials');
}
throw new Error(`S3 check failed: ${error.name} - ${error.message}`);
}
}
async function uploadToS3(s3Client, bucketName, url, key) {
try {
if (await fileExistsInS3(s3Client, bucketName, key)) {
return { skipped: true, key };
}
const response = await fetch(url);
if (!response.ok) {
throw new Error(`Failed to fetch file: ${response.status} ${response.statusText}`);
}
const buffer = Buffer.from(await response.arrayBuffer());
const command = new PutObjectCommand({
Bucket: bucketName,
Key: key,
Body: buffer,
});
await s3Client.send(command);
return { skipped: false, key };
} catch (error) {
if (error.name === 'AccessDenied') {
throw new Error('Access denied to S3 bucket - check your credentials');
}
if (error.name === 'NoSuchBucket') {
throw new Error(`Bucket ${bucketName} does not exist`);
}
throw new Error(`Upload failed for ${key}: ${error.message}`);
}
}
async function backupVercelStorageToS3(options) {
const s3Client = createS3Client(options);
const bucketName = options.bucket || process.env.AWS_BUCKET_NAME;
async function fileExistsInS3(key) {
try {
await s3Client.send(new HeadObjectCommand({
Bucket: bucketName,
Key: key,
}));
return true;
} catch (error) {
if (error.name === 'NotFound') return false;
if (error.$metadata?.httpStatusCode === 404) return false;
if (error.name === 'NoSuchBucket') {
throw new Error(`Bucket ${bucketName} does not exist`);
}
if (error.name === 'AccessDenied') {
throw new Error('Access denied to S3 bucket - check your credentials');
}
throw new Error(`S3 check failed: ${error.name} - ${error.message}`);
}
}
async function uploadToS3(url, key) {
try {
if (await fileExistsInS3(key)) {
return { skipped: true, key };
}
const response = await fetch(url);
if (!response.ok) {
throw new Error(`Failed to fetch file: ${response.status} ${response.statusText}`);
}
const buffer = Buffer.from(await response.arrayBuffer());
const command = new PutObjectCommand({
Bucket: bucketName,
Key: key,
Body: buffer,
});
await s3Client.send(command);
return { skipped: false, key };
} catch (error) {
if (error.name === 'AccessDenied') {
throw new Error('Access denied to S3 bucket - check your credentials');
}
if (error.name === 'NoSuchBucket') {
throw new Error(`Bucket ${bucketName} does not exist`);
}
throw new Error(`Upload failed for ${key}: ${error.message}`);
}
}
let cursor;
let totalProcessed = 0;
const BATCH_SIZE = options.batchSize || 10;
const prefix = options.prefix || 'production/';
console.log('Starting backup process...');
console.log(`Batch size: ${BATCH_SIZE}`);
console.log(`Prefix: ${prefix}`);
console.log(`Target bucket: ${bucketName}`);
console.log(`AWS Region: ${options.region || process.env.AWS_REGION}`);
do {
const listResult = await list({
cursor,
limit: 1000,
prefix,
});
if (listResult.blobs.length > 0) {
// Process files in batches
for (let i = 0; i < listResult.blobs.length; i += BATCH_SIZE) {
const batch = listResult.blobs.slice(i, i + BATCH_SIZE);
const promises = batch.map(blob =>
uploadToS3(blob.url, blob.pathname)
.then(result => {
if (result.skipped) {
console.log(`⏭️ Skipped: ${result.key} (already exists)`);
} else {
console.log(`✓ Backed up: ${result.key}`);
}
})
.catch(error => console.error(`✗ Failed: ${blob.pathname}`, error.message))
);
await Promise.all(promises);
totalProcessed += batch.length;
console.log(`Progress: ${totalProcessed} files processed`);
}
}
cursor = listResult.cursor;
} while (cursor);
console.log(`Backup complete. Total files processed: ${totalProcessed}`);
}
// Set up CLI
const program = new Command();
program
.name('backup-vercel-storage')
.description('Backup Vercel Blob Storage to S3')
.version('1.0.0')
.option('-b, --batch-size <number>', 'number of files to process concurrently', '10')
.option('-p, --prefix <string>', 'prefix for files to backup', 'production/')
.option('--region <string>', 'AWS region')
.option('--bucket <string>', 'S3 bucket name')
.option('--access-key-id <string>', 'AWS access key ID')
.option('--secret-key <string>', 'AWS secret access key')
.action(async (options) => {
try {
// Check for required parameters/env vars
const requiredParams = [
['region', 'AWS_REGION'],
['accessKeyId', 'AWS_ACCESS_KEY_ID'],
['secretKey', 'AWS_SECRET_ACCESS_KEY'],
['bucket', 'AWS_BUCKET_NAME']
];
const missing = requiredParams.filter(([param, envVar]) => {
return !options[param] && !process.env[envVar];
});
if (missing.length > 0) {
console.error('Missing required parameters. Please provide either command line arguments or environment variables:');
missing.forEach(([param, envVar]) => {
console.error(` --${param.replace(/[A-Z]/g, m => `-${m.toLowerCase()}`)} or ${envVar}`);
});
process.exit(1);
}
options.batchSize = parseInt(options.batchSize, 10);
if (isNaN(options.batchSize) || options.batchSize < 1) {
console.error('Batch size must be a positive number');
process.exit(1);
}
await backupVercelStorageToS3(options);
} catch (error) {
console.error('Backup process failed:', error.message);
process.exit(1);
}
});
program.parse();