forked from jasonpolites/gcf-recipes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
171 lines (139 loc) · 3.95 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
var gcloud = require('gcloud');
// Promise-compartible request module.
var req = require('request-promise');
// Use our logging utilty just as a convenience to skip
// console logs during tests
var logger = require('./logger');
// Use a simple shared key to assert calling authority.
var SHARED_KEY = 'some_random_high_entropy_string';
// HTTP Binding for worker function
var worker = function(req, res) {
_httpBinder(req, res, _worker);
};
// HTTP Binding for master function
var master = function(req, res) {
_httpBinder(req, res, _master);
};
/**
* Simple binder function to cater for new HTTP function signatures.
**/
var _httpBinder = function(req, res, fn) {
fn({
success: function(val) {
res.send(val);
},
failure: function(val) {
res.status(500).send(val);
}
}, req.body);
};
/**
* Counts the number of words in the line.
*/
var _worker = function(context, data) {
// Simple shared key to authorize the caller
var key = data['key'];
if (key !== SHARED_KEY) {
context.failure('Invalid key');
return;
}
// We expect the data argument to contain a 'line' property.
var batch = data['batch'];
// Batch should be an array.
var count = 0;
for (var i = 0; i < batch.length; i++) {
var line = batch[i];
// Just split to count words.
count += line.split(/\s+/).length;
}
logger.log(
'Total [' + count + '] words in batch of size [' + batch.length + ']');
context.success(count + '');
};
/**
* Reads the source file and fans out to the mappers.
*/
var _master = function(context, data) {
// Create a gcs client
var gcs = gcloud.storage({
// We're using the API from the same project as the Cloud Function.
projectId: process.env.GCP_PROJECT,
});
// Get the location (url) of the map function
var fnUrl = data['workerFunctionUrl'];
// Get the bucket containing our source file
var bucket = gcs.bucket(data['bucket']);
// Load the master file using the stream API
logger.log(
'Opening file [' + data['file'] + '] and creating a read stream...');
var inStream = bucket.file(data['file']).createReadStream()
.on('error', function(err) {
context.failure('Error reading file stream for ' + data['file'] +
': ' + err.message);
return;
});
// use the readLine module to read the stream line-by line
logger.log('Got stream, reading file line-by-line...');
var lineReader = require('readline').createInterface({
input: inStream
});
// Create an array to hold our request promises
var promises = [];
// We are going to batch the lines, we could use any number here
var batch = [];
var BATCH_SIZE = data['batch_size'] || 3; // 3 is defauld
lineReader.on('line', function(line) {
if (batch.length === BATCH_SIZE) {
// Send the batch.
promises.push(invoke(fnUrl, batch, SHARED_KEY));
batch = [];
}
batch.push(line.trim());
});
lineReader.on('close', function() {
// We might have trailing lines in an incomplete batch.
if (batch.length > 0) {
promises.push(invoke(fnUrl, batch, SHARED_KEY));
}
Promise.all(promises).then(
function(result) {
logger.log('All workers have returned');
// The result will be an array of return values from the workers.
var count = 0;
for (var i = 0; i < result.length; ++i) {
count += parseInt(result[i]);
}
context.success(
'The file ' + data['file'] + ' has ' + count + ' words');
},
function(err) {
logger.error(err);
context.failure(err);
});
});
};
/**
* Invokes another Cloud Function.
*/
var invoke = function(url, batch, key) {
// This will return a promise
return req({
method: 'POST',
uri: url,
body: {
batch: batch,
key: key,
},
headers: {
accept: '*/*',
},
json: true,
});
};
module.exports = {
worker: worker,
master: master,
invoke: invoke,
_worker: _worker,
_master: _master,
};