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

perf: resolve jsonurls while merging reports #499

Merged
merged 1 commit into from
Sep 11, 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
45 changes: 44 additions & 1 deletion lib/merge-reports/index.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,17 @@
'use strict';

const axios = require('axios');
const _ = require('lodash');
const serverUtils = require('../server-utils');

module.exports = async (pluginConfig, hermione, srcPaths, {destination: destPath}) => {
validateOpts(srcPaths, destPath);

const resolvedUrls = await tryResolveUrls(srcPaths);

await Promise.all([
serverUtils.saveStaticFilesToReportDir(hermione.htmlReporter, pluginConfig, destPath),
serverUtils.writeDatabaseUrlsFile(destPath, srcPaths)
serverUtils.writeDatabaseUrlsFile(destPath, resolvedUrls)
]);

await hermione.htmlReporter.emitAsync(hermione.htmlReporter.events.REPORT_SAVED, {reportPath: destPath});
Expand All @@ -22,3 +26,42 @@ function validateOpts(srcPaths, destPath) {
throw new Error(`Destination report path: ${destPath}, exists in source report paths`);
}
}

async function tryResolveUrls(urls) {
const resolvedUrls = [];
const results = await Promise.all(urls.map(tryResolveUrl));

results.forEach(({jsonUrls, dbUrls}) => {
resolvedUrls.push(...jsonUrls.concat(dbUrls));
});

return resolvedUrls;
Comment on lines +34 to +38
Copy link
Member Author

Choose a reason for hiding this comment

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

Все urls вставляются в один массив, потому что это позволяет не ломать API слияния отчетов

}

async function tryResolveUrl(url) {
Copy link
Member Author

Choose a reason for hiding this comment

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

Рекурсивно проходит по всем вложенным .json базам. Если возникает ошибка при получении данных, возвращаем саму json-базу. Помимо "ничего не сломать", фоллбэк нужен для драфт отчетов

const jsonUrls = [];
const dbUrls = [];

if (serverUtils.isDbUrl(url)) {
dbUrls.push(url);
} else if (serverUtils.isJsonUrl(url)) {
try {
const {data} = await axios.get(url);
const currentDbUrls = _.get(data, 'dbUrls', []);
const currentJsonUrls = _.get(data, 'jsonUrls', []);

const responses = await Promise.all(currentJsonUrls.map(tryResolveUrl));

dbUrls.push(...currentDbUrls);

responses.forEach(response => {
dbUrls.push(...response.dbUrls);
jsonUrls.push(...response.jsonUrls);
Copy link
Member

Choose a reason for hiding this comment

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

для чего нам здесь накапливать json-урлы? просто на всякий случай, чтобы понять откуда базы приехали?

Copy link
Member Author

Choose a reason for hiding this comment

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

Нет, тут логика такая:

в responses хранятся dbUrls и jsonUrls, и этот responses образуется как результат выполнения этой же функции

Эта же функция берет url и если это jsonUrl, пытается ее развернуть. Результаты .db складывает, результаты .json пытается развернуть. Если не получилось по какой-то причине, возвращаем этот json-урл. Собственно, там не изначальные json-урлы, а только те, по которым не получилось скачать сами json-ы. В результате, если сеть работает, а запросы шлются нормально - эти jsonUrls будут пустыми. Если сеть не работает, или запрос выкинул ошибку - jsonUrls будет равен исходному

});
} catch (e) {
jsonUrls.push(url);
}
}
Copy link
Member

Choose a reason for hiding this comment

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

у нас разве где-то есть проверка на то, что мы можем передать только путы формата json/db? сейчас у тебя нет обработки на такой случай и мы вернем пустые массивы. Это вроде и норм, но ругнуться все равно на это нужно

Copy link
Member Author

Choose a reason for hiding this comment

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

В этом плане поведение идентично текущему:
Вот тут прокидываем сырые srcPaths (тут могут быть и .json, и .db, и что угодно), а затем эта функция вот тут втихую фильтрует все, что не .json и не .db


return {jsonUrls, dbUrls};
}
12 changes: 10 additions & 2 deletions lib/server-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -171,9 +171,17 @@ export function urlPathNameEndsWith(currentUrl: string, searchString: string): b
}
}

export function isJsonUrl(url: string): boolean {
return urlPathNameEndsWith(url, '.json');
}

export function isDbUrl(url: string): boolean {
return urlPathNameEndsWith(url, '.db');
}

export async function writeDatabaseUrlsFile(destPath: string, srcPaths: string[]): Promise<void> {
const jsonUrls = srcPaths.filter(p => urlPathNameEndsWith(p, '.json'));
const dbUrls = srcPaths.filter(p => urlPathNameEndsWith(p, '.db'));
const jsonUrls = srcPaths.filter(isJsonUrl);
const dbUrls = srcPaths.filter(isDbUrl);
const data = {
dbUrls,
jsonUrls
Expand Down
37 changes: 34 additions & 3 deletions test/unit/lib/merge-reports/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ const originalServerUtils = require('lib/server-utils');

describe('lib/merge-reports', () => {
const sandbox = sinon.sandbox.create();
let htmlReporter, serverUtils, mergeReports;
let htmlReporter, serverUtils, mergeReports, axiosStub;

const execMergeReports_ = async ({pluginConfig = stubConfig(), hermione = stubTool(stubConfig()), paths = [], opts = {}}) => {
opts = _.defaults(opts, {destination: 'default-dest-report/path'});
Expand All @@ -17,6 +17,7 @@ describe('lib/merge-reports', () => {

beforeEach(() => {
serverUtils = _.clone(originalServerUtils);
axiosStub = {get: sandbox.stub().rejects()};

sandbox.stub(serverUtils, 'saveStaticFilesToReportDir').resolves();
sandbox.stub(serverUtils, 'writeDatabaseUrlsFile').resolves();
Expand All @@ -26,7 +27,8 @@ describe('lib/merge-reports', () => {
htmlReporter.emitAsync = sinon.stub();

mergeReports = proxyquire('lib/merge-reports', {
'../server-utils': serverUtils
'../server-utils': serverUtils,
'axios': axiosStub
});
});

Expand All @@ -51,7 +53,7 @@ describe('lib/merge-reports', () => {
it('should merge reports', async () => {
const pluginConfig = stubConfig();
const hermione = stubTool(pluginConfig, {}, {}, htmlReporter);
const paths = ['src-report/path-1', 'src-report/path-2'];
const paths = ['src-report/path-1.json', 'src-report/path-2.db'];
const destination = 'dest-report/path';

await execMergeReports_({pluginConfig, hermione, paths, opts: {destination}});
Expand All @@ -60,6 +62,35 @@ describe('lib/merge-reports', () => {
assert.calledOnceWith(serverUtils.writeDatabaseUrlsFile, destination, paths);
});

it('should resolve json urls while merging reports', async () => {
const pluginConfig = stubConfig();
const hermione = stubTool(pluginConfig, {}, {}, htmlReporter);
const paths = ['src-report/path-1.json'];
const destination = 'dest-report/path';

axiosStub.get.withArgs('src-report/path-1.json').resolves({data: {jsonUrls: ['src-report/path-2.json', 'src-report/path-3.json'], dbUrls: ['path-1.db']}});
axiosStub.get.withArgs('src-report/path-2.json').resolves({data: {jsonUrls: [], dbUrls: ['path-2.db']}});
axiosStub.get.withArgs('src-report/path-3.json').resolves({data: {jsonUrls: ['src-report/path-4.json'], dbUrls: ['path-3.db']}});
axiosStub.get.withArgs('src-report/path-4.json').resolves({data: {jsonUrls: [], dbUrls: ['path-4.db']}});

await execMergeReports_({pluginConfig, hermione, paths, opts: {destination}});

assert.calledOnceWith(serverUtils.writeDatabaseUrlsFile, destination, ['path-1.db', 'path-2.db', 'path-3.db', 'path-4.db']);
});

it('should fallback to json url while merging reports', async () => {
const pluginConfig = stubConfig();
const hermione = stubTool(pluginConfig, {}, {}, htmlReporter);
const paths = ['src-report/path-1.json'];
const destination = 'dest-report/path';

axiosStub.get.rejects();

await execMergeReports_({pluginConfig, hermione, paths, opts: {destination}});

assert.calledOnceWith(serverUtils.writeDatabaseUrlsFile, destination, ['src-report/path-1.json']);
});

it('should emit REPORT_SAVED event', async () => {
const hermione = stubTool({}, {}, {}, htmlReporter);
const destination = 'dest-report/path';
Expand Down
Loading