Skip to content

Commit

Permalink
[FSSDK-10935] log adjustment
Browse files Browse the repository at this point in the history
  • Loading branch information
junaed-optimizely committed Dec 13, 2024
1 parent d34f250 commit 7c9ee78
Show file tree
Hide file tree
Showing 17 changed files with 86 additions and 44 deletions.
17 changes: 13 additions & 4 deletions lib/error_messages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,8 @@ export const NO_EVENT_PROCESSOR = 'No event processor is provided';
export const NO_VARIATION_FOR_EXPERIMENT_KEY = '%s: No variation key %s defined in datafile for experiment %s.';
export const ODP_CONFIG_NOT_AVAILABLE = '%s: ODP is not integrated to the project.';
export const ODP_EVENT_FAILED = 'ODP event send failed.';
export const ODP_EVENT_MANAGER_IS_NOT_RUNNING = 'ODP event manager is not running.';
export const ODP_EVENTS_SHOULD_HAVE_ATLEAST_ONE_KEY_VALUE = 'ODP events should have at least one key-value pair in identifiers.';
export const ODP_FETCH_QUALIFIED_SEGMENTS_SEGMENTS_MANAGER_MISSING =
'%s: ODP unable to fetch qualified segments (Segments Manager not initialized).';
export const ODP_IDENTIFY_FAILED_EVENT_MANAGER_MISSING =
Expand Down Expand Up @@ -93,7 +95,14 @@ export const INVALID_INPUT_FORMAT = '%s: Provided %s is in an invalid format.';
export const INVALID_DATAFILE_VERSION =
'%s: This version of the JavaScript SDK does not support the given datafile version: %s';
export const INVALID_VARIATION_KEY = '%s: Provided variation key is in an invalid format.';
export const UNABLE_TO_GET_VUID = 'Unable to get VUID - ODP Manager is not instantiated yet.'
export const ERROR_FETCHING_DATAFILE = 'Error fetching datafile: %s'
export const DATAFILE_FETCH_REQUEST_FAILED = 'Datafile fetch request failed with status: %s'
export const ONRUNNING_ERROR = 'onRunning error'
export const UNABLE_TO_GET_VUID = 'Unable to get VUID - ODP Manager is not instantiated yet.';
export const ERROR_FETCHING_DATAFILE = 'Error fetching datafile: %s';
export const DATAFILE_FETCH_REQUEST_FAILED = 'Datafile fetch request failed with status: %s';
export const ONRUNNING_ERROR = 'onRunning error';
export const EVENT_DATA_FOUND_TO_BE_INVALID = 'Event data found to be invalid.';
export const EVENT_ACTION_INVALID = 'Event action invalid.';
export const FAILED_TO_SEND_ODP_EVENTS = 'failed to send odp events';
export const UNABLE_TO_OVERWRITE_GLOBAL_WINDOW = 'Unable to overwrite global.window.';
export const UNABLE_TO_GET_VUID_VUID_MANAGER_NOT_AVAILABLE = 'Unable to get VUID - VuidManager is not available'


5 changes: 5 additions & 0 deletions lib/exception_messages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,20 +23,25 @@ export const SEND_BEACON_FAILED = 'sendBeacon failed';
export const CANNOT_START_WITHOUT_ODP_CONFIG = 'cannot start without ODP config';
export const START_CALLED_WHEN_ODP_IS_NOT_INTEGRATED = 'start() called when ODP is not integrated';
export const ODP_ACTION_IS_NOT_VALID = 'ODP action is not valid (cannot be empty).';
export const ODP_MANAGER_STOPPED_BEFORE_RUNNING = 'odp manager stopped before running';
export const ODP_EVENT_MANAGER_STOPPED = "ODP event manager stopped before it could start";
export const ONREADY_TIMEOUT_EXPIRED = 'onReady timeout expired after %s ms';
export const INSTANCE_CLOSED = 'Instance closed';
export const DATAFILE_MANAGER_STOPPED = 'Datafile manager stopped before it could be started';
export const DATAFILE_MANAGER_FAILED_TO_START = 'Datafile manager failed to start';
export const FAILED_TO_FETCH_DATAFILE = 'Failed to fetch datafile';
export const FAILED_TO_START = 'Failed to start';
export const FAILED_TO_STOP = 'Failed to stop';
export const YOU_MUST_PROVIDE_DATAFILE_IN_SSR = 'You must provide datafile in SSR';
export const YOU_MUST_PROVIDE_AT_LEAST_ONE_OF_SDKKEY_OR_DATAFILE = 'You must provide at least one of sdkKey or datafile';
export const RETRY_CANCELLED = 'Retry cancelled';
export const REQUEST_ERROR = 'Request error';
export const REQUEST_FAILED = 'Request failed';
export const UNSUPPORTED_PROTOCOL = 'Unsupported protocol: %s';
export const REQUEST_TIMEOUT = 'Request timed out';
export const NO_STATUS_CODE_IN_RESPONSE = 'No status code in response';
export const MODULE_NOT_FOUND_REACT_NATIVE_ASYNC_STORAGE = 'Module not found: @react-native-async-storage/async-storage';
export const MODULE_NOT_FOUND_REACT_NATIVE_NETINFO = 'Module not found: @react-native-community/netinfo';
export const INVALID_CONFIG_OR_SOMETHING = 'Invalid config or something';
export const PROMISE_SHOULD_NOT_HAVE_RESOLVED = 'Promise should not have resolved';
export const VUID_IS_NOT_SUPPORTED_IN_NODEJS= 'VUID is not supported in Node.js environment';
5 changes: 2 additions & 3 deletions lib/index.browser.tests.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,7 @@ import optimizelyFactory from './index.browser';
import configValidator from './utils/config_validator';
import { getMockProjectConfigManager } from './tests/mock/mock_project_config_manager';
import { createProjectConfig } from './project_config/project_config';
import { ODP_EVENT_FAILED_ODP_MANAGER_MISSING } from './error_messages';
import { ODP_DISABLED, ODP_SEND_EVENT_IDENTIFIER_CONVERSION_FAILED } from './log_messages';
import { UNABLE_TO_OVERWRITE_GLOBAL_WINDOW } from './error_messages';
import { INVALID_CONFIG_OR_SOMETHING } from './exception_messages';


Expand Down Expand Up @@ -57,7 +56,7 @@ if (!global.window) {
localStorage: new MockLocalStorage(),
};
} catch (e) {
console.error('Unable to overwrite global.window.');
console.error(UNABLE_TO_OVERWRITE_GLOBAL_WINDOW);
}
}

Expand Down
6 changes: 6 additions & 0 deletions lib/log_messages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -123,3 +123,9 @@ export const UPDATED_OPTIMIZELY_CONFIG = '%s: Updated Optimizely config to revis
export const OUT_OF_BOUNDS =
'%s: Audience condition %s evaluated to UNKNOWN because the number value for user attribute "%s" is not in the range [-2^53, +2^53].';
export const UNABLE_TO_ATTACH_UNLOAD = '%s: unable to bind optimizely.close() to page unload event: "%s"';
export const UNABLE_TO_PARSE_AND_SKIPPED_HEADER = 'Unable to parse & skipped header item';
export const ADDING_AUTHORIZATION_HEADER_WITH_BEARER_TOKEN = 'Adding Authorization header with Bearer Token';
export const MAKING_DATAFILE_REQ_TO_URL_WITH_HEADERS = 'Making datafile request to url %s with headers: %s';
export const RESPONSE_STATUS_CODE = 'Response status code: %s';
export const SAVED_LAST_MODIFIED_HEADER_VALUE_FROM_RESPONSE = 'Saved last modified header value from response: %s';

4 changes: 2 additions & 2 deletions lib/odp/event_manager/odp_event_api_manager.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import { describe, it, expect, vi } from 'vitest';

import { DefaultOdpEventApiManager, eventApiRequestGenerator, pixelApiRequestGenerator } from './odp_event_api_manager';
Expand Down Expand Up @@ -42,6 +41,7 @@ const PIXEL_URL = 'https://odp.pixel.com';
const odpConfig = new OdpConfig(API_KEY, API_HOST, PIXEL_URL, []);

import { getMockRequestHandler } from '../../tests/mock/mock_request_handler';
import { REQUEST_FAILED } from '../../exception_messages';

describe('DefaultOdpEventApiManager', () => {
it('should generate the event request using the correct odp config and event', async () => {
Expand Down Expand Up @@ -101,7 +101,7 @@ describe('DefaultOdpEventApiManager', () => {
it('should return a promise that fails if the requestHandler response promise fails', async () => {
const mockRequestHandler = getMockRequestHandler();
mockRequestHandler.makeRequest.mockReturnValue({
responsePromise: Promise.reject(new Error('Request failed')),
responsePromise: Promise.reject(new Error(REQUEST_FAILED)),
});
const requestGenerator = vi.fn().mockReturnValue({
method: 'PATCH',
Expand Down
5 changes: 3 additions & 2 deletions lib/odp/event_manager/odp_event_manager.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import { OdpEvent } from './odp_event';
import { OdpConfig } from '../odp_config';
import { EventDispatchResponse } from './odp_event_api_manager';
import { advanceTimersByTime } from '../../../tests/testUtils';
import { FAILED_TO_DISPATCH_EVENTS } from '../../exception_messages';

const API_KEY = 'test-api-key';
const API_HOST = 'https://odp.example.com';
Expand Down Expand Up @@ -604,7 +605,7 @@ describe('DefaultOdpEventManager', () => {
const repeater = getMockRepeater();

const apiManager = getMockApiManager();
apiManager.sendEvents.mockReturnValue(Promise.reject(new Error('Failed to dispatch events')));
apiManager.sendEvents.mockReturnValue(Promise.reject(new Error(FAILED_TO_DISPATCH_EVENTS)));

const backoffController = {
backoff: vi.fn().mockReturnValue(666),
Expand Down Expand Up @@ -706,7 +707,7 @@ describe('DefaultOdpEventManager', () => {
const repeater = getMockRepeater();

const apiManager = getMockApiManager();
apiManager.sendEvents.mockReturnValue(Promise.reject(new Error('Failed to dispatch events')));
apiManager.sendEvents.mockReturnValue(Promise.reject(new Error(FAILED_TO_DISPATCH_EVENTS)));

const backoffController = {
backoff: vi.fn().mockReturnValue(666),
Expand Down
27 changes: 17 additions & 10 deletions lib/odp/event_manager/odp_event_manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,16 @@ import { Producer } from '../../utils/type';
import { runWithRetry } from '../../utils/executor/backoff_retry_runner';
import { isSuccessStatusCode } from '../../utils/http_request_handler/http_util';
import { ODP_DEFAULT_EVENT_TYPE, ODP_USER_KEY } from '../constant';
import { ODP_NOT_INTEGRATED } from '../../error_messages';
import {
EVENT_ACTION_INVALID,
EVENT_DATA_FOUND_TO_BE_INVALID,
FAILED_TO_SEND_ODP_EVENTS,
ODP_EVENT_MANAGER_IS_NOT_RUNNING,
ODP_EVENTS_SHOULD_HAVE_ATLEAST_ONE_KEY_VALUE,
ODP_NOT_INTEGRATED,
} from '../../error_messages';
import { sprintf } from '../../utils/fns';
import { FAILED_TO_DISPATCH_EVENTS_WITH_ARG, ODP_EVENT_MANAGER_STOPPED } from '../../exception_messages';

export interface OdpEventManager extends Service {
updateConfig(odpIntegrationConfig: OdpIntegrationConfig): void;
Expand Down Expand Up @@ -66,8 +75,7 @@ export class DefaultOdpEventManager extends BaseService implements OdpEventManag
private async executeDispatch(odpConfig: OdpConfig, batch: OdpEvent[]): Promise<unknown> {
const res = await this.apiManager.sendEvents(odpConfig, batch);
if (res.statusCode && !isSuccessStatusCode(res.statusCode)) {
// TODO: replace message with imported constants
return Promise.reject(new Error(`Failed to dispatch events: ${res.statusCode}`));
return Promise.reject(new Error(sprintf(FAILED_TO_DISPATCH_EVENTS_WITH_ARG, res.statusCode)));
}
return await Promise.resolve(res);
}
Expand All @@ -89,8 +97,7 @@ export class DefaultOdpEventManager extends BaseService implements OdpEventManag
return runWithRetry(
() => this.executeDispatch(odpConfig, batch), this.retryConfig.backoffProvider(), this.retryConfig.maxRetries
).result.catch((err) => {
// TODO: replace with imported constants
this.logger?.error('failed to send odp events', err);
this.logger?.error(FAILED_TO_SEND_ODP_EVENTS, err);
});
}

Expand Down Expand Up @@ -139,7 +146,7 @@ export class DefaultOdpEventManager extends BaseService implements OdpEventManag
}

if (this.isNew()) {
this.startPromise.reject(new Error('odp event manager stopped before it could start'));
this.startPromise.reject(new Error(ODP_EVENT_MANAGER_STOPPED));
}

this.flush();
Expand All @@ -149,7 +156,7 @@ export class DefaultOdpEventManager extends BaseService implements OdpEventManag

sendEvent(event: OdpEvent): void {
if (!this.isRunning()) {
this.logger?.error('ODP event manager is not running.');
this.logger?.error(ODP_EVENT_MANAGER_IS_NOT_RUNNING);
return;
}

Expand All @@ -159,17 +166,17 @@ export class DefaultOdpEventManager extends BaseService implements OdpEventManag
}

if (event.identifiers.size === 0) {
this.logger?.error('ODP events should have at least one key-value pair in identifiers.');
this.logger?.error(ODP_EVENTS_SHOULD_HAVE_ATLEAST_ONE_KEY_VALUE);
return;
}

if (!this.isDataValid(event.data)) {
this.logger?.error('Event data found to be invalid.');
this.logger?.error(EVENT_DATA_FOUND_TO_BE_INVALID);
return;
}

if (!event.action ) {
this.logger?.error('Event action invalid.');
this.logger?.error(EVENT_ACTION_INVALID);
return;
}

Expand Down
7 changes: 4 additions & 3 deletions lib/odp/odp_manager.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import { ODP_USER_KEY } from './constant';
import { OptimizelySegmentOption } from './segment_manager/optimizely_segment_option';
import { OdpEventManager } from './event_manager/odp_event_manager';
import { CLIENT_VERSION, JAVASCRIPT_CLIENT_ENGINE } from '../utils/enums';
import { FAILED_TO_START, FAILED_TO_STOP } from '../exception_messages';

const keyA = 'key-a';
const hostA = 'host-a';
Expand Down Expand Up @@ -166,7 +167,7 @@ describe('DefaultOdpManager', () => {
await exhaustMicrotasks();

expect(odpManager.getState()).toEqual(ServiceState.Starting);
eventManagerPromise.reject(new Error('Failed to start'));
eventManagerPromise.reject(new Error(FAILED_TO_START));

await expect(odpManager.onRunning()).rejects.toThrow();
await expect(odpManager.onTerminated()).rejects.toThrow();
Expand All @@ -186,7 +187,7 @@ describe('DefaultOdpManager', () => {
odpManager.start();
expect(odpManager.getState()).toEqual(ServiceState.Starting);

eventManagerPromise.reject(new Error('Failed to start'));
eventManagerPromise.reject(new Error(FAILED_TO_START));

await expect(odpManager.onRunning()).rejects.toThrow();
await expect(odpManager.onTerminated()).rejects.toThrow();
Expand Down Expand Up @@ -692,7 +693,7 @@ describe('DefaultOdpManager', () => {
await exhaustMicrotasks();
expect(odpManager.getState()).toEqual(ServiceState.Stopping);

eventManagerTerminatedPromise.reject(new Error('Failed to stop'));
eventManagerTerminatedPromise.reject(new Error(FAILED_TO_STOP));
await expect(odpManager.onTerminated()).rejects.toThrow();
});
});
Expand Down
3 changes: 2 additions & 1 deletion lib/odp/odp_manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import { CLIENT_VERSION, JAVASCRIPT_CLIENT_ENGINE } from '../utils/enums';
import { ODP_DEFAULT_EVENT_TYPE, ODP_EVENT_ACTION, ODP_USER_KEY } from './constant';
import { isVuid } from '../vuid/vuid';
import { Maybe } from '../utils/type';
import { ODP_MANAGER_STOPPED_BEFORE_RUNNING } from '../exception_messages';

export interface OdpManager extends Service {
updateConfig(odpIntegrationConfig: OdpIntegrationConfig): boolean;
Expand Down Expand Up @@ -131,7 +132,7 @@ export class DefaultOdpManager extends BaseService implements OdpManager {
}

if (!this.isRunning()) {
this.startPromise.reject(new Error('odp manager stopped before running'));
this.startPromise.reject(new Error(ODP_MANAGER_STOPPED_BEFORE_RUNNING));
}

this.state = ServiceState.Stopping;
Expand Down
3 changes: 2 additions & 1 deletion lib/odp/segment_manager/odp_segment_api_manager.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import { ODP_USER_KEY } from '../constant';
import { getMockRequestHandler } from '../../tests/mock/mock_request_handler';
import { getMockLogger } from '../../tests/mock/mock_logger';
import { DefaultOdpSegmentApiManager } from './odp_segment_api_manager';
import { REQUEST_TIMEOUT } from '../../exception_messages';

const API_KEY = 'not-real-api-key';
const GRAPHQL_ENDPOINT = 'https://some.example.com/graphql/endpoint';
Expand All @@ -46,7 +47,7 @@ describe('DefaultOdpSegmentApiManager', () => {
const requestHandler = getMockRequestHandler();
requestHandler.makeRequest.mockReturnValue({
abort: () => {},
responsePromise: Promise.reject(new Error('Request timed out')),
responsePromise: Promise.reject(new Error(REQUEST_TIMEOUT)),
});
const logger = getMockLogger();
const manager = new DefaultOdpSegmentApiManager(requestHandler, logger);
Expand Down
5 changes: 2 additions & 3 deletions lib/optimizely/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ import {
NO_EVENT_PROCESSOR,
ODP_EVENT_FAILED,
ODP_EVENT_FAILED_ODP_MANAGER_MISSING,
UNABLE_TO_GET_VUID,
UNABLE_TO_GET_VUID_VUID_MANAGER_NOT_AVAILABLE,
} from '../error_messages';
import {
EVENT_KEY_NOT_FOUND,
Expand All @@ -86,7 +86,6 @@ import {
INVALID_OBJECT,
NOT_ACTIVATING_USER,
NOT_TRACKING_USER,
ODP_SEND_EVENT_IDENTIFIER_CONVERSION_FAILED,
SHOULD_NOT_DISPATCH_ACTIVATE,
TRACK_EVENT,
UNRECOGNIZED_DECIDE_OPTION,
Expand Down Expand Up @@ -1736,7 +1735,7 @@ export default class Optimizely implements Client {
*/
public getVuid(): string | undefined {
if (!this.vuidManager) {
this.logger?.error('Unable to get VUID - VuidManager is not available');
this.logger?.error(UNABLE_TO_GET_VUID_VUID_MANAGER_NOT_AVAILABLE);
return undefined;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ async function mockRequireAsyncStorage() {
M._load = (uri: string, parent: string) => {
if (uri === '@react-native-async-storage/async-storage') {
if (isAsyncStorageAvailable) return { default: {} };
throw new Error('Module not found: @react-native-async-storage/async-storage');
throw new Error(MODULE_NOT_FOUND_REACT_NATIVE_ASYNC_STORAGE);
}
return M._load_original(uri, parent);
};
Expand Down
18 changes: 12 additions & 6 deletions lib/project_config/polling_datafile_manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,12 @@ import { Consumer, Fn } from '../utils/type';
import { isSuccessStatusCode } from '../utils/http_request_handler/http_util';
import { DATAFILE_MANAGER_STOPPED, FAILED_TO_FETCH_DATAFILE } from '../exception_messages';
import { DATAFILE_FETCH_REQUEST_FAILED, ERROR_FETCHING_DATAFILE } from '../error_messages';
import {
ADDING_AUTHORIZATION_HEADER_WITH_BEARER_TOKEN,
MAKING_DATAFILE_REQ_TO_URL_WITH_HEADERS,
RESPONSE_STATUS_CODE,
SAVED_LAST_MODIFIED_HEADER_VALUE_FROM_RESPONSE,
} from '../log_messages';

export class PollingDatafileManager extends BaseService implements DatafileManager {
private requestHandler: RequestHandler;
Expand Down Expand Up @@ -98,8 +104,8 @@ export class PollingDatafileManager extends BaseService implements DatafileManag
if (this.isNew() || this.isStarting()) {
this.startPromise.reject(new Error(DATAFILE_MANAGER_STOPPED));
}
// Todo: Replace this with constant
this.logger?.debug('Datafile manager stopped');

this.logger?.debug(DATAFILE_MANAGER_STOPPED);
this.state = ServiceState.Terminated;
this.repeater.stop();
this.currentRequest?.abort();
Expand Down Expand Up @@ -169,11 +175,11 @@ export class PollingDatafileManager extends BaseService implements DatafileManag
}

if (this.datafileAccessToken) {
this.logger?.debug('Adding Authorization header with Bearer Token');
this.logger?.debug(ADDING_AUTHORIZATION_HEADER_WITH_BEARER_TOKEN);
headers['Authorization'] = `Bearer ${this.datafileAccessToken}`;
}

this.logger?.debug('Making datafile request to url %s with headers: %s', this.datafileUrl, () => JSON.stringify(headers));
this.logger?.debug(MAKING_DATAFILE_REQ_TO_URL_WITH_HEADERS, this.datafileUrl, () => JSON.stringify(headers));
return this.requestHandler.makeRequest(this.datafileUrl, headers, 'GET');
}

Expand All @@ -200,7 +206,7 @@ export class PollingDatafileManager extends BaseService implements DatafileManag
}

private getDatafileFromResponse(response: Response): string | undefined{
this.logger?.debug('Response status code: %s', response.statusCode);
this.logger?.debug(RESPONSE_STATUS_CODE, response.statusCode);
if (response.statusCode === 304) {
return undefined;
}
Expand All @@ -211,7 +217,7 @@ export class PollingDatafileManager extends BaseService implements DatafileManag
const lastModifiedHeader = headers['last-modified'] || headers['Last-Modified'];
if (lastModifiedHeader !== undefined) {
this.lastResponseLastModified = lastModifiedHeader;
this.logger?.debug('Saved last modified header value from response: %s', this.lastResponseLastModified);
this.logger?.debug(SAVED_LAST_MODIFIED_HEADER_VALUE_FROM_RESPONSE, this.lastResponseLastModified);
}
}

Expand Down
Loading

0 comments on commit 7c9ee78

Please sign in to comment.