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

feat: opportunities audit #360

Merged
merged 7 commits into from
Aug 26, 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
89 changes: 5 additions & 84 deletions package-lock.json

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@
"@adobe/spacecat-shared-ahrefs-client": "1.4.1",
"@adobe/spacecat-shared-data-access": "1.41.2",
"@adobe/spacecat-shared-http-utils": "1.6.1",
"@adobe/spacecat-shared-rum-api-client": "2.7.3",
"@adobe/spacecat-shared-rum-api-client": "https://gitpkg.now.sh/adobe/spacecat-shared/packages/spacecat-shared-rum-api-client?cede51c05756f680ea6a31189323038f7171da85",
"@adobe/spacecat-shared-rum-api-client-v1": "npm:@adobe/[email protected]",
"@aws-sdk/client-lambda": "3.624.0",
"@aws-sdk/credential-provider-node": "3.624.0",
Expand Down
2 changes: 2 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import experimentation from './experimentation/handler.js';
import conversion from './conversion/handler.js';
import essExperimentationDaily from './experimentation-ess/daily.js';
import essExperimentationAll from './experimentation-ess/all.js';
import opportunities from './opportunities/opportunities.js';

const HANDLERS = {
apex,
Expand All @@ -43,6 +44,7 @@ const HANDLERS = {
conversion,
'experimentation-ess-daily': essExperimentationDaily,
'experimentation-ess-all': essExperimentationAll,
opportunities,
};

function getElapsedSeconds(startTime) {
Expand Down
69 changes: 69 additions & 0 deletions src/opportunities/opportunities.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
/*
* Copyright 2024 Adobe. All rights reserved.
* This file is licensed to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
* OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/

/* c8 ignore start */
import RUMAPIClient from '@adobe/spacecat-shared-rum-api-client';
import { AuditBuilder } from '../common/audit-builder.js';
import { getRUMDomainkey } from '../support/utils.js';

const DAYS = 30;

let log = console;

/**
* Audit handler container for all the opportunities
* @param {*} auditUrl
* @param {*} context
* @param {*} site
* @returns
*/

export async function opportunitiesHandler(auditUrl, context, site) {
log = context.log;
log.info(`Received Experimentation Opportunities audit request for ${auditUrl}`);
const startTime = process.hrtime();

const rumAPIClient = RUMAPIClient.createFrom(context);
const domainkey = await getRUMDomainkey(site.getBaseURL(), context);
const options = {
domain: auditUrl,
domainkey,
interval: DAYS,
granularity: 'hourly',
};
const experimentationHandlers = ['rageclick'];
const queryResults = await rumAPIClient.queryMulti(experimentationHandlers, options);
const auditData = {
experimentationOpportunities: [],
};
for (const queryResult of Object.keys(queryResults)) {
if (experimentationHandlers.includes(queryResult)) {
auditData.experimentationOpportunities.push(...queryResults[queryResult]);
}
}

const endTime = process.hrtime(startTime);
const elapsedSeconds = endTime[0] + endTime[1] / 1e9;
const formattedElapsed = elapsedSeconds.toFixed(2);

log.info(`Experimentation opportunities Audit is completed in ${formattedElapsed} seconds for ${auditUrl}`);

return {
auditResult: auditData,
fullAuditRef: auditUrl,
};
}

export default new AuditBuilder()
.withRunner(opportunitiesHandler)
.build();
/* c8 ignore stop */
110 changes: 110 additions & 0 deletions test/audits/opportunities.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
/*
* Copyright 2023 Adobe. All rights reserved.
* This file is licensed to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
* OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/

/* eslint-env mocha */

import chai from 'chai';
import sinon from 'sinon';
import sinonChai from 'sinon-chai';
import nock from 'nock';
import { opportunitiesHandler } from '../../src/opportunities/opportunities.js';
import { MockContextBuilder } from '../shared.js';
import opportunitiesData from '../fixtures/opportunitiesdata.json' assert { type: 'json' };

chai.use(sinonChai);
const { expect } = chai;

describe('Opportunities Tests', () => {
const url = 'https://abc.com';
let context;
let processEnvCopy;
let messageBodyJson;
let sandbox;
before('setup', function () {
sandbox = sinon.createSandbox();
const mockDate = '2023-11-27T12:30:01.124Z';
this.clock = sandbox.useFakeTimers({
now: new Date(mockDate).getTime(),
});
});

beforeEach('setup', () => {
messageBodyJson = {
type: '404',
url: 'https://abc.com',
auditContext: {
finalUrl: 'abc.com',
},
};
context = new MockContextBuilder()
.withSandbox(sandbox)
.withOverrides({
env: {
AUDIT_RESULTS_QUEUE_URL: 'queueUrl',
AWS_REGION: 'us-east-1',
AWS_ACCESS_KEY_ID: 'some-key-id',
AWS_SECRET_ACCESS_KEY: 'some-secret-key',
AWS_SESSION_TOKEN: 'some-secret-token',
},
runtime: { name: 'aws-lambda', region: 'us-east-1' },
func: { package: 'spacecat-services', version: 'ci', name: 'test' },
})
.build(messageBodyJson);
processEnvCopy = { ...process.env };
process.env = {
...process.env,
...context.env,
};
});
after('clean', function () {
this.clock.uninstall();
});

afterEach(() => {
process.env = processEnvCopy;
nock.cleanAll();
sinon.restore();
});

it('fetch bundles for base url > process > send opportunities', async () => {
nock('https://secretsmanager.us-east-1.amazonaws.com/')
.post('/', (body) => body.SecretId === '/helix-deploy/spacecat-services/customer-secrets/abc_com/ci')
.reply(200, {
SecretString: JSON.stringify({
RUM_DOMAIN_KEY: 'abc_dummy_key',
}),
});
nock('https://abc.com')
.get('/')
.reply(200);
context.rumApiClient = {
queryMulti: sinon.stub().resolves(opportunitiesData),
};
const site = {
getBaseURL: () => 'https://abc.com',
};
const auditData = await opportunitiesHandler(url, context, site);

expect(context.rumApiClient.queryMulti).calledWith(
['rageclick'],
{
domain: 'https://abc.com',
domainkey: 'abc_dummy_key',
interval: 30,
granularity: 'hourly',
},
);
expect(
auditData.auditResult.experimentationOpportunities,
).to.deep.equal(opportunitiesData.rageclick);
});
});
47 changes: 47 additions & 0 deletions test/fixtures/opportunitiesdata.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
{
"rageclick": [
{
"type": "rageclick",
"page": "https://abc.com/abc-adoption/survey",
"screenshot": "",
"trackedPageKPIName": "The percentage of users who click on the same element lot of times in a short period of time.",
"trackedPageKPIValue": 43.25513196480938,
"pageViews": 34100,
"samples": 341,
"metrics": [
{
"type": "click",
"selector": ".abc-survey",
"value": 2111,
"samples": 138,
"percentage": 40.469208211143695
},
{
"type": "click",
"selector": ".abc-survey #abc-survey-next",
"value": 2160,
"samples": 157,
"percentage": 46.04105571847507
}
]
},
{
"type": "rageclick",
"page": "https://abc.com/abc-adoption/account",
"screenshot": "",
"trackedPageKPIName": "The percentage of users who click on the same element lot of times in a short period of time.",
"trackedPageKPIValue": 8.771929824561402,
"pageViews": 11400,
"samples": 114,
"metrics": [
{
"type": "click",
"selector": ".account #favorites",
"value": 138,
"samples": 10,
"percentage": 8.771929824561402
}
]
}
]
}
Loading