Skip to content

[FSSDK-10989] refactor notification center using event emitter #975

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
merged 7 commits into from
Dec 11, 2024
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
3 changes: 1 addition & 2 deletions lib/export_types.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/**
* Copyright 2022-2023, Optimizely
* Copyright 2022-2024, Optimizely
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand Down Expand Up @@ -39,7 +39,6 @@ export {
ListenerPayload,
OptimizelyDecision,
OptimizelyUserContext,
NotificationListener,
Config,
Client,
ActivateListenerPayload,
Expand Down
322 changes: 141 additions & 181 deletions lib/notification_center/index.tests.js

Large diffs are not rendered by default.

214 changes: 71 additions & 143 deletions lib/notification_center/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/**
* Copyright 2020, 2022, Optimizely
* Copyright 2020, 2022, 2024, Optimizely
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand All @@ -15,29 +15,38 @@
*/
import { LogHandler, ErrorHandler } from '../modules/logging';
import { objectValues } from '../utils/fns';
import { NotificationListener, ListenerPayload } from '../shared_types';

import {
LOG_LEVEL,
LOG_MESSAGES,
NOTIFICATION_TYPES,
} from '../utils/enums';

import { NOTIFICATION_TYPES } from './type';
import { NotificationType, NotificationPayload } from './type';
import { Consumer, Fn } from '../utils/type';
import { EventEmitter } from '../utils/event_emitter/event_emitter';

const MODULE_NAME = 'NOTIFICATION_CENTER';

interface NotificationCenterOptions {
logger: LogHandler;
errorHandler: ErrorHandler;
}

interface ListenerEntry {
id: number;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
callback: (notificationData: any) => void;
export interface NotificationCenter {
addNotificationListener<N extends NotificationType>(
notificationType: N,
callback: Consumer<NotificationPayload[N]>
): number
removeNotificationListener(listenerId: number): boolean;
clearAllNotificationListeners(): void;
clearNotificationListeners(notificationType: NotificationType): void;
}

type NotificationListeners = {
[key: string]: ListenerEntry[];
export interface NotificationSender {
sendNotifications<N extends NotificationType>(
notificationType: N,
notificationData: NotificationPayload[N]
): void;
}

/**
Expand All @@ -46,11 +55,13 @@ type NotificationListeners = {
* - ACTIVATE: An impression event will be sent to Optimizely.
* - TRACK a conversion event will be sent to Optimizely
*/
export class NotificationCenter {
export class DefaultNotificationCenter implements NotificationCenter, NotificationSender {
private logger: LogHandler;
private errorHandler: ErrorHandler;
private notificationListeners: NotificationListeners;
private listenerId: number;

private removerId = 1;
private eventEmitter: EventEmitter<NotificationPayload> = new EventEmitter();
private removers: Map<number, Fn> = new Map();

/**
* @constructor
Expand All @@ -61,13 +72,6 @@ export class NotificationCenter {
constructor(options: NotificationCenterOptions) {
this.logger = options.logger;
this.errorHandler = options.errorHandler;
this.notificationListeners = {};
objectValues(NOTIFICATION_TYPES).forEach(
(notificationTypeEnum) => {
this.notificationListeners[notificationTypeEnum] = [];
}
);
this.listenerId = 1;
}

/**
Expand All @@ -80,47 +84,40 @@ export class NotificationCenter {
* can happen if the first argument is not a valid notification type, or if the same callback
* function was already added as a listener by a prior call to this function.
*/
addNotificationListener<T extends ListenerPayload>(
notificationType: string,
callback: NotificationListener<T>
addNotificationListener<N extends NotificationType>(
notificationType: N,
callback: Consumer<NotificationPayload[N]>
): number {
try {
const notificationTypeValues: string[] = objectValues(NOTIFICATION_TYPES);
const isNotificationTypeValid = notificationTypeValues.indexOf(notificationType) > -1;
if (!isNotificationTypeValid) {
return -1;
}

if (!this.notificationListeners[notificationType]) {
this.notificationListeners[notificationType] = [];
}

let callbackAlreadyAdded = false;
(this.notificationListeners[notificationType] || []).forEach(
(listenerEntry) => {
if (listenerEntry.callback === callback) {
callbackAlreadyAdded = true;
return;
}
});

if (callbackAlreadyAdded) {
return -1;
}

this.notificationListeners[notificationType].push({
id: this.listenerId,
callback: callback,
});

const returnId = this.listenerId;
this.listenerId += 1;
return returnId;
} catch (e: any) {
this.logger.log(LOG_LEVEL.ERROR, e.message);
this.errorHandler.handleError(e);
const notificationTypeValues: string[] = objectValues(NOTIFICATION_TYPES);
const isNotificationTypeValid = notificationTypeValues.indexOf(notificationType) > -1;
if (!isNotificationTypeValid) {
return -1;
}

const returnId = this.removerId++;
const remover = this.eventEmitter.on(
notificationType, this.wrapWithErrorHandling(notificationType, callback));
this.removers.set(returnId, remover);
return returnId;
}

private wrapWithErrorHandling<N extends NotificationType>(
notificationType: N,
callback: Consumer<NotificationPayload[N]>
): Consumer<NotificationPayload[N]> {
return (notificationData: NotificationPayload[N]) => {
try {
callback(notificationData);
} catch (ex: any) {
this.logger.log(
LOG_LEVEL.ERROR,
LOG_MESSAGES.NOTIFICATION_LISTENER_EXCEPTION,
MODULE_NAME,
notificationType,
ex.message,
);
}
};
}

/**
Expand All @@ -130,103 +127,40 @@ export class NotificationCenter {
* otherwise.
*/
removeNotificationListener(listenerId: number): boolean {
try {
let indexToRemove: number | undefined;
let typeToRemove: string | undefined;

Object.keys(this.notificationListeners).some(
(notificationType) => {
const listenersForType = this.notificationListeners[notificationType];
(listenersForType || []).every((listenerEntry, i) => {
if (listenerEntry.id === listenerId) {
indexToRemove = i;
typeToRemove = notificationType;
return false;
}

return true;
});

if (indexToRemove !== undefined && typeToRemove !== undefined) {
return true;
}

return false;
}
);

if (indexToRemove !== undefined && typeToRemove !== undefined) {
this.notificationListeners[typeToRemove].splice(indexToRemove, 1);
return true;
}
} catch (e: any) {
this.logger.log(LOG_LEVEL.ERROR, e.message);
this.errorHandler.handleError(e);
const remover = this.removers.get(listenerId);
if (remover) {
remover();
return true;
}

return false;
return false
}

/**
* Removes all previously added notification listeners, for all notification types
*/
clearAllNotificationListeners(): void {
try {
objectValues(NOTIFICATION_TYPES).forEach(
(notificationTypeEnum) => {
this.notificationListeners[notificationTypeEnum] = [];
}
);
} catch (e: any) {
this.logger.log(LOG_LEVEL.ERROR, e.message);
this.errorHandler.handleError(e);
}
this.eventEmitter.removeAllListeners();
}

/**
* Remove all previously added notification listeners for the argument type
* @param {NOTIFICATION_TYPES} notificationType One of NOTIFICATION_TYPES
* @param {NotificationType} notificationType One of NotificationType
*/
clearNotificationListeners(notificationType: NOTIFICATION_TYPES): void {
try {
this.notificationListeners[notificationType] = [];
} catch (e: any) {
this.logger.log(LOG_LEVEL.ERROR, e.message);
this.errorHandler.handleError(e);
}
clearNotificationListeners(notificationType: NotificationType): void {
this.eventEmitter.removeListeners(notificationType);
}

/**
* Fires notifications for the argument type. All registered callbacks for this type will be
* called. The notificationData object will be passed on to callbacks called.
* @param {string} notificationType One of NOTIFICATION_TYPES
* @param {NotificationType} notificationType One of NotificationType
* @param {Object} notificationData Will be passed to callbacks called
*/
sendNotifications<T extends ListenerPayload>(
notificationType: string,
notificationData?: T
sendNotifications<N extends NotificationType>(
notificationType: N,
notificationData: NotificationPayload[N]
): void {
try {
(this.notificationListeners[notificationType] || []).forEach(
(listenerEntry) => {
const callback = listenerEntry.callback;
try {
callback(notificationData);
} catch (ex: any) {
this.logger.log(
LOG_LEVEL.ERROR,
LOG_MESSAGES.NOTIFICATION_LISTENER_EXCEPTION,
MODULE_NAME,
notificationType,
ex.message,
);
}
}
);
} catch (e: any) {
this.logger.log(LOG_LEVEL.ERROR, e.message);
this.errorHandler.handleError(e);
}
this.eventEmitter.emit(notificationType, notificationData);
}
}

Expand All @@ -235,12 +169,6 @@ export class NotificationCenter {
* @param {NotificationCenterOptions} options
* @returns {NotificationCenter} An instance of NotificationCenter
*/
export function createNotificationCenter(options: NotificationCenterOptions): NotificationCenter {
return new NotificationCenter(options);
}

export interface NotificationSender {
// TODO[OASIS-6649]: Don't use any type
// eslint-disable-next-line @typescript-eslint/no-explicit-any
sendNotifications(notificationType: NOTIFICATION_TYPES, notificationData?: any): void
export function createNotificationCenter(options: NotificationCenterOptions): DefaultNotificationCenter {
return new DefaultNotificationCenter(options);
}
80 changes: 80 additions & 0 deletions lib/notification_center/type.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
/**
* Copyright 2024, Optimizely
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import { LogEvent } from '../event_processor/event_dispatcher/event_dispatcher';
import { EventTags, Experiment, UserAttributes, Variation } from '../shared_types';

export type UserEventListenerPayload = {
userId: string;
attributes?: UserAttributes;
}

export type ActivateListenerPayload = UserEventListenerPayload & {
experiment: Experiment | null;
variation: Variation | null;
logEvent: LogEvent;
}

export type TrackListenerPayload = UserEventListenerPayload & {
eventKey: string;
eventTags?: EventTags;
logEvent: LogEvent;
}

export const DECISION_NOTIFICATION_TYPES = {
AB_TEST: 'ab-test',
FEATURE: 'feature',
FEATURE_TEST: 'feature-test',
FEATURE_VARIABLE: 'feature-variable',
ALL_FEATURE_VARIABLES: 'all-feature-variables',
FLAG: 'flag',
} as const;

export type DecisionNotificationType = typeof DECISION_NOTIFICATION_TYPES[keyof typeof DECISION_NOTIFICATION_TYPES];

// TODO: Add more specific types for decision info
export type OptimizelyDecisionInfo = Record<string, any>;

export type DecisionListenerPayload = UserEventListenerPayload & {
type: DecisionNotificationType;
decisionInfo: OptimizelyDecisionInfo;
}

export type LogEventListenerPayload = LogEvent;

export type OptimizelyConfigUpdateListenerPayload = undefined;

export type NotificationPayload = {
ACTIVATE: ActivateListenerPayload;
DECISION: DecisionListenerPayload;
TRACK: TrackListenerPayload;
LOG_EVENT: LogEventListenerPayload;
OPTIMIZELY_CONFIG_UPDATE: OptimizelyConfigUpdateListenerPayload;
};

export type NotificationType = keyof NotificationPayload;

export type NotificationTypeValues = {
[key in NotificationType]: key;
}

export const NOTIFICATION_TYPES: NotificationTypeValues = {
ACTIVATE: 'ACTIVATE',
DECISION: 'DECISION',
LOG_EVENT: 'LOG_EVENT',
OPTIMIZELY_CONFIG_UPDATE: 'OPTIMIZELY_CONFIG_UPDATE',
TRACK: 'TRACK',
};
Loading
Loading