Skip to content

Commit 0931c2e

Browse files
authored
feat: ignore proxy configuration locally if no valid token or password is found (#272)
We use the proxy configuration in all the templates, as we want users to run behind a proxy all the times. This PR changes the internal mechanism to gracefully ignore the proxy configuration locally when we don't see a valid token or proxy password. This way, new users can run their actors locally without being logged in. Closes #262
1 parent 3ec01d5 commit 0931c2e

4 files changed

Lines changed: 64 additions & 23 deletions

File tree

‎packages/apify/src/actor.ts‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -873,9 +873,12 @@ export class Actor<Data extends Dictionary = Dictionary> {
873873
}
874874

875875
const proxyConfiguration = new ProxyConfiguration(options, this.config);
876-
await proxyConfiguration.initialize();
877876

878-
return proxyConfiguration;
877+
if (await proxyConfiguration.initialize()) {
878+
return proxyConfiguration;
879+
}
880+
881+
return undefined;
879882
}
880883

881884
/**

‎packages/apify/src/proxy_configuration.ts‎

Lines changed: 47 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import {
77
ProxyConfiguration as CoreProxyConfiguration,
88
} from '@crawlee/core';
99
import { gotScraping } from '@crawlee/utils';
10+
import type { UserProxy } from 'apify-client';
1011
import ow from 'ow';
1112

1213
import { Actor } from './actor';
@@ -213,11 +214,13 @@ export class ProxyConfiguration extends CoreProxyConfiguration {
213214
* You should use the {@apilink createProxyConfiguration} function to create a pre-initialized
214215
* `ProxyConfiguration` instance instead of calling this manually.
215216
*/
216-
async initialize(): Promise<void> {
217+
async initialize(): Promise<boolean> {
217218
if (this.usesApifyProxy) {
218219
await this._setPasswordIfToken();
219-
await this._checkAccess();
220+
return this._checkAccess();
220221
}
222+
223+
return true;
221224
}
222225

223226
/**
@@ -315,7 +318,20 @@ export class ProxyConfiguration extends CoreProxyConfiguration {
315318
const token = this.config.get('token');
316319

317320
if (token) {
318-
const { proxy } = await Actor.apifyClient.user().get();
321+
let proxy: UserProxy;
322+
323+
try {
324+
const user = await Actor.apifyClient.user().get();
325+
proxy = user.proxy!;
326+
} catch (error) {
327+
if (Actor.isAtHome()) {
328+
throw error;
329+
} else {
330+
this.log.warning(`Failed to fetch user data based on token, disabling proxy.`, { error });
331+
return;
332+
}
333+
}
334+
319335
const { password } = proxy!;
320336

321337
if (this.password) {
@@ -329,8 +345,14 @@ export class ProxyConfiguration extends CoreProxyConfiguration {
329345
}
330346

331347
if (!this.password) {
332-
throw new Error(`Apify Proxy password must be provided using options.password or the "${APIFY_ENV_VARS.PROXY_PASSWORD}" environment variable. `
333-
+ `If you add the "${APIFY_ENV_VARS.TOKEN}" environment variable, the password will be automatically inferred.`);
348+
if (Actor.isAtHome()) {
349+
throw new Error(`Apify Proxy password must be provided using options.password or the "${APIFY_ENV_VARS.PROXY_PASSWORD}" environment variable. `
350+
+ `If you add the "${APIFY_ENV_VARS.TOKEN}" environment variable, the password will be automatically inferred.`);
351+
} else {
352+
this.log.warning(`No proxy password or token detected, running without proxy. To use Apify Proxy locally, `
353+
+ `provide options.password or "${APIFY_ENV_VARS.PROXY_PASSWORD}" environment variable. `
354+
+ `If you add the "${APIFY_ENV_VARS.TOKEN}" environment variable, the password will be automatically inferred.`);
355+
}
334356
}
335357
}
336358

@@ -339,17 +361,31 @@ export class ProxyConfiguration extends CoreProxyConfiguration {
339361
* If the check can not be made, it only prints a warning and allows the program to continue. This is to
340362
* prevent program crashes caused by short downtimes of Proxy.
341363
*/
342-
protected async _checkAccess(): Promise<void> {
364+
protected async _checkAccess(): Promise<boolean> {
343365
const status = await this._fetchStatus();
344-
if (status) {
345-
const { connected, connectionError, isManInTheMiddle } = status;
346-
this.isManInTheMiddle = isManInTheMiddle;
347366

348-
if (!connected) this._throwApifyProxyConnectionError(connectionError);
349-
} else {
367+
if (!status) {
350368
this.log.warning('Apify Proxy access check timed out. Watch out for errors with status code 407. '
351369
+ 'If you see some, it most likely means you don\'t have access to either all or some of the proxies you\'re trying to use.');
370+
return true;
352371
}
372+
373+
const { connected, connectionError, isManInTheMiddle } = status;
374+
this.isManInTheMiddle = isManInTheMiddle;
375+
376+
if (connected) {
377+
return true;
378+
}
379+
380+
// Throw only on the platform, locally we just print a warning and run requests without the proxy.
381+
// This is because the user might not have set up things correctly yet.
382+
// It still fails on the platform, where we don't want to allow this behavior.
383+
if (Actor.isAtHome()) {
384+
throw new Error(connectionError);
385+
}
386+
387+
this.log.warning(connectionError);
388+
return false;
353389
}
354390

355391
/**
@@ -376,14 +412,6 @@ export class ProxyConfiguration extends CoreProxyConfiguration {
376412
return undefined;
377413
}
378414

379-
/**
380-
* Throws Apify Proxy is not connected
381-
* @internal
382-
*/
383-
protected _throwApifyProxyConnectionError(errorMessage: string) {
384-
throw new Error(errorMessage);
385-
}
386-
387415
/**
388416
* Throws cannot combine custom proxies with Apify Proxy
389417
* @internal

‎test/apify/actor.test.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -532,15 +532,15 @@ describe('Actor', () => {
532532
};
533533

534534
const initializeSpy = vitest.spyOn(ProxyConfiguration.prototype, 'initialize');
535-
initializeSpy.mockImplementationOnce(async () => {});
535+
initializeSpy.mockImplementationOnce(async () => true);
536536
await expect(Actor.createProxyConfiguration(proxyConfiguration)).resolves.toBeInstanceOf(ProxyConfiguration);
537537
expect(initializeSpy).toBeCalledTimes(1);
538538
});
539539

540540
test('createProxyConfiguration should create ProxyConfiguration', async () => {
541541
const sdk = new Actor();
542542
const initializeSpy = vitest.spyOn(ProxyConfiguration.prototype, 'initialize');
543-
initializeSpy.mockImplementationOnce(async () => {});
543+
initializeSpy.mockImplementationOnce(async () => true);
544544
await sdk.createProxyConfiguration();
545545
expect(initializeSpy).toBeCalledTimes(1);
546546
});

‎test/apify/proxy_configuration.test.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ afterEach(() => {
3434
delete process.env[APIFY_ENV_VARS.PROXY_PASSWORD];
3535
delete process.env[APIFY_ENV_VARS.PROXY_HOSTNAME];
3636
delete process.env[APIFY_ENV_VARS.PROXY_STATUS_URL];
37+
delete process.env[APIFY_ENV_VARS.IS_AT_HOME];
3738
});
3839

3940
describe('ProxyConfiguration', () => {
@@ -406,9 +407,11 @@ describe('Actor.createProxyConfiguration()', () => {
406407
gotScrapingSpy.mockRestore();
407408
});
408409

410+
// TODO: test that on platform we throw but locally we only print warning
409411
test('should throw missing password', async () => {
410412
delete process.env[APIFY_ENV_VARS.PROXY_PASSWORD];
411413
delete process.env[APIFY_ENV_VARS.TOKEN];
414+
process.env[APIFY_ENV_VARS.IS_AT_HOME] = '1';
412415

413416
const status = { connected: true };
414417

@@ -421,11 +424,15 @@ describe('Actor.createProxyConfiguration()', () => {
421424
await expect(Actor.createProxyConfiguration()).rejects.toThrow('Apify Proxy password must be provided');
422425

423426
gotScrapingSpy.mockRestore();
427+
428+
delete process.env[APIFY_ENV_VARS.IS_AT_HOME];
429+
await expect(Actor.createProxyConfiguration()).resolves.toBeInstanceOf(ProxyConfiguration);
424430
});
425431

426432
test('should throw when group is not available', async () => {
427433
delete process.env[APIFY_ENV_VARS.PROXY_PASSWORD];
428434
process.env.APIFY_TOKEN = '123456789';
435+
process.env[APIFY_ENV_VARS.IS_AT_HOME] = '1';
429436
const connectionError = 'Invalid username: proxy group "GROUP2"; not found or not accessible.';
430437
const status = { connected: false, connectionError };
431438
const getUserSpy = vitest.spyOn(UserClient.prototype, 'get');
@@ -436,6 +443,9 @@ describe('Actor.createProxyConfiguration()', () => {
436443

437444
gotScrapingSpy.mockRestore();
438445
getUserSpy.mockRestore();
446+
447+
delete process.env[APIFY_ENV_VARS.IS_AT_HOME];
448+
await expect(Actor.createProxyConfiguration({ groups })).resolves.toBeInstanceOf(ProxyConfiguration);
439449
});
440450

441451
test('should not throw when access check is unresponsive', async () => {

0 commit comments

Comments
 (0)