Skip to content
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
6 changes: 6 additions & 0 deletions apps/src/lib/metrics/MetricsApi.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
/**
* Interface for interacting with a metrics service API.
*/
export default interface MetricsApi {
sendLogs: (logs: object[]) => Promise<Response>;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should we define the log type more than just an object?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I was thinking this could just be a generic JSON object payload; but I guess if we know about some required parameters that the metrics reporter adds (such as device info), this could be defined in a little more detail?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I opted to just keep this as an object for now for flexibility and to match the backend method signature (which just takes a list of JSON objects to log).

}
116 changes: 116 additions & 0 deletions apps/src/lib/metrics/MetricsReporter.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
import MetricsApi from './MetricsApi';

const isDevelopmentEnvironment =
require('../../utils').isDevelopmentEnvironment;

/**
* If we receive an unauthorized response from the server, this may
* indicate that browser event reporting has been temporarily disabled.
* We will wait for a specific time interval (defined below) before making
* a request again, so as to not flood the server with requests.
*/
const CHECK_CAN_REPORT_INTERVAL_MINUTES = 30;
const CHECK_CAN_REPORT_INTERVAL_MS =
CHECK_CAN_REPORT_INTERVAL_MINUTES * 60 * 1000;
const LOCAL_STORAGE_KEY_NAME = 'cdo-metrics-reporter-last-check-time';

type LogLevel = 'INFO' | 'WARNING' | 'SEVERE';

/**
* Reports logs and metrics, intended primarily for developer-facing
* error reporting, metric reporting, and logging.
*
* For tracking user interactions and behaviors (product-facing),
* see {@link AnalyticsReporter} which reports to Amplitude.
*
* For legacy client-side reporting see {@link firehose} for AWS
* Firehose reporting and {@link logToCloud} for New Relic reporting.
*/
class MetricsReporter {
private lastCheckCanReportTime: number;

constructor(private readonly metricsApi: MetricsApi) {
this.metricsApi = metricsApi;
this.lastCheckCanReportTime =
parseInt(localStorage.getItem(LOCAL_STORAGE_KEY_NAME) || '0') || 0;
}

logInfo(message: string | object) {
this.log('INFO', message);
if (isDevelopmentEnvironment()) {
console.log('[MetricsReporter] ' + JSON.stringify(message));
}
}

logWarning(message: string | object) {
this.log('WARNING', message);
if (isDevelopmentEnvironment()) {
console.warn('[MetricsReporter] ' + JSON.stringify(message));
}
}

logError(message: string | object) {
this.log('SEVERE', message);
if (isDevelopmentEnvironment()) {
console.error('[MetricsReporter] ' + JSON.stringify(message));
}
}

private log(level: LogLevel, message: string | object) {
const payload = {
level,
message,
deviceInfo: this.getDeviceInfo()
};

if (!this.isReportingEnabled()) {
this.fallbackLog(payload);
return;
}

this.metricsApi.sendLogs([payload]).then(response => {
if (!response.ok) {
this.fallbackLog(payload);
}

if (response.status === 401) {
// Unauthorized response from server; client logging is likely disabled.
// We will check again after a time period of CHECK_CAN_REPORT_INTERVAL
this.setReportingDisabled();
}
});
}

private getDeviceInfo(): object {
return {
user_agent: window.navigator.userAgent,
window_width: window.innerWidth,
window_height: window.innerHeight,
hostname: window.location.hostname,
full_path: window.location.href
};
}

private fallbackLog(payload: object) {
if (isDevelopmentEnvironment()) {
console.log(
'Client-side reporting disabled. Attempted to report: ' +
JSON.stringify(payload)
);
}
}

private isReportingEnabled(): boolean {
return (
Date.now() - this.lastCheckCanReportTime > CHECK_CAN_REPORT_INTERVAL_MS
);
}

private setReportingDisabled() {
this.lastCheckCanReportTime = Date.now();
localStorage.setItem(
LOCAL_STORAGE_KEY_NAME,
this.lastCheckCanReportTime.toString()
);
}
}