diff --git a/lib/optimizely/index.spec.ts b/lib/optimizely/index.spec.ts index de52df270..2b60e3b75 100644 --- a/lib/optimizely/index.spec.ts +++ b/lib/optimizely/index.spec.ts @@ -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'; @@ -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 = [ @@ -134,6 +138,143 @@ describe('Optimizely', () => { expect(odpManager!.setLogger).toHaveBeenCalledWith(odpManagerChildLogger); }); + describe('start failure', () => { + const getFailingProjectConfigManager = (err: Error) => { + const onRunning = resolvablePromise(); + 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(); + 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(); + 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(); + 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())); diff --git a/lib/optimizely/index.tests.js b/lib/optimizely/index.tests.js index d1ea1b8b3..a63d327a1 100644 --- a/lib/optimizely/index.tests.js +++ b/lib/optimizely/index.tests.js @@ -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, diff --git a/lib/optimizely/index.ts b/lib/optimizely/index.ts index 0d194b08e..b403b99ab 100644 --- a/lib/optimizely/index.ts +++ b/lib/optimizely/index.ts @@ -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'; @@ -113,7 +113,6 @@ type StringInputs = Partial>; 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'; @@ -142,8 +141,6 @@ export type OptimizelyOptions = { } export default class Optimizely extends BaseService implements Client { - private cleanupTasks: Map = new Map(); - private nextCleanupTaskId = 0; private clientEngine: string; private clientVersion: string; private errorNotifier?: ErrorNotifier; @@ -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); }); } + 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} @@ -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(), @@ -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 ============//