Skip to content
Open
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
900 changes: 66 additions & 834 deletions package-lock.json

Large diffs are not rendered by default.

41 changes: 24 additions & 17 deletions src/digest/handler-external.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,19 +16,19 @@ import { BaseSlackClient, SLACK_TARGETS } from '@adobe/spacecat-shared-slack-cli
import {
getSlackContextForAlert, hasAlertConfig, isDigestReport,
} from '../support/config.js';
import { sendInitialMessage } from '../support/slack.js';
import { sendMessage } from '../support/slack.js';

export default async function externalDigestHandler(
context,
type,
INITIAL_MESSAGE,
processLatestAudit,
sendReport,
NO_DATA_MESSAGE,
) {
const { dataAccess, log } = context;

const organizations = await dataAccess.getOrganizations();
let sentInitialMessage = false;
const slackClient = BaseSlackClient.createFrom(context, SLACK_TARGETS.WORKSPACE_EXTERNAL);

for (const organization of organizations) {
Expand All @@ -42,25 +42,25 @@ export default async function externalDigestHandler(
false,
);
let slackContext = {};
const isDigest = isDigestReport(orgConfig, type);
if (isDigest && sites.length > 0) {
slackContext = getSlackContextForAlert(orgConfig, {}, type);
try {
// eslint-disable-next-line no-await-in-loop
slackContext = await sendMessage(slackClient, slackContext, INITIAL_MESSAGE);
} catch (e) {
log.error(`Failed to send initial Slack message. Reason: ${e.message}`);
return internalServerError('Failed to send initial Slack message');
}
}
for (const site of sites) {
const latestAuditReports = site.getAudits();
const siteConfig = site.getConfig();
if (!isDigest) {
slackContext = getSlackContextForAlert(orgConfig, siteConfig, type);
}
const message = processLatestAudit(context, site, latestAuditReports);
if (Object.keys(message).length > 0) {
const siteConfig = site.getConfig();
const isDigest = isDigestReport(orgConfig, type);
if (!isDigest || !sentInitialMessage) {
slackContext = getSlackContextForAlert(orgConfig, siteConfig, type);
}
if (!sentInitialMessage && isDigest) {
try {
// eslint-disable-next-line no-await-in-loop
slackContext = await sendInitialMessage(slackClient, slackContext, INITIAL_MESSAGE);
sentInitialMessage = true;
} catch (e) {
log.error(`Failed to send initial Slack message. Reason: ${e.message}`);
return internalServerError('Failed to send initial Slack message');
}
}
try {
// eslint-disable-next-line no-await-in-loop
await sendReport({
Expand All @@ -71,6 +71,13 @@ export default async function externalDigestHandler(
} catch (e) {
log.error(`Failed to send Slack message for ${site.getBaseURL()}. Reason: ${e.message}`);
}
} else {
try {
// eslint-disable-next-line no-await-in-loop
await sendMessage(slackClient, slackContext, NO_DATA_MESSAGE(site.getBaseURL()));
} catch (e) {
log.error(`Failed to send Slack message for ${site.getBaseURL()}. Reason: ${e.message}`);
}
}
}
}
Expand Down
4 changes: 2 additions & 2 deletions src/digest/handler-internal.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@

import { internalServerError, noContent } from '@adobe/spacecat-shared-http-utils';
import { BaseSlackClient, SLACK_TARGETS } from '@adobe/spacecat-shared-slack-client';
import { sendInitialMessage } from '../support/slack.js';
import { sendMessage } from '../support/slack.js';

export default async function internalDigestHandler(
context,
Expand All @@ -36,7 +36,7 @@ export default async function internalDigestHandler(
if (!sentInitialMessage) {
try {
// eslint-disable-next-line no-await-in-loop
slackContext = await sendInitialMessage(
slackContext = await sendMessage(
slackClient,
{ channel: slackChannelId },
INITIAL_MESSAGE,
Expand Down
8 changes: 7 additions & 1 deletion src/notfound/handler-external.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,12 @@
* governing permissions and limitations under the License.
*/
import externalDigestHandler from '../digest/handler-external.js';
import { INITIAL_404_SLACK_MESSAGE, processLatest404Audit, send404Report } from '../support/notfound.js';
import {
INITIAL_404_SLACK_MESSAGE,
NO_404_SLACK_MESSAGE,
processLatest404Audit,
send404Report,
} from '../support/notfound.js';

const ALERT_TYPE = '404';

Expand All @@ -21,5 +26,6 @@ export default async function notFoundExternalDigestHandler(message, context) {
INITIAL_404_SLACK_MESSAGE,
processLatest404Audit,
send404Report,
NO_404_SLACK_MESSAGE,
);
}
6 changes: 5 additions & 1 deletion src/notfound/handler-internal.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,11 @@
* governing permissions and limitations under the License.
*/
import internalDigestHandler from '../digest/handler-internal.js';
import { send404Report, INITIAL_404_SLACK_MESSAGE, processLatest404Audit } from '../support/notfound.js';
import {
send404Report,
INITIAL_404_SLACK_MESSAGE,
processLatest404Audit,
} from '../support/notfound.js';

const ALERT_TYPE = '404';

Expand Down
3 changes: 2 additions & 1 deletion src/support/notfound.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import commaNumber from 'comma-number';
import { markdown, section } from './slack.js';

export const INITIAL_404_SLACK_MESSAGE = '*404 REPORT* for the *last week* :thread:';
export const NO_404_SLACK_MESSAGE = (url) => `Good news! For ${url}, there were no 404 errors last week for the end users`;

export const get404Backlink = async (context, url) => {
try {
Expand All @@ -30,7 +31,7 @@ export function build404SlackMessage(url, auditResult, backlink, mentions) {
const blocks = [];

blocks.push(section({
text: markdown(`${isArray(mentions) ? mentions.join(' ').toString() : ''} For *${url}*, ${auditResult.length} page(s) had 404s *last week* for the real users.\n More information is below (up to three pages):`),
text: markdown(`${isArray(mentions) ? mentions.join(' ').toString() : ''} For *${url}*, ${auditResult.length} page(s) had 404s *last week* for for the end users of the site.\n More information is below (up to three pages):`),
}));

for (let i = 0; i < Math.min(3, auditResult.length); i += 1) {
Expand Down
8 changes: 4 additions & 4 deletions src/support/slack.js
Original file line number Diff line number Diff line change
Expand Up @@ -106,20 +106,20 @@ export async function uploadSlackFile(token, opts) {
}
}

export function buildInitialSlackMessage(initialMessage, mentions) {
export function buildSlackMessage(message, mentions) {
return [
{
type: 'section',
text: {
type: 'mrkdwn',
text: `${isArray(mentions) ? `${mentions.join(' ').toString()} ` : ''}${initialMessage}`,
text: `${isArray(mentions) ? `${mentions.join(' ').toString()} ` : ''}${message}`,
},
},
];
}

export const sendInitialMessage = async (slackClient, slackContext, initialMessage) => {
const blocks = buildInitialSlackMessage(initialMessage, slackContext?.mentions);
export const sendMessage = async (slackClient, slackContext, message) => {
const blocks = buildSlackMessage(message, slackContext?.mentions);
const { threadId } = await slackClient.postMessage(
{
channel: slackContext?.channel,
Expand Down
37 changes: 30 additions & 7 deletions test/notfound/handler-external.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@ import chai from 'chai';
import sinonChai from 'sinon-chai';
import chaiAsPromised from 'chai-as-promised';
import notFoundExternalDigestHandler from '../../src/notfound/handler-external.js';
import { INITIAL_404_SLACK_MESSAGE, build404SlackMessage } from '../../src/support/notfound.js';
import { buildInitialSlackMessage } from '../../src/support/slack.js';
import { INITIAL_404_SLACK_MESSAGE, build404SlackMessage, NO_404_SLACK_MESSAGE } from '../../src/support/notfound.js';
import { buildSlackMessage } from '../../src/support/slack.js';

chai.use(sinonChai);
chai.use(chaiAsPromised);
Expand Down Expand Up @@ -109,13 +109,29 @@ describe('not found external handler', () => {
getAudits: () => [auditData],
};

const siteData3 = {
getId: () => 'site3',
getBaseURL: () => 'https://abcd.com',
getConfig: () => ({
slack: {
workspace: 'workspace',
channel: 'channelSite3',
},
alerts: [{
type: '404',
mentions: [{ slack: ['slackSiteId3'] }],
}],
}),
getAudits: () => [],
};

const mockDataAccess = {
getOrganizations: sinon.stub().resolves([organizationData1, { getId: () => 'default', getConfig: () => {} }, organizationData2]),
getSitesByOrganizationIDWithLatestAudits: sinon.stub(),
getLatestAuditForSite: sinon.stub().resolves(auditData),
};
mockDataAccess.getSitesByOrganizationIDWithLatestAudits.withArgs(organizationData1.getId(), '404', false).returns([siteData1]);
mockDataAccess.getSitesByOrganizationIDWithLatestAudits.withArgs(organizationData2.getId(), '404', false).returns([siteData2]);
mockDataAccess.getSitesByOrganizationIDWithLatestAudits.withArgs(organizationData2.getId(), '404', false).returns([siteData2, siteData3]);
beforeEach('setup', () => {
context = {
log: console,
Expand All @@ -135,11 +151,13 @@ describe('not found external handler', () => {
create404Backlink: sandbox.stub().resolves(backlink),
};
const orgChannel = 'channelOrg1';
const siteChannel = 'channelSite2';
const siteChannel2 = 'channelSite2';
const siteChannel3 = 'channelSite3';
context.slackClients = {
WORKSPACE_EXTERNAL_STANDARD: { postMessage: sandbox.stub().resolves({ channel: orgChannel, threadId: 'thread-1' }) },
};
const initialBlocks = buildInitialSlackMessage(INITIAL_404_SLACK_MESSAGE, ['slackOrgId1']);
const initialBlocks = buildSlackMessage(INITIAL_404_SLACK_MESSAGE, ['slackOrgId1']);
const noNotFoundBlocks = buildSlackMessage(NO_404_SLACK_MESSAGE('https://abcd.com'), ['slackSiteId3']);
const blocksOrg = build404SlackMessage(
'https://abcd.com',
auditData.getAuditResult().result,
Expand All @@ -162,15 +180,20 @@ describe('not found external handler', () => {
);
expect(context.slackClients.WORKSPACE_EXTERNAL_STANDARD.postMessage).calledWith(
{
blocks: blocksSite, channel: siteChannel, mentions: ['slackSiteId2'], unfurl_links: false,
blocks: blocksSite, channel: siteChannel2, mentions: ['slackSiteId2'], unfurl_links: false,
},
);
expect(context.slackClients.WORKSPACE_EXTERNAL_STANDARD.postMessage).calledWith(
{
blocks: noNotFoundBlocks, channel: siteChannel3,
},
);
expect(resp.status).to.equal(204);
});

it('builds no message when there is no audit', async () => {
context.slackClients = {
WORKSPACE_EXTERNAL_STANDARD: { postMessage: sandbox.stub().resolves() },
WORKSPACE_EXTERNAL_STANDARD: { postMessage: sandbox.stub().resolves({ threadId: 't1' }) },
};
const noAuditContext = { ...context };
noAuditContext.dataAccess = { ...context.dataAccess };
Expand Down