forked from odota/core
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparser.js
More file actions
382 lines (377 loc) · 11.8 KB
/
parser.js
File metadata and controls
382 lines (377 loc) · 11.8 KB
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
var express = require('express');
var utility = require('./utility');
var bodyParser = require('body-parser');
var app = express();
var capacity = require('os').cpus().length;
var startedAt = new Date();
var os = require('os');
var config = require('./config');
var request = require('request');
var cp = require('child_process');
var ndjson = require('ndjson');
var spawn = cp.spawn;
var progress = require('request-progress');
var processAllPlayers = require('./processors/processAllPlayers');
var processTeamfights = require('./processors/processTeamfights');
var processReduce = require('./processors/processReduce');
var processUploadProps = require('./processors/processUploadProps');
var processParsedData = require('./processors/processParsedData');
var processMetadata = require('./processors/processMetadata');
var processExpand = require('./processors/processExpand');
var stream = require('stream');
var queue = require('./queue');
var pQueue = queue.getQueue('parse');
var getReplayUrl = require('./getReplayUrl');
var db = require('./db');
var redis = require('./redis');
var moment = require('moment');
var queries = require('./queries');
var insertMatch = queries.insertMatch;
var async = require('async');
var compute = require('./compute');
var renderMatch = compute.renderMatch;
var computeMatchData = compute.computeMatchData;
var computePlayerMatchData = compute.computePlayerMatchData;
var benchmarkMatch = require('./benchmarkMatch');
app.use(bodyParser.json());
app.get('/', function(req, res)
{
res.json(
{
capacity: capacity,
version: utility.getParseSchema().version,
started_at: startedAt
});
});
app.get('/redis/:key', function(req, res, cb)
{
redis.get(new Buffer('upload_blob:' + req.params.key), function(err, result)
{
if (err)
{
return cb(err);
}
res.send(result);
});
});
app.listen(config.PARSER_PORT);
pQueue.process(1, function(job, cb)
{
console.log("parse job: %s", job.jobId);
var match = job.data.payload;
async.series(
{
"getDataSource": match.replay_blob_key ? function(cb)
{
match.url = "http://localhost:" + config.PARSER_PORT + "/redis/" + match.replay_blob_key;
cb();
} : function(cb)
{
getReplayUrl(db, redis, match, cb);
},
"runParse": function(cb)
{
runParse(match, job, function(err, parsed_data)
{
if (err)
{
return cb(err);
}
//extend match object with parsed data, keep existing data if key conflict
//match.players was deleted earlier during insertion of api data
for (var key in parsed_data)
{
match[key] = match[key] || parsed_data[key];
}
match.parse_status = 2;
cb(err);
});
},
"insertMatch": match.replay_blob_key ? function(cb)
{
//save uploaded replay parse in redis
match.match_id = match.upload.match_id;
match.game_mode = match.upload.game_mode;
match.radiant_win = match.upload.radiant_win;
match.duration = match.upload.duration;
match.players.forEach(function(p, i)
{
utility.mergeObjects(p, match.upload.player_map[p.player_slot]);
p.gold_per_min = ~~(p.gold / match.duration * 60);
p.xp_per_min = ~~(p.xp / match.duration * 60);
p.duration = match.duration;
computePlayerMatchData(p);
});
computeMatchData(match);
renderMatch(match);
benchmarkMatch(redis, match, function(err)
{
if (err)
{
return cb(err);
}
redis.setex('match:' + match.replay_blob_key, 60 * 60 * 24 * 7, JSON.stringify(match), cb);
});
} : function(cb)
{
//fs.writeFileSync('output.json', JSON.stringify(match));
insertMatch(db, redis, match,
{
type: "parsed"
}, cb);
},
}, function(err)
{
if (err)
{
console.log(err, err.stack);
if (err !== "404")
{
setTimeout(function()
{
console.error('encountered exception, restarting');
process.exit(1);
}, 1000);
}
return cb(err);
}
var hostname = os.hostname();
redis.zadd("parser:" + hostname, moment().format('X'), match.match_id);
if (match.start_time)
{
redis.lpush("parse_delay", new Date() - (match.start_time + match.duration) * 1000);
redis.ltrim("parse_delay", 0, 10000);
}
return cb(err, match.match_id);
});
});
function runParse(match, job, cb)
{
var timeout = setTimeout(function()
{
exit('timeout');
}, 300000);
var url = match.url;
var inStream;
var parseStream;
var bz;
var parser;
var entries = [];
createInputStream();
function createInputStream()
{
inStream = progress(request(
{
url: url,
encoding: null,
timeout: 30000
})).on('progress', function(state)
{
console.log(JSON.stringify(
{
url: url,
state: state
}));
if (job)
{
job.progress(state.percentage * 100);
}
}).on('response', function(response)
{
if (response.statusCode === 200)
{
forwardInput(inStream);
}
else
{
exit(response.statusCode.toString());
}
}).on('error', exit);
}
function forwardInput(inStream)
{
parser = spawn("java", ["-jar",
"-Xmx64m",
"java_parser/target/stats-0.1.0.jar"
],
{
//we may want to ignore stderr so the child doesn't stay open
stdio: ['pipe', 'pipe', 'pipe'],
encoding: 'utf8'
});
parser.on('close', (code) =>
{
if (code)
{
exit(code);
}
});
parseStream = ndjson.parse();
if (url && url.slice(-3) === "bz2")
{
bz = spawn("bunzip2");
}
else
{
var str = stream.PassThrough();
bz = {
stdin: str,
stdout: str
};
}
inStream.pipe(bz.stdin);
bz.stdout.pipe(parser.stdin);
bz.stdin.on('error', exit);
bz.stdout.on('error', exit);
parser.stdout.pipe(parseStream);
parser.stdin.on('error', exit);
parser.stdout.on('error', exit);
parser.stderr.on('data', function printStdErr(data)
{
console.log(data.toString());
});
parseStream.on('data', function handleStream(e)
{
if (e.type === 'epilogue')
{
incomplete = false;
}
entries.push(e);
});
parseStream.on('end', exit);
parseStream.on('error', exit);
}
var incomplete = "incomplete";
var exited = false;
function exit(err)
{
if (exited)
{
return;
}
exited = true;
err = err || incomplete;
clearTimeout(timeout);
if (err)
{
return cb(err);
}
else
{
try
{
var message = "time spent on post-processing match ";
console.time(message);
var meta = processMetadata(entries);
var res = processExpand(entries, meta, populate);
var parsed_data = processParsedData(res.parsed_data, meta, populate);
var teamfights = processTeamfights(res.tf_data, meta, populate);
var upload = processUploadProps(res.uploadProps, meta, populate);
var ap = processAllPlayers(res.int_data);
parsed_data.teamfights = teamfights;
parsed_data.radiant_gold_adv = ap.radiant_gold_adv;
parsed_data.radiant_xp_adv = ap.radiant_xp_adv;
parsed_data.upload = upload;
//processMultiKillStreaks();
//processReduce(res.expanded);
console.timeEnd(message);
return cb(err, parsed_data);
}
catch (e)
{
return cb(e);
}
}
}
}
function populate(e, container)
{
switch (e.type)
{
case 'interval':
break;
case 'player_slot':
container.players[e.key].player_slot = e.value;
break;
case 'chat':
container.chat.push(JSON.parse(JSON.stringify(e)));
break;
case 'CHAT_MESSAGE_TOWER_KILL':
case 'CHAT_MESSAGE_TOWER_DENY':
case 'CHAT_MESSAGE_BARRACKS_KILL':
case 'CHAT_MESSAGE_FIRSTBLOOD':
case 'CHAT_MESSAGE_AEGIS':
case 'CHAT_MESSAGE_AEGIS_STOLEN':
case 'CHAT_MESSAGE_DENIED_AEGIS':
case 'CHAT_MESSAGE_ROSHAN_KILL':
container.objectives.push(JSON.parse(JSON.stringify(e)));
break;
default:
if (!container.players[e.slot])
{
//couldn't associate with a player, probably attributed to a creep/tower/necro unit
//console.log(e);
return;
}
var t = container.players[e.slot][e.type];
if (typeof t === "undefined")
{
//container.players[0] doesn't have a type for this event
console.log("no field in parsed_data.players for %s", e.type);
return;
}
else if (e.posData)
{
//fill 2d hash with x,y values
var x = e.key[0];
var y = e.key[1];
if (!t[x])
{
t[x] = {};
}
if (!t[x][y])
{
t[x][y] = 0;
}
t[x][y] += 1;
}
else if (e.max)
{
//check if value is greater than what was stored
if (e.value > t.value)
{
container.players[e.slot][e.type] = e;
}
}
else if (t.constructor === Array)
{
//determine whether we want the value only (interval) or the time and key (log)
//either way this creates a new value so e can be mutated later
var arrEntry = (e.interval) ? e.value :
{
time: e.time,
key: e.key
};
t.push(arrEntry);
}
else if (typeof t === "object")
{
//add it to hash of counts
e.value = e.value || 1;
t[e.key] ? t[e.key] += e.value : t[e.key] = e.value;
}
else if (typeof t === "string")
{
//string, used for steam id
container.players[e.slot][e.type] = e.key;
}
else
{
//we must use the full reference since this is a primitive type
//use the value most of the time, but key when stuns since value only holds Integers in Java
//replace the value directly
container.players[e.slot][e.type] = e.value || Number(e.key);
}
break;
}
}