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

Snowplow analytics plugin #149

Merged
merged 6 commits into from
Jul 29, 2024
Merged
Show file tree
Hide file tree
Changes from 5 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 packages/app/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@
"@material-ui/lab": "^4.0.0-alpha.61",
"@material-ui/styles": "^4.11.5",
"@snowplow/browser-plugin-link-click-tracking": "^3.15.0",
"@snowplow/browser-plugin-site-tracking": "^3.23.1",
"@snowplow/browser-tracker": "^3.15.0",
"backstage-plugin-techdocs-addon-mermaid": "^0.11.0",
"history": "^5.0.0",
Expand Down
7 changes: 7 additions & 0 deletions packages/app/src/apis.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@ import {
AnyApiFactory,
configApiRef,
createApiFactory,
analyticsApiRef,
} from '@backstage/core-plugin-api';
import { SnowplowAnalytics } from '@internal/plugin-analytics-module-snowplow'

export const apis: AnyApiFactory[] = [
createApiFactory({
Expand All @@ -16,4 +18,9 @@ export const apis: AnyApiFactory[] = [
factory: ({ configApi }) => ScmIntegrationsApi.fromConfig(configApi),
}),
ScmAuth.createDefaultApiFactory(),
createApiFactory({
api: analyticsApiRef,
deps: { configApi: configApiRef },
factory: ({ configApi }) => SnowplowAnalytics.fromConfig(configApi),
}),
];
58 changes: 1 addition & 57 deletions packages/app/src/components/Root/Root.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { PropsWithChildren, useEffect } from 'react';
import React, { PropsWithChildren } from 'react';
import { makeStyles } from '@material-ui/core';
import HomeIcon from '@material-ui/icons/Home';
// import CatalogIcon from '@material-ui/icons/LocalLibrary';
Expand Down Expand Up @@ -33,61 +33,6 @@ import MenuIcon from '@material-ui/icons/Menu';
import SearchIcon from '@material-ui/icons/Search';
import { CustomSearchModal } from '../search/CustomModal';

import {useApi, configApiRef} from '@backstage/core-plugin-api';


// snowplow analytics
import {newTracker, trackPageView, enableActivityTracking} from '@snowplow/browser-tracker';
import {
enableLinkClickTracking,
refreshLinkClickTracking,
LinkClickTrackingPlugin as linkTrackingPlugin
} from '@snowplow/browser-plugin-link-click-tracking';
import {useLocation} from "react-router-dom";


const MyReactComponent = () => {
const config = useApi(configApiRef);

const location = useLocation();

// refresh link tracking whenever local navigation occurs
useEffect(() => {
setTimeout(refreshLinkClickTracking, 250);
}, [location]);

console.log("**********Setting up analytics (or not...)********");
console.log(`Config: ${JSON.stringify(config)}`);

if (config.getOptionalConfig('app.analytics') && config.getBoolean('app.analytics.snowplow.enabled')) {
console.log("**********Analytics enabled...********");

// const collectorUrl = "spm.apps.gov.bc.ca"
const collectorUrl = config.getString("app.analytics.snowplow.collectorUrl");

newTracker('rt', `${collectorUrl}`, {
appId: 'Snowplow_standalone_OCIO',
cookieLifetime: 86400 * 548,
platform: "web",
contexts: {
webPage: true
},
plugins: [linkTrackingPlugin()]
});

enableActivityTracking({
minimumVisitLength: 30,
heartbeatDelay: 30
});

enableLinkClickTracking();

trackPageView();
}
return null;
}


const storedTheme = localStorage.getItem('theme');

// Set the default theme to custom DevEx theme if no stored preference is found
Expand Down Expand Up @@ -144,7 +89,6 @@ export const Root = ({ children }: PropsWithChildren<{}>) => {

return (
<SidebarPage>
<MyReactComponent/>
<Sidebar>
<SidebarLogo />
<SidebarGroup label="Search" icon={<SearchIcon />} to="/search">
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,12 @@ import { CatalogSearchResultListItem } from '@backstage/plugin-catalog';
import { StackOverflowSearchResultListItem, StackOverflowIcon } from '@backstage/plugin-stack-overflow';
import { CatalogIcon, DocsIcon } from '@backstage/core-components';
import { TechDocsSearchResultCustomListItem } from './TechDocsSearchResultCustomListItem';
import { refreshLinkClickTracking } from '@snowplow/browser-plugin-link-click-tracking';

const SearchResultCustomList = () => {
return (
<SearchResult>
{({ results }) => (
<List onMouseEnter={() => refreshLinkClickTracking()}>
<List>
{results.map(({ type, document, highlight, rank }) => {
switch (type) {
case 'software-catalog':
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ export const TechDocsSearchResultCustomListItem = (

const LinkWrapper = ({ children }: PropsWithChildren<{}>) =>
asLink ? (
<Link noTrack to={result.location}>
<Link to={result.location}>
{children}
</Link>
) : (
Expand Down
30 changes: 25 additions & 5 deletions plugins/analytics-module-snowplow/config.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,31 @@ export interface Config {
* @visibility frontend
*/
enabled: boolean;
/**
*
* @visibility frontend
*/
collectorUrl: string;
/**
*
* @visibility frontend
*/
collectorUrl: string;
/**
*
* @visibility frontend
*/
appId?: string;
/**
*
* @visibility frontend
*/
trackerId?: string;
/**
*
* @visibility frontend
*/
cookieLifetime?: number;
/**
*
* @visibility frontend
*/
debounceTime?: number;
}
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
import { Config } from '@backstage/config';
import {
AnalyticsApi,
AnalyticsEvent,
} from '@backstage/core-plugin-api';
import { newTracker, trackPageView, enableActivityTracking } from '@snowplow/browser-tracker';
import { LinkClickTrackingPlugin, trackLinkClick } from '@snowplow/browser-plugin-link-click-tracking';
import { SiteTrackingPlugin, trackSiteSearch } from '@snowplow/browser-plugin-site-tracking';

export class SnowplowAnalytics implements AnalyticsApi {
private readonly enabled: boolean;
private readonly baseUrl: string;
private readonly debounceTime: number;
private cancelProc: NodeJS.Timeout | null;

private constructor(options: {
enabled: boolean,
baseUrl: string,
trackerId: string,
endpoint: string,
appId: string,
cookieLifetime: number,
debounceTime: number
}) {
const {
enabled,
baseUrl,
trackerId,
endpoint,
appId,
cookieLifetime,
debounceTime
} = options;

this.enabled = enabled;
this.baseUrl = baseUrl;
this.cancelProc = null;
this.debounceTime = debounceTime;

// create the Snowplow tracker
console.log("**********Setting up analytics (or not...)********");
oomIRL marked this conversation as resolved.
Show resolved Hide resolved
if (this.enabled) {
console.log("**********Analytics enabled...********");

newTracker(trackerId, endpoint, {
appId: appId,
cookieLifetime: cookieLifetime,
platform: "web",
contexts: {
webPage: true
},
plugins: [LinkClickTrackingPlugin(), SiteTrackingPlugin()]
});

enableActivityTracking({
minimumVisitLength: 30,
heartbeatDelay: 30
});
}
}

static fromConfig(config: Config): SnowplowAnalytics {
const enabled = config.getBoolean('app.analytics.snowplow.enabled');
const baseUrl = config.getString('app.baseUrl');
const endpoint = config.getString('app.analytics.snowplow.collectorUrl');
const appId = config.getOptionalString('app.analytics.snowplow.appId') || 'Snowplow_standalone_OCIO' ;
const trackerId = config.getOptionalString('app.analytics.snowplow.trackerId') || 'rt';
const cookieLifetime = config.getOptionalNumber('app.analytics.snowplow.cookieLifetime') ?? 86400 * 548;
const debounceTime = config.getOptionalNumber('app.analytics.snowplow.debounceTime') ?? 3000;

return new SnowplowAnalytics({
enabled,
baseUrl,
trackerId,
endpoint,
appId,
cookieLifetime,
debounceTime
});
}

captureEvent(event: AnalyticsEvent): void {
if (this.enabled) {
switch (event.action) {
case "search":
this.captureSearch(event);
break;
case "navigate":
trackPageView();
break;
case "click":
case "discover":
this.trackClick(event);
break;
}
}
}

private trackClick(event: AnalyticsEvent): void {
let to: string = event.attributes?.to as string ?? '';
const hasDomain = new RegExp(/[A-Za-z0-9-]{1,63}\.[A-Za-z]{2,6}/).test(to);
const isMailto = to.startsWith('mailto:');

// add the baseUrl to relative path links (this is largely to remain consistent with previous analytics)
if (!hasDomain && !isMailto) {
to = (to.startsWith('/'))? this.baseUrl + to : this.baseUrl + '/' + to;
}

trackLinkClick({ targetUrl: to, elementContent: event.subject });
}

private trackSearch(event: AnalyticsEvent): void {
// trim whitespace, split into non-empty terms
trackSiteSearch({ terms: event.subject.trim().split(" ").filter( t => t ) });
oomIRL marked this conversation as resolved.
Show resolved Hide resolved
}

private captureSearch(event: AnalyticsEvent): void {
// cancel any pending trackSearch call
if (this.cancelProc) {
clearTimeout(this.cancelProc);
}

// track event once the debounceTime has elapsed
this.cancelProc = setTimeout(() => {
this.trackSearch(event);
this.cancelProc = null;
}, this.debounceTime);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { SnowplowAnalytics } from './SnowplowAnalytics';
3 changes: 2 additions & 1 deletion plugins/analytics-module-snowplow/src/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
export {}
export { analyticsModuleSnowplow } from './plugin';
export * from './apis/implementations/AnalyticsApi';
5 changes: 5 additions & 0 deletions plugins/analytics-module-snowplow/src/plugin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { createPlugin } from '@backstage/core-plugin-api';

export const analyticsModuleSnowplow = createPlugin({
id: 'analytics-provider-snowplow',
});
Loading
Loading