This repository has been archived by the owner on Apr 7, 2020. It is now read-only.
/
window_pool.js
93 lines (80 loc) · 2.11 KB
/
window_pool.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
const queue = require('async/queue');
const { renderWorker, createWindow } = require('./renderer');
/**
* Queues renderjobs in a pool of BrowserWindow's
*/
module.exports = class WindowPool {
/**
* Create Electron window pool
*/
constructor() {
const concurrency = parseInt(process.env.CONCURRENCY, 10) || 1;
this.windowPool = {};
this.createPool(concurrency);
this.queue = queue(this.queueWorker.bind(this), concurrency);
}
/**
* Push a render task to queue
*/
enqueue(...args) {
this.queue.push(...args);
}
/**
* Fetch stats for debugging
*/
stats() {
return {
concurrency: this.queue.concurrency,
queue_length: this.queue.length(),
workersList: this.queue.workersList().map(({ data }) => ({
url: data.url,
options: data.options,
type: data.type
}))
};
}
/**
* Get a free BrowserWindow from pool
*/
getAvailableWindow() {
const availableId = Object.keys(this.windowPool).filter(
id => this.windowPool[id].busy === false
)[0];
if (!availableId) return null;
return this.windowPool[availableId];
}
/**
* Create a pool of BrowserWindow's
*/
createPool(concurrency) {
let n = concurrency;
const setBusy = (id, value) => {
this.windowPool[id].busy = value;
};
while (n > 0) {
n -= 1;
const window = createWindow();
// Basic locking
window.busy = false;
window.unlock = setBusy.bind(this, window.id, false);
window.lock = setBusy.bind(this, window.id, true);
// Add to pool
this.windowPool[window.id] = window;
}
}
/**
* Wrap queue worker with locking mechanism
*/
queueWorker(task, done) {
const window = this.getAvailableWindow();
if (!window) throw new Error('Pool is empty while queue is not saturated!?');
window.lock();
renderWorker(window, task, (...args) => {
// Load blank state after render
if (process.env.NODE_ENV !== 'development') window.loadURL('about:blank');
window.webContents.clearHistory();
window.unlock();
done(...args);
});
}
};