All files / approval-engine-2/domain asset-state-change-logs-event.handler.ts

76.19% Statements 48/63
57.89% Branches 22/38
69.23% Functions 9/13
75.8% Lines 47/62

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                                                      1x   1x 1x 1x   1x 1x                 1x 1x   1x   1x                       1x 1x   1x         1x 2x     1x                     1x   1x             1x         1x         1x 1x           1x 1x             1x 1x 1x 1x   1x   1x           1x           1x     1x           1x                                         1x   1x     1x                         1x                                 1x 3x   1x                           1x 1x                             2x 2x 2x     2x          
import type { Logger } from "pino";
import { autoInjectable, inject, singleton } from "tsyringe";
 
import { AmountMapper } from "../../commons/mappers/amount.mapper.js";
import { tokens } from "../../registry/tokens.js";
import {
  SyncSignalEvent,
  SemaphoreValue,
} from "../../sync-engine/domain/sync-events.js";
import {
  AssetState,
  AssetStateChangeLog,
  MarkedStateChangeLog,
  MetricStateChangeLog,
} from "../../tr8-script/domain/eval.js";
import { zero } from "../../tr8-script/domain/utils/math-low-level.js";
import { plus } from "../../tr8-script/domain/utils/math.js";
import { AssetStateChangeLogsEvent } from "../dtos/asset-state-change-logs-event.dto.js";
 
import type { KafkaProducer } from "../../commons/interfaces/kafka-producer.base.js";
import { RedisMarkedStateStore } from "../store/redis-marked.store.js";
import { RedisIABAssetStore } from "../store/redis-iab-asset.store.js";
import { RedisProcessedEventStateStore } from "../store/redis-processed-event.store.js";
import { Result } from "../../tr8-script/domain/utils/types.js";
 
@singleton()
@autoInjectable()
class AssetStateChangeLogsEventHandler {
  constructor(
    private readonly iabAssetRepository: RedisIABAssetStore,
    private readonly markedStateRepository: RedisMarkedStateStore,
    private readonly processedEventRepository: RedisProcessedEventStateStore,
    @inject(tokens.SyncSignalEventProducer)
    private readonly syncSignalEventProducer: KafkaProducer<SyncSignalEvent>,
    @inject(tokens.Logger) private readonly logger: Logger,
  ) {}
 
  async handle(
    event: AssetStateChangeLogsEvent,
    commit: () => void,
    partition: number,
    offset: string,
  ): Promise<Result<{ bookId: string; iabAsset: AssetState }, Error> | null> {
    const { bookId, assetTxLogs, markedTxLogs } = event;
    const eventId = `${partition}#${offset}#${event.scriptId}`;
 
    const redisState = await this.processedEventRepository.get(eventId);
 
    Iif (redisState.ok) {
      const existingOffset = redisState.value.offset;
 
      if (existingOffset === offset) {
        this.logger.info(
          { offset, bookId },
          "Offset for bookId already processed, skipping",
        );
        return null;
      }
    }
 
    const accounts = this.extractAccounts(assetTxLogs);
    const markedAccounts = this.extractAccounts(markedTxLogs);
 
    const results = await Promise.all([
      this.iabAssetRepository.get(bookId, [accounts].flat()),
      this.markedStateRepository.get(bookId, markedAccounts),
    ]);
 
    const failedResult = results.find(
      (r): r is { ok: false; error: Error } => r === null || r?.ok === false,
    );
 
    Iif (failedResult) {
      return {
        ok: false,
        error:
          failedResult?.error ||
          new Error(
            "Received null result from repository - repository operation failed",
          ),
      };
    }
 
    const [iabAssetResult, markedAssetResult] = results;
 
    Iif (!iabAssetResult || !markedAssetResult) {
      return {
        ok: false,
        error: new Error("Received null result from repository"),
      };
    }
 
    const { value: iabAsset } = iabAssetResult as {
      ok: true;
      value: AssetState;
    };
 
    const { value: markedAsset } = markedAssetResult as {
      ok: true;
      value: AssetState;
    };
 
    for (const txLog of assetTxLogs) {
      iabAsset[txLog.account] = plus(
        iabAsset[txLog.account] ?? zero,
        txLog.change,
      );
    }
 
    for (const txLog of markedTxLogs) {
      markedAsset[txLog.account] = plus(
        markedAsset[txLog.account] ?? zero,
        txLog.change,
      );
    }
 
    // Find a non-global bookId (without '#') from transaction logs
    const nonGlobalBooks = event.assetTxLogs
      .map((log) => log.book.book)
      .filter((book) => !book.includes("#"))
      .filter((book, index, array) => array.indexOf(book) === index); // remove duplicates
 
    const syncBookId = nonGlobalBooks.length > 0 ? nonGlobalBooks[0]! : bookId;
 
    Iif (nonGlobalBooks.length === 0) {
      this.logger.warn(
        { bookId },
        "No non-global books found in transaction logs, using original bookId for sync",
      );
    } else {
      this.logger.info(
        { syncBookId, originalBookId: bookId },
        "Using non-global bookId for sync instead of global bookId",
      );
    }
 
    const semaphore = [
      [event.scriptId, event.subId, event.semaphore[bookId]!],
    ] as SemaphoreValue[];
    const syncSignalEvent: SyncSignalEvent = {
      scriptId: event.scriptId,
      scriptType: event.type,
      bookId: syncBookId,
      semaphore,
      status: "APPROVED",
      txLogs: event.assetTxLogs.map((x) => ({
        ...x,
        change: AmountMapper.toDTO(x.change),
        subId: event.subId,
      })),
      metricLogs: event.metricLogs.map((x) => ({
        ...x,
        change: AmountMapper.toDTO(x.change),
      })),
      vars: {},
      message:
        event.type === "NOTIF"
          ? "NOTIF event successfully processed"
          : event.type === "PARTIAL_NOTIF"
          ? "PARTIAL_NOTIF event successfully processed"
          : event.type === "REQ"
          ? "REQ event successfully processed"
          : "Event successfully processed",
      partial_notif_id: event.partial_notif_id ?? null,
    };
 
    this.logger.info({ syncSignalEvent }, "approve asset event");
 
    const sendSignalApprove = await this.syncSignalEventProducer.send(
      syncSignalEvent,
    );
    Iif (!sendSignalApprove || !sendSignalApprove.ok) {
      this.logger.error(
        { err: sendSignalApprove?.error },
        "Sync signal event failed to send approve",
      );
      return {
        ok: false,
        error:
          sendSignalApprove?.error ||
          new Error("Sync signal producer returned null"),
      };
    }
 
    const resultPromise = await Promise.all([
      this.iabAssetRepository.set(
        bookId,
        iabAsset,
        partition,
        offset,
        event.transaction_time,
      ),
      this.markedStateRepository.set(bookId, markedAsset),
      this.processedEventRepository.set(
        eventId,
        event.scriptId,
        partition,
        offset,
      ),
    ]);
 
    const errors = resultPromise
      .filter((r): r is { ok: false; error: Error } => !r.ok)
      .map((r) => r.error);
    Iif (errors.length > 0) {
      this.logger.error(
        { errors: errors.map((e) => e.message) },
        "Multiple Redis operations failed",
      );
 
      return {
        ok: false,
        error: new Error(
          `Multiple failures: ${errors.map((e) => e.message).join("; ")}`,
        ),
      };
    }
 
    commit();
    return {
      ok: true,
      value: {
        bookId,
        iabAsset,
      },
    };
  }
 
  extractAccounts(
    txLogs:
      | AssetStateChangeLog[]
      | MarkedStateChangeLog[]
      | MetricStateChangeLog[],
  ): string[] {
    const accounts = new Set<string>();
    for (const txLog of txLogs) {
      accounts.add(txLog.account);
    }
 
    return [...accounts];
  }
}
 
export { AssetStateChangeLogsEventHandler };