-
Notifications
You must be signed in to change notification settings - Fork 29
/
actor.ts
1823 lines (1650 loc) · 71 KB
/
actor.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
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { createPrivateKey } from 'node:crypto';
import { ACTOR_ENV_VARS, APIFY_ENV_VARS, INTEGER_ENV_VARS } from '@apify/consts';
import { decryptInputSecrets } from '@apify/input_secrets';
import log from '@apify/log';
import { addTimeoutToPromise } from '@apify/timeout';
import type {
ConfigurationOptions,
EventManager,
EventTypeName,
IStorage,
RecordOptions,
UseStateOptions,
} from '@crawlee/core';
import {
Configuration as CoreConfiguration,
Dataset,
EventType,
RequestQueue,
StorageManager,
purgeDefaultStorages,
} from '@crawlee/core';
import type { Awaitable, Constructor, Dictionary, SetStatusMessageOptions, StorageClient } from '@crawlee/types';
import { sleep, snakeCaseToCamelCase } from '@crawlee/utils';
import type {
ActorCallOptions,
ApifyClientOptions,
RunAbortOptions,
TaskCallOptions,
Webhook,
WebhookEventType,
} from 'apify-client';
import {
ActorRun as ClientActorRun,
ApifyClient,
} from 'apify-client';
import ow from 'ow';
import { Configuration } from './configuration';
import { KeyValueStore } from './key_value_store';
import { PlatformEventManager } from './platform_event_manager';
import type { ProxyConfigurationOptions } from './proxy_configuration';
import { ProxyConfiguration } from './proxy_configuration';
import { checkCrawleeVersion, logSystemInfo, printOutdatedSdkWarning } from './utils';
/**
* `Actor` class serves as an alternative approach to the static helpers exported from the package. It allows to pass configuration
* that will be used on the instance methods. Environment variables will have precedence over this configuration.
* See {@apilink Configuration} for details about what can be configured and what are the default values.
*/
export class Actor<Data extends Dictionary = Dictionary> {
/** @internal */
static _instance: Actor;
/**
* Configuration of this SDK instance (provided to its constructor). See {@apilink Configuration} for details.
* @internal
*/
readonly config: Configuration;
/**
* Default {@apilink ApifyClient} instance.
* @internal
*/
readonly apifyClient: ApifyClient;
/**
* Default {@apilink EventManager} instance.
* @internal
*/
readonly eventManager: EventManager;
/**
* Whether the Actor instance was initialized. This is set by calling {@apilink Actor.init}.
*/
initialized = false;
/**
* Set if the Actor called a method that requires the instance to be initialized, but did not do so.
* A call to `init` after this warning is emitted is considered an invalid state and will throw an error.
*/
private warnedAboutMissingInitCall = false;
constructor(options: ConfigurationOptions = {}) {
// use default configuration object if nothing overridden (it fallbacks to env vars)
this.config = Object.keys(options).length === 0 ? Configuration.getGlobalConfig() : new Configuration(options);
this.apifyClient = this.newClient();
this.eventManager = new PlatformEventManager(this.config);
}
/**
* Runs the main user function that performs the job of the Actor
* and terminates the process when the user function finishes.
*
* **The `Actor.main()` function is optional** and is provided merely for your convenience.
* It is mainly useful when you're running your code as an Actor on the [Apify platform](https://apify.com/actors).
* However, if you want to use Apify SDK tools directly inside your existing projects, e.g.
* running in an [Express](https://expressjs.com/) server, on
* [Google Cloud functions](https://cloud.google.com/functions)
* or [AWS Lambda](https://aws.amazon.com/lambda/), it's better to avoid
* it since the function terminates the main process when it finishes!
*
* The `Actor.main()` function performs the following actions:
*
* - When running on the Apify platform (i.e. `APIFY_IS_AT_HOME` environment variable is set),
* it sets up a connection to listen for platform events.
* For example, to get a notification about an imminent migration to another server.
* See {@apilink Actor.events} for details.
* - It invokes the user function passed as the `userFunc` parameter.
* - If the user function returned a promise, waits for it to resolve.
* - If the user function throws an exception or some other error is encountered,
* prints error details to console so that they are stored to the log.
* - Exits the Node.js process, with zero exit code on success and non-zero on errors.
*
* The user function can be synchronous:
*
* ```js
* await Actor.main(() => {
* // My synchronous function that returns immediately
* console.log('Hello world from Actor!');
* });
* ```
*
* If the user function returns a promise, it is considered asynchronous:
* ```js
* import { gotScraping } from 'got-scraping';
*
* await Actor.main(() => {
* // My asynchronous function that returns a promise
* return gotScraping('http://www.example.com').then((html) => {
* console.log(html);
* });
* });
* ```
*
* To simplify your code, you can take advantage of the `async`/`await` keywords:
*
* ```js
* import { gotScraping } from 'got-scraping';
*
* await Actor.main(async () => {
* // My asynchronous function
* const html = await request('http://www.example.com');
* console.log(html);
* });
* ```
*
* @param userFunc User function to be executed. If it returns a promise,
* the promise will be awaited. The user function is called with no arguments.
* @param options
* @ignore
*/
async main<T>(userFunc: UserFunc, options?: MainOptions): Promise<T> {
if (!userFunc || typeof userFunc !== 'function') {
throw new Error(`First parameter for Actor.main() must be a function (was '${userFunc === null ? 'null' : typeof userFunc}').`);
}
return (async () => {
await this.init(options);
let ret: T;
try {
ret = await userFunc() as T;
await this.exit(options);
} catch (err: any) {
log.exception(err, err.message);
await this.exit({ exitCode: EXIT_CODES.ERROR_USER_FUNCTION_THREW });
}
return ret!;
})();
}
/**
* @ignore
*/
async init(options: InitOptions = {}): Promise<void> {
if (this.initialized) {
log.debug(`Actor SDK was already initialized`);
return;
}
// If the warning about forgotten init call was emitted, we will not continue the init procedure.
if (this.warnedAboutMissingInitCall) {
throw new Error([
'Actor.init() was called after a method that would access a storage client was used.',
'This in an invalid state. Please make sure to call Actor.init() before such methods are called.',
].join('\n'));
}
this.initialized = true;
checkCrawleeVersion();
logSystemInfo();
printOutdatedSdkWarning();
// reset global config instance to respect APIFY_ prefixed env vars
CoreConfiguration.globalConfig = Configuration.getGlobalConfig();
if (this.isAtHome()) {
this.config.set('availableMemoryRatio', 1);
this.config.set('disableBrowserSandbox', true); // for browser launcher, adds `--no-sandbox` to args
this.config.useStorageClient(this.apifyClient);
this.config.useEventManager(this.eventManager);
} else if (options.storage) {
this.config.useStorageClient(options.storage);
}
// Init the event manager the config uses
await this.config.getEventManager().init();
log.debug(`Events initialized`);
await purgeDefaultStorages({
config: this.config,
onlyPurgeOnce: true,
});
log.debug(`Default storages purged`);
Configuration.storage.enterWith(this.config);
}
/**
* @ignore
*/
async exit(messageOrOptions?: string | ExitOptions, options: ExitOptions = {}): Promise<void> {
options = typeof messageOrOptions === 'string' ? { ...options, statusMessage: messageOrOptions } : { ...messageOrOptions, ...options };
options.exit ??= true;
options.exitCode ??= EXIT_CODES.SUCCESS;
options.timeoutSecs ??= 30;
const client = this.config.getStorageClient();
const events = this.config.getEventManager();
// Close the event manager and emit the final PERSIST_STATE event
await events.close();
log.debug(`Events closed`);
// Emit the exit event
events.emit(EventType.EXIT, options);
// Wait for all event listeners to be processed
log.debug(`Waiting for all event listeners to complete their execution (with ${options.timeoutSecs} seconds timeout)`);
await addTimeoutToPromise(
async () => {
await events.waitForAllListenersToComplete();
if (client.teardown) {
let finished = false;
setTimeout(() => {
if (!finished) {
log.info('Waiting for the storage to write its state to file system.');
}
}, 1000);
await client.teardown();
finished = true;
}
if (options.statusMessage != null) {
await this.setStatusMessage(options.statusMessage, { isStatusMessageTerminal: true, level: options.exitCode! > 0 ? 'ERROR' : 'INFO' });
}
},
options.timeoutSecs * 1000,
`Waiting for all event listeners to complete their execution timed out after ${options.timeoutSecs} seconds`,
).catch(() => {
if (options.exit) {
process.exit(options.exitCode);
}
});
if (!options.exit) {
return;
}
process.exit(options.exitCode);
}
/**
* @ignore
*/
async fail(messageOrOptions?: string | ExitOptions, options: ExitOptions = {}): Promise<void> {
return this.exit(messageOrOptions, { exitCode: 1, ...options });
}
/**
* @ignore
*/
on(event: EventTypeName, listener: (...args: any[]) => any): void {
this.config.getEventManager().on(event, listener);
}
/**
* @ignore
*/
off(event: EventTypeName, listener?: (...args: any[]) => any): void {
this.config.getEventManager().off(event, listener);
}
/**
* Runs an Actor on the Apify platform using the current user account (determined by the `APIFY_TOKEN` environment variable).
*
* The result of the function is an {@apilink ActorRun} object that contains details about the Actor run.
*
* If you want to run an Actor task rather than an Actor, please use the {@apilink Actor.callTask} function instead.
*
* For more information about Actors, read the [documentation](https://docs.apify.com/actor).
*
* **Example usage:**
*
* ```js
* const run = await Actor.call('apify/hello-world', { myInput: 123 });
* ```
*
* @param actorId
* Allowed formats are `username/actor-name`, `userId/actor-name` or Actor ID.
* @param [input]
* Input for the Actor. If it is an object, it will be stringified to
* JSON and its content type set to `application/json; charset=utf-8`.
* Otherwise the `options.contentType` parameter must be provided.
* @param [options]
* @ignore
*/
async call(actorId: string, input?: unknown, options: CallOptions = {}): Promise<ClientActorRun> {
const { token, ...rest } = options;
const client = token ? this.newClient({ token }) : this.apifyClient;
return client.actor(actorId).call(input, rest);
}
/**
* Runs an Actor on the Apify platform using the current user account (determined by the `APIFY_TOKEN` environment variable),
* unlike `Actor.call`, this method just starts the run without waiting for finish.
*
* The result of the function is an {@apilink ActorRun} object that contains details about the Actor run.
*
* For more information about Actors, read the
* [documentation](https://docs.apify.com/actor).
*
* **Example usage:**
*
* ```js
* const run = await Actor.start('apify/hello-world', { myInput: 123 });
* ```
*
* @param actorId
* Allowed formats are `username/actor-name`, `userId/actor-name` or Actor ID.
* @param [input]
* Input for the Actor. If it is an object, it will be stringified to
* JSON and its content type set to `application/json; charset=utf-8`.
* Otherwise the `options.contentType` parameter must be provided.
* @param [options]
* @ignore
*/
async start(actorId: string, input?: unknown, options: CallOptions = {}): Promise<ClientActorRun> {
const { token, ...rest } = options;
const client = token ? this.newClient({ token }) : this.apifyClient;
return client.actor(actorId).start(input, rest);
}
/**
* Aborts given Actor run on the Apify platform using the current user account (determined by the `APIFY_TOKEN` environment variable).
*
* The result of the function is an {@apilink ActorRun} object that contains details about the Actor run.
*
* For more information about Actors, read the
* [documentation](https://docs.apify.com/actor).
*
* **Example usage:**
*
* ```js
* const run = await Actor.abort(runId);
* ```
* @ignore
*/
async abort(runId: string, options: AbortOptions = {}): Promise<ClientActorRun> {
const { token, statusMessage, ...rest } = options;
const client = token ? this.newClient({ token }) : this.apifyClient;
if (statusMessage) {
await this.setStatusMessage(statusMessage, { isStatusMessageTerminal: true });
}
return client.run(runId).abort(rest);
}
/**
* Runs an actor task on the Apify platform using the current user account (determined by the `APIFY_TOKEN` environment variable).
*
* The result of the function is an {@apilink ActorRun} object that contains details about the Actor run.
*
* Note that an Actor task is a saved input configuration and options for an Actor.
* If you want to run an Actor directly rather than an Actor task, please use the
* {@apilink Actor.call} function instead.
*
* For more information about Actor tasks, read the [documentation](https://docs.apify.com/tasks).
*
* **Example usage:**
*
* ```js
* const run = await Actor.callTask('bob/some-task');
* ```
*
* @param taskId
* Allowed formats are `username/task-name`, `userId/task-name` or task ID.
* @param [input]
* Input overrides for the Actor task. If it is an object, it will be stringified to
* JSON and its content type set to `application/json; charset=utf-8`.
* Provided input will be merged with Actor task input.
* @param [options]
* @ignore
*/
async callTask(taskId: string, input?: Dictionary, options: CallTaskOptions = {}): Promise<ClientActorRun> {
const { token, ...rest } = options;
const client = token ? this.newClient({ token }) : this.apifyClient;
return client.task(taskId).call(input, rest);
}
/**
* Transforms this Actor run to an Actor run of a given Actor. The system stops the current container and starts
* the new container instead. All the default storages are preserved and the new input is stored under the `INPUT-METAMORPH-1` key
* in the same default key-value store.
*
* @param targetActorId
* Either `username/actor-name` or Actor ID of an Actor to which we want to metamorph.
* @param [input]
* Input for the Actor. If it is an object, it will be stringified to
* JSON and its content type set to `application/json; charset=utf-8`.
* Otherwise, the `options.contentType` parameter must be provided.
* @param [options]
* @ignore
*/
async metamorph(targetActorId: string, input?: unknown, options: MetamorphOptions = {}): Promise<void> {
if (!this.isAtHome()) {
log.warning('Actor.metamorph() is only supported when running on the Apify platform.');
return;
}
const {
customAfterSleepMillis = this.config.get('metamorphAfterSleepMillis'),
...metamorphOpts
} = options;
const runId = this.config.get('actorRunId')!;
await this.apifyClient.run(runId).metamorph(targetActorId, input, metamorphOpts);
// Wait some time for container to be stopped.
await sleep(customAfterSleepMillis);
}
/**
* Internally reboots this Actor. The system stops the current container and starts
* a new container with the same run ID.
* This can be used to get the Actor out of irrecoverable error state and continue where it left off.
*
* @ignore
*/
async reboot(options: RebootOptions = {}): Promise<void> {
if (!this.isAtHome()) {
log.warning('Actor.reboot() is only supported when running on the Apify platform.');
return;
}
// Waiting for all the listeners to finish, as `.reboot()` kills the container.
await Promise.all([
// `persistState` for individual RequestLists, RequestQueue... instances to be persisted
...this.config.getEventManager().listeners(EventType.PERSIST_STATE).map(async (x) => x()),
// `migrating` to pause Apify crawlers
...this.config.getEventManager().listeners(EventType.MIGRATING).map(async (x) => x()),
]);
const runId = this.config.get('actorRunId')!;
await this.apifyClient.run(runId).reboot();
// Wait some time for container to be stopped.
const { customAfterSleepMillis = this.config.get('metamorphAfterSleepMillis') } = options;
await sleep(customAfterSleepMillis);
}
/**
* Creates an ad-hoc webhook for the current Actor run, which lets you receive a notification when the Actor run finished or failed.
* For more information about Apify Actor webhooks, please see the [documentation](https://docs.apify.com/webhooks).
*
* Note that webhooks are only supported for Actors running on the Apify platform.
* In local environment, the function will print a warning and have no effect.
*
* @param options
* @returns The return value is the Webhook object.
* For more information, see the [Get webhook](https://apify.com/docs/api/v2#/reference/webhooks/webhook-object/get-webhook) API endpoint.
* @ignore
*/
async addWebhook(options: WebhookOptions): Promise<Webhook | undefined> {
ow(options, ow.object.exactShape({
eventTypes: ow.array.ofType<WebhookEventType>(ow.string),
requestUrl: ow.string,
payloadTemplate: ow.optional.string,
idempotencyKey: ow.optional.string,
}));
const { eventTypes, requestUrl, payloadTemplate, idempotencyKey } = options;
if (!this.isAtHome()) {
log.warning('Actor.addWebhook() is only supported when running on the Apify platform. The webhook will not be invoked.');
return undefined;
}
const runId = this.config.get('actorRunId')!;
if (!runId) {
throw new Error(`Environment variable ${ACTOR_ENV_VARS.RUN_ID} is not set!`);
}
return this.apifyClient.webhooks().create({
isAdHoc: true,
eventTypes,
condition: {
actorRunId: runId,
},
requestUrl,
payloadTemplate,
idempotencyKey,
});
}
/**
* Sets the status message for the current Actor run.
*
* @returns The return value is the Run object.
* For more information, see the [Actor Runs](https://docs.apify.com/api/v2#/reference/actor-runs/) API endpoints.
* @ignore
*/
async setStatusMessage(statusMessage: string, options?: SetStatusMessageOptions): Promise<ClientActorRun> {
const { isStatusMessageTerminal, level } = options || {};
ow(statusMessage, ow.string);
ow(isStatusMessageTerminal, ow.optional.boolean);
const loggedStatusMessage = `[Status message]: ${statusMessage}`;
switch (level) {
case 'DEBUG':
log.debug(loggedStatusMessage);
break;
case 'WARNING':
log.warning(loggedStatusMessage);
break;
case 'ERROR':
log.error(loggedStatusMessage);
break;
default:
log.info(loggedStatusMessage);
break;
}
const client = this.config.getStorageClient();
// just to be sure, this should be fast
await addTimeoutToPromise(
async () => client.setStatusMessage!(statusMessage, { isStatusMessageTerminal, level }),
1000,
'Setting status message timed out after 1s',
).catch((e) => log.warning(e.message));
const runId = this.config.get('actorRunId')!;
if (runId) {
// just to be sure, this should be fast
const run = await addTimeoutToPromise(
async () => this.apifyClient.run(runId).get(),
1000,
'Getting the current run timed out after 1s',
).catch((e) => log.warning(e.message));
if (run) {
return run;
}
}
return {} as ClientActorRun;
}
/**
* Stores an object or an array of objects to the default {@apilink Dataset} of the current Actor run.
*
* This is just a convenient shortcut for {@apilink Dataset.pushData}.
* For example, calling the following code:
* ```js
* await Actor.pushData({ myValue: 123 });
* ```
*
* is equivalent to:
* ```js
* const dataset = await Actor.openDataset();
* await dataset.pushData({ myValue: 123 });
* ```
*
* For more information, see {@apilink Actor.openDataset} and {@apilink Dataset.pushData}
*
* **IMPORTANT**: Make sure to use the `await` keyword when calling `pushData()`,
* otherwise the Actor process might finish before the data are stored!
*
* @param item Object or array of objects containing data to be stored in the default dataset.
* The objects must be serializable to JSON and the JSON representation of each object must be smaller than 9MB.
* @ignore
*/
async pushData(item: Data | Data[]): Promise<void> {
this._ensureActorInit('pushData');
const dataset = await this.openDataset();
return dataset.pushData(item);
}
/**
* Opens a dataset and returns a promise resolving to an instance of the {@apilink Dataset} class.
*
* Datasets are used to store structured data where each object stored has the same attributes,
* such as online store products or real estate offers.
* The actual data is stored either on the local filesystem or in the cloud.
*
* For more details and code examples, see the {@apilink Dataset} class.
*
* @param [datasetIdOrName]
* ID or name of the dataset to be opened. If `null` or `undefined`,
* the function returns the default dataset associated with the Actor run.
* @param [options]
* @ignore
*/
async openDataset(
datasetIdOrName?: string | null,
options: OpenStorageOptions = {},
): Promise<Dataset<Data>> {
ow(datasetIdOrName, ow.optional.string);
ow(options, ow.object.exactShape({
forceCloud: ow.optional.boolean,
}));
this._ensureActorInit('openDataset');
return this._openStorage<Dataset<Data>>(Dataset, datasetIdOrName, options);
}
/**
* Gets a value from the default {@apilink KeyValueStore} associated with the current Actor run.
*
* This is just a convenient shortcut for {@apilink KeyValueStore.getValue}.
* For example, calling the following code:
* ```js
* const value = await Actor.getValue('my-key');
* ```
*
* is equivalent to:
* ```js
* const store = await Actor.openKeyValueStore();
* const value = await store.getValue('my-key');
* ```
*
* To store the value to the default key-value store, you can use the {@apilink Actor.setValue} function.
*
* For more information, see {@apilink Actor.openKeyValueStore}
* and {@apilink KeyValueStore.getValue}.
*
* @param key Unique record key.
* @returns
* Returns a promise that resolves to an object, string
* or [`Buffer`](https://nodejs.org/api/buffer.html), depending
* on the MIME content type of the record, or `null`
* if the record is missing.
* @ignore
*/
async getValue<T = unknown>(key: string): Promise<T | null> {
this._ensureActorInit('getValue');
const store = await this.openKeyValueStore();
return store.getValue<T>(key);
}
/**
* Stores or deletes a value in the default {@apilink KeyValueStore} associated with the current Actor run.
*
* This is just a convenient shortcut for {@apilink KeyValueStore.setValue}.
* For example, calling the following code:
* ```js
* await Actor.setValue('OUTPUT', { foo: "bar" });
* ```
*
* is equivalent to:
* ```js
* const store = await Actor.openKeyValueStore();
* await store.setValue('OUTPUT', { foo: "bar" });
* ```
*
* To get a value from the default key-value store, you can use the {@apilink Actor.getValue} function.
*
* For more information, see {@apilink Actor.openKeyValueStore}
* and {@apilink KeyValueStore.getValue}.
*
* @param key
* Unique record key.
* @param value
* Record data, which can be one of the following values:
* - If `null`, the record in the key-value store is deleted.
* - If no `options.contentType` is specified, `value` can be any JavaScript object, and it will be stringified to JSON.
* - If `options.contentType` is set, `value` is taken as is, and it must be a `String` or [`Buffer`](https://nodejs.org/api/buffer.html).
* For any other value an error will be thrown.
* @param [options]
* @ignore
*/
async setValue<T>(key: string, value: T | null, options: RecordOptions = {}): Promise<void> {
this._ensureActorInit('setValue');
const store = await this.openKeyValueStore();
return store.setValue(key, value, options);
}
/**
* Gets the Actor input value from the default {@apilink KeyValueStore} associated with the current Actor run.
*
* This is just a convenient shortcut for [`keyValueStore.getValue('INPUT')`](core/class/KeyValueStore#getValue).
* For example, calling the following code:
* ```js
* const input = await Actor.getInput();
* ```
*
* is equivalent to:
* ```js
* const store = await Actor.openKeyValueStore();
* await store.getValue('INPUT');
* ```
*
* Note that the `getInput()` function does not cache the value read from the key-value store.
* If you need to use the input multiple times in your Actor,
* it is far more efficient to read it once and store it locally.
*
* For more information, see {@apilink Actor.openKeyValueStore}
* and {@apilink KeyValueStore.getValue}.
*
* @returns
* Returns a promise that resolves to an object, string
* or [`Buffer`](https://nodejs.org/api/buffer.html), depending
* on the MIME content type of the record, or `null`
* if the record is missing.
* @ignore
*/
async getInput<T = Dictionary | string | Buffer>(): Promise<T | null> {
this._ensureActorInit('getInput');
const inputSecretsPrivateKeyFile = this.config.get('inputSecretsPrivateKeyFile');
const inputSecretsPrivateKeyPassphrase = this.config.get('inputSecretsPrivateKeyPassphrase');
const input = await this.getValue<T>(this.config.get('inputKey'));
if (ow.isValid(input, ow.object.nonEmpty) && inputSecretsPrivateKeyFile && inputSecretsPrivateKeyPassphrase) {
const privateKey = createPrivateKey({
key: Buffer.from(inputSecretsPrivateKeyFile, 'base64'),
passphrase: inputSecretsPrivateKeyPassphrase,
});
return decryptInputSecrets<T>({ input, privateKey });
}
return input;
}
/**
* Gets the Actor input value just like the {@apilink Actor.getInput} method,
* but throws if it is not found.
*/
async getInputOrThrow<T = Dictionary | string | Buffer>(): Promise<T> {
const input = await this.getInput<T>();
if (input == null) {
throw new Error('Input does not exist');
}
return input;
}
/**
* Opens a key-value store and returns a promise resolving to an instance of the {@apilink KeyValueStore} class.
*
* Key-value stores are used to store records or files, along with their MIME content type.
* The records are stored and retrieved using a unique key.
* The actual data is stored either on a local filesystem or in the Apify cloud.
*
* For more details and code examples, see the {@apilink KeyValueStore} class.
*
* @param [storeIdOrName]
* ID or name of the key-value store to be opened. If `null` or `undefined`,
* the function returns the default key-value store associated with the Actor run.
* @param [options]
* @ignore
*/
async openKeyValueStore(storeIdOrName?: string | null, options: OpenStorageOptions = {}): Promise<KeyValueStore> {
ow(storeIdOrName, ow.optional.string);
ow(options, ow.object.exactShape({
forceCloud: ow.optional.boolean,
}));
this._ensureActorInit('openKeyValueStore');
return this._openStorage(KeyValueStore, storeIdOrName, options);
}
/**
* Opens a request queue and returns a promise resolving to an instance
* of the {@apilink RequestQueue} class.
*
* {@apilink RequestQueue} represents a queue of URLs to crawl, which is stored either on local filesystem or in the cloud.
* The queue is used for deep crawling of websites, where you start with several URLs and then
* recursively follow links to other pages. The data structure supports both breadth-first
* and depth-first crawling orders.
*
* For more details and code examples, see the {@apilink RequestQueue} class.
*
* @param [queueIdOrName]
* ID or name of the request queue to be opened. If `null` or `undefined`,
* the function returns the default request queue associated with the Actor run.
* @param [options]
* @ignore
*/
async openRequestQueue(queueIdOrName?: string | null, options: OpenStorageOptions = {}): Promise<RequestQueue> {
ow(queueIdOrName, ow.optional.string);
ow(options, ow.object.exactShape({
forceCloud: ow.optional.boolean,
}));
this._ensureActorInit('openRequestQueue');
return this._openStorage(RequestQueue, queueIdOrName, options);
}
/**
* Creates a proxy configuration and returns a promise resolving to an instance
* of the {@apilink ProxyConfiguration} class that is already initialized.
*
* Configures connection to a proxy server with the provided options. Proxy servers are used to prevent target websites from blocking
* your crawlers based on IP address rate limits or blacklists. Setting proxy configuration in your crawlers automatically configures
* them to use the selected proxies for all connections.
*
* For more details and code examples, see the {@apilink ProxyConfiguration} class.
*
* ```js
*
* // Returns initialized proxy configuration class
* const proxyConfiguration = await Actor.createProxyConfiguration({
* groups: ['GROUP1', 'GROUP2'] // List of Apify proxy groups
* countryCode: 'US'
* });
*
* const crawler = new CheerioCrawler({
* // ...
* proxyConfiguration,
* requestHandler({ proxyInfo }) {
* const usedProxyUrl = proxyInfo.url; // Getting the proxy URL
* }
* })
*
* ```
*
* For compatibility with existing Actor Input UI (Input Schema), this function
* returns `undefined` when the following object is passed as `proxyConfigurationOptions`.
*
* ```
* { useApifyProxy: false }
* ```
* @ignore
*/
async createProxyConfiguration(
proxyConfigurationOptions: ProxyConfigurationOptions & { useApifyProxy?: boolean } = {},
): Promise<ProxyConfiguration | undefined> {
// Compatibility fix for Input UI where proxy: None returns { useApifyProxy: false }
// Without this, it would cause proxy to use the zero config / auto mode.
const { useApifyProxy, ...options } = proxyConfigurationOptions;
const dontUseApifyProxy = useApifyProxy === false;
const dontUseCustomProxies = !proxyConfigurationOptions.proxyUrls;
if (dontUseApifyProxy && dontUseCustomProxies) {
return undefined;
}
const proxyConfiguration = new ProxyConfiguration(options, this.config);
if (await proxyConfiguration.initialize()) {
return proxyConfiguration;
}
return undefined;
}
/**
* Modifies Actor env vars so parsing respects the structure of {@apilink ApifyEnv} interface.
*/
private getModifiedActorEnvVars() {
const modifiedActorEnvVars: Record<string, string> = {};
Object.entries(ACTOR_ENV_VARS).forEach(([k, v]) => {
// Prepend `ACTOR_` to env vars so ApifyEnv structure is preserved
if (['ID', 'RUN_ID', 'TASK_ID'].includes(k)) {
modifiedActorEnvVars[`ACTOR_${k}`] = v;
} else {
modifiedActorEnvVars[k] = v;
}
});
return modifiedActorEnvVars;
}
/**
* Returns a new {@apilink ApifyEnv} object which contains information parsed from all the Apify environment variables.
*
* For the list of the Apify environment variables, see
* [Actor documentation](https://docs.apify.com/actor/run#environment-variables).
* If some variables are not defined or are invalid, the corresponding value in the resulting object will be null.
* @ignore
*/
getEnv(): ApifyEnv {
// NOTE: Don't throw if env vars are invalid to simplify local development and debugging of Actors
const env = process.env || {};
const envVars = {} as ApifyEnv;
for (const [shortName, fullName] of Object.entries({ ...APIFY_ENV_VARS, ...this.getModifiedActorEnvVars() })) {
const camelCaseName = snakeCaseToCamelCase(shortName) as keyof ApifyEnv;
let value: string | number | Date | undefined = env[fullName];
// Parse dates and integers.
if (value && fullName.endsWith('_AT')) {
const unix = Date.parse(value);
value = unix > 0 ? new Date(unix) : undefined;
} else if ((INTEGER_ENV_VARS as readonly string[]).includes(fullName)) {
value = parseInt(value!, 10);
}
Reflect.set(envVars, camelCaseName, value || value === 0 ? value : null);
}
return envVars;
}
/**
* Returns a new instance of the Apify API client. The `ApifyClient` class is provided
* by the [apify-client](https://www.npmjs.com/package/apify-client)
* NPM package, and it is automatically configured using the `APIFY_API_BASE_URL`, and `APIFY_TOKEN`
* environment variables. You can override the token via the available options. That's useful
* if you want to use the client as a different Apify user than the SDK internals are using.
* @ignore
*/
newClient(options: ApifyClientOptions = {}): ApifyClient {
const { storageDir, ...storageClientOptions } = this.config.get('storageClientOptions') as Dictionary;
return new ApifyClient({
baseUrl: this.config.get('apiBaseUrl'),
token: this.config.get('token'),
...storageClientOptions,
...options, // allow overriding the instance configuration
});
}
/**
* Returns `true` when code is running on Apify platform and `false` otherwise (for example locally).
* @ignore
*/
isAtHome(): boolean {
return !!process.env[APIFY_ENV_VARS.IS_AT_HOME];
}
/**
* Easily create and manage state values. All state values are automatically persisted.
*
* Values can be modified by simply using the assignment operator.
*
* @param name The name of the store to use.
* @param defaultValue If the store does not yet have a value in it, the value will be initialized with the `defaultValue` you provide.
* @param options An optional object parameter where a custom `keyValueStoreName` and `config` can be passed in.
*/
async useState<State extends Dictionary = Dictionary>(
name?: string,
defaultValue = {} as State,
options?: UseStateOptions,
) {
const kvStore = await KeyValueStore.open(options?.keyValueStoreName, { config: options?.config || Configuration.getGlobalConfig() });
return kvStore.getAutoSavedValue<State>(name || 'APIFY_GLOBAL_STATE', defaultValue);
}
/**
* Easily create and manage state values. All state values are automatically persisted.
*
* Values can be modified by simply using the assignment operator.
*
* @param name The name of the store to use.
* @param defaultValue If the store does not yet have a value in it, the value will be initialized with the `defaultValue` you provide.
* @param options An optional object parameter where a custom `keyValueStoreName` and `config` can be passed in.
*/
static async useState<State extends Dictionary = Dictionary>(
name?: string,
defaultValue = {} as State,
options?: UseStateOptions,
) {
return Actor.getDefaultInstance().useState<State>(name, defaultValue, options);
}
/**
* Runs the main user function that performs the job of the Actor
* and terminates the process when the user function finishes.
*
* **The `Actor.main()` function is optional** and is provided merely for your convenience.
* It is mainly useful when you're running your code as an Actor on the [Apify platform](https://apify.com/actors).
* However, if you want to use Apify SDK tools directly inside your existing projects, e.g.
* running in an [Express](https://expressjs.com/) server, on
* [Google Cloud functions](https://cloud.google.com/functions)