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
5 changes: 5 additions & 0 deletions .changeset/fair-snails-explain.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@alfalab/scripts-modules': minor
---

Добавлены вызовы метрик начала и конца загрузки модуля
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import { removeModuleResources } from './utils/dom-utils';
import { fetchResources, getResourcesTargetNodes } from './utils/fetch-resources';
import { getCompatModule, getModule } from './utils/get-module';
import { addCleanupMethod, cleanupModule, getModulesCache } from './utils/modules-cache';
import { MODULE_METRICS } from './metrics';
import { trackCommonAlfaMetrics } from './track-common-alfa-metrics';
import {
type BaseModuleState,
type GetResourcesRequest,
Expand Down Expand Up @@ -92,13 +94,23 @@ export function createModuleLoader<
const paramsSerialized = JSON.stringify(getResourcesParams);

if (resourcesCache === 'single-item' && modulesCache[moduleId]?.[paramsSerialized]) {
trackCommonAlfaMetrics(MODULE_METRICS.startFetch, {
moduleId,
hostAppId,
fromCache: 1,
});

return modulesCache[moduleId][paramsSerialized] as ModuleResources<ModuleState>;
}

// Если мы делаем запрос - значит либо данные не закешированы, либо в кеши лежат данные не для тех параметров.
// В любом случае нам надо удалить ресурсы и почистить глобальные переменные
cleanupModule(moduleId);

trackCommonAlfaMetrics(MODULE_METRICS.startFetch, {
moduleId,
hostAppId,
});
const resources = await getModuleResources({
moduleId,
hostAppId,
Expand Down Expand Up @@ -201,6 +213,11 @@ export function createModuleLoader<

await onAfterModuleMount?.(moduleId, moduleResources, loadedModule);

trackCommonAlfaMetrics(MODULE_METRICS.fetchSuccess, {
moduleId,
hostAppId,
});

return {
unmount: () => {
onBeforeModuleUnmount?.(moduleId, moduleResources, loadedModule);
Expand Down
25 changes: 25 additions & 0 deletions packages/arui-scripts-modules/src/module-loader/metrics.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
const EVENT_CATEGORY = {
module: 'Module',
};

export const MODULE_METRICS = {
startFetch: {
category: EVENT_CATEGORY.module,
action: 'fetch module',
label: 'Модуль начал загружаться',
dimensionsMapping: {
moduleId: '2',
hostAppId: '3',
fromCache: '4',
},
},
fetchSuccess: {
category: EVENT_CATEGORY.module,
action: 'fetch module > success',
label: 'Модуль успешно загрузился',
dimensionsMapping: {
moduleId: '2',
hostAppId: '3',
},
},
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
const METRICS_SCHEMA = 'iglu:com.alfabank/custom_dimension/jsonschema/1-0-0';

function mapDimensions(
dimensionMap?: Record<string, string>,
dimensionData?: Record<string, string | number>,
) {
if (dimensionData && dimensionMap) {
const additionalDataKeys = Object.keys(dimensionData);

return Object.keys(dimensionMap).reduce<Record<string, string | number | undefined>>(
(result, key) => {
const dimensionLevel = dimensionMap[key];

if (dimensionLevel && additionalDataKeys.includes(key)) {
return { ...result, [dimensionLevel]: dimensionData[key] };
}

return result;
},
{},
);
}

return {};
}

export type SnowPlowFn = (
action: string,
trackerId: string,
trackerUrl?: string,
options?: Record<string, string | number | boolean> | string,
property?: string | null,
value?: number | null,
data?: Array<{
schema: string;
data: Record<string, string | number | undefined>;
}>,
) => void;

type Metric = {
category: string;
action: string;
label: string;
property?: string | null;
value?: number | null;
dimensionsMapping?: Record<string, string>;
};

/**
* Пишет метрику, используя функцию, которая записана в window.sp
*
* @param {Object} metric метрика вида:
* { category: String; action: String; label: String; property: String; value: SQL Numeric; dimensionsMapping: Object; }
* @param {Object} additionalData дополнительные данные в виде объекта
*/
export function trackCommonAlfaMetrics(
metric: Metric,
additionalData: Record<string, string | number> = {},
) {
if (typeof window !== 'undefined' && typeof window.sp === 'function') {
const dimensions = mapDimensions(metric.dimensionsMapping, additionalData);

window.sp(
'trackStructEvent:mainApp',
metric.category,
metric.action,
metric.label,
metric.property,
metric.value,
[
{
schema: METRICS_SCHEMA,
data: dimensions,
},
],
);
}
}
11 changes: 11 additions & 0 deletions packages/arui-scripts-modules/src/module-loader/types.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { type SnowPlowFn } from './track-common-alfa-metrics';

/**
* То, как подключать модуль на страницу.
* compat - режим подключения без использования module-federation. В этом случае мы сами подключаем все скрипты и стили.
Expand Down Expand Up @@ -109,3 +111,12 @@ export type ModuleFederationContainer = {
init: (...args: unknown[]) => Promise<void>;
get<T>(id: string): Promise<() => T>;
};

declare global {
interface Window {
sp: SnowPlowFn;
}

/* eslint-disable no-var,@typescript-eslint/naming-convention,no-underscore-dangle,vars-on-top */
var sp: SnowPlowFn;
}
Loading