Skip to content

Commit

Permalink
Merge branch 'feat/adoptionMetrics' into feat/adoptMetrics-metrics-docs
Browse files Browse the repository at this point in the history
  • Loading branch information
peter-rr authored Feb 19, 2024
2 parents 42aa925 + e3fc3c7 commit 68e2488
Show file tree
Hide file tree
Showing 5 changed files with 67 additions and 15 deletions.
8 changes: 4 additions & 4 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
"@oclif/core": "^1.26.2",
"@oclif/errors": "^1.3.6",
"@oclif/plugin-not-found": "^2.3.22",
"@smoya/asyncapi-adoption-metrics": "^2.3.0",
"@smoya/asyncapi-adoption-metrics": "^2.4.0",
"@smoya/multi-parser": "^4.0.0",
"@stoplight/spectral-cli": "6.9.0",
"ajv": "^8.12.0",
Expand Down
37 changes: 28 additions & 9 deletions src/base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import { Command } from '@oclif/core';
import { MetadataFromDocument, MetricMetadata, NewRelicSink, Recorder, Sink, StdOutSink } from '@smoya/asyncapi-adoption-metrics';
import { Parser } from '@asyncapi/parser';
import { Specification } from 'models/SpecificationFile';
import { join, resolve } from 'path';
import { existsSync, readFileSync, writeFile } from 'fs-extra';

class DiscardSink implements Sink {
async send() {
Expand Down Expand Up @@ -32,7 +34,7 @@ export default abstract class extends Command {
}
}

async recordActionExecuted(action: string, metadata: MetricMetadata = {}, rawDocument?: string) {
async recordActionFinished(action: string, metadata: MetricMetadata = {}, rawDocument?: string) {
if (rawDocument !== undefined) {
try {
const {document} = await this.parser.parse(rawDocument);
Expand All @@ -47,7 +49,7 @@ export default abstract class extends Command {
}

const callable = async function(recorder: Recorder) {
await recorder.recordActionExecuted(action, metadata);
await recorder.recordActionFinished(action, metadata);
};

await this.recordActionMetric(callable);
Expand All @@ -63,8 +65,8 @@ export default abstract class extends Command {

async recordActionMetric(recordFunc: (recorder: Recorder) => Promise<void>) {
try {
await recordFunc(this.recorder);
await this.recorder.flush();
await recordFunc(await this.recorder);
await (await this.recorder).flush();
} catch (e: any) {
if (e instanceof Error) {
this.log(`Skipping submitting anonymous metrics due to the following error: ${e.name}: ${e.message}`);
Expand All @@ -75,12 +77,23 @@ export default abstract class extends Command {
async finally(error: Error | undefined): Promise<any> {
await super.finally(error);
this.metricsMetadata['success'] = error === undefined;
await this.recordActionExecuted(this.id as string, this.metricsMetadata, this.specFile?.text());
await this.recordActionFinished(this.id as string, this.metricsMetadata, this.specFile?.text());
}

recorderFromEnv(prefix: string): Recorder {
async recorderFromEnv(prefix: string): Promise<Recorder> {
let sink: Sink = new DiscardSink();
if (process.env.ASYNCAPI_METRICS !== 'false') {
const analyticsConfigFile = join(process.cwd(), '.asyncapi-analytics');

if (!existsSync(analyticsConfigFile)) {
await writeFile(analyticsConfigFile, JSON.stringify({ analyticsEnabled: 'true', infoMessageShown: 'false' }), { encoding: 'utf8' });
} else {
const analyticsConfigFileContent = JSON.parse(readFileSync(resolve(analyticsConfigFile), 'utf-8'));
if (analyticsConfigFileContent.analyticsEnabled === 'false') {
process.env.ASYNCAPI_METRICS = 'false';
}
}

if (process.env.ASYNCAPI_METRICS !== 'false' && process.env.CI !== 'true') {
switch (process.env.NODE_ENV) {
case 'development':
// NODE_ENV set to `development` in bin/run
Expand All @@ -91,8 +104,14 @@ export default abstract class extends Command {
break;
case 'production':
// NODE_ENV set to `production` in bin/run_bin, which is specified in 'bin' package.json section
sink = new NewRelicSink(process.env.ASYNCAPI_METRICS_NEWRELIC_KEY || 'eu01xx73a8521047150dd9414f6aedd2FFFFNRAL');
this.log('\nAsyncAPI anonymously tracks command executions to improve the specification and tools, ensuring no sensitive data reaches our servers. It aids in comprehending how AsyncAPI tools are used and adopted, facilitating ongoing improvements to our specifications and tools.\n\nTo disable tracking, please run the following command:\n asyncapi config analytics --disable\n\nOnce disabled, if you want to enable tracking back again then run:\n asyncapi config analytics');
sink = new NewRelicSink(process.env.ASYNCAPI_METRICS_NEWRELIC_KEY || 'eu01xx73a8521047150dd9414f6aedd2FFFFNRAL');
const analyticsConfigFileContent = JSON.parse(readFileSync(resolve(analyticsConfigFile), 'utf-8'));

if (existsSync(analyticsConfigFile) && (analyticsConfigFileContent.infoMessageShown === 'false')) {
this.log('\nAsyncAPI anonymously tracks command executions to improve the specification and tools, ensuring no sensitive data reaches our servers. It aids in comprehending how AsyncAPI tools are used and adopted, facilitating ongoing improvements to our specifications and tools.\n\nTo disable tracking, please run the following command:\n asyncapi config analytics --disable\n\nOnce disabled, if you want to enable tracking back again then run:\n asyncapi config analytics');
analyticsConfigFileContent.infoMessageShown = 'true';
await writeFile(analyticsConfigFile, JSON.stringify(analyticsConfigFileContent), { encoding: 'utf8' });
}
break;
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/commands/bundle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ export default class Bundle extends Command {
private async collectMetricsData(document: Document) {
try {
// We collect the metadata from the final output so it contains all the files
this.specFile = await load(new Specification(document.string()).text());
this.specFile = new Specification(document.string());
} catch (e: any) {
if (e instanceof Error) {
this.log(`Skipping submitting anonymous metrics due to the following error: ${e.name}: ${e.message}`);
Expand Down
33 changes: 33 additions & 0 deletions src/commands/config/analytics.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { Flags } from '@oclif/core';
import { readFileSync, writeFile } from 'fs-extra';
import { join, resolve } from 'path';
import Command from '../../base';

export default class Analytics extends Command {
static description = 'Enable or disable analytics for metrics collection';
static flags = {
help: Flags.help({ char: 'h' }),
disable: Flags.boolean({ char: 'd', description: 'disable analytics', default: false })
};

async run() {
try {
const { flags } = await this.parse(Analytics);
const isDisabled = flags.disable;
const analyticsConfigFile = join(process.cwd(), '.asyncapi-analytics');
const analyticsConfigFileContent = JSON.parse(readFileSync(resolve(process.cwd(), '.asyncapi-analytics'), 'utf-8'));

if (isDisabled) {
analyticsConfigFileContent.analyticsEnabled = 'false';
await writeFile(analyticsConfigFile, JSON.stringify(analyticsConfigFileContent), {encoding: 'utf8'});
this.log('Analytics disabled.');
} else {
analyticsConfigFileContent.analyticsEnabled = 'true';
await writeFile(analyticsConfigFile, JSON.stringify(analyticsConfigFileContent), {encoding: 'utf8'});
this.log('Analytics enabled.');
}
} catch (e: any) {
this.error(e as Error);
}
}
}

0 comments on commit 68e2488

Please sign in to comment.