-
Notifications
You must be signed in to change notification settings - Fork 1
/
do-multipart-upload.ts
188 lines (160 loc) · 4.53 KB
/
do-multipart-upload.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
import fs from "node:fs/promises";
import assert from "node:assert";
const {
SALAD_API_KEY,
SALAD_ORG_NAME,
STORAGE_API_URL = "http://localhost:8787",
PART_SIZE_MB = "20",
} = process.env;
assert(SALAD_API_KEY, "SALAD_API_KEY must be set");
assert(SALAD_ORG_NAME, "SALAD_ORG_NAME must be set");
export const createUpload = async (filename: string, remotePath: string) => {
const primaryURL = new URL(
`/organizations/${SALAD_ORG_NAME}/files/${remotePath}`,
STORAGE_API_URL
);
const createUrl = primaryURL.toString() + "?action=mpu-create";
const createResp = await fetch(createUrl, {
method: "PUT",
headers: {
"Content-Type": "application/json",
"Salad-Api-Key": SALAD_API_KEY,
},
});
if (!createResp.ok) {
throw new Error(
`Failed to create multipart upload: ${createResp.statusText}`
);
}
const { uploadId } = (await createResp.json()) as { uploadId: string };
return uploadId;
};
export const uploadPart = async (
remotePath: string,
uploadId: string,
partNumber: number,
part: Buffer
) => {
const primaryURL = new URL(
`/organizations/${SALAD_ORG_NAME}/file_parts/${remotePath}`,
STORAGE_API_URL
);
const partUrl =
primaryURL.toString() + `?uploadId=${uploadId}&partNumber=${partNumber}`;
const partResp = await fetch(partUrl, {
method: "PUT",
headers: {
"Content-Type": "application/octet-stream",
"Salad-Api-Key": SALAD_API_KEY,
},
body: part,
});
if (!partResp.ok) {
throw new Error(`Failed to upload part: ${partResp.statusText}`);
}
const partRespBody = (await partResp.json()) as {
etag: string;
partNumber: number;
};
return partRespBody;
};
export const completeUpload = async (
remotePath: string,
uploadId: string,
parts: { etag: string; partNumber: number }[]
) => {
const primaryURL = new URL(
`/organizations/${SALAD_ORG_NAME}/files/${remotePath}`,
STORAGE_API_URL
);
const completeUrl =
primaryURL.toString() + `?action=mpu-complete&uploadId=${uploadId}`;
const completeResp = await fetch(completeUrl, {
method: "PUT",
headers: {
"Content-Type": "application/json",
"Salad-Api-Key": SALAD_API_KEY,
},
body: JSON.stringify({ parts }),
});
if (!completeResp.ok) {
console.log(await completeResp.text());
throw new Error(`Failed to complete upload: ${completeResp.statusText}`);
}
return completeResp;
};
async function readFileInChunks(
filePath: string,
maxChunkSize: number,
eachChunk: (
chunkNumber: number,
chunk: Buffer
) => Promise<{ etag: string; partNumber: number }>
): Promise<{ etag: string; partNumber: number }[]> {
const fileHandle = await fs.open(filePath, "r");
const fileStats = await fileHandle.stat();
const totalSize = fileStats.size;
const numChunks = Math.ceil(totalSize / maxChunkSize);
const realChunkSize = Math.ceil(totalSize / numChunks);
let bytesRead = 0;
let chunkNumber = 1;
const allChunks = [];
while (chunkNumber <= numChunks) {
const buffer = Buffer.alloc(realChunkSize);
const { bytesRead: bytesJustRead } = await fileHandle.read(
buffer,
0,
realChunkSize,
bytesRead
);
bytesRead += bytesJustRead;
allChunks.push(eachChunk(chunkNumber, buffer));
chunkNumber++;
}
await fileHandle.close();
return Promise.all(allChunks);
}
export const uploadFileInParts = async (
filename: string,
remotePath: string,
partSize: number
) => {
const fileSize = (
await fs.stat(filename).catch(() => {
throw new Error(`File not found: ${filename}`);
})
).size;
const uploadId = await createUpload(filename, remotePath);
// console.log(
// `Uploading ${filename} to ${remotePath} in ${numChunks} parts of ${partSize} bytes`
// );
const parts = await readFileInChunks(
filename,
partSize,
async (partNumber, chunk) => {
const partResp = await uploadPart(
remotePath,
uploadId,
partNumber,
chunk
);
// console.log(`Uploaded part ${partNumber}`);
return partResp;
}
);
await completeUpload(remotePath, uploadId, parts);
// console.log("Upload complete");
const url = new URL(
`/organizations/${SALAD_ORG_NAME}/files/${remotePath}`,
STORAGE_API_URL
).toString();
return url;
};
async function main() {
const filename = process.argv[2];
const remotePath = process.argv[3] || filename;
const partSize = parseInt(PART_SIZE_MB) * 1024 * 1024;
const url = await uploadFileInParts(filename, remotePath, partSize);
console.log(url);
}
main();