-
Notifications
You must be signed in to change notification settings - Fork 2
/
storage.ts
201 lines (161 loc) · 4.79 KB
/
storage.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
189
190
191
192
193
194
195
196
197
198
199
200
201
import { promisify } from 'util';
import { ReadStream } from 'fs';
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
import * as S3 from 'aws-sdk/clients/s3';
import * as uuidv4 from 'uuid/v4';
import * as mime from 'mime';
import { getLogger } from '../../util-libs/logging';
import { Bus } from '../bus';
import { Event, mkEvent } from './event';
const logger = getLogger('lib:storage');
// ------
// Domain
// ------
interface PreparedUpload {
postUrl: string;
postFields: S3.PresignedPost.Fields;
fileName: string;
fileUrl: string;
fileType: string;
}
type PreparedUploadResult =
| { kind: 'Success', data: PreparedUpload }
| { kind: 'BadMimeType' };
// ---------
// Publishes
// ---------
const mkPreparedUploadCreatedEvent = (preparedUpload: PreparedUpload) => mkEvent(
'prepared-upload-created',
{ preparedUpload },
);
// -------
// Service
// -------
interface StorageServiceConfig {
bus: Bus<Event>;
awsAccessKey: string;
awsSecretAccessKey: string;
awsBucket: string;
bucketEndpoint: string;
awsRegion: string;
prefix: string;
}
export class StorageService {
private bus: Bus<Event>;
private s3: S3;
private bucket: string;
private prefix: string;
/**
* Instantiate a StorageService.
*/
public constructor(config: StorageServiceConfig) {
this.bus = config.bus;
this.s3 = new S3({
accessKeyId: config.awsAccessKey,
secretAccessKey: config.awsSecretAccessKey,
params: {
Bucket: config.awsBucket,
},
endpoint: config.bucketEndpoint,
region: config.awsRegion,
s3ForcePathStyle: true,
signatureVersion: 'v4'
});
this.bucket = config.awsBucket;
this.prefix = config.prefix;
}
/**
* Prepare pre-signed post data that can be used to upload directly to our
* storage.
*
* NOTE: The uploaded file is stored in a private temporary location.
*/
public async createPreparedUpload(mimeType: string): Promise<PreparedUploadResult> {
const suffix = mime.getExtension(mimeType);
if (!suffix) {
logger.warn(`Unknown mime-type: ${mimeType}`);
return { kind: 'BadMimeType' };
}
const fileName = `${uuidv4()}.${suffix}`;
const uploadData = await this.s3.createPresignedPost({
Fields: {
'Key': this.generateUploadKey(fileName),
'ACL': 'private',
//'ServerSideEncryption': 'AES256',
'Content-Type': mimeType,
},
Expires: 60 * 60 * 24,
});
const preparedUpload = {
postUrl: uploadData.url,
postFields: uploadData.fields,
fileName,
fileUrl: `${uploadData.url}/${uploadData.fields.Key}`,
fileType: mimeType,
};
this.bus.publish(mkPreparedUploadCreatedEvent(preparedUpload));
return { kind: 'Success', data: preparedUpload };
}
/**
* Retrieve an item from our user-upload storage.
*
* @param fileName The uploaded fileName as generated by a PreparedUpload
*/
public async getUserUpload(fileName: string): Promise<ReadStream> {
const getObjectRequest = this.s3.getObject({
Bucket: this.bucket,
Key: this.generateUploadKey(fileName),
});
const result = await getObjectRequest.promise();
const filePath = path.join(os.tmpdir(), `${uuidv4()}-${fileName}`);
try {
await promisify(fs.writeFile)(filePath, result.Body);
return fs.createReadStream(filePath);
} finally {
await promisify(fs.unlink)(filePath).catch((unlinkError) => {
logger.error(unlinkError, 'CleanupError');
});
}
}
/**
* Upload a file to our asset-storage.
*
* Assets are expected to be immutable and are stored publicly with long cache
* headers.
*
* @param fileName The filename to upload as-- TODO!!! (NOTE mimeType is read from this)
* @returns The URI of the uploaded asset
*/
public async uploadAsset(fileName: string, body: ReadStream): Promise<string> {
const mimeType = mime.getType(fileName);
if (!mimeType) {
const msg = `Unknown file-type: ${fileName}`;
logger.warn(msg);
throw new Error(msg);
}
const managedUpload = this.s3.upload({
Bucket: this.bucket,
Key: this.generateAssetKey(fileName),
Body: body,
ACL: 'public-read',
ContentType: mimeType,
CacheControl: PUBLIC_CACHING,
//ServerSideEncryption: 'AES256',
});
const sendData = await managedUpload.promise();
return sendData.Location;
}
private generateUploadKey(name: string): string {
return `${this.prefix}/uploads/${name}`;
}
private generateAssetKey(name: string): string {
return `${this.prefix}/assets/${name}`;
}
}
// -------
// Helpers
// -------
const ONE_YEAR = 31536000; // Seconds
const PUBLIC_CACHING = `public, max-age=${ONE_YEAR}, stale-while-revalidate=${ONE_YEAR}, stale-if-error=${ONE_YEAR}`;