forked from derrekmc/skipper-azure
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
231 lines (189 loc) · 7.54 KB
/
index.js
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
/**
*
* Author: Lukas Reichart on 3/9/15.
* Purpose: Skipper adapter ( used by the sails.js framework )
* License: MIT
* Copyright Lukas Reichart @Antum 2015, Arryon Tijsma
*/
var path = require('path');
var Writable = require('stream').Writable;
var concat = require('concat-stream');
var azure = require( 'azure-storage');
var BlobConstants = require('azure-storage/lib/common/common.core').Constants.BlobConstants;
var _ = require( 'lodash' );
var mime = require( 'mime' );
module.exports = function SkipperAzure( globalOptions ) {
globalOptions = globalOptions || {};
var blobService = azure.createBlobService();
var adapter;
adapter = {
read: function( fd, cb ) {
var prefix = fd;
var res;
blobService.doesContainerExist( globalOptions.container, prefix, function( err, result ) {
console.log("doesContainerExist", err);
if ( err ) return cb( err );
if (result){
console.log("doesContainerExist:result", result);
response(result);
} else {
blobService.createContainer( globalOptions.container, prefix, function( err, result ) {
console.log("createContainer", err);
if ( err ) return cb( err );
console.log("createContainer:result", result);
response(result);
});
}
function response(result){
blobService.createReadStream(globalOptions.container, prefix, res, function (err, result, response) {
if (err) { return cb(err); }
}).pipe(concat(function (data) {
return cb(null, data);
}));
}
});
},
rm: function( fd, cb ) {
blobService.deleteBlobIfExists( globalOptions.container, fd, function( err, result, response ){
if( err ) {
return cb( err );
}
// construct response
cb( null, {
filename: fd,
success: true,
extra: response
});
});
},
ls: function( dirname, cb ) {
if ( !dirname ) {
dirname = '/';
}
var prefix = dirname;
blobService.listBlobsSegmentedWithPrefix( globalOptions.container, prefix,
null, function( err, result, response ) {
if( err ) {
return cb( err );
}
var data = _.map( result.entries, 'name');
data = _.map(data, function snipPathPrefixes (thisPath) {
thisPath = thisPath.replace(/^.*[\/]([^\/]*)$/, '$1');
// Join the dirname with the filename
thisPath = path.join(dirname, path.basename(thisPath));
return thisPath;
});
cb( null, data );
})
},
receive: AzureReceiver
};
return adapter;
/**
* A simple receiver for Skipper that writes Upstreams to Azure Blob Storage
* to the configured container at the configured path.
*
* @param {Object} options
* @returns {Stream.Writable}
*/
function AzureReceiver( options ) {
var self = this;
options = options || {};
options = _.defaults( options, globalOptions );
var bytesRemaining = options.maxBytes || BlobConstants.MAX_BLOCK_BLOB_BLOCK_SIZE;
if (bytesRemaining > BlobConstants.DEFAULT_SINGLE_BLOB_PUT_THRESHOLD_IN_BYTES * 50000) {
throw new Error('Upload exceeds the size limitation. Max size is ' + BlobConstants.DEFAULT_SINGLE_BLOB_PUT_THRESHOLD_IN_BYTES * 50000 + ' but the current size is ' + bytesRemaining);
}
var receiver = Writable({
objectMode: true
});
receiver.once( 'error', function( err ) {
console.log( 'ERROR ON RECEIVER :: ', err );
});
receiver._write = function onFile( newFile, encoding, done ) {
var startedAt = new Date();
newFile.once( 'error', function( err ) {
console.log( ('ERROR ON file read stream in receiver (%s) :: ', newFile.filename, err ).red );
});
var headers = options.headers || {};
// Lookup content type with mime if not set
if ( typeof headers['content-type'] === 'undefined' ) {
headers['content-type'] = mime.getType( newFile.fd );
}
var uploadOptions = {
contentType: headers['content-type']
};
var abortUpload = function () {
var err = new Error('E_EXCEEDS_UPLOAD_LIMIT');
err.code = 'E_EXCEEDS_UPLOAD_LIMIT';
receiver.emit('error', err);
}
if (bytesRemaining <= 0) {
abortUpload();
return;
}
/**
* As per the convention of streaming a multipart upload, the stream does not beforehand know
* how large the multipart upload will be, even if a Content-Length header is present.
* To know the exact multipart file size, the ending boundary would have to be scanned, which
* is exactly what we want to prevent. Our only option with Azure is to assume the max amount of
* bytes will be sent.
*
* Azure saves blobs in different ways based on the file size. These constants can be found in the package 'azure-storage' for:
*
* - blob: lib/common/util/constants.js, in BlobConstants.DEFAULT_SINGLE_BLOB_PUT_THRESHOLD_IN_BYTES, 32MB by default
* - block: lib/common/util/constants.js, in BlobConstants.MAX_BLOCK_BLOB_BLOCK_SIZE, 100MB by default
*
* Since we don't know the stream size, we have to assume it will be options.maxBytes long.
* We can upload many of these files in one upload, but the remaining bytes should be calculated after each
* streamed chunk upload, to be able to refuse uploading past the limit of maxBytes.
*
* This is why we tell Azure to expect 'byteLength', which is the remaining bytes from multiple succesful uploads.
*/
var byteLength = bytesRemaining;
newFile.on('data', function (chunk) {
bytesRemaining -= chunk.length;
});
console.info('stream length: ', bytesRemaining);
var uploader = blobService.createBlockBlobFromStream(
options.container,
newFile.fd,
newFile,
byteLength,
uploadOptions,
function( err, result, response ) {
if( err ) {
console.log( ('Receiver: Error writing ' + newFile.filename + ' :: Cancelling upload and cleaning up already-written bytes ... ' ).red );
receiver.emit( 'error', err );
return;
}
function callback (err, result, response) {
if( err ) {
console.log( ('Receiver: Error writing ' + newFile.filename + ' :: Cancelling upload and cleaning up already-written bytes ... ' ).red );
receiver.emit( 'error', err );
return;
}
if ( bytesRemaining < 0 ) {
adapter.rm(newFile.fd, function (err, result) {
if (err) {
receiver.emit(err);
}
abortUpload();
});
return;
}
newFile.byteCount = +result.contentLength;
newFile.size = newFile.byteCount;
newFile.extra = response;
var endedAt = new Date();
var duration = ( endedAt - startedAt ) / 1000;
console.log( 'UPLOAD took ' + duration + ' seconds .. ' );
receiver.emit('writefile', newFile);
done();
}
blobService.getBlobProperties(options.container, newFile.fd, callback);
});
};
return receiver;
}
};