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
|
#!/usr/bin/node
/* jshint esnext:true */
/* download data from AWS and push into process queues */
"use strict";
const amqp = require("amqplib"),
Promise = require("bluebird"),
winston = require("winston"),
loggly = require("winston-loggly-bulk"),
request = require("request-promise"),
sleep = require("sleep-promise"),
jsonapi = require("../orm/jsonapi"),
moment = require("moment"),
AdmZip = require("adm-zip");
const RABBITMQ_URI = process.env.RABBITMQ_URI || "amqp://localhost",
QUEUE = process.env.QUEUE || "sample",
PROCESS_QUEUE = process.env.PROCESS_QUEUE || "process",
PROCESS_BRAWL_QUEUE = process.env.PROCESS_BRAWL_QUEUE || "process_brawl",
LOGGLY_TOKEN = process.env.LOGGLY_TOKEN,
SAMPLERS = parseInt(process.env.SAMPLERS) || 5;
const logger = new (winston.Logger)({
transports: [
new (winston.transports.Console)({
timestamp: true,
colorize: true
})
]
});
// loggly integration
if (LOGGLY_TOKEN)
logger.add(winston.transports.Loggly, {
inputToken: LOGGLY_TOKEN,
subdomain: "kvahuja",
tags: ["backend", "sampler", QUEUE],
json: true
});
(async () => {
let rabbit, ch;
while (true) {
try {
rabbit = await amqp.connect(RABBITMQ_URI);
ch = await rabbit.createChannel();
await ch.assertQueue(QUEUE, {durable: true});
break;
} catch (err) {
logger.error("error connecting", err);
await sleep(5000);
}
}
await ch.prefetch(SAMPLERS);
ch.consume(QUEUE, async (msg) => {
const payload = JSON.parse(msg.content.toString());
if (msg.properties.type == "sample")
await getSample(payload);
if (msg.properties.type == "telemetry") {
try {
await getTelemetry(payload, msg.properties.headers.match_api_id);
} catch (err) {
logger.error("Telemetry download error", err);
ch.nack(msg, false, true); // TODO how to handle this?
return;
}
}
logger.info("done", payload);
ch.ack(msg);
}, { noAck: false });
// download a sample ZIP and send to processor
async function getSample(url) {
logger.info("downloading sample", url);
const zipdata = await request({
uri: url,
encoding: null
}),
zip = new AdmZip(zipdata);
await Promise.map(zip.getEntries(), async (entry) => {
if (entry.isDirectory) return;
const match = jsonapi.parse(JSON.parse(entry.getData().toString("utf8")));
await sendMatchToProcessor(match);
});
logger.info("sample processed", url);
}
// send to seperated queues or just to `process`
async function sendMatchToProcessor(match) {
if (["casual", "ranked"].indexOf(match.attributes.gameMode) != -1)
await ch.sendToQueue(PROCESS_QUEUE, new Buffer(JSON.stringify(match)),
{ persistent: true, type: "match" })
else
await ch.sendToQueue(PROCESS_BRAWL_QUEUE, new Buffer(JSON.stringify(match)),
{ persistent: true, type: "match" })
}
// download Telemetry, filter irrelevant events, forward the rest to `process`
async function getTelemetry(url, match_api_id) {
logger.info("downloading Telemetry",
{ url: url, match_api_id: match_api_id });
// download
const telemetry = await loggedRequest(url),
spawn = telemetry.filter((ev) => ev.type == "PlayerFirstSpawn")[0],
spawn_time = moment(spawn.time);
const forward_profiler = logger.startTimer();
// return telemetry { m_a_id, data, start, end } in an interval
const gamePhase = (start, end) => { return {
match_api_id: match_api_id,
data: telemetry.slice(
// assumes Telemetry is ordered by timestamp.
telemetry.findIndex((ev) =>
moment(ev.time).isSameOrAfter(
spawn_time.clone().add(start, "seconds")
) ),
telemetry.findIndex((ev) =>
moment(ev.time).isSameOrAfter(
spawn_time.clone().add(end, "seconds")
) ) // slice does not include end
),
start: start,
match_start: spawn.time,
end: end
} };
// split into phases
const phases = [
// genious idea to put bans into Telemetry.
gamePhase(-5 * 60, 0), // draft
gamePhase(0, 90 * 60), // whole
gamePhase(0, 1 * 60), // start
gamePhase(0, 4 * 60), // early game
gamePhase(0, 8 * 60), // miner full
gamePhase(0, 12 * 60), // miner full
gamePhase(0, 15 * 60), // Kraken spawn
gamePhase(0, 20 * 60), // late mid game
gamePhase(0, 25 * 60), // late game
gamePhase(0, 30 * 60) // late game
];
await Promise.each(phases, async (phase) => {
if (phase.data.length > 0) {
const notify = "match." + match_api_id;
await ch.publish("amq.topic", notify, new Buffer("phase_pending"));
await ch.sendToQueue(PROCESS_QUEUE, new Buffer(
JSON.stringify(phase)), {
persistent: true, type: "telemetry",
headers: { notify }
})
}
});
forward_profiler.done("Telemetry splitting");
logger.info("Telemetry done",
{ url: url, match_api_id: match_api_id });
}
async function loggedRequest(url) {
let response;
try {
const opts = {
json: true,
gzip: true,
time: true,
forever: true,
strictSSL: true,
resolveWithFullResponse: true
};
logger.info("AWS request", { uri: url, });
response = await request(url, opts);
return response.body;
} catch (err) {
logger.warn("AWS error", {
uri: url,
error: err.response.body
});
throw err;
} finally {
if (response != undefined) // else non-requests error
logger.info("AWS response", {
status: response.statusCode,
connection_start: response.timings.connect,
connection_end: response.timings.end
});
}
}
})();
|