-
Notifications
You must be signed in to change notification settings - Fork 107
Expand file tree
/
Copy pathrender-coordinator.js
More file actions
100 lines (89 loc) · 2.34 KB
/
Copy pathrender-coordinator.js
File metadata and controls
100 lines (89 loc) · 2.34 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
const {
OperationTimeoutError,
withTimeout
} = require("./operation-timeout");
class RenderCoordinator {
constructor({
renderJobTimeout,
ensureBrowser,
closeBrowser,
onSuccess,
logger = console
}) {
this.renderJobTimeout = renderJobTimeout;
this.ensureBrowser = ensureBrowser;
this.closeBrowser = closeBrowser;
this.onSuccess = onSuccess;
this.logger = logger;
this.queue = Promise.resolve();
this.pendingCount = 0;
this.renderInProgress = false;
this.renderStartedAt = null;
}
hasWork() {
return this.pendingCount > 0;
}
getState(now = Date.now()) {
return {
renderInProgress: this.renderInProgress,
renderInProgressFor: this.renderStartedAt
? now - this.renderStartedAt
: null
};
}
run(label, work, options = {}) {
if (options.skipIfBusy && this.hasWork()) {
this.logger.log(`Render already queued or in progress, skipping ${label}`);
return Promise.resolve({
status: "skipped",
reason: "render_in_progress"
});
}
this.pendingCount++;
const queuedWork = this.queue
.catch(() => {})
.then(() => this.execute(label, work, options))
.finally(() => {
this.pendingCount--;
});
this.queue = queuedWork.catch(() => {});
return queuedWork;
}
async execute(label, work, options) {
this.renderInProgress = true;
this.renderStartedAt = Date.now();
let timedOut = false;
try {
const browser = await this.ensureBrowser({
resetBrowserCache: options.resetBrowserCache === true
});
await withTimeout(
work(browser),
this.renderJobTimeout,
label,
() => {
timedOut = true;
}
);
if (options.updateLastSuccessfulRender !== false && this.onSuccess) {
this.onSuccess();
}
return { status: "ok" };
} catch (err) {
this.logger.error(`${label} failed but server stays alive:`, err);
if (timedOut || err instanceof OperationTimeoutError) {
await this.closeBrowser(`${label} timeout`);
}
return {
status: "failed",
error: err && err.message ? err.message : String(err)
};
} finally {
this.renderInProgress = false;
this.renderStartedAt = null;
}
}
}
module.exports = {
RenderCoordinator
};