-
-
Notifications
You must be signed in to change notification settings - Fork 71
/
worker.ts
442 lines (371 loc) · 11 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
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
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
import os from "os";
import { logger, formatErr } from "./logger.js";
import { sleep, timedRun } from "./timing.js";
import { Recorder } from "./recorder.js";
import { rxEscape } from "./seeds.js";
import { CDPSession, Page } from "puppeteer-core";
import { PageState, WorkerId } from "./state.js";
import { Crawler } from "../crawler.js";
const MAX_REUSE = 5;
const NEW_WINDOW_TIMEOUT = 20;
const TEARDOWN_TIMEOUT = 10;
const FINISHED_TIMEOUT = 60;
// ===========================================================================
export type WorkerOpts = {
page: Page;
cdp: CDPSession;
workerid: WorkerId;
// eslint-disable-next-line @typescript-eslint/ban-types
callbacks: Record<string, Function>;
directFetchCapture?:
| ((url: string) => Promise<{ fetched: boolean; mime: string }>)
| null;
};
// ===========================================================================
export type WorkerState = WorkerOpts & {
data: PageState;
};
// ===========================================================================
export class PageWorker {
id: WorkerId;
crawler: Crawler;
maxPageTime: number;
reuseCount = 0;
page?: Page | null;
cdp?: CDPSession | null;
// eslint-disable-next-line @typescript-eslint/ban-types
callbacks?: Record<string, Function>;
opts?: WorkerOpts;
// TODO: Fix this the next time the file is edited.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
logDetails: Record<string, any> = {};
crashed = false;
markCrashed?: (reason: string) => void;
crashBreak?: Promise<void>;
recorder: Recorder;
constructor(
id: WorkerId,
crawler: Crawler,
maxPageTime: number,
collDir: string,
) {
this.id = id;
this.crawler = crawler;
this.maxPageTime = maxPageTime;
this.logDetails = { workerid: this.id };
this.recorder = new Recorder({
workerid: id,
collDir,
crawler: this.crawler,
});
this.crawler.browser.recorders.push(this.recorder);
}
async closePage() {
if (!this.page) {
return;
}
if (this.recorder) {
await this.recorder.onClosePage();
}
if (!this.crashed && this.opts) {
try {
await timedRun(
this.crawler.teardownPage(this.opts),
TEARDOWN_TIMEOUT,
"Page Teardown Timed Out",
this.logDetails,
"worker",
);
} catch (e) {
// ignore
}
}
try {
logger.debug(
"Closing page",
{ crashed: this.crashed, workerid: this.id },
"worker",
);
await timedRun(
this.page.close(),
TEARDOWN_TIMEOUT,
"Page Close Timed Out",
this.logDetails,
"worker",
);
} catch (e) {
// ignore
} finally {
this.cdp = null;
this.page = null;
}
}
isSameOrigin(url: string) {
try {
const currURL = new URL(this.page ? this.page.url() : "");
const newURL = new URL(url);
return currURL.origin === newURL.origin;
} catch (e) {
return false;
}
}
async initPage(url: string): Promise<WorkerOpts> {
if (
!this.crashed &&
this.page &&
this.opts &&
++this.reuseCount <= MAX_REUSE &&
this.isSameOrigin(url)
) {
logger.debug(
"Reusing page",
{ reuseCount: this.reuseCount, ...this.logDetails },
"worker",
);
return this.opts;
} else if (this.page) {
await this.closePage();
}
this.reuseCount = 1;
const workerid = this.id;
let retry = 0;
while (await this.crawler.isCrawlRunning()) {
try {
logger.debug("Getting page in new window", { workerid }, "worker");
const result = await timedRun(
this.crawler.browser.newWindowPageWithCDP(),
NEW_WINDOW_TIMEOUT,
"New Window Timed Out",
{ workerid },
"worker",
);
if (!result) {
throw new Error("timed out");
}
const { page, cdp } = result;
this.page = page;
this.cdp = cdp;
this.callbacks = {};
const directFetchCapture = this.recorder
? (x: string) => this.recorder.directFetchCapture(x)
: null;
this.opts = {
page,
cdp,
workerid,
callbacks: this.callbacks,
directFetchCapture,
};
if (this.recorder) {
await this.recorder.onCreatePage(this.opts);
}
// updated per page crawl
this.crashed = false;
this.crashBreak = new Promise(
(resolve, reject) => (this.markCrashed = reject),
);
this.logDetails = { page: page.url(), workerid };
// more serious page crash, mark as failed
// TODO: Fix this the next time the file is edited.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
page.on("error", (err: any) => {
// ensure we're still on this page, otherwise ignore!
if (this.page === page) {
logger.error(
"Page Crashed",
{ ...formatErr(err), ...this.logDetails },
"worker",
);
this.crashed = true;
if (this.markCrashed) {
this.markCrashed("crashed");
}
}
});
await this.crawler.setupPage(this.opts);
return this.opts;
} catch (err) {
logger.warn(
"Error getting new page",
{ workerid: this.id, ...formatErr(err) },
"worker",
);
retry++;
if (!this.crawler.browser.browser) {
break;
}
if (retry >= MAX_REUSE) {
logger.fatal(
"Unable to get new page, browser likely crashed",
this.logDetails,
"worker",
);
}
await sleep(0.5);
logger.warn("Retrying getting new page", this.logDetails, "worker");
if (this.crawler.healthChecker) {
this.crawler.healthChecker.incError();
}
}
}
throw new Error("no page available, shouldn't get here");
}
async crawlPage(opts: WorkerState) {
const res = await this.crawler.crawlPage(opts);
if (this.recorder) {
await this.recorder.awaitPageResources();
}
return res;
}
async timedCrawlPage(opts: WorkerState) {
const workerid = this.id;
const { data } = opts;
const { url, pageid } = data;
logger.info("Starting page", { workerid, page: url }, "worker");
this.logDetails = { page: url, workerid };
if (this.recorder) {
this.recorder.startPage({ pageid, url });
}
try {
await Promise.race([
timedRun(
this.crawlPage(opts),
this.maxPageTime,
"Page Worker Timeout",
this.logDetails,
"worker",
),
this.crashBreak,
]);
} catch (e) {
if (e instanceof Error && e.message !== "logged" && !this.crashed) {
logger.error(
"Worker Exception",
{ ...formatErr(e), ...this.logDetails },
"worker",
);
}
await this.closePage();
} finally {
try {
if (this.recorder) {
opts.data.ts = await this.recorder.writePageInfoRecord();
}
} catch (e) {
logger.error(
"Error writing pageinfo recorder",
{ ...formatErr(e), ...this.logDetails },
"recorder",
);
}
await timedRun(
this.crawler.pageFinished(data),
FINISHED_TIMEOUT,
"Page Finished Timed Out",
this.logDetails,
"worker",
);
}
}
async run() {
logger.info("Worker starting", { workerid: this.id }, "worker");
try {
await this.runLoop();
logger.info(
"Worker done, all tasks complete",
{ workerid: this.id },
"worker",
);
} catch (e) {
logger.error(
"Worker error, exiting",
{ ...formatErr(e), workerid: this.id },
"worker",
);
}
}
async finalize(waitTime?: number) {
if (this.recorder) {
await this.recorder.onDone(waitTime ?? this.maxPageTime);
}
}
async runLoop() {
const crawlState = this.crawler.crawlState;
let loggedWaiting = false;
while (await this.crawler.isCrawlRunning()) {
await crawlState.processMessage(this.crawler.params.scopedSeeds);
const data = await crawlState.nextFromQueue();
// see if any work data in the queue
if (data) {
// filter out any out-of-scope pages right away
if (!this.crawler.isInScope(data, this.logDetails)) {
logger.info("Page no longer in scope", data);
await crawlState.markExcluded(data.url);
continue;
}
// init page (new or reuse)
const opts = await this.initPage(data.url);
// run timed crawl of page
await this.timedCrawlPage({ ...opts, data });
loggedWaiting = false;
} else {
// indicate that the worker has no more work (mostly for screencasting, status, etc...)
// depending on other works, will either get more work or crawl will end
this.crawler.workerIdle(this.id);
// check if any pending urls
const pending = await crawlState.numPending();
// if pending, sleep and check again
if (pending) {
if (!loggedWaiting) {
logger.debug(
"No crawl tasks, but pending tasks remain, waiting",
{ pending, workerid: this.id },
"worker",
);
loggedWaiting = true;
}
await sleep(0.5);
} else {
// if no pending and queue size is still empty, we're done!
if (!(await crawlState.queueSize())) {
break;
}
}
}
}
}
}
// ===========================================================================
const workers: PageWorker[] = [];
// ===========================================================================
export async function runWorkers(
crawler: Crawler,
numWorkers: number,
maxPageTime: number,
collDir: string,
) {
logger.info(`Creating ${numWorkers} workers`, {}, "worker");
let offset = 0;
// automatically set worker start by ordinal in k8s
// if hostname is "crawl-id-name-N"
// while CRAWL_ID is "crawl-id-name", then set starting
// worker index offset to N * numWorkers
if (process.env.CRAWL_ID) {
const rx = new RegExp(rxEscape(process.env.CRAWL_ID) + "\\-([\\d]+)$");
const m = os.hostname().match(rx);
if (m) {
offset = Number(m[1]) * numWorkers;
logger.info("Starting workerid index at " + offset, "worker");
}
}
for (let i = 0; i < numWorkers; i++) {
workers.push(new PageWorker(i + offset, crawler, maxPageTime, collDir));
}
await Promise.allSettled(workers.map((worker) => worker.run()));
await crawler.browser.close();
await closeWorkers();
}
// ===========================================================================
export function closeWorkers(waitTime?: number) {
return Promise.allSettled(workers.map((worker) => worker.finalize(waitTime)));
}