-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.js
86 lines (71 loc) · 2.18 KB
/
client.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
var Emitter = require("events").EventEmitter;
var Util = require("util");
var Async = require("async");
var Knox = require("knox");
var Utils = require("./utils");
/**
* Useful for overriding `knox` client methods.
*/
var noop = function(client, name) {
return function(source, destination, callback) {
process.nextTick(function() {
client.emit('progress', name, source, destination);
callback(null, {
resume: function() {}
});
});
}
};
/**
* Returns a rate-limited Client for `bucket`. If `dryRun` is passed,
* return a non-client.
*/
var Client = module.exports = function(options) {
var self = this;
self.s3 = Knox.createClient({
bucket: options.bucket,
key: options.key,
secret: options.secret,
});
Emitter.call(self);
if (options.dryRun) {
self.put = noop(self, 'put');
self.copy = noop(self, 'copy');
return;
}
// Rate limit `put` to avoid too many concurrent uploads.
var put = self.put;
var putQueue = Async.queue(function(task, callback) {
var done = function(err, res) {
callback();
task.callback(err, res)
};
put.apply(self, [task.source, task.destination, done]);
}, options.concurrency || 10);
self.put = function(source, destination, callback) {
putQueue.push({
source: source,
destination: destination,
callback: callback
});
};
};
Util.inherits(Client, Emitter);
Client.prototype.copy = function(source, destination, callback) {
var self = this;
self.s3.copyFile(source, destination, Utils.getHeaders(source), function(err, res) {
if (err) return callback(err);
self.emit('progress', 'copy', source, destination);
res.resume();
callback(null, res);
});
}
Client.prototype.put = function(path, destination, callback) {
var self = this;
self.s3.putFile(path, destination, Utils.getHeaders(path), function(err, res) {
if (err) return callback(err);
self.emit('progress', 'put', path, destination);
res.resume();
callback(null, res);
});
}