forked from GoogleCloudPlatform/LabelCat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathworker.js
152 lines (132 loc) · 4.65 KB
/
worker.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
// Copyright 2015, Google, Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
'use strict';
let agent;
// Activate Google Cloud Trace API
if (process.env.NODE_ENV === 'production') {
agent = require('@google/cloud-trace').start();
} else {
agent = {
startSpan() {},
endSpan() {}
};
}
// Express and http server
let express = require('express');
let http = require('http');
// IOC container
let container = require('./container');
// By exporting our Express app creation functionality we can more easily write
// tests.
exports.createServer = function () {
// Pull an initial set of dependencies from our IOC container
return container.resolve(function (logger, messages, errorHandler, Model) {
let hasSubscription = false;
let app = express();
// Log every request
app.use(logger.requestLogger);
// Google Cloud status check endpoint
app.get('/_ah/health', statusCheck);
app.get('/', statusCheck);
// Add the error logger after all middleware and routes so that
// it can log errors from the whole application. Any custom error
// handlers should go after this.
app.use(logger.errorLogger);
// Catch all handler, assumes error
app.use(errorHandler);
// Subscribe to Cloud Pub/Sub and recieve messages to process models.
// The subscription will continue to listen for messages until the server
// is killed.
messages.subscribe('train', 'shared-worker-process')
.then(function (subscription) {
// Mark worker's status as "good"
hasSubscription = true;
// Begin listening for messages
subscription.on('message', handleMessage);
subscription.on('error', handleError);
// Clean up
process.on('exit', function () {
subscription.removeListener('message', handleMessage);
subscription.removeListener('error', handleError);
});
})
.catch(function (err) {
logger.error('Failed to subscribe to messages.', err);
});
/**
* Respond to Google Cloud status check.
*/
function statusCheck(req, res) {
res.status(hasSubscription ? 200 : 500).end();
}
/**
* Handle an incoming message from PubSub.
*
* @private
*
* @param {object} message - PubSub message. See https://googlecloudplatform.github.io/gcloud-node/#/docs/pubsub/topic?method=subscription
*/
function handleMessage(message) {
let modelKey = message.data;
if (typeof modelKey !== 'string' && typeof modelKey !== 'number') {
logger.warn('Unknown request', message.data);
// Immediately ack the message
message.ack(function (err) {
if (err) {
logger.error(err);
}
});
} else {
logger.info('Training model: ', modelKey);
let opaque = agent.startSpan('train_model', { key: modelKey });
Model.trainOne(modelKey).catch(function (err) {
logger.error('Failed to train model: ', modelKey);
logger.error(err);
}).finally(function () {
agent.endSpan(opaque, { key: modelKey });
logger.info('Acking model: ', modelKey);
message.ack(function (err) {
if (err) {
logger.error(err);
} else {
logger.info('Acked model: ', modelKey);
}
});
});
}
}
/**
* Handle a subscription error.
*
* @private
*
* @param {object} err - Error object.
*/
function handleError(err) {
logger.error('Subscription error.', err);
}
return app;
});
};
// Only initialize http server if this file is actually being executed as the
// "main" entry point of the program. The other case is that this file is being
// pulled into one of our tests.
if (module === require.main) {
let config = container.get('config');
let app = exports.createServer();
let server = http.createServer(app).listen(process.env.NODE_ENV === 'production' ? config.port : 8082, config.host, function () {
console.log(`App listening at http://${server.address().address}:${server.address().port}`);
console.log('Press Ctrl+C to quit.');
});
}