-
Notifications
You must be signed in to change notification settings - Fork 31
feat: Add identify timeout to client-sdk. #420
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
yusinto
merged 15 commits into
main
from
yus/sc-239001/add-identify-timeout-option-to-rn-sdk
Apr 3, 2024
Merged
Changes from all commits
Commits
Show all changes
15 commits
Select commit
Hold shift + click to select a range
5ec18c0
chore: Added identify options.
yusinto f78ff8f
chore: Added timeout function. Added comments.
yusinto c9e5fb1
Update LDClientImpl.ts
yusinto 59f66a5
chore: Added unit tests for timeout.
yusinto 31888fe
fix: Change default timeout to 5 seconds. Improved in-line comments.
yusinto 59906a0
chore: Add defaultIdentifyTimeout class variable so each sdk can spec…
yusinto e47fdb2
chore: Added more unit tests.
yusinto 0c80446
chore: Log timeout error. Added tests. Improve error listener arg type.
yusinto 53d4845
chore: Improve error logging.
yusinto 409f340
chore: Improve high timeout warning.
yusinto d9c0469
chore: Renamed timeoutSeconds to timeout. Renamed timeout function to…
yusinto 381feee
chore: Fixed broken tests due to warning string.
yusinto c45a867
chore: Minor comment improvement.
yusinto d64edae
chore: Introduce customizable highTimeoutThreshold to replace default…
yusinto ebb5d86
chore: Fixed broken unit tests.
yusinto File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,19 @@ | ||
| import { LDLogger } from '../api'; | ||
|
|
||
| /** | ||
| * Returns a promise which errors after t seconds. | ||
| * | ||
| * @param t Timeout in seconds. | ||
| * @param taskName Name of task being timed for logging and error reporting. | ||
| * @param logger {@link LDLogger} object. | ||
| */ | ||
| const timedPromise = (t: number, taskName: string, logger?: LDLogger) => | ||
| new Promise<void>((_res, reject) => { | ||
| setTimeout(() => { | ||
| const e = `${taskName} timed out after ${t} seconds.`; | ||
| logger?.error(e); | ||
| reject(new Error(e)); | ||
| }, t * 1000); | ||
| }); | ||
|
|
||
| export default timedPromise; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
148 changes: 148 additions & 0 deletions
148
packages/shared/sdk-client/src/LDClientImpl.timeout.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,148 @@ | ||
| import { AutoEnvAttributes, clone, LDContext } from '@launchdarkly/js-sdk-common'; | ||
| import { basicPlatform, logger, setupMockStreamingProcessor } from '@launchdarkly/private-js-mocks'; | ||
|
|
||
| import * as mockResponseJson from './evaluation/mockResponse.json'; | ||
| import LDClientImpl from './LDClientImpl'; | ||
| import { Flags } from './types'; | ||
| import { toMulti } from './utils/addAutoEnv'; | ||
|
|
||
| jest.mock('@launchdarkly/js-sdk-common', () => { | ||
| const actual = jest.requireActual('@launchdarkly/js-sdk-common'); | ||
| const m = jest.requireActual('@launchdarkly/private-js-mocks'); | ||
| return { | ||
| ...actual, | ||
| ...{ | ||
| internal: { | ||
| ...actual.internal, | ||
| StreamingProcessor: m.MockStreamingProcessor, | ||
| }, | ||
| }, | ||
| }; | ||
| }); | ||
|
|
||
| const testSdkKey = 'test-sdk-key'; | ||
| const carContext: LDContext = { kind: 'car', key: 'test-car' }; | ||
|
|
||
| let ldc: LDClientImpl; | ||
| let defaultPutResponse: Flags; | ||
|
|
||
| describe('sdk-client identify timeout', () => { | ||
| beforeAll(() => { | ||
| jest.useFakeTimers(); | ||
| }); | ||
|
|
||
| beforeEach(() => { | ||
| defaultPutResponse = clone<Flags>(mockResponseJson); | ||
|
|
||
| // simulate streamer error after a long timeout | ||
| setupMockStreamingProcessor(true, defaultPutResponse, undefined, undefined, 30); | ||
|
|
||
| ldc = new LDClientImpl(testSdkKey, AutoEnvAttributes.Enabled, basicPlatform, { | ||
| logger, | ||
| sendEvents: false, | ||
| }); | ||
| jest | ||
| .spyOn(LDClientImpl.prototype as any, 'createStreamUriPath') | ||
| .mockReturnValue('/stream/path'); | ||
| }); | ||
|
|
||
| afterEach(() => { | ||
| jest.resetAllMocks(); | ||
| }); | ||
|
|
||
| // streamer is setup to error in beforeEach to cause a timeout | ||
| test('rejects with default timeout of 5s', async () => { | ||
| jest.advanceTimersByTimeAsync(ldc.identifyTimeout * 1000).then(); | ||
| await expect(ldc.identify(carContext)).rejects.toThrow(/identify timed out/); | ||
| expect(logger.error).toHaveBeenCalledWith(expect.stringMatching(/identify timed out/)); | ||
| }); | ||
|
|
||
| // streamer is setup to error in beforeEach to cause a timeout | ||
| test('rejects with custom timeout', async () => { | ||
| const timeout = 15; | ||
| jest.advanceTimersByTimeAsync(timeout * 1000).then(); | ||
|
|
||
| await expect(ldc.identify(carContext, { timeout })).rejects.toThrow(/identify timed out/); | ||
| }); | ||
|
|
||
| test('resolves with default timeout', async () => { | ||
| setupMockStreamingProcessor(false, defaultPutResponse); | ||
| jest.advanceTimersByTimeAsync(ldc.identifyTimeout * 1000).then(); | ||
|
|
||
| await expect(ldc.identify(carContext)).resolves.toBeUndefined(); | ||
|
|
||
| expect(ldc.getContext()).toEqual(expect.objectContaining(toMulti(carContext))); | ||
| expect(ldc.allFlags()).toEqual({ | ||
| 'dev-test-flag': true, | ||
| 'easter-i-tunes-special': false, | ||
| 'easter-specials': 'no specials', | ||
| fdsafdsafdsafdsa: true, | ||
| 'log-level': 'warn', | ||
| 'moonshot-demo': true, | ||
| test1: 's1', | ||
| 'this-is-a-test': true, | ||
| }); | ||
| }); | ||
|
|
||
| test('resolves with custom timeout', async () => { | ||
| const timeout = 15; | ||
| setupMockStreamingProcessor(false, defaultPutResponse); | ||
| jest.advanceTimersByTimeAsync(timeout).then(); | ||
|
|
||
| await expect(ldc.identify(carContext, { timeout })).resolves.toBeUndefined(); | ||
|
|
||
| expect(ldc.getContext()).toEqual(expect.objectContaining(toMulti(carContext))); | ||
| expect(ldc.allFlags()).toEqual({ | ||
| 'dev-test-flag': true, | ||
| 'easter-i-tunes-special': false, | ||
| 'easter-specials': 'no specials', | ||
| fdsafdsafdsafdsa: true, | ||
| 'log-level': 'warn', | ||
| 'moonshot-demo': true, | ||
| test1: 's1', | ||
| 'this-is-a-test': true, | ||
| }); | ||
| }); | ||
|
|
||
| test('setting high timeout threshold with internalOptions', async () => { | ||
| const highTimeoutThreshold = 20; | ||
| setupMockStreamingProcessor(false, defaultPutResponse); | ||
| ldc = new LDClientImpl( | ||
| testSdkKey, | ||
| AutoEnvAttributes.Enabled, | ||
| basicPlatform, | ||
| { | ||
| logger, | ||
| sendEvents: false, | ||
| }, | ||
| { highTimeoutThreshold }, | ||
| ); | ||
| const customTimeout = 10; | ||
| jest.advanceTimersByTimeAsync(customTimeout * 1000).then(); | ||
| await ldc.identify(carContext, { timeout: customTimeout }); | ||
|
|
||
| expect(ldc.identifyTimeout).toEqual(10); | ||
| expect(logger.warn).not.toHaveBeenCalledWith(expect.stringMatching(/high timeout/)); | ||
| }); | ||
|
|
||
| test('warning when timeout is too high', async () => { | ||
| const highTimeout = 60; | ||
| setupMockStreamingProcessor(false, defaultPutResponse); | ||
| jest.advanceTimersByTimeAsync(highTimeout * 1000).then(); | ||
|
|
||
| await ldc.identify(carContext, { timeout: highTimeout }); | ||
|
|
||
| expect(logger.warn).toHaveBeenCalledWith(expect.stringMatching(/high timeout/)); | ||
| }); | ||
|
|
||
| test('safe timeout should not warn', async () => { | ||
| const { identifyTimeout } = ldc; | ||
| const safeTimeout = identifyTimeout; | ||
| setupMockStreamingProcessor(false, defaultPutResponse); | ||
| jest.advanceTimersByTimeAsync(identifyTimeout * 1000).then(); | ||
|
|
||
| await ldc.identify(carContext, { timeout: safeTimeout }); | ||
|
|
||
| expect(logger.warn).not.toHaveBeenCalledWith(expect.stringMatching(/high timeout/)); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -14,11 +14,13 @@ import { | |
| Platform, | ||
| ProcessStreamResponse, | ||
| EventName as StreamEventName, | ||
| timedPromise, | ||
| TypeValidators, | ||
| } from '@launchdarkly/js-sdk-common'; | ||
|
|
||
| import { ConnectionMode, LDClient, type LDOptions } from './api'; | ||
| import LDEmitter, { EventName } from './api/LDEmitter'; | ||
| import { LDIdentifyOptions } from './api/LDIdentifyOptions'; | ||
| import Configuration from './configuration'; | ||
| import createDiagnosticsManager from './diagnostics/createDiagnosticsManager'; | ||
| import createEventProcessor from './events/createEventProcessor'; | ||
|
|
@@ -34,9 +36,12 @@ export default class LDClientImpl implements LDClient { | |
| context?: LDContext; | ||
| diagnosticsManager?: internal.DiagnosticsManager; | ||
| eventProcessor?: internal.EventProcessor; | ||
| identifyTimeout: number = 5; | ||
| logger: LDLogger; | ||
| streamer?: internal.StreamingProcessor; | ||
|
|
||
| readonly highTimeoutThreshold: number = 15; | ||
|
|
||
| private eventFactoryDefault = new EventFactory(false); | ||
| private eventFactoryWithReasons = new EventFactory(true); | ||
| private emitter: LDEmitter; | ||
|
|
@@ -100,7 +105,7 @@ export default class LDClientImpl implements LDClient { | |
|
|
||
| if (this.context) { | ||
| // identify will start streamer | ||
| return this.identify(this.context); | ||
| return this.identify(this.context, { timeout: this.identifyTimeout }); | ||
| } | ||
| break; | ||
| default: | ||
|
|
@@ -233,13 +238,13 @@ export default class LDClientImpl implements LDClient { | |
| */ | ||
| protected createStreamUriPath(_context: LDContext): string { | ||
| throw new Error( | ||
| 'createStreamUriPath not implemented. Client sdks must implement createStreamUriPath for streamer to work', | ||
| 'createStreamUriPath not implemented. Client sdks must implement createStreamUriPath for streamer to work.', | ||
| ); | ||
| } | ||
|
|
||
| private createIdentifyPromise() { | ||
| private createIdentifyPromise(timeout: number) { | ||
| let res: any; | ||
| const p = new Promise<void>((resolve, reject) => { | ||
| const slow = new Promise<void>((resolve, reject) => { | ||
| res = resolve; | ||
|
|
||
| if (this.identifyChangeListener) { | ||
|
|
@@ -252,7 +257,7 @@ export default class LDClientImpl implements LDClient { | |
| this.identifyChangeListener = (c: LDContext, changedKeys: string[]) => { | ||
| this.logger.debug(`change: context: ${JSON.stringify(c)}, flags: ${changedKeys}`); | ||
| }; | ||
| this.identifyErrorListener = (c: LDContext, err: any) => { | ||
| this.identifyErrorListener = (c: LDContext, err: Error) => { | ||
| this.logger.debug(`error: ${err}, context: ${JSON.stringify(c)}`); | ||
| reject(err); | ||
| }; | ||
|
|
@@ -261,15 +266,34 @@ export default class LDClientImpl implements LDClient { | |
| this.emitter.on('error', this.identifyErrorListener); | ||
| }); | ||
|
|
||
| return { identifyPromise: p, identifyResolve: res }; | ||
| const timed = timedPromise(timeout, 'identify', this.logger); | ||
| const raced = Promise.race([timed, slow]); | ||
yusinto marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| return { identifyPromise: raced, identifyResolve: res }; | ||
| } | ||
|
|
||
| private async getFlagsFromStorage(canonicalKey: string): Promise<Flags | undefined> { | ||
| const f = await this.platform.storage?.get(canonicalKey); | ||
| return f ? JSON.parse(f) : undefined; | ||
| } | ||
|
|
||
| async identify(pristineContext: LDContext): Promise<void> { | ||
| /** | ||
| * Identifies a context to LaunchDarkly. See {@link LDClient.identify}. | ||
| * | ||
| * @param pristineContext The LDContext object to be identified. | ||
| * @param identifyOptions Optional configuration. See {@link LDIdentifyOptions}. | ||
| * | ||
| * @returns {Promise<void>}. | ||
| */ | ||
| async identify(pristineContext: LDContext, identifyOptions?: LDIdentifyOptions): Promise<void> { | ||
| if (identifyOptions?.timeout) { | ||
| this.identifyTimeout = identifyOptions.timeout; | ||
| } | ||
|
|
||
| if (this.identifyTimeout > this.highTimeoutThreshold) { | ||
| this.logger.warn('identify called with high timeout parameter.'); | ||
| } | ||
|
Comment on lines
+288
to
+295
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. shout: This is the core change. |
||
|
|
||
| let context = await ensureKey(pristineContext, this.platform); | ||
|
|
||
| if (this.autoEnvAttributes === AutoEnvAttributes.Enabled) { | ||
|
|
@@ -285,7 +309,7 @@ export default class LDClientImpl implements LDClient { | |
| } | ||
|
|
||
| this.eventProcessor?.sendEvent(this.eventFactoryDefault.identifyEvent(checkedContext)); | ||
| const { identifyPromise, identifyResolve } = this.createIdentifyPromise(); | ||
| const { identifyPromise, identifyResolve } = this.createIdentifyPromise(this.identifyTimeout); | ||
| this.logger.debug(`Identifying ${JSON.stringify(context)}`); | ||
|
|
||
| const flagsStorage = await this.getFlagsFromStorage(checkedContext.canonicalKey); | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,11 @@ | ||
| export interface LDIdentifyOptions { | ||
| /** | ||
| * In seconds. Determines when the identify promise resolves if no flags have been | ||
| * returned from the network. If you use a large timeout and await it, then | ||
| * any network delays will cause your application to wait a long time before | ||
| * continuing execution. | ||
| * | ||
| * Defaults to 5 seconds. | ||
| */ | ||
| timeout: number; | ||
| } |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Harcoded to 5s by default. This will be set in
identifyif provided.