-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbackup.ts
123 lines (108 loc) · 2.97 KB
/
backup.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
// Example usage: deno run --env -A ./docker/volumes/backups/board_backup_latest.sql.gz
import { format } from "jsr:@std/fmt/bytes";
import { parseArgs } from "jsr:@std/cli/parse-args";
import { basename } from "jsr:@std/path/windows";
import { retry } from "jsr:@std/async";
import { BackblazeClient } from "jsr:@nekz/b2";
const {
_: files,
"user-agent": userAgent = "backup-script/1.0.0",
"dry-run": dryRun,
} = parseArgs(Deno.args);
const uploadWebhookUrl = Deno.env.get("B2_UPLOAD_DISCORD_WEBHOOK_URL");
const headers = {
"Content-Type": "application/json",
"User-Agent": userAgent,
};
const retryOptions = {
multiplier: 2,
maxTimeout: 180_000,
maxAttempts: 5,
minTimeout: 30_000,
jitter: 1,
};
const bucketId = Deno.env.get("B2_BUCKET_ID");
if (!bucketId) {
console.error("Missing B2_BUCKET_ID");
Deno.exit(1);
}
const b2 = new BackblazeClient({ userAgent });
try {
await b2.authorizeAccount({
applicationKeyId: Deno.env.get("B2_APP_KEY_ID")!,
applicationKey: Deno.env.get("B2_APP_KEY")!,
});
for (const file of files) {
try {
const fileContents = await Deno.readFile(file.toString());
const fileName = basename(file.toString());
if (dryRun) {
console.log(`[DRY RUN]: Uploaded file ${fileName}`);
continue;
}
const upload = await retry(async () => {
return await b2.uploadFile({
bucketId,
fileName,
fileContents,
contentType: "application/octet-stream",
contentDisposition: `attachment; filename="${
encodeURIComponent(fileName)
}"`,
});
}, retryOptions);
console.log(`Uploaded file ${fileName} (${upload.fileId})`);
uploadWebhookUrl && await fetch(uploadWebhookUrl, {
method: "POST",
headers: {
"Content-Type": "application/json",
"User-Agent": userAgent,
},
body: JSON.stringify({
embeds: [
{
color: 0x0480A5,
description: `Uploaded file \`${fileName}\` (${
format(upload.contentLength)
}) ${upload.contentMd5}`,
},
],
}),
});
} catch (err) {
console.error(err);
try {
uploadWebhookUrl && await fetch(uploadWebhookUrl, {
method: "POST",
headers,
body: JSON.stringify({
embeds: [
{
color: 0xFF0000,
description:
`An error occurred when trying to upload \`${file}\``,
},
],
}),
});
} catch (err) {
console.error(err);
}
}
}
} catch (err) {
console.error(err);
uploadWebhookUrl && await fetch(uploadWebhookUrl, {
method: "POST",
headers,
body: JSON.stringify({
embeds: [
{
color: 0xFF0000,
description:
`An error occurred when trying to run the backup script.`,
},
],
}),
});
}