Skip to content

Commit

Permalink
Abstract access to injected globals (jaegertracing#1224)
Browse files Browse the repository at this point in the history
## Which problem is this PR solving?
- Split from jaegertracing#1212

## Short description of the changes
Create a wrapper module for accessing globals injected by the build
system. This makes it easier to rename or adjust those later.

Signed-off-by: Máté Szabó <mszabo@fandom.com>
  • Loading branch information
mszabo-wikia authored and Benjamin Klein committed Apr 18, 2023
1 parent e3e8a71 commit e8b94c9
Show file tree
Hide file tree
Showing 9 changed files with 83 additions and 28 deletions.
4 changes: 3 additions & 1 deletion packages/jaeger-ui/src/site-prefix.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,10 @@
// Per the resolution of https://github.com/jaegertracing/jaeger-ui/issues/42,
// package.json#homepage is set to "." and the document MUST have a <base>
// element to define a usable base URL.
import { getAppEnvironment } from './utils/constants';

const baseNode = document.querySelector('base');
if (!baseNode && process.env.NODE_ENV !== 'test') {
if (!baseNode && getAppEnvironment() !== 'test') {
throw new Error('<base> element not found');
}

Expand Down
4 changes: 2 additions & 2 deletions packages/jaeger-ui/src/utils/configure-store.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,13 @@

import { createStore, combineReducers, applyMiddleware, compose } from 'redux';
import { routerReducer, routerMiddleware } from 'react-router-redux';
import { window } from 'global';

import traceDiff from '../components/TraceDiff/duck';
import archive from '../components/TracePage/ArchiveNotifier/duck';
import traceTimeline from '../components/TracePage/TraceTimelineViewer/duck';
import jaegerReducers from '../reducers';
import * as jaegerMiddlewares from '../middlewares';
import { getAppEnvironment } from './constants';

export default function configureStore(history) {
return createStore(
Expand All @@ -38,7 +38,7 @@ export default function configureStore(history) {
.filter(Boolean),
routerMiddleware(history)
),
process.env.NODE_ENV !== 'production' && window && window.__REDUX_DEVTOOLS_EXTENSION__
getAppEnvironment() !== 'production' && window && window.__REDUX_DEVTOOLS_EXTENSION__
? window.__REDUX_DEVTOOLS_EXTENSION__()
: noop => noop
)
Expand Down
35 changes: 35 additions & 0 deletions packages/jaeger-ui/src/utils/constants.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
// Copyright (c) 2023 The Jaeger Authors.
//
// 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.

/**
* Provides access to constants injected by the build system.
*/

/**
* Get the current execution environment, as inferred from NODE_ENV at build time.
*/
export function getAppEnvironment() {
return process.env.NODE_ENV;
}

/**
* Get injected version details as a JSON-formatted string.
*/
export function getVersionInfo() {
return process.env.REACT_APP_VSN_STATE;
}

export function shouldDebugGoogleAnalytics() {
return process.env.REACT_APP_GA_DEBUG;
}
3 changes: 2 additions & 1 deletion packages/jaeger-ui/src/utils/prefix-url.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,9 @@
// limitations under the License.

import sitePrefix from '../site-prefix';
import { getAppEnvironment } from './constants';

const origin = process.env.NODE_ENV === 'test' ? global.location.origin : window.location.origin;
const origin = getAppEnvironment() === 'test' ? global.location.origin : window.location.origin;

/**
* Generate the URL prefix from `sitePrefix` and use it for all subsequent calls
Expand Down
18 changes: 9 additions & 9 deletions packages/jaeger-ui/src/utils/tracking/ga.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,23 +12,21 @@
// See the License for the specific language governing permissions and
// limitations under the License.

/* eslint-disable import/first */
import ReactGA from 'react-ga';
import * as GA from './ga';
import * as utils from './utils';
import { getVersionInfo, getAppEnvironment } from '../constants';

jest.mock('./conv-raven-to-ga', () => () => ({
category: 'jaeger/a',
action: 'some-action',
message: 'jaeger/a',
}));

jest.mock('./index', () => {
global.process.env.REACT_APP_VSN_STATE = '{}';
return require.requireActual('./index');
});

import ReactGA from 'react-ga';
import * as GA from './ga';
import * as utils from './utils';
jest.mock('../constants');

let longStr = '---';

function getStr(len) {
while (longStr.length < len) {
longStr += longStr.slice(0, len - longStr.length);
Expand All @@ -41,6 +39,7 @@ describe('google analytics tracking', () => {
let tracking;

beforeAll(() => {
getAppEnvironment.mockReturnValue('test');
tracking = GA.default(
{
tracking: {
Expand All @@ -55,6 +54,7 @@ describe('google analytics tracking', () => {
});

beforeEach(() => {
getVersionInfo.mockReturnValue('{}');
calls = ReactGA.testModeAPI.calls;
calls.length = 0;
});
Expand Down
12 changes: 7 additions & 5 deletions packages/jaeger-ui/src/utils/tracking/ga.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,17 +22,19 @@ import { TNil } from '../../types';
import { Config } from '../../types/config';
import { IWebAnalyticsFunc } from '../../types/tracking';
import { logTrackingCalls } from './utils';
import { getAppEnvironment, shouldDebugGoogleAnalytics } from '../constants';

const isTruish = (value?: string | string[]) => {
return Boolean(value) && value !== '0' && value !== 'false';
};

const GA: IWebAnalyticsFunc = (config: Config, versionShort: string, versionLong: string) => {
const isProd = process.env.NODE_ENV === 'production';
const isDev = process.env.NODE_ENV === 'development';
const isTest = process.env.NODE_ENV === 'test';
const appEnv = getAppEnvironment();
const isProd = appEnv === 'production';
const isDev = appEnv === 'development';
const isTest = appEnv === 'test';
const isDebugMode =
(isDev && isTruish(process.env.REACT_APP_GA_DEBUG)) ||
(isDev && isTruish(shouldDebugGoogleAnalytics())) ||
isTruish(queryString.parse(_get(window, 'location.search'))['ga-debug']);
const gaID = _get(config, 'tracking.gaID');
const isErrorsEnabled = isDebugMode || Boolean(_get(config, 'tracking.trackErrors'));
Expand Down Expand Up @@ -130,7 +132,7 @@ const GA: IWebAnalyticsFunc = (config: Config, versionShort: string, versionLong
dom: true,
location: true,
},
environment: process.env.NODE_ENV || 'unkonwn',
environment: getAppEnvironment() || 'unkonwn',
transport: trackRavenError,
};
if (versionShort && versionShort !== 'unknown') {
Expand Down
18 changes: 15 additions & 3 deletions packages/jaeger-ui/src/utils/tracking/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -126,14 +126,18 @@ describe('generic analytics tracking', () => {

it('get versions as a string or bad JSON test', () => {
const version = '123456';
process.env.REACT_APP_VSN_STATE = version;

jest.doMock('../config/get-config', () => {
return {
__esModule: true,
default: () => ({}),
};
});

jest.doMock('../constants', () => ({
getVersionInfo: () => version,
}));

return import('.').then(() => {
expect(internalVersionShort).toBe(version);
expect(internalVersionLong).toBe(version);
Expand All @@ -145,14 +149,18 @@ describe('generic analytics tracking', () => {
it('get versions as an object test', () => {
const vShot = '48956d5';
const vLong = ' | github.com/jaegertracing/jaeger-ui | 48956d5 | main';
process.env.REACT_APP_VSN_STATE = `{"remote":"github.com/jaegertracing/jaeger-ui","objName":"${vShot}","changed":{"hasChanged":false,"files":0,"insertions":0,"deletions":0,"untracked":0,"pretty":""},"refName":"main","pretty":"${vLong}"}`;
const rawVersion = `{"remote":"github.com/jaegertracing/jaeger-ui","objName":"${vShot}","changed":{"hasChanged":false,"files":0,"insertions":0,"deletions":0,"untracked":0,"pretty":""},"refName":"main","pretty":"${vLong}"}`;
jest.doMock('../config/get-config', () => {
return {
__esModule: true,
default: () => ({}),
};
});

jest.doMock('../constants', () => ({
getVersionInfo: () => rawVersion,
}));

return import('.').then(() => {
expect(internalVersionShort).toBe(vShot);
expect(internalVersionLong).toBe(vLong);
Expand All @@ -165,14 +173,18 @@ describe('generic analytics tracking', () => {
const vShotCommitSHA = '48956d5';
const vShotChanges = '2f +20 -3 1?';
const vLong = ' | github.com/jaegertracing/jaeger-ui | 48956d5 | main';
process.env.REACT_APP_VSN_STATE = `{"remote":"github.com/jaegertracing/jaeger-ui","objName":"${vShotCommitSHA}","changed":{"hasChanged":true,"files":2,"insertions":20,"deletions":3,"untracked":1,"pretty":"${vShotChanges}"},"refName":"main","pretty":"${vLong}"}`;
const rawVersion = `{"remote":"github.com/jaegertracing/jaeger-ui","objName":"${vShotCommitSHA}","changed":{"hasChanged":true,"files":2,"insertions":20,"deletions":3,"untracked":1,"pretty":"${vShotChanges}"},"refName":"main","pretty":"${vLong}"}`;
jest.doMock('../config/get-config', () => {
return {
__esModule: true,
default: () => ({}),
};
});

jest.doMock('../constants', () => ({
getVersionInfo: () => rawVersion,
}));

return import('.').then(() => {
expect(internalVersionShort).toBe(`${vShotCommitSHA} ${vShotChanges}`);
expect(internalVersionLong).toBe(vLong);
Expand Down
11 changes: 7 additions & 4 deletions packages/jaeger-ui/src/utils/tracking/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,24 +17,27 @@ import { IWebAnalyticsFunc } from '../../types/tracking';
import GA from './ga';
import NoopWebAnalytics from './noopWebAnalytics';
import getConfig from '../config/get-config';
import { getVersionInfo } from '../constants';

const TrackingImplementation = () => {
const config = getConfig();
let versionShort;
let versionLong;

if (process.env.REACT_APP_VSN_STATE) {
const versionInfo = getVersionInfo();

if (versionInfo) {
try {
const data = JSON.parse(process.env.REACT_APP_VSN_STATE);
const data = JSON.parse(versionInfo);
const joiner = [data.objName];
if (data.changed.hasChanged) {
joiner.push(data.changed.pretty);
}
versionShort = joiner.join(' ');
versionLong = data.pretty;
} catch (_) {
versionShort = process.env.REACT_APP_VSN_STATE;
versionLong = process.env.REACT_APP_VSN_STATE;
versionShort = versionInfo;
versionLong = versionInfo;
}
versionLong = versionLong.length > 99 ? `${versionLong.slice(0, 96)}...` : versionLong;
} else {
Expand Down
6 changes: 3 additions & 3 deletions packages/jaeger-ui/src/utils/version/get-version.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,9 @@ describe('getVersion()', () => {
console.warn = oldWarn;
});

describe('`window.getVersion` is not a function', () => {
describe('`window.getJaegerVersion` is not a function', () => {
beforeAll(() => {
window.getVersion = undefined;
window.getJaegerVersion = undefined;
});

it('warns once', () => {
Expand All @@ -51,7 +51,7 @@ describe('getVersion()', () => {
});
});

describe('`window.getVersion` is a function', () => {
describe('`window.getJaegerVersion` is a function', () => {
let embedded;
let getJaegerVersion;

Expand Down

0 comments on commit e8b94c9

Please sign in to comment.