-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.ts
More file actions
344 lines (291 loc) Β· 9.35 KB
/
Copy pathindex.ts
File metadata and controls
344 lines (291 loc) Β· 9.35 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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
#!/usr/bin/env bun
interface BackupConfig {
postgres: {
connectionString: string;
};
s3: {
region: string;
bucket: string;
accessKeyId: string;
secretAccessKey: string;
endpoint?: string;
};
backup: {
retentionDays: number;
compressionLevel: number;
};
}
class PostgreSQLBackupManager {
private config: BackupConfig;
private backupDir: string;
constructor(config: BackupConfig) {
this.config = config;
this.backupDir = "./backups";
}
private async ensureBackupDirectory(): Promise<void> {
const backupDirExists = await Bun.file(this.backupDir).exists();
if (!backupDirExists) {
await Bun.write(`${this.backupDir}/.gitkeep`, "");
}
}
async createBackup(): Promise<string> {
await this.ensureBackupDirectory();
const timestamp = new Date().toISOString().replace(/[:.]/g, "-");
const backupFileName = `postgres-backup-${timestamp}.sql`;
const backupPath = `${this.backupDir}/${backupFileName}`;
console.log(`Creating backup: ${backupFileName}`);
try {
const pgDumpCommand = [
"pg_dump",
this.config.postgres.connectionString,
"--verbose",
"--clean",
"--if-exists",
"--create",
"--format=custom",
"--file",
backupPath,
];
const proc = Bun.spawn(pgDumpCommand, {
stdout: "pipe",
stderr: "pipe",
});
const exitCode = await proc.exited;
if (exitCode !== 0) {
const stderr = await new Response(proc.stderr).text();
throw new Error(`pg_dump failed with exit code ${exitCode}: ${stderr}`);
}
console.log(`β
Backup created: ${backupPath}`);
return backupPath;
} catch (error) {
console.error(`β Backup failed:`, error);
throw error;
}
}
async compressBackup(filePath: string): Promise<string> {
console.log(`Compressing: ${filePath}`);
try {
const file = Bun.file(filePath);
const content = await file.arrayBuffer();
const level = Math.max(
0,
Math.min(9, this.config.backup.compressionLevel)
) as 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9;
const compressed = Bun.gzipSync(new Uint8Array(content), { level });
const compressedPath = `${filePath}.gz`;
await Bun.write(compressedPath, compressed);
const proc = Bun.spawn(["rm", filePath], {
stdout: "pipe",
stderr: "pipe",
});
await proc.exited;
console.log(`β
Compressed: ${compressedPath}`);
return compressedPath;
} catch (error) {
console.error(`β Compression failed:`, error);
throw error;
}
}
async uploadToS3(filePath: string): Promise<void> {
console.log(`Uploading to S3: ${filePath}`);
try {
const fileName = filePath.split("/").pop()!;
const s3Key = `private/postgres-backups/${new Date().getFullYear()}/${String(
new Date().getMonth() + 1
).padStart(2, "0")}/${fileName}`;
const s3Client = new Bun.S3Client({
region: this.config.s3.region,
accessKeyId: this.config.s3.accessKeyId,
secretAccessKey: this.config.s3.secretAccessKey,
bucket: this.config.s3.bucket,
endpoint: this.config.s3.endpoint,
});
const file = Bun.file(filePath);
await s3Client.write(s3Key, file, { type: "application/gzip" });
console.log(`β
Uploaded: s3://${this.config.s3.bucket}/${s3Key}`);
} catch (error) {
console.error(`β S3 upload failed:`, error);
throw error;
}
}
async cleanupOldBackups(): Promise<void> {
console.log("π§Ή Starting cleanup of old backups...");
await this.cleanupLocalBackups();
await this.cleanupS3Backups();
}
private async cleanupLocalBackups(): Promise<void> {
try {
if (!(await Bun.file(this.backupDir).exists())) {
console.log("No local backup directory found, skipping local cleanup");
return;
}
const entries = await Array.fromAsync(
new Bun.Glob("*.gz").scan({ cwd: this.backupDir })
);
const cutoffDate = new Date();
cutoffDate.setDate(
cutoffDate.getDate() - this.config.backup.retentionDays
);
let deletedCount = 0;
for (const file of entries) {
const filePath = `${this.backupDir}/${file}`;
const fileInfo = await Bun.file(filePath).exists();
if (fileInfo) {
const dateMatch = file.match(
/postgres-backup-(\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2})/
);
if (dateMatch && dateMatch[1]) {
const fileDate = new Date(
dateMatch[1].replace(/-/g, ":").replace("T", " ")
);
if (fileDate < cutoffDate) {
const proc = Bun.spawn(["rm", filePath], {
stdout: "pipe",
stderr: "pipe",
});
await proc.exited;
console.log(`ποΈ Removed old local backup: ${file}`);
deletedCount++;
}
}
}
}
if (deletedCount > 0) {
console.log(`β
Deleted ${deletedCount} old local backup(s)`);
} else {
console.log("No old local backups to delete");
}
} catch (error) {
console.error(`β Local cleanup failed:`, error);
}
}
private async cleanupS3Backups(): Promise<void> {
try {
console.log("π Checking S3 bucket for old backups...");
const s3Client = new Bun.S3Client({
region: this.config.s3.region,
accessKeyId: this.config.s3.accessKeyId,
secretAccessKey: this.config.s3.secretAccessKey,
bucket: this.config.s3.bucket,
endpoint: this.config.s3.endpoint,
});
const cutoffDate = new Date();
cutoffDate.setDate(
cutoffDate.getDate() - this.config.backup.retentionDays
);
const prefix = "private/postgres-backups/";
const response = await s3Client.list({ prefix });
let deletedCount = 0;
for (const obj of response.contents || []) {
if (!obj.key) continue;
const fileName = obj.key.split("/").pop();
if (!fileName) continue;
const dateMatch = fileName.match(
/postgres-backup-(\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2})/
);
if (dateMatch && dateMatch[1]) {
const fileDate = new Date(
dateMatch[1].replace(/-/g, ":").replace("T", " ")
);
if (fileDate < cutoffDate) {
await s3Client.delete(obj.key);
console.log(`ποΈ Removed old S3 backup: ${obj.key}`);
deletedCount++;
}
}
}
if (deletedCount > 0) {
console.log(`β
Deleted ${deletedCount} old S3 backup(s)`);
} else {
console.log("No old S3 backups to delete");
}
} catch (error) {
console.error(`β S3 cleanup failed:`, error);
}
}
async performBackup(): Promise<void> {
const startTime = new Date().toISOString();
console.log(`Starting backup: ${startTime}`);
try {
const backupPath = await this.createBackup();
const compressedPath = await this.compressBackup(backupPath);
await this.uploadToS3(compressedPath);
await this.cleanupOldBackups();
console.log(`β
Backup completed: ${new Date().toISOString()}`);
} catch (error) {
console.error(`β Backup failed:`, error);
process.exit(1);
}
}
async testConnection(): Promise<boolean> {
try {
const proc = Bun.spawn(
["pg_isready", "-d", this.config.postgres.connectionString],
{ stdout: "pipe", stderr: "pipe" }
);
const exitCode = await proc.exited;
return exitCode === 0;
} catch (error) {
console.error(`β Connection test failed:`, error);
return false;
}
}
}
function loadConfig(): BackupConfig {
const connectionString = process.env.DATABASE_URL;
console.log("connection string", connectionString);
const region = process.env.AWS_REGION || process.env.S3_REGION;
const bucket = process.env.S3_BUCKET;
const accessKeyId = process.env.S3_ACCESS_KEY_ID;
const secretAccessKey = process.env.S3_SECRET_ACCESS_KEY;
if (!connectionString) {
throw new Error("Missing DATABASE_URL or POSTGRES_CONNECTION_STRING");
}
if (!region) {
throw new Error("Missing AWS_REGION or S3_REGION");
}
if (!bucket) {
throw new Error("Missing S3_BUCKET");
}
if (!accessKeyId) {
throw new Error("Missing S3_ACCESS_KEY_ID");
}
if (!secretAccessKey) {
throw new Error("Missing S3_SECRET_ACCESS_KEY");
}
return {
postgres: { connectionString },
s3: {
region,
bucket,
accessKeyId,
secretAccessKey,
endpoint: process.env.S3_ENDPOINT,
},
backup: {
retentionDays: parseInt(process.env.BACKUP_RETENTION_DAYS || "30"),
compressionLevel: parseInt(process.env.COMPRESSION_LEVEL || "6"),
},
};
}
async function main(): Promise<void> {
try {
const config = loadConfig();
const backupManager = new PostgreSQLBackupManager(config);
const isConnected = await backupManager.testConnection();
if (!isConnected) {
console.error("β Database connection failed");
process.exit(1);
}
await backupManager.performBackup();
} catch (error) {
console.error("β System failed:", error);
process.exit(1);
}
}
if (import.meta.main) {
main().catch((error) => {
console.error("β Fatal error:", error);
process.exit(1);
});
}