Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
143 changes: 142 additions & 1 deletion lib/optimizely/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import Optimizely from '.';
import { getMockProjectConfigManager } from '../tests/mock/mock_project_config_manager';
import * as jsonSchemaValidator from '../utils/json_schema_validator';
Expand All @@ -32,6 +32,10 @@ import { ImpressionEvent } from '../event_processor/event_builder/user_event';
import { OptimizelyDecideOption } from '../shared_types';
import { NOTIFICATION_TYPES, DECISION_NOTIFICATION_TYPES } from '../notification_center/type';
import { ODP_MANAGER_MISSING } from 'error_message';
import { resolvablePromise } from '../utils/promise/resolvablePromise';
import { ServiceState, SERVICE_STOPPED_BEFORE_RUNNING } from '../service';
import { sprintf } from '../utils/fns';
import { ProjectConfigManager } from '../project_config/project_config_manager';


const holdoutData = [
Expand Down Expand Up @@ -134,6 +138,143 @@ describe('Optimizely', () => {
expect(odpManager!.setLogger).toHaveBeenCalledWith(odpManagerChildLogger);
});

describe('start failure', () => {
const getFailingProjectConfigManager = (err: Error) => {
const onRunning = resolvablePromise<void>();
onRunning.promise.catch(() => {});
onRunning.reject(err);
return getMockProjectConfigManager({ onRunning: onRunning.promise });
};

const getSpiedChildServices = (projectConfigManager: ProjectConfigManager) => {
const eventProcessor = getForwardingEventProcessor(eventDispatcher);
const odpManager = extractOdpManager(createOdpManager({}))!;

// spy on projectConfigManager.stop only if it is not already a spy
if (!vi.isMockFunction(projectConfigManager.stop)) {
vi.spyOn(projectConfigManager, 'stop');
}
vi.spyOn(eventProcessor, 'stop');
vi.spyOn(odpManager, 'stop');

return { projectConfigManager, eventProcessor, odpManager };
};

const createClient = (
projectConfigManager: ProjectConfigManager,
eventProcessor = getForwardingEventProcessor(eventDispatcher),
odpManager = extractOdpManager(createOdpManager({})),
) => new Optimizely({
clientEngine: 'node-sdk',
projectConfigManager,
jsonSchemaValidator,
logger,
eventProcessor,
odpManager,
cmabService: {} as any,
});

// The onReady() tests below use fake timers and never advance past the timeout,
// so the timeout can't fire. If onReady() waited for it instead of rejecting
// with the start error right away, the test would time out.
afterEach(() => {
vi.useRealTimers();
});

it('should reject onReady() immediately with the start error if start has already failed', async () => {
vi.useFakeTimers();
const err = new Error('config failed');
const client = createClient(getFailingProjectConfigManager(err));

await expect(client.onRunning()).rejects.toBe(err);
expect(client.getState()).toBe(ServiceState.Failed);

await expect(client.onReady({ timeout: 30000 })).rejects.toBe(err);
expect(vi.getTimerCount()).toBe(0);
});

it('should reject onReady() immediately with the start error if start fails while onReady() is waiting', async () => {
vi.useFakeTimers();
const onRunning = resolvablePromise<void>();
onRunning.promise.catch(() => {});
const client = createClient(getMockProjectConfigManager({ onRunning: onRunning.promise }));

const readyPromise = client.onReady({ timeout: 30000 });
await vi.advanceTimersByTimeAsync(500);

const err = new Error('config failed');
onRunning.reject(err);

await expect(readyPromise).rejects.toBe(err);
expect(client.getState()).toBe(ServiceState.Failed);
expect(vi.getTimerCount()).toBe(0);
});

it('should reject onReady() immediately if close() is called while onReady() is waiting', async () => {
vi.useFakeTimers();
const onRunning = resolvablePromise<void>();
const client = createClient(getMockProjectConfigManager({ onRunning: onRunning.promise }));

const readyPromise = client.onReady({ timeout: 30000 });
await vi.advanceTimersByTimeAsync(500);

const closePromise = client.close();

await expect(readyPromise).rejects.toThrow(sprintf(SERVICE_STOPPED_BEFORE_RUNNING, 'Client'));
await expect(closePromise).resolves.toBeUndefined();
expect(client.getState()).toBe(ServiceState.Terminated);
expect(vi.getTimerCount()).toBe(0);
});

it('should reject onTerminated() and close() with the start error', async () => {
const err = new Error('config failed');
const client = createClient(getFailingProjectConfigManager(err));

await expect(client.onRunning()).rejects.toBe(err);
await expect(client.onTerminated()).rejects.toBe(err);
await expect(client.close()).rejects.toBe(err);
expect(client.getState()).toBe(ServiceState.Failed);
});

it('should stop the child services', async () => {
const err = new Error('config failed');
const { projectConfigManager, eventProcessor, odpManager } =
getSpiedChildServices(getFailingProjectConfigManager(err));

const client = createClient(projectConfigManager, eventProcessor, odpManager);

await expect(client.onRunning()).rejects.toBe(err);

expect(projectConfigManager.stop).toHaveBeenCalledOnce();
expect(eventProcessor.stop).toHaveBeenCalledOnce();
expect(odpManager.stop).toHaveBeenCalledOnce();
});

it('should resolve close() and stop each child service once if close() is called while starting', async () => {
// child services reject onRunning() when stopped before running
const onRunning = resolvablePromise<void>();
onRunning.promise.catch(() => {});
const mockConfigManager = getMockProjectConfigManager({ onRunning: onRunning.promise });
vi.spyOn(mockConfigManager, 'stop').mockImplementation(() => {
onRunning.reject(new Error('stopped before running'));
});

const { projectConfigManager, eventProcessor, odpManager } = getSpiedChildServices(mockConfigManager);

const client = createClient(projectConfigManager, eventProcessor, odpManager);
expect(client.getState()).toBe(ServiceState.Starting);

await expect(client.close()).resolves.toBeUndefined();
await expect(client.onRunning()).rejects.toThrow();
expect(client.getState()).toBe(ServiceState.Terminated);

// stopped by stop() only, not again by the start failure handler
expect(projectConfigManager.stop).toHaveBeenCalledOnce();
expect(eventProcessor.stop).toHaveBeenCalledOnce();
expect(odpManager.stop).toHaveBeenCalledOnce();
});
});

describe('decideAsync', () => {
it('should return an error decision with correct reasons if decisionService returns error', async () => {
const projectConfig = createProjectConfig(JSON.stringify(getDecisionTestDatafile()));
Expand Down
2 changes: 1 addition & 1 deletion lib/optimizely/index.tests.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ import {
SERVICE_STOPPED_BEFORE_RUNNING
} from 'error_message';

import { ONREADY_TIMEOUT, INSTANCE_CLOSED } from './';
import { ONREADY_TIMEOUT } from './';
import {
AUDIENCE_EVALUATION_RESULT_COMBINED,
USER_NOT_IN_EXPERIMENT,
Expand Down
62 changes: 33 additions & 29 deletions lib/optimizely/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ import {
NODE_CLIENT_ENGINE,
CLIENT_VERSION,
} from '../utils/enums';
import { Fn, Maybe, OpType } from '../utils/type';
import { Maybe, OpType } from '../utils/type';
import { resolvablePromise } from '../utils/promise/resolvablePromise';

import { NOTIFICATION_TYPES, DecisionNotificationType, DECISION_NOTIFICATION_TYPES, ActivateListenerPayload } from '../notification_center/type';
Expand Down Expand Up @@ -113,7 +113,6 @@ type StringInputs = Partial<Record<InputKey, unknown>>;

type DecisionReasons = (string | number)[];

export const INSTANCE_CLOSED = 'Instance closed';
export const ONREADY_TIMEOUT = 'onReady timeout expired after %s ms';
export const INVALID_IDENTIFIER = 'Invalid identifier';
export const INVALID_ATTRIBUTES = 'Invalid attributes';
Expand Down Expand Up @@ -142,8 +141,6 @@ export type OptimizelyOptions = {
}

export default class Optimizely extends BaseService implements Client {
private cleanupTasks: Map<number, Fn> = new Map();
private nextCleanupTaskId = 0;
private clientEngine: string;
private clientVersion: string;
private errorNotifier?: ErrorNotifier;
Expand Down Expand Up @@ -277,12 +274,32 @@ export default class Optimizely extends BaseService implements Client {
this.odpManager?.setVuid(vuid);
}
}).catch((err) => {
this.state = ServiceState.Failed;
this.errorReporter.report(err);
this.startPromise.reject(err);
this.handleStartFailure(err);
Comment thread
raju-opti marked this conversation as resolved.
Resolved
});
}

private handleStartFailure(err: Error): void {
// If stop() was called while starting, the child services reject their onRunning()
// promises as a result. stop() is responsible for settling the stopPromise in that case.
if (this.isDone()) {
return;
}

this.state = ServiceState.Failed;
this.startPromise.reject(err);
// stop() is a no-op once the client has failed, so the stopPromise must be settled
// here, otherwise close() / onTerminated() would never settle.
this.stopPromise.reject(err);
this.stopChildServices();
}

private stopChildServices(): void {
this.projectConfigManager.stop();
this.eventProcessor?.stop();
this.odpManager?.stop();
}

/**
* Returns the project configuration retrieved from projectConfigManager
* @return {projectConfig.ProjectConfig}
Expand Down Expand Up @@ -1300,14 +1317,9 @@ export default class Optimizely extends BaseService implements Client {
}

this.state = ServiceState.Stopping;

this.projectConfigManager.stop();
this.eventProcessor?.stop();
this.odpManager?.stop();
this.stopChildServices();
this.notificationCenter.clearAllNotificationListeners();

this.cleanupTasks.forEach((onClose) => onClose());

Promise.all([
this.projectConfigManager.onTerminated(),
this.eventProcessor ? this.eventProcessor.onTerminated() : Promise.resolve(),
Expand Down Expand Up @@ -1357,26 +1369,18 @@ export default class Optimizely extends BaseService implements Client {

const timeoutPromise = resolvablePromise();

const cleanupTaskId = this.nextCleanupTaskId++;

const onReadyTimeout = () => {
this.cleanupTasks.delete(cleanupTaskId);
const readyTimeout = setTimeout(() => {
timeoutPromise.reject(new Error(
sprintf(ONREADY_TIMEOUT, timeoutValue)
));
};

const readyTimeout = setTimeout(onReadyTimeout, timeoutValue);

this.cleanupTasks.set(cleanupTaskId, () => {
clearTimeout(readyTimeout);
timeoutPromise.reject(new Error(INSTANCE_CLOSED));
});

return Promise.race([this.onRunning().then(() => {
clearTimeout(readyTimeout);
this.cleanupTasks.delete(cleanupTaskId);
}), timeoutPromise]);
}, timeoutValue);

// onRunning() settles in every case that should end the wait, including
// close() before the client is running, which rejects it via stop().
return Promise.race([
this.onRunning().finally(() => clearTimeout(readyTimeout)),
timeoutPromise,
]);
}

//============ decide ============//
Expand Down
Loading