All files / src/services field-action.service.ts

72.92% Statements 140/192
55.77% Branches 58/104
62.96% Functions 17/27
72.35% Lines 123/170

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                              8x           8x       8x           8x   8x       8x 102x 102x               102x 102x         102x   8x 16x 16x 15x 15x 938x     938x 938x           938x   14x   924x         15x 15x 15x 15x     1x       1x                 1x 1x 1x                                                                           8x       69x     69x 69x 30x   39x 195x     843x 843x 54x     15x                 8x                         8x                                                       8x     938x       938x 938x 938x 938x 938x 938x 938x 938x   938x 1610x 1610x 1610x 938x 938x   672x 672x     672x 672x 672x 672x 112x   672x 672x     938x     15x 15x   75x 75x 75x 19x     56x 56x 924x 924x 924x 924x 924x 924x   924x 924x     56x   924x 924x 1848x 924x     56x                           8x         13x     13x 13x   13x       2x     11x                     8x 26x   11x   26x                 8x                                                               8x         11x       11x 2x       9x       2x       7x       2x     5x       4x       1x                       8x 11x                           8x 9x                               15x 15x 75x     8x  
/*
    Copyright (C) 2017 Red Hat, Inc.
 
    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
 
    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.
*/
import {
  ErrorInfo,
  ErrorLevel,
  ErrorScope,
  ErrorType,
} from '../models/error.model';
import {
  FieldActionArgument,
  FieldActionDefinition,
} from '../models/field-action.model';
import {
  IActionDetail,
  IActionDetailsContainer,
  Multiplicity,
} from '../contracts/field-action';
 
import { ConfigModel } from '../models/config.model';
import { Field } from '../models/field.model';
import { FieldType } from '../contracts/common';
import { MappingModel } from '../models/mapping.model';
import ky from 'ky';
 
export class FieldActionService {
  cfg: ConfigModel = ConfigModel.getConfig();
  actions: { [key in Multiplicity]: FieldActionDefinition[] } = {
    [Multiplicity.ONE_TO_ONE]: [],
    [Multiplicity.ONE_TO_MANY]: [],
    [Multiplicity.MANY_TO_ONE]: [],
    [Multiplicity.ZERO_TO_ONE]: [],
    [Multiplicity.MANY_TO_MANY]: [],
  };
 
  isInitialized = false;
  private headers = {
    'Content-Type': 'application/json; application/octet-stream',
    Accept: 'application/json; application/octet-stream',
  };
 
  constructor(private api: typeof ky) {}
 
  async fetchFieldActions(): Promise<boolean> {
    return new Promise<boolean>((resolve) => {
      if (this.cfg.preloadedFieldActionMetadata) {
        this.clearActionDefinitions();
        if (this.cfg.preloadedFieldActionMetadata.ActionDetails) {
          for (const actionDetail of this.cfg.preloadedFieldActionMetadata
            .ActionDetails.actionDetail) {
            const fieldActionDefinition =
              this.extractFieldActionDefinition(actionDetail);
            Iif (!fieldActionDefinition.multiplicity) {
              this.cfg.logger!.info(
                `Field action (${fieldActionDefinition.name}) is missing multiplicity, ingoring`
              );
              continue;
            }
            if (fieldActionDefinition.name === 'Expression') {
              // Expression is handled in special manner
              continue;
            }
            this.actions[fieldActionDefinition.multiplicity].push(
              fieldActionDefinition
            );
          }
        }
        this.sortFieldActionDefinitions();
        this.isInitialized = true;
        resolve(true);
        return;
      }
 
      Eif (
        this.cfg.mappingService == null ||
        this.cfg.initCfg.baseMappingServiceUrl == null
      ) {
        this.cfg.errorService.addError(
          new ErrorInfo({
            message:
              'Mapping service URL is not provided. Field Actions will not be used.',
            level: ErrorLevel.WARN,
            scope: ErrorScope.APPLICATION,
            type: ErrorType.INTERNAL,
          })
        );
        this.isInitialized = true;
        resolve(false);
        return;
      }
 
      // Fetch the field actions from the runtime service.
      this.doFetchFieldActions()
        .then((fetchedActionConfigs: FieldActionDefinition[]) => {
          if (fetchedActionConfigs.length === 1) {
            this.cfg.logger!.info('No field action was returned from backend');
            resolve(false);
          }
          this.clearActionDefinitions();
          fetchedActionConfigs.forEach((action) => {
            if (!action.multiplicity) {
              this.cfg.logger!.info(
                `Field action  (${action.name}) is missing multiplicity, ignoring`
              );
              return;
            }
            if (action.name === 'Expression') {
              // Expression is handled in special manner
              return;
            }
            this.actions[action.multiplicity].push(action);
          });
          this.sortFieldActionDefinitions();
          this.isInitialized = true;
          resolve(true);
        })
        .catch((error: any) => {
          this.cfg.errorService.addBackendError(
            `Could not load field action configs: (${error.message})`,
            error
          );
          resolve(false);
        });
    });
  }
 
  getActionDefinitionForName(
    actionName: string,
    multiplicity?: Multiplicity
  ): FieldActionDefinition | null {
    Iif (!this.actions || !actionName) {
      return null;
    }
    let actions: FieldActionDefinition[] = [];
    if (multiplicity) {
      actions = this.actions[multiplicity];
    } else {
      Object.values(this.actions).forEach(
        (arr) => (actions = actions.concat(arr))
      );
    }
    for (const actionDef of actions) {
      if (actionName === actionDef.name) {
        return actionDef;
      }
    }
    return null;
  }
 
  /**
   * Return the field action Definitions applicable to the specified field mapping pair.
   * @param mapping
   * @param isSource
   * @param multiplicity
   */
  getActionsAppliesToField(
    mapping: MappingModel,
    isSource: boolean = true,
    multiplicity: Multiplicity = Multiplicity.ONE_TO_ONE
  ): FieldActionDefinition[] {
    if (!mapping || !this.actions) {
      return [];
    }
    return this.actions[multiplicity].filter((d) =>
      this.appliesToField(d, mapping, isSource)
    );
  }
 
  private doFetchFieldActions(): Promise<FieldActionDefinition[]> {
    return new Promise<FieldActionDefinition[]>((resolve, reject) => {
      const actionConfigs: FieldActionDefinition[] = [];
      const url: string =
        this.cfg.initCfg.baseMappingServiceUrl + 'fieldActions';
      this.cfg.logger!.debug('Field Action Config Request');
      this.api
        .get(url, { headers: this.headers })
        .json<IActionDetailsContainer>()
        .then((body) => {
          this.cfg.logger!.debug(
            `Field Action Config Response: ${JSON.stringify(body)}`
          );
          if (body?.ActionDetails?.actionDetail?.length) {
            for (const actionDetail of body.ActionDetails.actionDetail) {
              const fieldActionConfig =
                this.extractFieldActionDefinition(actionDetail);
              actionConfigs.push(fieldActionConfig);
            }
          }
          resolve(actionConfigs);
        })
        .catch((error: any) => {
          reject(error);
        });
    });
  }
 
  private extractFieldActionDefinition(
    actionDetail: IActionDetail
  ): FieldActionDefinition {
    this.cfg.logger!.trace(
      `Deserializing field action definition: ${JSON.stringify(actionDetail)}`
    );
 
    const fieldActionDefinition = new FieldActionDefinition();
    fieldActionDefinition.name = actionDetail.name;
    fieldActionDefinition.isCustom = actionDetail.custom;
    fieldActionDefinition.sourceType = actionDetail.sourceType;
    fieldActionDefinition.targetType = actionDetail.targetType;
    fieldActionDefinition.method = actionDetail.method;
    fieldActionDefinition.multiplicity = actionDetail.multiplicity;
    fieldActionDefinition.serviceObject = actionDetail;
 
    Eif (actionDetail.actionSchema) {
      for (const key of Object.keys(actionDetail.actionSchema.properties)) {
        const propertyObject = actionDetail.actionSchema.properties[key];
        if (key === '@type') {
          fieldActionDefinition.name = propertyObject.const;
          continue;
        }
        const argTypeString = (propertyObject.type as string).toUpperCase();
        const argType = argTypeString
          ? FieldType[argTypeString as keyof typeof FieldType]
          : FieldType.STRING;
        const argumentDefinition = new FieldActionArgument();
        argumentDefinition.name = key;
        argumentDefinition.type = argType;
        if (propertyObject.enum) {
          argumentDefinition.values = propertyObject.enum;
        }
        argumentDefinition.serviceObject = propertyObject;
        fieldActionDefinition.arguments.push(argumentDefinition);
      }
    }
    return fieldActionDefinition;
  }
 
  private sortFieldActionDefinitions() {
    (Object.keys(this.actions) as [keyof typeof Multiplicity]).forEach(
      (multiplicity) => {
        const definitions = this.actions[multiplicity];
        const sortedActionDefinitions: FieldActionDefinition[] = [];
        if (definitions == null || definitions.length === 0) {
          return;
        }
 
        const defsByName: { [key: string]: FieldActionDefinition[] } = {};
        const defNames: string[] = [];
        for (const fieldActionConfig of definitions) {
          const name: string = fieldActionConfig.name;
          let sameNamedDefs: FieldActionDefinition[] = defsByName[name];
          Eif (!sameNamedDefs) {
            sameNamedDefs = [];
            defNames.push(name);
          }
          sameNamedDefs.push(fieldActionConfig);
          defsByName[name] = sameNamedDefs;
        }
 
        defNames.sort();
 
        for (const name of defNames) {
          const sameNamedDefs: FieldActionDefinition[] = defsByName[name];
          for (const fieldActionDefinition of sameNamedDefs) {
            sortedActionDefinitions.push(fieldActionDefinition);
          }
        }
        this.actions[multiplicity] = sortedActionDefinitions;
      }
    );
  }
 
  /**
   * Return true if the action's source/target types and collection types match the respective source/target
   * field properties for source transformations, or matches the respective target field properties only for
   * a target transformation.
   *
   * @param action
   * @param mapping
   * @param isSource
   */
  appliesToField(
    action: FieldActionDefinition,
    mapping: MappingModel,
    isSource: boolean
  ): boolean {
    Iif (mapping == null) {
      return false;
    }
    const selectedSourceField: Field = this.getActualField(mapping, true);
    const selectedTargetField: Field = this.getActualField(mapping, false);
 
    if (
      (isSource && selectedSourceField == null) ||
      (!isSource && selectedTargetField == null)
    ) {
      return false;
    }
 
    return isSource
      ? this.appliesToSourceField(action, mapping, selectedSourceField)
      : this.appliesToTargetField(action, mapping, selectedTargetField);
  }
 
  /**
   * Return the first non-padding field in either the source or target mappings.
   *
   * @param mapping
   * @param isSource
   */
  private getActualField(mapping: MappingModel, isSource: boolean): Field {
    const targetField = mapping
      .getFields(isSource)
      .find((f) => f.name !== '<padding field>');
    // TODO: maybe throw an exception instead of assuming the field will be found?
    return targetField!;
  }
 
  /**
   * Check if it could be applied to source field.
   * @param action
   * @param _
   * @param selectedSourceField selected source field
   */
  private appliesToSourceField(
    action: FieldActionDefinition,
    _: MappingModel,
    selectedSourceField: Field
  ): boolean {
    // Check for matching types - date.
    if (this.matchesDate(action.sourceType, selectedSourceField.type)) {
      return true;
    }
 
    // Check for matching types - numeric.
    if (this.matchesNumeric(action.sourceType, selectedSourceField.type)) {
      return true;
    }
 
    // First check if the source types match.
    if (
      action.sourceType === 'ANY' ||
      selectedSourceField.type === action.sourceType
    ) {
      return true;
    }
 
    return false;
  }
 
  /**
   * Check if it could be applied for target field. Target type may not change.
   * @param action
   * @param _
   * @param selectedTargetField selected target field
   */
  private appliesToTargetField(
    action: FieldActionDefinition,
    _: MappingModel,
    selectedTargetField: Field
  ): boolean {
    Iif (selectedTargetField == null) {
      return false;
    }
 
    if (action.multiplicity !== Multiplicity.ONE_TO_ONE) {
      return false;
    }
 
    // Check for matching types - date.
    if (
      this.matchesDate(action.sourceType, selectedTargetField.type) &&
      this.matchesDate(action.targetType, selectedTargetField.type)
    ) {
      return true;
    }
 
    // Check for matching types - numeric.
    if (
      this.matchesNumeric(action.sourceType, selectedTargetField.type) &&
      this.matchesNumeric(action.targetType, selectedTargetField.type)
    ) {
      return true;
    }
 
    if (
      action.sourceType !== 'ANY' &&
      action.sourceType !== selectedTargetField.type
    ) {
      return false;
    }
 
    // All other types must match the selected field types with the candidate field action types.
    return (
      action.targetType === 'ANY' ||
      selectedTargetField.type === action.targetType
    );
  }
 
  /**
   * Return true if the candidate type and selected type are generically a date, false otherwise.
   *
   * @param candidateType
   * @param selectedType
   */
  private matchesDate(candidateType: string, selectedType: string): boolean {
    return (
      candidateType === 'ANY' ||
      (candidateType === 'ANY_DATE' &&
        ['DATE', 'DATE_TIME', 'DATE_TIME_TZ', 'TIME'].indexOf(selectedType) !==
          -1)
    );
  }
 
  /**
   * Return true if the candidate type and selected type are generically numeric, false otherwise.
   *
   * @param candidateType
   * @param selectedType
   */
  private matchesNumeric(candidateType: string, selectedType: string): boolean {
    return (
      candidateType === 'ANY' ||
      (candidateType === 'NUMBER' &&
        [
          'LONG',
          'INTEGER',
          'FLOAT',
          'DOUBLE',
          'SHORT',
          'BYTE',
          'DECIMAL',
          'NUMBER',
        ].indexOf(selectedType) !== -1)
    );
  }
 
  private clearActionDefinitions() {
    (Object.keys(Multiplicity) as [keyof typeof Multiplicity]).forEach(
      (m) => (this.actions[m] = [])
    );
  }
}