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: refactor metrics recording so it gets unified #4

Merged
merged 1 commit into from
Nov 23, 2023
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
35 changes: 34 additions & 1 deletion src/base.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { Command } from '@oclif/core';
import { NewRelicSink, Recorder, Sink, StdOutSink } from '@smoya/asyncapi-adoption-metrics';
import { MetadataFromDocument, MetricMetadata, NewRelicSink, Recorder, Sink, StdOutSink } from '@smoya/asyncapi-adoption-metrics';
import { Parser } from '@asyncapi/parser';

class DiscardSink implements Sink {
async send() {
Expand All @@ -9,6 +10,7 @@ class DiscardSink implements Sink {

export default abstract class extends Command {
recorder = recorderFromEnv('asyncapi_adoption');
parser = new Parser();

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

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

async recordActionInvoked(action: string, metadata?: MetricMetadata) {
await this.recordActionMetric(this.recorder.recordActionInvoked, action, metadata);
}

async recordActionMetric(recordFunc: (actionName: string, metadata?: MetricMetadata) => Promise<void>, action: string, metadata?: MetricMetadata) {
try {
await recordFunc(action, metadata);
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}`);
}
}
}
}

function recorderFromEnv(prefix: string): Recorder {
Expand Down
17 changes: 2 additions & 15 deletions src/commands/bundle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,21 +80,8 @@ export default class Bundle extends Command {

const result = await load(output);

try {
// Metrics recording.
const {document} = await this.parser.parse(result.text());
if (document !== undefined) {
const metadata = MetadataFromDocument(document);
metadata['success'] = true;
metadata['files'] = AsyncAPIFiles.length;
await this.recorder.recordActionExecuted('bundle', metadata);
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}`);
}
}
// Metrics recording.
await this.recordActionExecuted(result.text(), {success: true, files: AsyncAPIFiles.length});
}

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

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

Expand All @@ -29,8 +28,6 @@ export default class Convert extends Command {
{ name: 'spec-file', description: 'spec path, url, or context-name', required: false },
];

parser = new Parser();

async run() {
const { args, flags } = await this.parse(Convert);
const filePath = args['spec-file'];
Expand Down Expand Up @@ -74,21 +71,20 @@ export default class Convert extends Command {
}
}

// Metrics recording.
let metadata: MetricMetadata = {success: true, to_version: flags['target-version']};
try {
// Metrics recording.
const {document} = await this.parser.parse(specFile.text());
if (document !== undefined && convertedFileFormatted) {
const metadata = MetadataFromDocument(document);
metadata['success'] = true;
if (document !== undefined) {
metadata = MetadataFromDocument(document, metadata);
metadata['from_version'] = document.version();
metadata['to_version'] = flags['target-version'];
await this.recorder.recordActionExecuted('convert', metadata);
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}`);
}
}

await this.recordActionExecuted('convert', metadata);
}
}
21 changes: 2 additions & 19 deletions src/commands/validate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,6 @@ 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';
import { Parser } from '@asyncapi/parser';

export default class Validate extends Command {
static description = 'validate asyncapi file';
Expand All @@ -21,8 +19,6 @@ export default class Validate extends Command {
{ name: 'spec-file', description: 'spec path, url, or context-name', required: false },
];

parser = new Parser();

async run() {
const { args, flags } = await this.parse(Validate); //NOSONAR
const filePath = args['spec-file'];
Expand All @@ -35,20 +31,7 @@ export default class Validate extends Command {

const result = await validate(this, specFile, flags);

try {
// Metrics recording.
const {document} = await this.parser.parse(specFile.text());
if (document !== undefined) {
const metadata = MetadataFromDocument(document);
metadata['success'] = true;
metadata['validation_result'] = result;
await this.recorder.recordActionExecuted('validate', metadata);
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}`);
}
}
// Metrics recording.
await this.recordActionExecuted('validate', {success: true, validation_result: result}, specFile.text());
}
}
11 changes: 11 additions & 0 deletions src/hooks/prerun/invoke-metrics.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import {Hook} from '@oclif/core';
// import base from '../../base';

const hook: Hook<'prerun'> = async function (opts) {
// opts.Command._base.
// process.stdout.write(`example hook running ${opts.Command.name.toLowerCase()}\n`);
// await (opts.Command as any as base).recorder.recordActionInvoked(opts.Command.name.toLowerCase());
return;
};

export default hook;
Loading