This repository has been archived by the owner on Mar 19, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
400 lines (334 loc) · 9.58 KB
/
main.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
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
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
const os = require("os")
const nanoid = require("nanoid")
const puppeteer = require("puppeteer")
const amqplib = require("amqplib/callback_api")
const { EventEmitter } = require("emitting")
const FormData = require("form-data")
const fetch = require("node-fetch").default
const De = require("debug")
const debug = De("worker")
const RABBIT_HOST = process.env.RABBIT_HOST || "amqp://localhost:5672" // tls 5671
const RENDER_HOST = process.env.RENDER_HOST || "https://howtocards.io"
const UPLOADER_HOST = process.env.UPLOADER_HOST || "http://localhost:4000"
const QUEUE_NAME = process.env.QUEUE_NAME || "howtocards:render"
const CALLBACK_HOST = process.env.CALLBACK_HOST || "http://localhost:9002"
const POOL_SIZE = process.env.POOL_SIZE
? parseInt(process.env.POOL_SIZE, 10)
: os.cpus().length / 2
const VIEWPORT = { deviceScaleFactor: 2, width: 1920, height: 1080 }
main().catch((error) => {
console.error(error)
process.exit(-1)
})
async function main() {
console.log("worker: iron heating")
debug("worker starting")
const browser = await puppeteer.launch({
args: ["--disable-dev-shm-usage", "--no-sandbox"],
})
debug("browser started")
const pool = new Pool(POOL_SIZE)
debug("pool created")
await pool.init(async () => {
const page = await browser.newPage()
await page.setViewport(VIEWPORT)
await page.goto(`${RENDER_HOST}`, { waitUntil: "networkidle0" })
return page
})
debug("pool initialized")
let timeValues = []
try {
const connection = await connect(RABBIT_HOST)
debug("rabbit connected")
const channel = await createChannel(connection)
debug("rabbit channel created")
console.log("worker: ready to accept tasks")
let currentInQueue = 0
channel.consume(
QUEUE_NAME,
async (message) => {
try {
const task = JSON.parse(message.content.toString())
debug("handled event", task)
const type = getType(task)
if (!type) {
debug("received unknown message type", task)
channel.ack(message)
return
}
currentInQueue++
const id = nanoid(5)
const timeStart = Date.now()
// console.group(`${id} start ${timeStart}`)
const result = await pool.process((page) =>
render({
page,
id,
...createParams(type, task),
injectCSS: "header { opacity: 0 }",
}),
)
const screenshotPath = await upload(result.image)
if (task.callback) {
await callApiBack(task.callback, screenshotPath, result.html)
}
const timeEnd = Date.now()
channel.ack(message)
const timeDiff = timeEnd - timeStart
console.log(
`worker:render ${type}:${id} — ${screenshotPath} in ${timeDiff}ms`,
`(med ${getMedian(timeDiff)}ms)`,
`(avg ${Math.floor(getAverage(timeDiff))}ms)`,
`(queue length ${currentInQueue})`,
)
currentInQueue--
} catch (error) {
console.error("failed to render", error, message.content)
channel.ack(message)
debug("message acked")
}
},
{ noAck: false },
)
process.on("SIGINT", async () => {
debug("caught interrupt signal")
channel.close()
debug("rabbit channel closed")
connection.close()
debug("rabbit connection closed")
await browser.close()
debug("browser killed")
process.exit()
})
} catch (error) {
console.error(error)
debug("FAILED to init connection to rabbit")
await browser.close()
}
function getMedian(diff) {
timeValues.push(diff)
if (timeValues.length < 2) {
return diff
}
timeValues.sort((a, b) => a - b)
const half = Math.floor(timeValues.length / 2)
if (timeValues.length % 2) {
return timeValues[half]
}
return timeValues[half - 1] + timeValues[half] / 2.0
}
function getAverage(diff) {
timeValues.push(diff)
return timeValues.reduce((a, b) => a + b) / timeValues.length
}
}
function connect(url) {
return new Promise((resolve, reject) => {
amqplib.connect(url, (err, conn) => {
if (err) return reject(err)
return resolve(conn)
})
})
}
function createChannel(connection) {
return new Promise((resolve, reject) => {
connection.createChannel((err, channel) => {
if (err) return reject(err)
return resolve(channel)
})
})
}
/**
* Render page and create screenshot
* Optionally snapshot html for specified selector
* @param {object} param0
* @param {object} param0.page
* @param {string} param0.id
* @param {string} param0.url
* @param {object} param0.screenshot
* @param {string} param0.screenshot.selector
* @param {string | null} param0.injectCSS
* @param {object} param0.snapshot
* @param {string | null} param0.snapshot.selector
* @returns {Promise<{ image: Buffer, html?: string }>}
*/
async function render({ page, id, url, screenshot, snapshot, injectCSS }) {
const debug = De(`worker:${id}`)
const timeLabel = `worker: screenshot ${id}:${url}`
// debug(timeLabel)
console.log(timeLabel)
console.time(timeLabel)
await page.goto(`${RENDER_HOST}${url}`, { waitUntil: "networkidle0" })
debug(`opened ${RENDER_HOST}${url}`)
if (injectCSS) {
await page.addStyleTag({ content: injectCSS })
debug("CSS injected")
}
const el = await page.$(screenshot.selector)
debug("element found")
const { x, y, width } = await el.boundingBox()
const height = Math.round((width / 16) * 9)
debug("bounding box", { x, y, width, height })
const image = await page.screenshot({
omitBackground: true,
type: "png",
clip: { x, y, width, height },
})
debug("screenshot taken")
console.timeEnd(timeLabel)
if (snapshot) {
const selector = snapshot.selector || screenshot.selector
const html = await page.$eval(selector, (node) => node.outerHTML)
debug("snapshot taken")
// debug("snapshot html", html.slice(0, 90))
return { image, html }
}
return { image }
}
async function upload(image) {
debug("image uploading started")
const form = new FormData()
form.append("image", image, { filename: "preview.png" })
const response = await fetch(`${UPLOADER_HOST}/upload`, {
method: "POST",
body: form,
}).then((r) => r.json())
debug("image uploaded")
if (response.status === "ok") {
return response.files[0].path
}
debug("image upload status is not ok")
throw new Error(response.error)
}
/**
* @param {string} callback
* @param {string} screenshotPath
* @param {string | void} snapshotContent
*/
async function callApiBack(callback, screenshotPath, snapshotContent) {
debug(
"calling internal api",
callback,
screenshotPath,
debugSnapshot(snapshotContent),
)
try {
const body = JSON.stringify({
screenshot: screenshotPath,
snapshot: snapshotContent,
})
const response = await fetch(`${CALLBACK_HOST}${callback}`, {
method: "POST",
body: body,
headers: {
"Content-Type": "application/json",
accept: "application/json",
},
}).then((r) => r.json())
debug(
"callback successfully called",
callback,
screenshotPath,
debugSnapshot(snapshotContent),
response,
)
if (response.status === "ok") {
return true
}
return false
} catch (error) {
console.error("failed to call internal api", error)
return false
}
}
function debugSnapshot(snapshot) {
return snapshot ? snapshot.slice(0, 20) : ""
}
const debPool = De("pool")
class Pool {
constructor(count) {
this.events = new EventEmitter()
this.count = count
this.pages = []
this.queue = []
this.events.on("finished", this.checkNext.bind(this))
}
init(creator) {
debPool("initialize", this.count)
return Promise.all(Array.from({ length: this.count }, creator)).then(
(pages) => {
this.pages = pages
},
)
}
checkNext() {
if (this.queue.length) {
this.runNext()
}
}
runNext() {
this.run(this.queue.shift())
}
async run(task) {
const page = this.pages.pop()
let result = null
try {
result = await task.fn(page)
} catch (error) {
console.error("failed to execute task", task.id, error)
} finally {
this.pages.push(page)
this.events.emit(`resolved:${task.id}`, result)
this.events.emit("finished", null)
}
}
/**
* @template T
* @param {(page) => Promise<T>} fn
* @returns {Promise<T>}
*/
process(fn) {
const id = nanoid(4)
const deb = De(`pool:process:${id}`)
this.queue.push({ id, fn })
deb(`enqueue:${id}`)
if (this.queue.length <= this.pages.length) {
this.runNext()
}
this.events.once(`resolved:${id}`, () => deb(`resolved:${id}`))
return this.events.take(`resolved:${id}`)
}
}
function getType(task) {
if (typeof task.user === "string" && typeof task.callback === "string") {
return "user"
}
if (typeof task.card === "string" && typeof task.callback === "string") {
return "card"
}
return null
}
function createParams(type, payload) {
switch (type) {
case "user":
return {
url: `/@${payload.user}`,
screenshot: { selector: "header + div > div" },
snapshot: null,
}
case "card":
return {
url: `/open/${payload.card}`,
screenshot: { selector: "article" },
snapshot: { selector: "article [data-slate-editor]" },
}
}
}
function checkEvent(task) {
switch (getType(task)) {
case "card":
case "user":
return true
}
return false
}