-
Notifications
You must be signed in to change notification settings - Fork 299
/
Worker.ts
144 lines (116 loc) · 3.94 KB
/
Worker.ts
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
import Job from './Job';
import Cluster, { TaskFunction } from './Cluster';
import { Page } from 'puppeteer';
import { timeoutExecute, debugGenerator, log } from './util';
import { inspect } from 'util';
import { WorkerInstance, JobInstance } from './concurrency/ConcurrencyImplementation';
const debug = debugGenerator('Worker');
const DEFAULT_OPTIONS = {
args: [],
};
interface WorkerOptions {
cluster: Cluster;
args: string[];
id: number;
browser: WorkerInstance;
}
const BROWSER_INSTANCE_TRIES = 10;
export interface WorkError {
type: 'error';
error: Error;
}
export interface WorkData {
type: 'success';
data: any;
}
export type WorkResult = WorkError | WorkData;
export default class Worker<JobData, ReturnData> implements WorkerOptions {
cluster: Cluster;
args: string[];
id: number;
browser: WorkerInstance;
activeTarget: Job<JobData, ReturnData> | null = null;
public constructor({ cluster, args, id, browser }: WorkerOptions) {
this.cluster = cluster;
this.args = args;
this.id = id;
this.browser = browser;
debug(`Starting #${this.id}`);
}
public async handle(
task: TaskFunction<JobData, ReturnData>,
job: Job<JobData, ReturnData>,
timeout: number,
): Promise<WorkResult> {
this.activeTarget = job;
let jobInstance: JobInstance | null = null;
let page: Page | null = null;
let tries = 0;
while (jobInstance === null) {
try {
jobInstance = await this.browser.jobInstance();
page = jobInstance.resources.page;
} catch (err) {
debug(`Error getting browser page (try: ${tries}), message: ${err.message}`);
await this.browser.repair();
tries += 1;
if (tries >= BROWSER_INSTANCE_TRIES) {
throw new Error('Unable to get browser page');
}
}
}
// We can be sure that page is set now, otherwise an exception would've been thrown
page = page as Page; // this is just for TypeScript
let errorState: Error | null = null;
page.on('error', (err) => {
errorState = err;
log(`Error (page error) crawling ${inspect(job.data)} // message: ${err.message}`);
});
debug(`Executing task on worker #${this.id} with data: ${inspect(job.data)}`);
let result: any;
try {
result = await timeoutExecute(
timeout,
task({
page,
// data might be undefined if queue is only called with a function
// we ignore that case, as the user should use Cluster<undefined> in that case
// to get correct typings
data: job.data as JobData,
worker: {
id: this.id,
},
}),
);
} catch (err) {
errorState = err;
log(`Error crawling ${inspect(job.data)} // message: ${err.message}`);
}
debug(`Finished executing task on worker #${this.id}`);
try {
await jobInstance.close();
} catch (e) {
debug(`Error closing browser instance for ${inspect(job.data)}: ${e.message}`);
await this.browser.repair();
}
this.activeTarget = null;
if (errorState) {
return {
type: 'error',
error: errorState || new Error('asf'),
};
}
return {
data: result,
type: 'success',
};
}
public async close(): Promise<void> {
try {
await this.browser.close();
} catch (err) {
debug(`Unable to close worker browser. Error message: ${err.message}`);
}
debug(`Closed #${this.id}`);
}
}