Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 | 25x 25x 25x 2352x 2348x 2348x 2348x 7039x 7039x 2x 2x 7037x 1252x 5785x 2348x 2348x 2x 1x 25x 57x 131x 57x 57x 57x 57x 323x 323x 181x 253x 214x 214x 214x 214x 214x 214x 214x 151x 151x 151x 151x 63x 63x 214x 35x 35x 75x 75x 10x 65x 75x 29x 46x 15x 15x 15x 15x 31x 7x 12x 7x 2x 5x 10x 8x 8x 8x 3x 3x 24x 19x 4x 2x 4x 15x 15x 35x 18x 18x 214x 151x 151x 63x 63x 10x 63x 214x 172x 214x 206x 8x 214x 25x 7x 67180x 2x 2x 67180x 67178x 1x 1x 3x 3x 2x 1x 1x 1x 67177x 25x 4x 1x 4x 1x 25x 25x 6x 8x 8x 6x 6x 6x 6x 4x 2x 12x 1x 1x 1x 11x 1x 1x 1x 10x 10x 2x 8x 8x 8x 25x 486x 1x 486x 512x 512x 512x 486x 485x 485x 485x 485x 485x 485x 485x 485x 2072x 2422x 1x 1x 1x 1x 1x 485x 19x 485x 470x 3x 2x 485x 1x 485x 1x 485x 48x 511x 511x 511x 4x 4x 4x 511x 499x 499x 12x 12x 1x 1x 486x | /*
Copyright (C) 2021 owner Roman Piontik R.Piontik@mail.ru
Copyright (C) 2022 Sber
Licensed 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
In any derivative products, you must retain the information of
owner of the original code and provide clear attribution to the project
https://dochub.info
The use of this product or its derivatives for any purpose cannot be a secret.
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 CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Maintainers:
R.Piontik <r.piontik@mail.ru>
Contributors:
R.Piontik <r.piontik@mail.ru> - 2023
*/
import jsonata from 'jsonata';
import ajv from 'ajv';
import addFormats from 'ajv-formats';
import source from '../datasets/source.mjs';
import {PerformanceLogger} from '../logger/perf-logger.mjs';
import {getLogger, getLoggerWithTag} from '@global/logger/v2/logger.mjs';
import {mergeDeep} from '@global/helpers/mergedeep.mjs';
const LOG_TAG = 'jsonata-driver';
const logger = getLoggerWithTag(LOG_TAG);
const loggerWithoutTag = getLogger();
// Расширенные функции JSONata
function wcard(id, template) {
if (!id || !template) return false;
const tmlStruct = template.split('.');
let items = [];
for (let i = 0; i < tmlStruct.length; i++) {
const pice = tmlStruct[i];
if (pice === '**') {
items.push('.*$');
break;
} else if (pice === '*') {
items.push('[^\\.]*');
} else items.push(pice);
}
const isOk = new RegExp(`^${items.join('\\.')}$`);
return isOk.test(id);
}
async function parseSource(source) {
return await this.getDatasetDriver()?.getData(this.manifest, source);
}
function jsonataMergeDeep(sources) {
return mergeDeep({}, sources);
}
let jsonValidatorLog = getLoggerWithTag('jsonValidator');
function jsonSchema(schema) {
const rules = new ajv(
{
allErrors: true,
unicodeRegExp: false,
allowUnionTypes: true,
verbose: true,
logger: {
log: (args) => {
jsonValidatorLog.info(() => JSON.stringify(args));
},
warn: (args) => {
jsonValidatorLog.debug(() => JSON.stringify(args));
},
error: (args) => {
jsonValidatorLog.debug(() => JSON.stringify(args));
}
}
});
addFormats(rules);
rules.addKeyword({
keyword: '$rels'
});
const validator = rules.compile(schema);
return (data) => {
const isOk = validator(data);
if (isOk) return true;
return validator.errors
.filter(err => err.keyword !== 'if')
.map((err) => {
// убираем из ответа verbose инфу, т.к. она не нужна
let attrInfo = {};
try {
attrInfo = __getAttrInfoByError(err, schema);
} catch (e) {
// TODO: вернуть лог с уровнем дебаг после доработки ERA-1219,
// пока игнорируем, отработает jsonata функция поиска
// console.error(e);
}
return {
attrInfo: attrInfo,
instancePath: err.instancePath,
schemaPath: err.schemaPath,
keyword: err.keyword,
params: err.params,
allowedValues: err.allowedValues,
message: err.message
};
}
);
};
}
/**
* Метод собирает подробную информацию об ошибке
* 1. Если ошибка в атрибуте со schemaPath, который начинается на $rels то необходимо найти реальную схему атрибута,
* т.к. rels перечисление создается в райнтайме, по сущностям пользователя и по факту это ограничение типа enum
* 2. Для ошибок типа required в самой ошибке содержится схема всего объекта, чей атрибут пропущен, там и ищем описание параметра
* 3. Для остальных случаев берем из parentSchema данные
*
* @param err - ошибка ajv валидатора
* @param schema - схема использованная для валидации
* @returns Объект описывающий ошибку
*
* @private
*/
function __getAttrInfoByError(err, schema) {
let currentSchema;
let title;
let type;
let instancePathSplit = !err.instancePath ? [] : err.instancePath.replace(/^\//, '').split('/');
// глубина массива, используется при формировании attrName, чтобы собрать название атрибута из имени массива и индексов
let arrayDepth = 0;
if (err.keyword === 'required') { // если ошибка в required, то в parentSchema схема всего объекта с ошибкой, а не атрибута
let propertyName = err.params.missingProperty;
let propertyDesc = err.parentSchema?.properties?.[propertyName];
title = propertyDesc?.title;
type = propertyDesc?.type;
} else { // иначе в parentSchema описание атрибута
title = err.parentSchema?.title;
type = err.parentSchema?.type;
}
if ((!title || !type) && instancePathSplit.length > 0) {
//если не нашли тип или заголовок и есть путь для поиска в схеме, то ищем в схеме
let segment;
currentSchema = schema;
for (segment of instancePathSplit) {
Iif (segment === '') {
continue;
}
if (currentSchema.type === 'array') {
// увеличиваем глубину если в пути наткнулись на массив
arrayDepth++;
} else {
// обнуляем глубину массива если наткнулись на обычный элемент, не массив
arrayDepth = 0;
}
if (currentSchema?.properties?.[segment]) {
currentSchema = currentSchema.properties[segment];
} else if (currentSchema?.patternProperties) {
const matchingPattern = Object.keys(currentSchema.patternProperties).find(pattern =>
new RegExp(pattern).test(segment)
);
if (matchingPattern) {
currentSchema = currentSchema.patternProperties[matchingPattern];
} else E{
currentSchema = null;
break;
}
} else if (currentSchema.allOf || currentSchema.oneOf || currentSchema.anyOf) {
const merged = [
...safeArray(currentSchema.allOf),
...safeArray(currentSchema.oneOf),
...safeArray(currentSchema.anyOf)
];
// пробуем найти описание атрибута в properties какого-нибудь из allOf/oneOf/anyOf
let segmentInProperties = merged.find(el => el?.properties?.[segment]);
if (segmentInProperties) {
currentSchema = segmentInProperties.properties[segment];
} else {
// если в properties нету, и есть $ref ссылки, поищем в них
currentSchema = merged
.filter(el => el.$ref)
.map(el => el.$ref)
.map(el => el.replace('#/$defs/', ''))
.filter(el => Object.hasOwn(schema.$defs[el].properties, segment))
.map(el => schema.$defs[el].properties[segment])
.filter(el => el)[0];
}
} else if (currentSchema.type === 'array' && currentSchema.items.$ref) {
// т.к. текущая схема это массив ссылающийся на другой элемент, ничего не делаем
} else if (currentSchema.type === 'array' && currentSchema.items.type === 'array') {
if (!currentSchema.items.title) {
// если у вложенного массива нет заголовка, то протаскиваем его от родительского массива
currentSchema.items.title = currentSchema.title;
}
// т.к. текущая схема это массив ссылающийся на другой массив то переходим в схему items
currentSchema = currentSchema.items;
} else {
currentSchema = null;
break;
}
}
if (currentSchema) {
title = currentSchema['title'];
type = currentSchema['type'];
}
}
let currentValue;
let attrName;
if (err.keyword === 'required') {
attrName = err.params.missingProperty;
currentValue = err.data[attrName];
} else {
attrName = instancePathSplit.at(-arrayDepth - 1);
for (let i = arrayDepth; i > 0; i--) {
attrName += `[${instancePathSplit.at(-i)}]`;
}
currentValue = err.data;
}
if (!title) {
// если заголовок атрибута в конце парсинга не найден, то попробуем добавить атрибут "комментарий", так договорились
title = err.parentSchema.$comment;
}
// если attrName есть (не null/undefined/не пустая строка), тогда срезаем пробелы по краям
if (attrName) {
attrName = attrName.trim();
} else {
attrName = undefined;
}
return {
title: title,
type: type,
currentValue: currentValue,
name: attrName
};
}
const safeArray = (arr) => Array.isArray(arr) ? arr : [];
function sourceType(content) {
return source.type(content);
}
// Функция для переопределения встроенной $lookup()
// должна допускать null в качестве ключа, и возвращать null в этом случае.
function lookup(source, key) {
// обрабатываем ситуацию, когда функция была вызвана в виде $obj.$lookup('key');
if (key === undefined && (typeof source === 'string' || source === null)) {
key = source;
source = this.input;
}
if (key === null) return null;
if (Array.isArray(source)) {
const output = [];
for (let i = 0; i < source.length; i++) {
let value = lookup(source[i], key);
if (value !== undefined) {
if (Array.isArray(value)) {
output.push(...value);
} else output.push(value);
}
}
return output;
} else if (typeof source === 'object' && !source._jsonata_function && !source._jsonata_lambda) return source[key];
}
const coreFunctions = {
sourcetype: sourceType,
wcard: wcard,
mergedeep: jsonataMergeDeep,
jsonschema: jsonSchema
};
/**
* Метод для добавления функции со стороны frontend или backend. Когда одна функция работает по-разному в этих режимах
* Важно соблюдать корректность поведения функции в обоих режимах, чтобы поведение было ожидаемо
* @param name - название функции
* @param func - тело функция
*/
export function appendCoreFunctions(name, func) {
if (coreFunctions[name]) {
logger.error(() => `WARN: some add func '${name}' twice, check source code by func name`);
}
coreFunctions[name] = func;
}
function getDatasetDriver() {
logger.error(() => 'ERROR: Cant get dataset driver from jsonata driver core');
}
// JSONata writes err.message only in evaluate()'s catch,
// so we need to re-throw the same object through evaluate() to get it.
const jsonataErrorMessageFiller = jsonata('$raise($err)');
jsonataErrorMessageFiller.registerFunction('raise', (err) => {
throw err;
});
async function tryExecuteErrorMessage(err) {
Iif (typeof err === 'string' && err) return err;
if (err && typeof err.message === 'string' && err.message) return err.message;
Eif (err && typeof err === 'object') {
try {
await jsonataErrorMessageFiller.evaluate(undefined, {err});
} catch (filled) {
if (filled && typeof filled.message === 'string' && filled.message) return filled.message;
if (typeof err.code === 'string' && err.code) return err.code;
}
}
return 'Unknown error';
}
async function tryExecute(func, args) {
if (typeof func !== 'function') {
const message = `tryExecute error: First argument of tryExecute must be a function. Received ${typeof func} instead.`;
logger.error(() => message);
return {success: false, result: null, error: message};
}
if (args != null && !Array.isArray(args)) {
const message = `tryExecute error: Second argument of tryExecute must be an array. Received ${typeof args} instead.`;
logger.error(() => message);
return {success: false, result: null, error: message};
}
try {
const result = await func.apply(this, args);
return {success: true, result};
} catch (e) {
const message = await tryExecuteErrorMessage(e);
logger.error(() => `tryExecute error: ${message}`, e);
return {success: false, result: null, error: message};
}
}
const PERF_LOG_ENABLE = process.env.VUE_APP_DOCHUB_PERF_LOGGER_ENABLE?.toLowerCase() === 'on';
export default {
// Функция должна возвращать коллекцию пользовательских функций JSONata
customFunctions: null,
// Функция возвращает актуальную схему данных
manifestSchema: null,
logger: logger,
performanceLogger: PERF_LOG_ENABLE ? new PerformanceLogger(loggerWithoutTag) : null,
isJsonataLogFuncEnable: process.env.VUE_APP_DOCHUB_JSONATA_LOG_FUNC_ENABLE?.toLowerCase() !== 'off',
getDatasetDriver,
// Создает объект запроса JSONata
// expression - JSONata выражение
// self - объект, который вызывает запрос (доступен по $self в запросе)
// params - параметры передающиеся в запрос
// isTrace - признак необходимости проанализировать выполнение запроса.
// Если true, то в объекте запроса, после его выполнения, появится поле "trace"
// funcs - кастомные функции, регистрируемые в JSONata
expression(expression, self_, params, isTrace, funcs) {
const resolveManifestSchema = typeof this.manifestSchema === 'function'
? this.manifestSchema
: () => this.manifestSchema;
const obj = {
expression,
customFunctions: typeof this.customFunctions === 'function' ? this.customFunctions() : {},
core: null,
onError: null, // Событие ошибки выполнения запроса
store: {}, // Хранилище вспомогательных переменных для запросов
logger: this.logger, // Логгер трассировки запросов
performanceLogger: this.performanceLogger, // Логгер производительности функций
getDatasetDriver: this.getDatasetDriver,
isJsonataLogFuncEnable: this.isJsonataLogFuncEnable,
// Исполняет запрос
// context - контекст исполнения запроса
async evaluate(context) {
try {
const performanceLogger = this.performanceLogger;
if (!this.core) {
this.core = jsonata(this.expression);
this.core.assign('self', self_);
this.core.assign('params', params);
this.manifest = context;
this.core.registerFunction('lookup', lookup);
this.core.registerFunction('parsesource', parseSource.bind(this));
this.core.registerFunction('tryexecute', tryExecute.bind(this));
this.core.registerFunction('manifestschema', () => resolveManifestSchema() || {});
for (const functionId in coreFunctions) {
this.core.registerFunction(functionId, function() {
if (!PERF_LOG_ENABLE) return coreFunctions[functionId](...arguments);
const jsonataPerfLogger = performanceLogger?.getJsonataLogger(functionId, arguments);
jsonataPerfLogger?.setStart();
const output = coreFunctions[functionId](...arguments);
jsonataPerfLogger?.setEnd(output);
return output;
});
}
for (const functionId in this.customFunctions) {
this.core.registerFunction(functionId, this.customFunctions[functionId]);
}
if (!funcs?.log) {
this.core.registerFunction('log', (content, tag) => {
if (this.isJsonataLogFuncEnable) {
loggerWithoutTag.info(tag ?? 'log-func-no-tag', () => JSON.stringify(content, null, 2));
}
});
}
this.core.registerFunction('set', (key, data) => {
return obj.store[key] = data;
});
this.core.registerFunction('get', (key) => {
return obj.store[key];
});
for (const name in funcs || {}) {
if (funcs[name]) this.core.registerFunction(name, funcs[name]);
}
}
return new Promise((success, reject) => {
obj.trace = {
start: (new Date()).getTime(),
end: null
};
const doStat = (result) => {
obj.trace.end = (new Date()).getTime();
obj.trace.exposition = this.trace.end - this.trace.start;
logger.trace(() => [
`JSONata tracer expression (${obj.trace.exposition / 1000} seconds)`,
{title: 'Statistics', obj: obj.trace},
{title: 'Query', obj: obj.expression},
result ? {title: 'Result', obj: result} : null
]);
};
this.core.evaluate(context)
.then((result) => {
isTrace && doStat(result);
success(result);
})
.catch((error) => {
isTrace && doStat();
Eif (reject) reject(error);
});
});
} catch (e) {
logger.error(() => [
'JSONata error:',
{title: 'Error', obj: e.message},
{
title: 'Expression',
obj: this.expression.slice(0, e.position) + '%c' + this.expression.slice(e.position)
}
], e);
throw e;
}
}
};
return obj;
}
};
|