Skip to content
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

Apply port adapter pattern to mixpanel analytics #6632

Merged
merged 5 commits into from
Feb 14, 2024
Merged
Show file tree
Hide file tree
Changes from 3 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
1 change: 1 addition & 0 deletions libs/adapters/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
"async-rwlock": "^1.1.1",
"express": "^4.18.2",
"hot-shots": "^9",
"mixpanel": "^0.14.0",
"pg": "^8.11.3",
"node-fetch": "2",
"rascal": "^14.4.5",
Expand Down
1 change: 1 addition & 0 deletions libs/adapters/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
export * from './express';
export * from './hot-shots';
export * from './mixpanel';
export * from './rabbitmq';
export * from './redis';
export * from './typescript-logging';
Expand Down
30 changes: 30 additions & 0 deletions libs/adapters/src/mixpanel/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { Analytics, AnalyticsOptions } from '@hicommonwealth/core';
import MixpanelLib from 'mixpanel';

export const MixpanelAnalytics = (): Analytics => {
let mixpanelNode;

try {
if (process.env.NODE_ENV === 'production') {
mixpanelNode = MixpanelLib.init(process.env.MIXPANEL_PROD_TOKEN);
} else if (process.env.NODE_ENV === 'development') {
// NOTE: Only works if NODE_ENV defined in .env
// Make sure that is set to development if you want to use backend Mixpanel locally.
mixpanelNode = MixpanelLib.init(process.env.MIXPANEL_DEV_TOKEN);
}
} catch (e) {
console.error('Unable to initialized the backend mixpanel client: ', e);
}

return {
name: 'mixpanel-analytics',
dispose: async () => {},
rbennettcw marked this conversation as resolved.
Show resolved Hide resolved
track: (event: string, payload: AnalyticsOptions) => {
try {
mixpanelNode?.track(event, payload);
} catch (e) {
console.log(`Failed to track event, ${event.toString()}:`, e.message);
}
},
};
};
19 changes: 18 additions & 1 deletion libs/core/src/ports/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Cache, Logger, Stats } from './interfaces';
import { AnalyticsOptions } from '../types';
import { Analytics, Cache, Logger, Stats } from './interfaces';
import { port } from './port';

export * from './enums';
Expand Down Expand Up @@ -81,3 +82,19 @@ export const cache = port(function cache(cache?: Cache) {
}
);
});

/**
* Analytics port factory
*/

export const analytics = port(function analytics(analytics?: Analytics) {
return (
analytics || {
name: 'in-memory-analytics',
dispose: () => Promise.resolve(),
track: (event: string, payload: AnalyticsOptions) => {
console.log(`TRACK [${event}]: ${JSON.stringify(payload)}`);
rbennettcw marked this conversation as resolved.
Show resolved Hide resolved
},
}
);
});
9 changes: 8 additions & 1 deletion libs/core/src/ports/interfaces.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { CacheNamespaces } from '../types';
import { AnalyticsOptions, CacheNamespaces } from '../types';

/**
* Resource disposer function
Expand Down Expand Up @@ -104,3 +104,10 @@ export interface Cache extends Disposable {
ttlInSeconds: number,
): Promise<boolean>;
}

/**
* Analytics port
*/
export interface Analytics extends Disposable {
track(event: string, payload: AnalyticsOptions): void;
}
2 changes: 2 additions & 0 deletions libs/core/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -239,3 +239,5 @@ export type ChainEventNotification = {
created_at: Date;
ChainEvent: ChainEventAttributes;
};

export type AnalyticsOptions = Record<string, any>;
1 change: 0 additions & 1 deletion packages/commonwealth/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,6 @@
"marked-footnote": "^1.2.2",
"marked-smartypants": "1.1.5",
"marked-xhtml": "1.0.8",
"mixpanel": "^0.14.0",
"mixpanel-browser": "^2.45.0",
"moment": "^2.23.0",
"morgan": "^1.9.1",
Expand Down
4 changes: 3 additions & 1 deletion packages/commonwealth/server.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,17 @@
import {
HotShotsStats,
MixpanelAnalytics,
ServiceKey,
TypescriptLoggingLogger,
startHealthCheckLoop,
} from '@hicommonwealth/adapters';
import { logger, stats } from '@hicommonwealth/core';
import { analytics, logger, stats } from '@hicommonwealth/core';
import express from 'express';

// bootstrap production adapters
const log = logger(TypescriptLoggingLogger()).getLogger(__filename);
stats(HotShotsStats());
analytics(MixpanelAnalytics());

let isServiceHealthy = false;
startHealthCheckLoop({
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import { analytics } from '@hicommonwealth/core';
import { AnalyticsPayload } from 'shared/analytics/types';
import { SERVER_URL } from '../config';
import { TrackOptions, __track } from './server_analytics_methods/track';

export type TrackOptions = Record<string, any> & AnalyticsPayload;

export class ServerAnalyticsController {
/**
Expand All @@ -17,7 +20,8 @@ export class ServerAnalyticsController {
...(host && { isCustomDomain: SERVER_URL.includes(host) }),
};
}
return __track.call(this, newOptions);
const { event, ...payload } = newOptions;
analytics().track(event, payload);
}
}

Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import { REACTION_WEIGHT_OVERRIDE } from 'server/config';
import { MixpanelCommunityInteractionEvent } from '../../../shared/analytics/types';
import { validateTopicGroupsMembership } from '../../util/requirementsModule/validateTopicGroupsMembership';
import { findAllRoles } from '../../util/roles';
import { TrackOptions } from '../server_analytics_methods/track';
import { TrackOptions } from '../server_analytics_controller';
import { ServerCommentsController } from '../server_comments_controller';
import { EmitOptions } from '../server_notifications_methods/emit';

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import { MixpanelCommunityInteractionEvent } from '../../../shared/analytics/typ
import { urlHasValidHTTPPrefix } from '../../../shared/utils';
import { ALL_COMMUNITIES } from '../../middleware/databaseValidationService';
import { findOneRole } from '../../util/roles';
import { TrackOptions } from '../server_analytics_methods/track';
import { TrackOptions } from '../server_analytics_controller';
import { ServerCommunitiesController } from '../server_communities_controller';

export const Errors = {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import { MixpanelCommunityInteractionEvent } from '../../../shared/analytics/typ
import validateMetadata from '../../util/requirementsModule/validateMetadata';
import validateRequirements from '../../util/requirementsModule/validateRequirements';
import { validateOwner } from '../../util/validateOwner';
import { TrackOptions } from '../server_analytics_methods/track';
import { TrackOptions } from '../server_analytics_controller';
import { ServerGroupsController } from '../server_groups_controller';

const MAX_GROUPS_PER_COMMUNITY = 20;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import { MixpanelCommunityInteractionEvent } from '../../../shared/analytics/typ
import validateMetadata from '../../util/requirementsModule/validateMetadata';
import validateRequirements from '../../util/requirementsModule/validateRequirements';
import { validateOwner } from '../../util/validateOwner';
import { TrackOptions } from '../server_analytics_methods/track';
import { TrackOptions } from '../server_analytics_controller';
import { ServerGroupsController } from '../server_groups_controller';

const Errors = {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import {
} from '@hicommonwealth/model';
import { MixpanelCommunityInteractionEvent } from '../../../shared/analytics/types';
import { validateTopicGroupsMembership } from '../../util/requirementsModule/validateTopicGroupsMembership';
import { TrackOptions } from '../server_analytics_methods/track';
import { TrackOptions } from '../server_analytics_controller';
import { ServerPollsController } from '../server_polls_controller';

export const Errors = {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import { renderQuillDeltaToText } from '../../../shared/utils';
import { parseUserMentions } from '../../util/parseUserMentions';
import { validateTopicGroupsMembership } from '../../util/requirementsModule/validateTopicGroupsMembership';
import { validateOwner } from '../../util/validateOwner';
import { TrackOptions } from '../server_analytics_methods/track';
import { TrackOptions } from '../server_analytics_controller';
import { EmitOptions } from '../server_notifications_methods/emit';
import { ServerThreadsController } from '../server_threads_controller';

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import { getCommentDepth } from '../../util/getCommentDepth';
import { parseUserMentions } from '../../util/parseUserMentions';
import { validateTopicGroupsMembership } from '../../util/requirementsModule/validateTopicGroupsMembership';
import { validateOwner } from '../../util/validateOwner';
import { TrackOptions } from '../server_analytics_methods/track';
import { TrackOptions } from '../server_analytics_controller';
import { EmitOptions } from '../server_notifications_methods/emit';
import { ServerThreadsController } from '../server_threads_controller';

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { PollAttributes, UserInstance } from '@hicommonwealth/model';
import moment from 'moment';
import { MixpanelCommunityInteractionEvent } from '../../../shared/analytics/types';
import { validateOwner } from '../../util/validateOwner';
import { TrackOptions } from '../server_analytics_methods/track';
import { TrackOptions } from '../server_analytics_controller';
import { ServerThreadsController } from '../server_threads_controller';

export const Errors = {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import { REACTION_WEIGHT_OVERRIDE } from 'server/config';
import { MixpanelCommunityInteractionEvent } from '../../../shared/analytics/types';
import { validateTopicGroupsMembership } from '../../util/requirementsModule/validateTopicGroupsMembership';
import { validateOwner } from '../../util/validateOwner';
import { TrackOptions } from '../server_analytics_methods/track';
import { TrackOptions } from '../server_analytics_controller';
import { EmitOptions } from '../server_notifications_methods/emit';
import { ServerThreadsController } from '../server_threads_controller';

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import { MixpanelCommunityInteractionEvent } from '../../../shared/analytics/typ
import { renderQuillDeltaToText, validURL } from '../../../shared/utils';
import { parseUserMentions } from '../../util/parseUserMentions';
import { findAllRoles } from '../../util/roles';
import { TrackOptions } from '../server_analytics_methods/track';
import { TrackOptions } from '../server_analytics_controller';
import { EmitOptions } from '../server_notifications_methods/emit';
import { ServerThreadsController } from '../server_threads_controller';

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import {
import { sanitizeQuillText } from 'server/util/sanitizeQuillText';
import { MixpanelCommunityInteractionEvent } from '../../../shared/analytics/types';
import { validateOwner } from '../../util/validateOwner';
import { TrackOptions } from '../server_analytics_methods/track';
import { TrackOptions } from '../server_analytics_controller';
import { ServerTopicsController } from '../server_topics_controller';

export const Errors = {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { TopicAttributes, UserInstance } from '@hicommonwealth/model';
import { sanitizeQuillText } from 'server/util/sanitizeQuillText';
import { MixpanelCommunityInteractionEvent } from '../../../shared/analytics/types';
import { validateOwner } from '../../util/validateOwner';
import { TrackOptions } from '../server_analytics_methods/track';
import { TrackOptions } from '../server_analytics_controller';
import { ServerTopicsController } from '../server_topics_controller';

export const Errors = {
Expand Down
39 changes: 0 additions & 39 deletions packages/commonwealth/shared/analytics/server-track.ts

This file was deleted.

Loading