Skip to content

Commit bd3ea3a

Browse files
raju-opticlaude
andauthored
[FSSDK-13442] Settle the close promise after client init failure (#1189)
## Summary After a failed init, `close()` and `onTerminated()` never settled. The failure handler only rejected `startPromise`, and `stop()` does nothing once the client is `Failed`, so awaiting `close()` hung (e.g. with an invalid datafile). - On start failure, reject `stopPromise` with the init error and stop the child services (config manager, event processor, ODP manager) through a shared `stopChildServices()` helper. - `onReady()` clears its timeout in `onRunning().finally()`. Before, a failed init left the timer pending until the timeout (30 s by default), keeping a Node process alive. - Remove the `onReady()` cleanup tasks and `INSTANCE_CLOSED`. `close()` during start already rejects `onRunning()` via `stop()`, so they were redundant. `onReady()` rejects with the same errors as before. `close()` while the client is still starting still resolves. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 77957f4 commit bd3ea3a

3 files changed

Lines changed: 176 additions & 31 deletions

File tree

‎lib/optimizely/index.spec.ts‎

Lines changed: 142 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
* See the License for the specific language governing permissions and
1414
* limitations under the License.
1515
*/
16-
import { describe, it, expect, vi, beforeEach } from 'vitest';
16+
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
1717
import Optimizely from '.';
1818
import { getMockProjectConfigManager } from '../tests/mock/mock_project_config_manager';
1919
import * as jsonSchemaValidator from '../utils/json_schema_validator';
@@ -32,6 +32,10 @@ import { ImpressionEvent } from '../event_processor/event_builder/user_event';
3232
import { OptimizelyDecideOption } from '../shared_types';
3333
import { NOTIFICATION_TYPES, DECISION_NOTIFICATION_TYPES } from '../notification_center/type';
3434
import { ODP_MANAGER_MISSING } from 'error_message';
35+
import { resolvablePromise } from '../utils/promise/resolvablePromise';
36+
import { ServiceState, SERVICE_STOPPED_BEFORE_RUNNING } from '../service';
37+
import { sprintf } from '../utils/fns';
38+
import { ProjectConfigManager } from '../project_config/project_config_manager';
3539

3640

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

141+
describe('start failure', () => {
142+
const getFailingProjectConfigManager = (err: Error) => {
143+
const onRunning = resolvablePromise<void>();
144+
onRunning.promise.catch(() => {});
145+
onRunning.reject(err);
146+
return getMockProjectConfigManager({ onRunning: onRunning.promise });
147+
};
148+
149+
const getSpiedChildServices = (projectConfigManager: ProjectConfigManager) => {
150+
const eventProcessor = getForwardingEventProcessor(eventDispatcher);
151+
const odpManager = extractOdpManager(createOdpManager({}))!;
152+
153+
// spy on projectConfigManager.stop only if it is not already a spy
154+
if (!vi.isMockFunction(projectConfigManager.stop)) {
155+
vi.spyOn(projectConfigManager, 'stop');
156+
}
157+
vi.spyOn(eventProcessor, 'stop');
158+
vi.spyOn(odpManager, 'stop');
159+
160+
return { projectConfigManager, eventProcessor, odpManager };
161+
};
162+
163+
const createClient = (
164+
projectConfigManager: ProjectConfigManager,
165+
eventProcessor = getForwardingEventProcessor(eventDispatcher),
166+
odpManager = extractOdpManager(createOdpManager({})),
167+
) => new Optimizely({
168+
clientEngine: 'node-sdk',
169+
projectConfigManager,
170+
jsonSchemaValidator,
171+
logger,
172+
eventProcessor,
173+
odpManager,
174+
cmabService: {} as any,
175+
});
176+
177+
// The onReady() tests below use fake timers and never advance past the timeout,
178+
// so the timeout can't fire. If onReady() waited for it instead of rejecting
179+
// with the start error right away, the test would time out.
180+
afterEach(() => {
181+
vi.useRealTimers();
182+
});
183+
184+
it('should reject onReady() immediately with the start error if start has already failed', async () => {
185+
vi.useFakeTimers();
186+
const err = new Error('config failed');
187+
const client = createClient(getFailingProjectConfigManager(err));
188+
189+
await expect(client.onRunning()).rejects.toBe(err);
190+
expect(client.getState()).toBe(ServiceState.Failed);
191+
192+
await expect(client.onReady({ timeout: 30000 })).rejects.toBe(err);
193+
expect(vi.getTimerCount()).toBe(0);
194+
});
195+
196+
it('should reject onReady() immediately with the start error if start fails while onReady() is waiting', async () => {
197+
vi.useFakeTimers();
198+
const onRunning = resolvablePromise<void>();
199+
onRunning.promise.catch(() => {});
200+
const client = createClient(getMockProjectConfigManager({ onRunning: onRunning.promise }));
201+
202+
const readyPromise = client.onReady({ timeout: 30000 });
203+
await vi.advanceTimersByTimeAsync(500);
204+
205+
const err = new Error('config failed');
206+
onRunning.reject(err);
207+
208+
await expect(readyPromise).rejects.toBe(err);
209+
expect(client.getState()).toBe(ServiceState.Failed);
210+
expect(vi.getTimerCount()).toBe(0);
211+
});
212+
213+
it('should reject onReady() immediately if close() is called while onReady() is waiting', async () => {
214+
vi.useFakeTimers();
215+
const onRunning = resolvablePromise<void>();
216+
const client = createClient(getMockProjectConfigManager({ onRunning: onRunning.promise }));
217+
218+
const readyPromise = client.onReady({ timeout: 30000 });
219+
await vi.advanceTimersByTimeAsync(500);
220+
221+
const closePromise = client.close();
222+
223+
await expect(readyPromise).rejects.toThrow(sprintf(SERVICE_STOPPED_BEFORE_RUNNING, 'Client'));
224+
await expect(closePromise).resolves.toBeUndefined();
225+
expect(client.getState()).toBe(ServiceState.Terminated);
226+
expect(vi.getTimerCount()).toBe(0);
227+
});
228+
229+
it('should reject onTerminated() and close() with the start error', async () => {
230+
const err = new Error('config failed');
231+
const client = createClient(getFailingProjectConfigManager(err));
232+
233+
await expect(client.onRunning()).rejects.toBe(err);
234+
await expect(client.onTerminated()).rejects.toBe(err);
235+
await expect(client.close()).rejects.toBe(err);
236+
expect(client.getState()).toBe(ServiceState.Failed);
237+
});
238+
239+
it('should stop the child services', async () => {
240+
const err = new Error('config failed');
241+
const { projectConfigManager, eventProcessor, odpManager } =
242+
getSpiedChildServices(getFailingProjectConfigManager(err));
243+
244+
const client = createClient(projectConfigManager, eventProcessor, odpManager);
245+
246+
await expect(client.onRunning()).rejects.toBe(err);
247+
248+
expect(projectConfigManager.stop).toHaveBeenCalledOnce();
249+
expect(eventProcessor.stop).toHaveBeenCalledOnce();
250+
expect(odpManager.stop).toHaveBeenCalledOnce();
251+
});
252+
253+
it('should resolve close() and stop each child service once if close() is called while starting', async () => {
254+
// child services reject onRunning() when stopped before running
255+
const onRunning = resolvablePromise<void>();
256+
onRunning.promise.catch(() => {});
257+
const mockConfigManager = getMockProjectConfigManager({ onRunning: onRunning.promise });
258+
vi.spyOn(mockConfigManager, 'stop').mockImplementation(() => {
259+
onRunning.reject(new Error('stopped before running'));
260+
});
261+
262+
const { projectConfigManager, eventProcessor, odpManager } = getSpiedChildServices(mockConfigManager);
263+
264+
const client = createClient(projectConfigManager, eventProcessor, odpManager);
265+
expect(client.getState()).toBe(ServiceState.Starting);
266+
267+
await expect(client.close()).resolves.toBeUndefined();
268+
await expect(client.onRunning()).rejects.toThrow();
269+
expect(client.getState()).toBe(ServiceState.Terminated);
270+
271+
// stopped by stop() only, not again by the start failure handler
272+
expect(projectConfigManager.stop).toHaveBeenCalledOnce();
273+
expect(eventProcessor.stop).toHaveBeenCalledOnce();
274+
expect(odpManager.stop).toHaveBeenCalledOnce();
275+
});
276+
});
277+
137278
describe('decideAsync', () => {
138279
it('should return an error decision with correct reasons if decisionService returns error', async () => {
139280
const projectConfig = createProjectConfig(JSON.stringify(getDecisionTestDatafile()));

‎lib/optimizely/index.tests.js‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ import {
4747
SERVICE_STOPPED_BEFORE_RUNNING
4848
} from 'error_message';
4949

50-
import { ONREADY_TIMEOUT, INSTANCE_CLOSED } from './';
50+
import { ONREADY_TIMEOUT } from './';
5151
import {
5252
AUDIENCE_EVALUATION_RESULT_COMBINED,
5353
USER_NOT_IN_EXPERIMENT,

‎lib/optimizely/index.ts‎

Lines changed: 33 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ import {
6060
NODE_CLIENT_ENGINE,
6161
CLIENT_VERSION,
6262
} from '../utils/enums';
63-
import { Fn, Maybe, OpType } from '../utils/type';
63+
import { Maybe, OpType } from '../utils/type';
6464
import { resolvablePromise } from '../utils/promise/resolvablePromise';
6565

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

114114
type DecisionReasons = (string | number)[];
115115

116-
export const INSTANCE_CLOSED = 'Instance closed';
117116
export const ONREADY_TIMEOUT = 'onReady timeout expired after %s ms';
118117
export const INVALID_IDENTIFIER = 'Invalid identifier';
119118
export const INVALID_ATTRIBUTES = 'Invalid attributes';
@@ -142,8 +141,6 @@ export type OptimizelyOptions = {
142141
}
143142

144143
export default class Optimizely extends BaseService implements Client {
145-
private cleanupTasks: Map<number, Fn> = new Map();
146-
private nextCleanupTaskId = 0;
147144
private clientEngine: string;
148145
private clientVersion: string;
149146
private errorNotifier?: ErrorNotifier;
@@ -277,12 +274,32 @@ export default class Optimizely extends BaseService implements Client {
277274
this.odpManager?.setVuid(vuid);
278275
}
279276
}).catch((err) => {
280-
this.state = ServiceState.Failed;
281277
this.errorReporter.report(err);
282-
this.startPromise.reject(err);
278+
this.handleStartFailure(err);
283279
});
284280
}
285281

282+
private handleStartFailure(err: Error): void {
283+
// If stop() was called while starting, the child services reject their onRunning()
284+
// promises as a result. stop() is responsible for settling the stopPromise in that case.
285+
if (this.isDone()) {
286+
return;
287+
}
288+
289+
this.state = ServiceState.Failed;
290+
this.startPromise.reject(err);
291+
// stop() is a no-op once the client has failed, so the stopPromise must be settled
292+
// here, otherwise close() / onTerminated() would never settle.
293+
this.stopPromise.reject(err);
294+
this.stopChildServices();
295+
}
296+
297+
private stopChildServices(): void {
298+
this.projectConfigManager.stop();
299+
this.eventProcessor?.stop();
300+
this.odpManager?.stop();
301+
}
302+
286303
/**
287304
* Returns the project configuration retrieved from projectConfigManager
288305
* @return {projectConfig.ProjectConfig}
@@ -1300,14 +1317,9 @@ export default class Optimizely extends BaseService implements Client {
13001317
}
13011318

13021319
this.state = ServiceState.Stopping;
1303-
1304-
this.projectConfigManager.stop();
1305-
this.eventProcessor?.stop();
1306-
this.odpManager?.stop();
1320+
this.stopChildServices();
13071321
this.notificationCenter.clearAllNotificationListeners();
13081322

1309-
this.cleanupTasks.forEach((onClose) => onClose());
1310-
13111323
Promise.all([
13121324
this.projectConfigManager.onTerminated(),
13131325
this.eventProcessor ? this.eventProcessor.onTerminated() : Promise.resolve(),
@@ -1357,26 +1369,18 @@ export default class Optimizely extends BaseService implements Client {
13571369

13581370
const timeoutPromise = resolvablePromise();
13591371

1360-
const cleanupTaskId = this.nextCleanupTaskId++;
1361-
1362-
const onReadyTimeout = () => {
1363-
this.cleanupTasks.delete(cleanupTaskId);
1372+
const readyTimeout = setTimeout(() => {
13641373
timeoutPromise.reject(new Error(
13651374
sprintf(ONREADY_TIMEOUT, timeoutValue)
13661375
));
1367-
};
1368-
1369-
const readyTimeout = setTimeout(onReadyTimeout, timeoutValue);
1370-
1371-
this.cleanupTasks.set(cleanupTaskId, () => {
1372-
clearTimeout(readyTimeout);
1373-
timeoutPromise.reject(new Error(INSTANCE_CLOSED));
1374-
});
1375-
1376-
return Promise.race([this.onRunning().then(() => {
1377-
clearTimeout(readyTimeout);
1378-
this.cleanupTasks.delete(cleanupTaskId);
1379-
}), timeoutPromise]);
1376+
}, timeoutValue);
1377+
1378+
// onRunning() settles in every case that should end the wait, including
1379+
// close() before the client is running, which rejects it via stop().
1380+
return Promise.race([
1381+
this.onRunning().finally(() => clearTimeout(readyTimeout)),
1382+
timeoutPromise,
1383+
]);
13801384
}
13811385

13821386
//============ decide ============//

0 commit comments

Comments
 (0)