-
Notifications
You must be signed in to change notification settings - Fork 2
/
ratings.js
258 lines (235 loc) · 8.46 KB
/
ratings.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
// Copyright Istio Authors
//
// 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.
var http = require('http')
var dispatcher = require('httpdispatcher')
var port = parseInt(process.argv[2])
var userAddedRatings = [] // used to demonstrate POST functionality
var unavailable = false
var healthy = true
if (process.env.SERVICE_VERSION === 'v-unavailable') {
// make the service unavailable once in 60 seconds
setInterval(function () {
unavailable = !unavailable
}, 60000);
}
if (process.env.SERVICE_VERSION === 'v-unhealthy') {
// make the service unavailable once in 15 minutes for 15 minutes.
// 15 minutes is chosen since the Kubernetes's exponential back-off is reset after 10 minutes
// of successful execution
// see https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/#restart-policy
// Kiali shows the last 10 or 30 minutes, so to show the error rate of 50%,
// it will be required to run the service for 30 minutes, 15 minutes of each state (healthy/unhealthy)
setInterval(function () {
healthy = !healthy
unavailable = !unavailable
}, 900000);
}
/**
* We default to using mongodb, if DB_TYPE is not set to mysql.
*/
if (process.env.SERVICE_VERSION === 'v2') {
if (process.env.DB_TYPE === 'mysql') {
var mysql = require('mysql')
var hostName = process.env.MYSQL_DB_HOST
var portNumber = process.env.MYSQL_DB_PORT
var username = process.env.MYSQL_DB_USER
var password = process.env.MYSQL_DB_PASSWORD
} else {
var MongoClient = require('mongodb').MongoClient
var url = process.env.MONGO_DB_URL
}
}
dispatcher.onPost(/^\/ratings\/[0-9]*/, function (req, res) {
var productIdStr = req.url.split('/').pop()
var productId = parseInt(productIdStr)
var ratings = {}
if (Number.isNaN(productId)) {
res.writeHead(400, {'Content-type': 'application/json'})
res.end(JSON.stringify({error: 'please provide numeric product ID'}))
return
}
try {
ratings = JSON.parse(req.body)
} catch (error) {
res.writeHead(400, {'Content-type': 'application/json'})
res.end(JSON.stringify({error: 'please provide valid ratings JSON'}))
return
}
if (process.env.SERVICE_VERSION === 'v2') { // the version that is backed by a database
res.writeHead(501, {'Content-type': 'application/json'})
res.end(JSON.stringify({error: 'Post not implemented for database backed ratings'}))
} else { // the version that holds ratings in-memory
res.writeHead(200, {'Content-type': 'application/json'})
res.end(JSON.stringify(putLocalReviews(productId, ratings)))
}
})
dispatcher.onGet(/^\/ratings\/[0-9]*/, function (req, res) {
var productIdStr = req.url.split('/').pop()
var productId = parseInt(productIdStr)
if (Number.isNaN(productId)) {
res.writeHead(400, {'Content-type': 'application/json'})
res.end(JSON.stringify({error: 'please provide numeric product ID'}))
} else if (process.env.SERVICE_VERSION === 'v2') {
var firstRating = 0
var secondRating = 0
if (process.env.DB_TYPE === 'mysql') {
var connection = mysql.createConnection({
host: hostName,
port: portNumber,
user: username,
password: password,
database: 'test'
})
connection.connect(function(err) {
if (err) {
res.end(JSON.stringify({error: 'could not connect to ratings database'}))
console.log(err)
return
}
connection.query('SELECT Rating FROM ratings', function (err, results, fields) {
if (err) {
res.writeHead(500, {'Content-type': 'application/json'})
res.end(JSON.stringify({error: 'could not perform select'}))
console.log(err)
} else {
if (results[0]) {
firstRating = results[0].Rating
}
if (results[1]) {
secondRating = results[1].Rating
}
var result = {
id: productId,
ratings: {
Reviewer1: firstRating,
Reviewer2: secondRating
}
}
res.writeHead(200, {'Content-type': 'application/json'})
res.end(JSON.stringify(result))
}
})
// close the connection
connection.end()
})
} else {
MongoClient.connect(url, function (err, db) {
if (err) {
res.writeHead(500, {'Content-type': 'application/json'})
res.end(JSON.stringify({error: 'could not connect to ratings database'}))
} else {
db.collection('ratings').find({}).toArray(function (err, data) {
if (err) {
res.writeHead(500, {'Content-type': 'application/json'})
res.end(JSON.stringify({error: 'could not load ratings from database'}))
} else {
firstRating = data[0].rating
secondRating = data[1].rating
var result = {
id: productId,
ratings: {
Reviewer1: firstRating,
Reviewer2: secondRating
}
}
res.writeHead(200, {'Content-type': 'application/json'})
res.end(JSON.stringify(result))
}
// close DB once done:
db.close()
})
}
})
}
} else {
if (process.env.SERVICE_VERSION === 'v-faulty') {
// in half of the cases return error,
// in another half proceed as usual
var random = Math.random(); // returns [0,1]
if (random <= 0.5) {
getLocalReviewsServiceUnavailable(res)
} else {
getLocalReviewsSuccessful(res, productId)
}
}
else if (process.env.SERVICE_VERSION === 'v-delayed') {
// in half of the cases delay for 7 seconds,
// in another half proceed as usual
var random = Math.random(); // returns [0,1]
if (random <= 0.5) {
setTimeout(getLocalReviewsSuccessful, 7000, res, productId)
} else {
getLocalReviewsSuccessful(res, productId)
}
}
else if (process.env.SERVICE_VERSION === 'v-unavailable' || process.env.SERVICE_VERSION === 'v-unhealthy') {
if (unavailable) {
getLocalReviewsServiceUnavailable(res)
} else {
getLocalReviewsSuccessful(res, productId)
}
}
else {
getLocalReviewsSuccessful(res, productId)
}
}
})
dispatcher.onGet('/health', function (req, res) {
if (healthy) {
res.writeHead(200, {'Content-type': 'application/json'})
res.end(JSON.stringify({status: 'Ratings is healthy'}))
} else {
res.writeHead(500, {'Content-type': 'application/json'})
res.end(JSON.stringify({status: 'Ratings is not healthy'}))
}
})
function putLocalReviews (productId, ratings) {
userAddedRatings[productId] = {
id: productId,
ratings: ratings
}
return getLocalReviews(productId)
}
function getLocalReviewsSuccessful(res, productId) {
res.writeHead(200, {'Content-type': 'application/json'})
res.end(JSON.stringify(getLocalReviews(productId)))
}
function getLocalReviewsServiceUnavailable(res) {
res.writeHead(503, {'Content-type': 'application/json'})
res.end(JSON.stringify({error: 'Service unavailable'}))
}
function getLocalReviews (productId) {
if (typeof userAddedRatings[productId] !== 'undefined') {
return userAddedRatings[productId]
}
return {
id: productId,
ratings: {
'Reviewer1': 5,
'Reviewer2': 4
}
}
}
function handleRequest (request, response) {
try {
console.log(request.method + ' ' + request.url)
dispatcher.dispatch(request, response)
} catch (err) {
console.log(err)
}
}
var server = http.createServer(handleRequest)
server.listen(port, function () {
console.log('Server listening on: http://0.0.0.0:%s', port)
})