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

chore: unify logic for metrics collection when any command is executed #8

Merged
merged 8 commits into from
Jan 12, 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
38 changes: 17 additions & 21 deletions src/base.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { Command } from '@oclif/core';
import { MetadataFromDocument, MetricMetadata, NewRelicSink, Recorder, Sink, StdOutSink } from '@smoya/asyncapi-adoption-metrics';
import { MetricMetadata, NewRelicSink, Recorder, Sink, StdOutSink } from '@smoya/asyncapi-adoption-metrics';
import { Parser } from '@asyncapi/parser';
import { Specification } from 'models/SpecificationFile';

class DiscardSink implements Sink {
async send() {
Expand All @@ -11,6 +12,14 @@ class DiscardSink implements Sink {
export default abstract class extends Command {
recorder = this.recorderFromEnv('asyncapi_adoption');
parser = new Parser();
metricsMetadata: MetricMetadata = {};
specFile: Specification | undefined;

async init(): Promise<void> {
await super.init();
const commandName : string = this.id || '';
await this.recordActionInvoked(commandName);
}

async catch(err: Error & { exitCode?: number; }): Promise<any> {
try {
Expand All @@ -23,20 +32,7 @@ export default abstract class extends Command {
}
}

async recordActionExecuted(action: string, metadata: MetricMetadata = {}, rawDocument?: string) {
peter-rr marked this conversation as resolved.
Show resolved Hide resolved
if (rawDocument !== undefined) {
try {
const {document} = await this.parser.parse(rawDocument);
if (document !== undefined) {
metadata = MetadataFromDocument(document, metadata);
}
} catch (e: any) {
if (e instanceof Error) {
this.log(`Skipping submitting anonymous metrics due to the following error: ${e.name}: ${e.message}`);
}
}
}

async recordActionExecuted(action: string, metadata: MetricMetadata = {}) {
const callable = async function(recorder: Recorder) {
await recorder.recordActionExecuted(action, metadata);
};
Expand All @@ -63,12 +59,6 @@ export default abstract class extends Command {
}
}

async init(): Promise<void> {
await super.init();
const commandName : string = this.id || '';
await this.recordActionInvoked(commandName);
}

recorderFromEnv(prefix: string): Recorder {
let sink: Sink = new DiscardSink();
if (process.env.ASYNCAPI_METRICS !== 'false') {
Expand All @@ -90,5 +80,11 @@ export default abstract class extends Command {

return new Recorder(prefix, sink);
}

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);
}
}

13 changes: 12 additions & 1 deletion src/commands/bundle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import path from 'path';
import { Specification, load } from '../models/SpecificationFile';
import { Parser } from '@asyncapi/parser';
import { MetadataFromDocument } from '@smoya/asyncapi-adoption-metrics';

const { writeFile } = promises;

Expand All @@ -29,7 +30,7 @@

parser = new Parser();

async run() {

Check warning on line 33 in src/commands/bundle.ts

View workflow job for this annotation

GitHub Actions / Test NodeJS PR - ubuntu-latest

Refactor this function to reduce its Cognitive Complexity from 17 to the 15 allowed
const { argv, flags } = await this.parse(Bundle);
const output = flags.output;
let baseFile;
Expand Down Expand Up @@ -80,7 +81,17 @@
const result = await load(output);

// Metrics recording.
await this.recordActionExecuted(result.text(), {success: true, files: AsyncAPIFiles.length});
this.metricsMetadata = {success: true, files: AsyncAPIFiles.length};
peter-rr marked this conversation as resolved.
Show resolved Hide resolved
try {
const {document} = await this.parser.parse(result.text());
if (document !== undefined) {
this.metricsMetadata = MetadataFromDocument(document, this.metricsMetadata);
}
} catch (e: any) {
if (e instanceof Error) {
this.log(`Skipping submitting anonymous metrics due to the following error: ${e.name}: ${e.message}`);
}
}
}

async loadFiles(filepaths: string[]): Promise<Specification[]> {
Expand Down
10 changes: 4 additions & 6 deletions src/commands/convert.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
import { load } from '../models/SpecificationFile';
import { SpecificationFileNotFound } from '../errors/specification-file';
import { convert } from '@asyncapi/converter';
import { MetadataFromDocument, MetricMetadata } from '@smoya/asyncapi-adoption-metrics';
import { MetadataFromDocument } from '@smoya/asyncapi-adoption-metrics';

import type { ConvertVersion } from '@asyncapi/converter';

Expand All @@ -28,7 +28,7 @@
{ name: 'spec-file', description: 'spec path, url, or context-name', required: false },
];

async run() {

Check warning on line 31 in src/commands/convert.ts

View workflow job for this annotation

GitHub Actions / Test NodeJS PR - ubuntu-latest

Refactor this function to reduce its Cognitive Complexity from 16 to the 15 allowed
const { args, flags } = await this.parse(Convert);
const filePath = args['spec-file'];
let specFile;
Expand Down Expand Up @@ -72,19 +72,17 @@
}

// Metrics recording.
let metadata: MetricMetadata = {success: true, to_version: flags['target-version']};
this.metricsMetadata = {success: true, to_version: flags['target-version']};
try {
const {document} = await this.parser.parse(specFile.text());
if (document !== undefined) {
metadata = MetadataFromDocument(document, metadata);
metadata['from_version'] = document.version();
this.metricsMetadata = MetadataFromDocument(document, this.metricsMetadata);
this.metricsMetadata['from_version'] = document.version();
}
} catch (e: any) {
if (e instanceof Error) {
this.log(`Skipping submitting anonymous metrics due to the following error: ${e.name}: ${e.message}`);
}
}

await this.recordActionExecuted('convert', metadata);
}
}
13 changes: 12 additions & 1 deletion src/commands/generate/fromTemplate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { isLocalTemplate, Watcher } from '../../utils/generator';
import { ValidationError } from '../../errors/validation-error';
import { GeneratorError } from '../../errors/generator-error';
import { Parser } from '@asyncapi/parser';
import { MetadataFromDocument } from '@smoya/asyncapi-adoption-metrics';

import type { Example } from '@oclif/core/lib/interfaces';

Expand Down Expand Up @@ -147,7 +148,17 @@ export default class Template extends Command {
}

// Metrics recording.
await this.recordActionExecuted('generate_from_template', {success: true, template}, asyncapiInput.text());
this.metricsMetadata = {success: true, template};
try {
const {document} = await this.parser.parse(asyncapiInput.text());
if (document !== undefined) {
this.metricsMetadata = MetadataFromDocument(document, this.metricsMetadata);
}
} catch (e: any) {
if (e instanceof Error) {
this.log(`Skipping submitting anonymous metrics due to the following error: ${e.name}: ${e.message}`);
}
}
}

private parseFlags(disableHooks?: string[], params?: string[], mapBaseUrl?: string): ParsedFlags {
Expand Down
19 changes: 15 additions & 4 deletions src/commands/optimize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,14 @@
import { promises } from 'fs';
import { Example } from '@oclif/core/lib/interfaces';
import { Parser } from '@asyncapi/parser';
import { MetadataFromDocument } from '@smoya/asyncapi-adoption-metrics';

const { writeFile } = promises;

export enum Optimizations {
REMOVE_COMPONENTS='remove-components',
REUSE_COMPONENTS='reuse-components',
MOVE_TO_COMPONETS='move-to-components'
MOVE_TO_COMPONENTS='move-to-components'
Copy link
Owner

Choose a reason for hiding this comment

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

john-cena-deformed-gif

Copy link
Collaborator Author

@peter-rr peter-rr Jan 10, 2024

Choose a reason for hiding this comment

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

Yeah...it was there since a loooong time ago 🙈

}

export enum Outputs {
Expand Down Expand Up @@ -48,7 +49,7 @@

parser = new Parser();

async run() {

Check warning on line 52 in src/commands/optimize.ts

View workflow job for this annotation

GitHub Actions / Test NodeJS PR - ubuntu-latest

Refactor this function to reduce its Cognitive Complexity from 19 to the 15 allowed
const { args, flags } = await this.parse(Optimize); //NOSONAR
const filePath = args['spec-file'];
let specFile: Specification;
Expand Down Expand Up @@ -96,7 +97,7 @@

try {
const optimizedDocument = optimizer.getOptimizedDocument({rules: {
moveToComponents: this.optimizations.includes(Optimizations.MOVE_TO_COMPONETS),
moveToComponents: this.optimizations.includes(Optimizations.MOVE_TO_COMPONENTS),
removeComponents: this.optimizations.includes(Optimizations.REMOVE_COMPONENTS),
reuseComponents: this.optimizations.includes(Optimizations.REUSE_COMPONENTS)
}, output: Output.YAML});
Expand Down Expand Up @@ -129,7 +130,17 @@
}

// Metrics recording.
await this.recordActionExecuted('optimize', {success: true, optimizations: this.optimizations}, specFile.text());
this.metricsMetadata = {success: true, optimizations: this.optimizations};
try {
const {document} = await this.parser.parse(specFile.text());
if (document !== undefined) {
this.metricsMetadata = MetadataFromDocument(document, this.metricsMetadata);
}
} catch (e: any) {
if (e instanceof Error) {
this.log(`Skipping submitting anonymous metrics due to the following error: ${e.name}: ${e.message}`);
}
}
}

private showOptimizations(elements: ReportElement[] | undefined) {
Expand Down Expand Up @@ -159,7 +170,7 @@
const totalMove = report.moveToComponents?.filter((e: ReportElement) => e.action === 'move').length;
this.log(`\n${chalk.green(totalMove)} components can be moved to the components sections.\nthe following changes will be made:`);
this.showOptimizations(report.moveToComponents);
choices.push({name: 'move to components section', value: Optimizations.MOVE_TO_COMPONETS});
choices.push({name: 'move to components section', value: Optimizations.MOVE_TO_COMPONENTS});
}
if (canRemove) {
const totalMove = report.removeComponents?.length;
Expand Down
14 changes: 12 additions & 2 deletions src/commands/validate.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { Flags } from '@oclif/core';

import Command from '../base';
import { validate, validationFlags } from '../parser';
import { load } from '../models/SpecificationFile';
import { specWatcher } from '../globals';
import { watchFlag } from '../flags';
import { MetadataFromDocument } from '@smoya/asyncapi-adoption-metrics';

export default class Validate extends Command {
static description = 'validate asyncapi file';
Expand Down Expand Up @@ -32,6 +32,16 @@ export default class Validate extends Command {
const result = await validate(this, specFile, flags);

// Metrics recording.
await this.recordActionExecuted('validate', {success: true, validation_result: result}, specFile.text());
this.metricsMetadata = {success: true, validation_result: result};
try {
const {document} = await this.parser.parse(specFile.text());
if (document !== undefined) {
this.metricsMetadata = MetadataFromDocument(document, this.metricsMetadata);
}
} catch (e: any) {
if (e instanceof Error) {
this.log(`Skipping submitting anonymous metrics due to the following error: ${e.name}: ${e.message}`);
}
}
}
}
Loading