-
Notifications
You must be signed in to change notification settings - Fork 7
/
blob.js
2481 lines (2282 loc) · 109 KB
/
blob.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
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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'use strict';
import assert from 'assert';
import debugFactory from 'debug';
const debug = debugFactory('azure:blob');
import * as utils from './utils.js';
import querystring from 'querystring';
import * as xml from './xml-parser.js';
import util from 'util';
import events from 'events';
import * as agent from './agent.js';
import * as auth from './authorization.js';
/*
* Azure storage service version
* @const
*/
var SERVICE_VERSION = '2016-05-31';
/*
* The maximum size, in bytes, of a block blob that can be uploaded, before it must be separated into blocks.
* @const
*/
var MAX_SINGLE_UPLOAD_BLOCK_BLOB_SIZE_IN_BYTES = 256 * 1024 * 1024;
/*
* The maximum size of a single block.
* @const
*/
var MAX_BLOCK_SIZE = 4 * 1024 * 1024;
/*
* Page blob length.
* @const
*/
var PAGE_SIZE = 512;
/*
* The maximum size, in bytes, of a page blob.
* @const
*/
var MAX_PAGE_SIZE = 1 * 1024 * 1024 * 1024;
/*
* The maximum size of an append block.
* @const
*/
var MAX_APPEND_BLOCK_SIZE = 4 * 1024 * 1024;
/* Transient error codes (we'll retry request when encountering these codes */
var TRANSIENT_ERROR_CODES = [
// Azure error codes we should retry on according to azure docs
'InternalError',
'ServerBusy'
].concat(utils.TRANSIENT_HTTP_ERROR_CODES);
/*
* List of query-string parameter supported in lexicographical order, used for
* construction of the canonicalized resource.
*/
var QUERY_PARAMS_SUPPORTED = [
'comp',
'timeout',
'restype',
'prefix',
'marker',
'maxResults',
'include',
'delimiter',
'blockid',
'blocklisttype'
].sort();
function anonymous(method, path, query, headers) {
// Serialize query-string
var qs = querystring.stringify(query);
if (qs.length > 0) {
qs += '&';
}
return Promise.resolve({
host: this.hostname,
method: method,
path: path + '?' + qs,
headers: headers,
agent: this.options.agent
});
}
/**
* Blob client class for interacting with Azure Blob Storage.
*
* @class Blob
* @constructor
* @param {object} options - options on the form:
*
* ```js
* {
* // Value for the x-ms-version header fixing the API version
* version: SERVICE_VERSION,
*
* // Value for the x-ms-client-request-id header identifying the client
* clientId: 'fast-azure-storage',
*
* // Server-side request timeout
* timeout: 30 * 1000,
*
* // Delay between client- and server-side timeout
* clientTimeoutDelay: 500,
*
* // Max number of request retries
* retries: 5,
*
* // HTTP Agent to use (defaults to a global azure.Agent instance)
* agent: azure.Agent.globalAgent,
*
* // Multiplier for computation of retry delay: 2 ^ retry * delayFactor
* delayFactor: 100,
*
* // Randomization factor added as:
* // delay = delay * random([1 - randomizationFactor; 1 + randomizationFactor])
* randomizationFactor: 0.25,
*
* // Maximum retry delay in ms (defaults to 30 seconds)
* maxDelay: 30 * 1000,
*
* // Error codes for which we should retry
* transientErrorCodes: TRANSIENT_ERROR_CODES,
*
* // Azure storage accountId (required)
* accountId: undefined,
*
* // Azure shared accessKey, required unless options.sas is given
* accessKey: undefined,
*
* // Function that returns SAS string or promise for SAS string, in which
* // case we will refresh SAS when a request occurs less than
* // minSASAuthExpiry from signature expiry. This property may also be a
* // SAS string.
* sas: undefined,
*
* // Minimum SAS expiry before refreshing SAS credentials, if a function for
* // refreshing SAS credentials is given as options.sas
* minSASAuthExpiry: 15 * 60 * 1000
* }
* ```
*/
export function Blob(options) {
// Initialize EventEmitter parent class
events.EventEmitter.call(this);
// Set default options
this.options = {
version: SERVICE_VERSION,
clientId: 'fast-azure-storage',
timeout: 30 * 1000,
clientTimeoutDelay: 500,
agent: agent.globalAgent,
retries: 5,
delayFactor: 100,
randomizationFactor: 0.25,
maxDelay: 30 * 1000,
transientErrorCodes: TRANSIENT_ERROR_CODES,
accountId: undefined,
accessKey: undefined,
sas: undefined,
minSASAuthExpiry: 15 * 60 * 1000,
};
// Overwrite default options
for (var key in options) {
if (options.hasOwnProperty(key) && options[key] !== undefined) {
this.options[key] = options[key];
}
}
// Validate options
assert(this.options.accountId, "`options.accountId` must be given");
// Construct hostname
this.hostname = this.options.accountId + '.blob.core.windows.net';
// Compute `timeout` for client-side timeout (in ms), and `timeoutInSeconds`
// for server-side timeout in seconds.
this.timeout = this.options.timeout + this.options.clientTimeoutDelay;
this.timeoutInSeconds = Math.floor(this.options.timeout / 1000);
// Define `this.authorize`
if (this.options.accessKey) {
// If set authorize to use shared key signatures
this.authorize = auth.authorizeWithSharedKey.call(this, 'blob', QUERY_PARAMS_SUPPORTED);
// Decode accessKey
this._accessKey = new Buffer(this.options.accessKey, 'base64');
} else if (this.options.sas instanceof Function) {
// Set authorize to use shared-access-signatures with refresh function
this.authorize = auth.authorizeWithRefreshSAS;
// Set state with _nextSASRefresh = -1, we'll refresh on the first request
this._nextSASRefresh = -1;
this._sas = '';
} else if (typeof(this.options.sas) === 'string') {
// Set authorize to use shared-access-signature as hardcoded
this.authorize = auth.authorizeWithSAS;
} else {
this.authorize = anonymous;
}
};
// Export Blob
export default Blob;
// Subclass EventEmitter
util.inherits(Blob, events.EventEmitter);
/**
* Generate a SAS string on the form 'key1=va1&key2=val2&...'.
*
* @method sas
* @param {string} container - Name of the container that this SAS string applies to.
* @param {string} blob - Name of the blob that this SAS string applies to.
* @param {object} options - Options for the following form:
*```js
* {
* start: new Date(), // Time from which signature is valid (optional)
* expiry: new Date(), // Expiration of signature (required).
* resourceType: 'blob|container', // Specifies which resources are accessible via the SAS(required)
* // Possible values are: 'blob' or 'container'.
* // Specify 'blob' if the shared resource is a 'blob'.
* // This grants access to the content and metadata of the blob.
* // Specify 'container' if the shared resource is a 'container'.
* // This grants access to the content and metadata of any
* // blob in the container, and to the list of blobs in
* // the container.
* permissions: { // Set of permissions delegated (required)
* // It must be omitted if it has been specified in the associated
* // stored access policy.
* read: false, // Read the content, properties, metadata or block list of a blob
* // or of any blob in the container if the resourceType is
* // a container.
* add: false, // Add a block to an append blob or to any append blob if the
* // resourceType is a container.
* create: false, // Write a new blob, snapshot a blob, or copy a blob
* // to a new blob.
* // These operations can be done to any blob in the container
* // if the resourceType is a container.
* write: false, // Create or write content, properties, metadata, or block list.
* // Snapshot or lease the blob. Resize the blob (page blob only).
* // These operations can be done for every blob in the container
* // if the resourceType is a container.
* delete: false, // Delete the blob or any blob in the container if the
* // resourceType is a container.
* list: false, // List blobs in the container.
* },
* cacheControl: '...', // The value of the Cache-Control response header
* // to be returned. (optional)
* contentDisposition: '...', // The value of the Content-Disposition response header
* // to be returned. (optional)
* contentEncoding: '...', // The value of the Content-Encoding response header
* // to be returned. (optional)
* contentLanguage: '...', // The value of the Content-Language response header
* // to be returned. (optional)
* contentType: '...', // The value of the Content-Type response header to
* // be returned. (optional)
* accessPolicy: '...' // Reference to stored access policy (optional)
* // A GUID string
* }
* ```
* @returns {string} Shared-Access-Signature on string form.
*
*/
Blob.prototype.sas = function sas(container, blob, options){
// verify the required options
assert(options, "options is required");
assert(options.expiry instanceof Date,
"options.expiry must be a Date object");
assert(options.resourceType, 'options.resourceType is required');
assert(options.resourceType === 'blob' || options.resourceType === 'container',
'The possible values for options.resourceType are `blob` or `container`');
assert(options.permissions || options.accessPolicy, "options.permissions or options.accessPolicy must be specified");
if (options.resourceType === 'container' && blob){
throw new Error('If `options.resourceType` is container, the blob cannot be specified.');
}
// Check that we have credentials
if (!this.options.accountId ||
!this.options.accessKey) {
throw new Error("accountId and accessKey are required for SAS creation!");
}
// Construct query-string with required parameters
var query = {
sv: SERVICE_VERSION,
se: utils.dateToISOWithoutMS(options.expiry),
sr: options.resourceType === 'blob' ? 'b' : 'c',
spr: 'https'
}
if (options.permissions){
if (options.permissions.list && options.resourceType === 'blob') {
throw new Error('The permission `list` is forbidden for the blob resource type.');
}
// Construct permissions string (in correct order)
var permissions = '';
if (options.permissions.read) permissions += 'r';
if (options.permissions.add) permissions += 'a';
if (options.permissions.create) permissions += 'c';
if (options.permissions.write) permissions += 'w';
if (options.permissions.delete) permissions += 'd';
if (options.permissions.list && options.resourceType === 'container') permissions += 'l';
query.sp = permissions;
}
// Add optional parameters to query-string
if (options.cacheControl) query.rscc = options.cacheControl;
if (options.contentDisposition) query.rscd = options.contentDisposition;
if (options.contentEncoding) query.rsce = options.contentEncoding;
if (options.contentLanguage) query.rscl = options.contentLanguage;
if (options.contentType) query.rsct = options.contentType;
if (options.start) {
assert(options.start instanceof Date, "if specified start must be a Date object");
query.st = utils.dateToISOWithoutMS(options.start);
}
if (options.accessPolicy) {
assert(/^[0-9a-fA-F]{1,64}$/i.test(options.accessPolicy), 'The `options.accessPolicy` is not valid.' );
query.si = options.accessPolicy;
}
// Construct string-to-sign
var canonicalizedResource = '/blob/' + this.options.accountId.toLowerCase() + '/' + container;
if (blob){
canonicalizedResource += '/' + blob;
}
var stringToSign = [
query.sp || '',
query.st || '',
query.se || '',
canonicalizedResource,
query.si || '',
'', // TODO: Support signed IP addresses
query.spr,
query.sv,
query.rscc || '',
query.rscd || '',
query.rsce || '',
query.rscl || '',
query.rsct || ''
].join('\n');
// Compute signature
query.sig = utils.hmacSha256(this._accessKey, stringToSign);
// Return Shared-Access-Signature as query-string
return querystring.stringify(query);
};
/**
* Construct authorized request options by adding signature or
* shared-access-signature, return promise for the request options.
*
* @protected
* @method authorize
* @param {string} method - HTTP verb in upper case, e.g. `GET`.
* @param {string} path - Path on blob resource for storage account.
* @param {object} query - Query-string parameters.
* @param {object} header - Mapping from header key in lowercase to value.
* @returns {Promise} A promise for an options object compatible with
* `https.request`.
*/
Blob.prototype.authorize = function(method, path, query, headers) {
throw new Error("authorize is not implemented, must be defined!");
};
/**
* Make a signed request to `path` using `method` in upper-case and all `query`
* parameters and `headers` keys in lower-case. The request will carry `data`
* as payload and will be retried using the configured retry policy,
*
* @private
* @method request
* @param {string} method - HTTP verb in upper case, e.g. `GET`.
* @param {string} path - Path on blob resource for storage account.
* @param {object} query - Query-string parameters.
* @param {object} header - Mapping from header key in lowercase to value.
* @return {Promise} A promise for HTTPS response with `payload` property as
* string containing the response payload.
*/
Blob.prototype.request = function request(method, path, query, headers, data) {
// Set timeout, if not provided
if (query.timeout === undefined) {
query.timeout = this.timeoutInSeconds;
}
// Set date, version and client-request-id headers
headers['x-ms-date'] = new Date().toUTCString();
headers['x-ms-version'] = this.options.version;
headers['x-ms-client-request-id'] = this.options.clientId;
// Set content-length, if data is given
if (data && data.length > 0 && !headers['content-length']) {
headers['content-length'] = Buffer.byteLength(data, 'utf-8');
}
// Construct authorized request options with shared key signature or
// shared-access-signature.
var self = this;
return this.authorize(method, path, query, headers).then(function(options) {
// Retry with retry policy
return utils.retry(function(retry) {
debug("Request: %s %s, retry: %s", method, path, retry);
// Construct a promise chain first handling the request, and then parsing
// any potential error message
return utils.request(options, data, self.timeout).then(function(res) {
// Accept the response if it's 2xx, otherwise we construct and
// throw an error
if (200 <= res.statusCode && res.statusCode < 300) {
return res;
}
// Parse error message
var data = xml.parseError(res);
var resMSHeaders = {};
Object.keys(res.headers).forEach(h => {
if (h.startsWith('x-ms-')) {
resMSHeaders[h] = res.headers[h];
}
});
// Construct error object
var err = new Error(data.message);
err.name = data.code + 'Error';
err.code = data.code;
err.statusCode = res.statusCode;
err.message = data.message;
err.retries = retry;
err.resMSHeaders = resMSHeaders;
debug("Error code: %s (%s) for %s %s on retry: %s",
data.code, res.statusCode, method, path, retry);
// Throw the constructed error
throw err;
});
}, self.options);
});
};
/**
* Sets properties for a storage account’s Blob service endpoint
*
* @method setServiceProperties
* @param {object} options - Options on the following form:
* ```js
* {
* logging: { // The Azure Analytics Logging settings.
* version: '...', // The version of Storage Analytics to configure (required if logging specified)
* delete: true|false, // Indicates whether all delete requests should be logged
* // (required if logging specified)
* read: true|false, // Indicates whether all read requests should be logged
* // (required if logging specified)
* write: true|false, // Indicates whether all write requests should be logged
* // (required if logging specified)
* retentionPolicy: {
* enabled: true|false, // Indicates whether a retention policy is enabled for the
* // storage service. (required)
* days: '...', // Indicates the number of days that metrics or logging data should be retained.
* // Required only if a retention policy is enabled.
* },
* },
* hourMetrics: { // The Azure Analytics HourMetrics settings
* version: '...', // The version of Storage Analytics to configure
* // (required if hourMetrics specified)
* enabled: true|false, // Indicates whether metrics are enabled for the Blob service
* //(required if hourMetrics specified).
* includeAPIs: true|false, // Indicates whether metrics should generate summary statistics for called API
* // operations (Required only if metrics are enabled).
* retentionPolicy: {
* enabled: true|false,
* days: '...',
* },
* },
* minuteMetrics: { // The Azure Analytics MinuteMetrics settings
* version: '...', // The version of Storage Analytics to configure
* // (required if minuteMetrics specified)
* enabled: true|false, // Indicates whether metrics are enabled for the Blob service
* // (required if minuteMetrics specified).
* includeAPIs: true|false, // Indicates whether metrics should generate summary statistics for called API
* // operations (Required only if metrics are enabled).
* retentionPolicy: {
* enabled: true|false,
* days: '...',
* },
* },
* corsRules: [{ // CORS rules
* allowedOrigins: [], // A list of origin domains that will be allowed via CORS,
* // or "*" to allow all domains
* allowedMethods: [], // List of HTTP methods that are allowed to be executed by the origin
* maxAgeInSeconds: [], // The number of seconds that the client/browser should cache a
* // preflight response
* exposedHeaders: [], // List of response headers to expose to CORS clients
* allowedHeaders: [], // List of headers allowed to be part of the cross-origin request
* }]
* }
* ```
* @return {Promise} A promise that the properties have been set
*/
Blob.prototype.setServiceProperties = function setServiceProperties(options) {
var payload = '<?xml version="1.0" encoding="utf-8"?>';
payload += '<StorageServiceProperties>';
if (options) {
if (options.logging) {
payload += '<Logging>';
var logging = options.logging;
assert(logging.version, 'The `options.logging.version` must be supplied if `options.logging` is specified');
payload += '<Version>' + logging.version + '</Version>';
assert(logging.delete, 'The `options.logging.delete` must be supplied if `options.logging` is specified');
payload += '<Delete>' + logging.delete + '</Delete>';
assert(logging.read, 'The `options.logging.read` must be supplied if `options.logging` is specified');
payload += '<Read>' + logging.read + '</Read>';
assert(logging.write, 'The `options.logging.write` must be supplied if `options.logging` is specified');
payload += '<Write>' + logging.write + '</Write>';
assert(logging.retentionPolicy, 'The `options.logging.retentionPolicy` must be supplied if `options.logging` is specified');
payload += '<RetentionPolicy>';
assert(logging.retentionPolicy.enabled, 'The `options.logging.retentionPolicy.enabled` must be supplied if `options.logging` is specified');
payload += '<Enabled>' + logging.retentionPolicy.enabled + '</Enabled>';
if (logging.retentionPolicy.enabled === true) {
assert(logging.retentionPolicy.days, 'The `options.logging.retentionPolicy.days` must be supplied if a retention policy is enabled');
assert(logging.retentionPolicy.days > 1 && logging.retentionPolicy.days < 365,
'The `options.logging.retentionPolicy.days` must be a number between 1 and 365.');
payload += '<Days>' + logging.retentionPolicy.days + '</Days>';
}
payload += '</RetentionPolicy>';
payload += '</Logging>';
}
if(options.hourMetrics) {
payload += '<HourMetrics>';
var hourMetrics = options.hourMetrics;
assert(hourMetrics.version, 'The `options.hourMetrics.version` must be supplied if `options.hourMetrics` is specified');
payload += '<Version>' + hourMetrics.version + '</Version>';
if (hourMetrics.enabled === undefined || hourMetrics.enabled === null) {
throw new Error('The `options.hourMetrics.enabled` must be supplied if `options.hourMetrics` is specified');
}
payload += '<Enabled>' + hourMetrics.enabled + '</Enabled>';
if (hourMetrics.enabled === true) {
if (hourMetrics.includeAPIs === undefined || hourMetrics.includeAPIs === null) {
throw new Error('The `options.hourMetrics.includeAPIs` must be supplied if `options.hourMetrics` is specified');
}
payload += '<IncludeAPIs>' + hourMetrics.includeAPIs + '</IncludeAPIs>';
}
assert(hourMetrics.retentionPolicy, 'The `options.hourMetrics.retentionPolicy` must be supplied if `options.hourMetrics` is specified');
payload += '<RetentionPolicy>';
if (hourMetrics.retentionPolicy.enabled === undefined || hourMetrics.retentionPolicy.enabled === null) {
throw new Error('The `options.hourMetrics.retentionPolicy.enabled` must be supplied if `options.hourMetrics` is specified');
}
payload += '<Enabled>' + hourMetrics.retentionPolicy.enabled + '</Enabled>';
if (hourMetrics.retentionPolicy.enabled === true) {
assert(hourMetrics.retentionPolicy.days, 'The `options.hourMetrics.retentionPolicy.days` must be supplied if a retention policy is enabled');
assert(hourMetrics.retentionPolicy.days > 1 && hourMetrics.retentionPolicy.days < 365,
'The `options.hourMetrics.retentionPolicy.days` must be a number between 1 and 365.');
payload += '<Days>' + hourMetrics.retentionPolicy.days + '</Days>';
}
payload += '</RetentionPolicy>';
payload += '</HourMetrics>';
}
if(options.minuteMetrics) {
payload += '<MinuteMetrics>';
var minuteMetrics = options.minuteMetrics;
assert(minuteMetrics.version, 'The `options.minuteMetrics.version` must be supplied if `options.minuteMetrics` is specified');
payload += '<Version>' + minuteMetrics.version + '</Version>';
if (minuteMetrics.enabled === undefined || minuteMetrics.enabled === null) {
throw new Error('The `options.minuteMetrics.enabled` must be supplied if `options.minuteMetrics` is specified');
}
payload += '<Enabled>' + minuteMetrics.enabled + '</Enabled>';
if (minuteMetrics.enabled === true) {
if (minuteMetrics.includeAPIs === undefined || minuteMetrics.includeAPIs === null) {
throw new Error('The `options.minuteMetrics.includeAPIs` must be supplied if `options.minuteMetrics` is specified');
}
payload += '<IncludeAPIs>' + minuteMetrics.includeAPIs + '</IncludeAPIs>';
}
assert(minuteMetrics.retentionPolicy, 'The `options.minuteMetrics.retentionPolicy` must be supplied if `options.minuteMetrics` is specified');
payload += '<RetentionPolicy>';
if (minuteMetrics.retentionPolicy.enabled === undefined || minuteMetrics.retentionPolicy.enabled === null) {
throw new Error('The `options.minuteMetrics.retentionPolicy.enabled` must be supplied if `options.minuteMetrics` is specified');
}
payload += '<Enabled>' + minuteMetrics.retentionPolicy.enabled + '</Enabled>';
if (minuteMetrics.retentionPolicy.enabled === true) {
assert(minuteMetrics.retentionPolicy.days, 'The `options.minuteMetrics.retentionPolicy.days` must be supplied if a retention policy is enabled');
assert(minuteMetrics.retentionPolicy.days >= 1 && minuteMetrics.retentionPolicy.days <= 365,
'The `options.minuteMetrics.retentionPolicy.days` must be a number between 1 and 365.');
payload += '<Days>' + minuteMetrics.retentionPolicy.days + '</Days>';
}
payload += '</RetentionPolicy>';
payload += '</MinuteMetrics>';
}
if(options.corsRules) {
payload += '<Cors>';
options.corsRules.forEach(function(rule) {
payload += '<CorsRule>';
assert(rule.allowedOrigins, 'For CORS rule, the allowedOrigins must be specified');
payload += '<AllowedOrigins>' + rule.allowedOrigins.join(',') + '</AllowedOrigins>';
assert(rule.allowedMethods, 'For CORS rule, the allowedMethods must be specified');
payload += '<AllowedMethods>' + rule.allowedMethods.join(',') + '</AllowedMethods>';
assert(rule.maxAgeInSeconds, 'For CORS rule, the maxAgeInSeconds must be specified');
if (rule.maxAgeInSeconds) payload += '<MaxAgeInSeconds>' + rule.maxAgeInSeconds + '</MaxAgeInSeconds>';
assert(rule.exposedHeaders, 'For CORS rule, the exposedHeaders must be specified');
if (rule.exposedHeaders) payload += '<ExposedHeaders>' + rule.exposedHeaders.join(',') + '</ExposedHeaders>';
assert(rule.allowedHeaders, 'For CORS rule, the allowedHeaders must be specified');
if (rule.allowedHeaders) payload += '<AllowedHeaders>' + rule.allowedHeaders.join(',') + '</AllowedHeaders>';
payload += '</CorsRule>';
});
payload += '</Cors>';
}
}
payload += '</StorageServiceProperties>';
var query = {
restype: 'service',
comp: 'properties'
};
return this.request('PUT', '/', query, {}, payload).then(function(response) {
if (response.statusCode !== 202) {
throw new Error("setServiceProperties: Unexpected statusCode: " + response.statusCode);
}
});
};
/**
* Gets the properties of a storage account’s Blob service, including properties for Storage Analytics and
* CORS (Cross-Origin Resource Sharing) rules.
*
* @method getServiceProperties
* @return {Promise} A promise for an object on the form:
* ```js
* {
* logging: { // The Azure Analytics Logging settings.
* version: '...', // The version of Storage Analytics to configure
* delete: true|false, // Indicates whether all delete requests should be logged
* read: true|false, // Indicates whether all read requests should be logged
* write: true|false, // Indicates whether all write requests should be logged
* retentionPolicy: {
* enabled: true|false, // Indicates whether a retention policy is enabled for the storage service
* days: '...', // Indicates the number of days that metrics or logging data should be retained.
* },
* },
* hourMetrics: { // The Azure Analytics HourMetrics settings
* version: '...', // The version of Storage Analytics to configure
* enabled: true|false, // Indicates whether metrics are enabled for the Blob service
* includeAPIs: true|false, // Indicates whether metrics should generate summary statistics
* // for called API operations.
* retentionPolicy: {
* enabled: true|false,
* days: '...',
* },
* },
* minuteMetrics: { // The Azure Analytics MinuteMetrics settings
* version: '...', // The version of Storage Analytics to configure
* enabled: true|false, // Indicates whether metrics are enabled for the Blob service
* includeAPIs: true|false, // Indicates whether metrics should generate summary statistics
* // for called API operations.
* retentionPolicy: {
* enabled: true|false,
* days: '...',
* },
* },
* corsRules: [{ // CORS rules
* allowedOrigins: [], // A list of origin domains that will be allowed via CORS,
* // or "*" to allow all domains.
* allowedMethods: [], // List of HTTP methods that are allowed to be executed by the origin
* maxAgeInSeconds: [], // The number of seconds that the client/browser should cache a preflight response
* exposedHeaders: [], // List of response headers to expose to CORS clients
* allowedHeaders: [], // List of headers allowed to be part of the cross-origin request
* }]
* }
* ```
*/
Blob.prototype.getSeviceProperties = function getSeviceProperties() {
var query = {
restype: 'service',
comp: 'properties'
};
return this.request('GET', '/', query, {}).then(function(response) {
if (response.statusCode !== 200) {
throw new Error("setServiceProperties: Unexpected statusCode: " + response.statusCode);
}
return xml.blobParseServiceProperties(response);
});
};
/**
* Create a new container with the given 'name' under the storage account.
*
* @method createContainer
* @param {string} name - Name of the container to create
* @param {object} options - Options on the following form
* ```js
* {
* metadata: '...', // Mapping from metadata keys to values. (optional)
* publicAccessLevel: '...', // Specifies whether data in the container may be accessed
* // publicly and the level of access.
* // Possible values: container, blob. (optional)
* }
* ```
* @returns {Promise} a promise for metadata key/value pair
* A promise for an object on the form:
* ```js
* {
* eTag: '...', // The entity tag of the container
* lastModified: '...', // The date/time the container was last modified
* }
* ```
*/
Blob.prototype.createContainer = function createContainer(name, options) {
assert(typeof name === 'string', 'The name of the container must be specified and must be a string value.');
// Construct headers
var headers = {};
if (options){
if (options.metadata) {
for(var key in options.metadata) {
if (options.metadata.hasOwnProperty(key)) {
headers['x-ms-meta-' + key] = options.metadata[key];
}
}
}
if(options.publicAccessLevel) {
assert( options.publicAccessLevel === 'container' || options.publicAccessLevel === 'blob',
'The `publicAccessLevel` is invalid. The possible values are: container and blob.'
)
headers['x-ms-blob-public-access'] = options.publicAccessLevel;
}
}
// Construct query string
var query = {
restype: 'container'
};
var path = '/' + name;
return this.request('PUT', path, query, headers).then(function(response) {
// container was created - response code 201
if (response.statusCode !== 201) {
throw new Error("createContainer: Unexpected statusCode: " + response.statusCode);
}
return {
eTag: response.headers['etag'],
lastModified: new Date(response.headers['last-modified'])
};
});
};
/**
* Sets metadata for the specified container.
* Overwrites all existing metadata that is associated with the container.
*
* @method setContainerMetadata
* @param {string} name - Name of the container to set metadata on
* @param {object} metadata - Mapping from metadata keys to values.
* @param {object} options - Options on the following form
* ```js
* {
* leaseId: '...', // Lease unique identifier. A GUID string.(optional)
* ifModifiedSince: new Date(), // Specify this to perform the operation only if the resource has been
* // modified since the specified time. (optional)
* }
*```
* @returns {Promise} a promise for metadata key/value pair
* A promise for an object on the form:
* ```js
* {
* eTag: '...', // The entity tag of the container
* lastModified: '...', // The date/time the container was last modified
* }
* ```
*/
Blob.prototype.setContainerMetadata = function setContainerMetadata(name, metadata, options) {
assert(typeof name === 'string', 'The name of the container must be specified and must be a string value.');
// Construct query string
var query = {
restype: 'container',
comp: 'metadata'
};
// Construct headers
var headers = {};
if (options) {
if (options.leaseId) {
assert(utils.isValidGUID(options.leaseId), '`leaseId` is not a valid GUID.');
headers['x-ms-lease-id'] = options.leaseId;
}
// set conditional header
if (options.ifModifiedSince){
assert(options.ifModifiedSince instanceof Date,
'If specified, the `options.ifModifiedSince` must be a Date');
headers['if-modified-since'] = options.ifModifiedSince.toUTCString();
}
}
for(var key in metadata) {
if (metadata.hasOwnProperty(key)) {
headers['x-ms-meta-' + key] = metadata[key];
}
}
var path = "/" + name;
return this.request('PUT', path, query, headers).then(function(response) {
if(response.statusCode !== 200) {
throw new Error('setContainerMetadata: Unexpected statusCode: ' + response.statusCode);
}
return {
eTag: response.headers['etag'],
lastModified: new Date(response.headers['last-modified'])
}
});
};
/**
* Get the metadata for the container with the given name.
*
* Note, this is a `HEAD` request, so if the container is missing you get an
* error with `err.statusCode = 404`, but `err.code` property will be
* `ErrorWithoutCode`.
*
* @method getContainerMetadata
* @param {string} name - the name of the container to get metadata from.
* @param {object} options - Options on the following form
* ```js
* {
* leaseId: '...' // Lease unique identifier. A GUID string.(optional)
* }
* @returns {Promise} a promise for metadata key/value pair
* A promise for an object on the form:
* ```js
* {
* eTag: '...', // The entity tag of the container
* lastModified: '...', // The date/time the container was last modified
* }
* ```
*/
Blob.prototype.getContainerMetadata = function getContainerMetadata(name, options) {
assert(typeof name === 'string', 'The name of the container must be specified and must be a string value.');
// Construct the query string
var query = {
comp: 'metadata',
restype: 'container'
}
var path = "/" + name;
var headers = {};
if (options && options.leaseId) {
assert(utils.isValidGUID(options.leaseId), '`leaseId` is not a valid GUID.');
headers['x-ms-lease-id'] = options.leaseId;
}
return this.request('HEAD', path, query, headers).then(function(response) {
if (response.statusCode !== 200) {
throw new Error("getContainerMetadata: Unexpected statusCode: " + response.statusCode);
}
return {
eTag: response.headers['etag'],
lastModified: new Date(response.headers['last-modified']),
metadata: utils.extractMetadataFromHeaders(response)
}
});
};
/**
* Delete container with the given 'name'.
*
* Note, when a container is deleted, a container with the same name cannot be created for at least 30 seconds;
* the container may not be available for more than 30 seconds if the service is still processing the request.
* Please see the documentation for more details.
*
* @method deleteContainer
* @param {string} name - Name of the container to delete
* @param {object} options - Options on the following form
* ```js
* {
* leaseId: '...', // Lease unique identifier. A GUID string.(optional)
* ifModifiedSince: new Date(), // Specify this to perform the operation only if the resource has
* // been modified since the specified time. (optional)
* ifUnmodifiedSince: new Date(), // Specify this to perform the operation only if the resource has
* // not been modified since the specified date/time. (optional)
* }
*```
* @returns {Promise} A promise that container has been marked for deletion.
*/
Blob.prototype.deleteContainer = function deleteContainer(name, options) {
assert(typeof name === 'string', 'The name of the container must be specified and must be a string value.');
// construct query string
var query = {
restype: 'container'
};
var path = '/' + name;
var headers = {};
if (options) {
if (options.leaseId) {
assert(utils.isValidGUID(options.leaseId), '`leaseId` is not a valid GUID.');
headers['x-ms-lease-id'] = options.leaseId;
}
utils.setConditionalHeaders(headers, options, true);
}
return this.request('DELETE', path, query, headers).then(function(response) {
if(response.statusCode !== 202) {
throw new Error('deleteContainer: Unexpected statusCode: ' + response.statusCode);
}
});
};
/**
* List the containers under the storage account
*
* @method listContainers
* @param {object} options - Options on the following form:
*
* ```js
* {
* prefix: '...', // Prefix of containers to list
* marker: '...', // Marker to list containers from
* maxResults: 5000, // Max number of results
* metadata: false // Whether or not to include metadata
* }
*
* @returns {Promise} A promise for an object on the form:
* ```js
* {
* containers: [
* {
* name: '...', // Name of container
* properties: {
* lastModified: '...', // Container's last modified time
* eTag: '...', // The entity tag of the container
* leaseStatus: '...', // The lease status of the container
* leaseState: '...', // The lease state of the container
* leaseDuration: '...' // The lease duration of the container
* publicAccessLevel: '...' // Indicates whether data in the container may be accessed publicly
* // and the level of access. If this is not returned in the response,
* // the container is private to the account owner.
* }
* metadata: {} // Meta-data dictionary if requested
* }
* ],
* prefix: '...', // prefix given in options (if given)
* marker: '...', // marker given in options (if given)
* maxResults: 5000, // maxResults given in options (if given)
* nextMarker: '...' // Next marker if not at end of list
* }
* ```
*/
Blob.prototype.listContainers = function listContainers(options) {
// Ensure options
options = options || {};
// Construct query string
var query = {
comp: 'list'
};
if (options.prefix) query.prefix = options.prefix;
if (options.marker) query.marker = options.marker;
if (options.maxResults) query.maxresults = options.maxResults;
if (options.metadata) query.include = 'metadata';
return this.request('GET', '/', query, {}).then(function(response) {
if(response.statusCode !== 200) {
throw new Error('listContainers: Unexpected statusCode: ' + response.statusCode);
}
return xml.blobParseListContainers(response);
});
};
/**
* Get all user-defined metadata and system properties for the container with the given name.
*