ParsingScheduler.kt

/*
  Copyright (C) 2026 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:
      Sergeev Viktor <sergeevviktor017@gmail.com>, Sber - 2025

  Contributors:
      Sergeev Viktor <sergeevviktor017@gmail.com>, Sber - 2025
*/

package org.archtool.archloader.service.scheduler

import java.nio.file.Files
import java.util.concurrent.Executors
import java.util.concurrent.RejectedExecutionException
import java.util.zip.ZipInputStream
import kotlin.io.path.inputStream
import org.slf4j.LoggerFactory
import org.springframework.scheduling.annotation.Scheduled
import org.springframework.stereotype.Component
import org.archtool.archloader.configuration.properties.SchedulersProperties
import org.archtool.archloader.exception.UserDataException
import org.archtool.archloader.service.TaskStoreService
import org.archtool.archloader.service.dto.UploadTask
import org.archtool.archloader.service.zip.FileConst
import org.archtool.archloader.service.zip.parsing.JsonElementExtractionRule
import org.archtool.archloader.service.zip.parsing.JsonToYamlByRuleWriter
import org.archtool.archloader.utils.ChecksumUtils
import org.archtool.archloader.utils.DateTimeComponent
import org.archtool.archloader.utils.TraceIdWrapper
import tools.jackson.databind.JsonNode
import tools.jackson.databind.json.JsonMapper

@Component
class ParsingScheduler(
    private val taskStoreService: TaskStoreService,
    private val jsonMapper: JsonMapper,
    private val parser: JsonToYamlByRuleWriter,
    private val rulesByType: Map<String, Set<JsonElementExtractionRule>>,
    private val dateTimeComponent: DateTimeComponent,
    private val checksumUtils: ChecksumUtils,
    private val traceIdWrapper: TraceIdWrapper,
    schedulersProperties: SchedulersProperties,
) {
    private val properties = schedulersProperties.parser

    private val executor = Executors.newFixedThreadPool(properties.workerThreadCount)
    private val log = LoggerFactory.getLogger(javaClass)

    init {
        log.info(
            "Шедулер запущен с {} потоками воркерами и частотой запуска {}",
            properties.workerThreadCount,
            properties.rate.toString(),
        )
    }

    @Scheduled(fixedRate = 1000)
    fun mainPipe() {
        generateSequence {
            taskStoreService.moveTaskToStatus(
                currentStatus = UploadTask.Status.INCOME_NEW,
                nextStatus = UploadTask.Status.INCOME_IN_PROGRESS,
            )
        }.forEach { nextTask ->
            val presStatusDesc = nextTask.statusDesc
            try {
                nextTask.statusDesc = "Парсинг zip в процессе"
                executor.submit {
                    traceIdWrapper(nextTask.traceHeaders) {
                        try {
                            exec(task = nextTask)
                        } catch (e: Exception) {
                            log.error(
                                "Непойманная Exception при выполнении парсинга + сохранения в zip для передачи в git",
                                e
                            )
                            nextTask.status = UploadTask.Status.ERROR
                            nextTask.statusDesc = UNEXPECTED_TASK_ERROR_DESC
                        } catch (e: Throwable) {
                            log.error(
                                "Непойманная Throwable при выполнении парсинга + сохранения в zip для передачи в git",
                                e
                            )
                            nextTask.status = UploadTask.Status.ERROR
                            nextTask.statusDesc = THROWABLE_DESC
                            throw e
                        }
                    }
                }
                log.debug("Задача передана в очередь на парсинг")
            } catch (e: RejectedExecutionException) {
                // откатываем статус задачи на NEW, чтобы взять в следующий раз, если она не поместилась в очередь
                nextTask.status = UploadTask.Status.INCOME_NEW
                nextTask.statusDesc = presStatusDesc
                log.warn(
                    "Пул не принял задачу {} на выполнение, возвращаем в статус {}, эту итерацию шедулера пропускаем, " +
                            "ждем пока очередь разберется, если ошибка повторяется часто, надо проверять количество запросов и время обработки",
                    nextTask.id, nextTask.status, e
                )
                return@forEach // выходим из цикла т.к. очередь заполнена
            } catch (e: Exception) {
                nextTask.status = UploadTask.Status.ERROR
                nextTask.statusDesc = UNEXPECTED_TASK_ERROR_DESC
                log.error(
                    "Ошибка при попытке запустить задачу {} в работу, переводим в статус {}",
                    nextTask.id,
                    nextTask.status,
                    e
                )
            }
        }
    }

    private fun exec(task: UploadTask) {
        // тут начать обработку файла в зависимости от типа
        log.debug(
            "Начали обработку задачи {}, должны прочитать файл {}, используемые правила = {}",
            task.id, task.incomeFile.path, task.metaData.type
        )
        log.trace("Данные по задаче {}", task)
        task.incomeFile.path.inputStream().use { fileInputStream ->
            checksumUtils.validateChecksum(
                inputStream = fileInputStream,
                expectedChecksum = task.incomeFile.checksum,
                context = "Проверка checksum файла клиента перед парсингом json -> yaml"
            )
        }
        val archParseRules = rulesByType[task.metaData.type]
        if (archParseRules == null) {
            task.status = UploadTask.Status.ERROR
            task.statusDesc =
                "Для типа ${task.metaData.type} нет правил обработки" // возможно написать тут про поддержку версии или как узнать список поддерживаемых типов
            return
        }

        val parsePayload = parsePayload(task)
        val payload = parsePayload.payload
        if (payload == null) {
            task.status = UploadTask.Status.ERROR
            task.statusDesc = "Ошибка при парсинге ${FileConst.PAYLOAD_JSON_FILE_NAME}: ${parsePayload.error}"
            return
        }

        val zipPath = FileConst.buildGitFileName(targetDir = task.targetDir, taskId = task.id)
        log.debug("Записываем данные в файл {}", zipPath)
        try {
            parser.jsonToYamlInZip(
                payload = payload,
                zipOutputPath = zipPath,
                rules = archParseRules
            )

            val checksumOfResultZip = zipPath.inputStream().use { fileInputSteam ->
                checksumUtils.calcChecksum(inputStream = fileInputSteam)
            }
            task.gitZipFile = UploadTask.FileData(
                path = zipPath,
                checksum = checksumOfResultZip
            )
            task.status = UploadTask.Status.GIT_SEND_NEW
            task.statusDesc = "Ожидаем отправки в git"
            task.timing.parsingEndTime = dateTimeComponent.now()
            log.debug(
                "Создание zip для отправки в git по задаче {} завершено, задача переведена в статус {}",
                task.id,
                task.status
            )
        } catch (e: UserDataException) {
            log.error("Ошибка в пользовательских данных", e)
            task.status = UploadTask.Status.ERROR
            task.statusDesc = e.message
        } catch (e: Exception) {
            log.error("Ошибка при создании zip файла для отправки в git", e)
            task.status = UploadTask.Status.ERROR
            task.statusDesc = UNEXPECTED_TASK_ERROR_DESC
        }
    }

    private fun parsePayload(newTask: UploadTask): PayloadParseResult {
        val incomeFile = newTask.incomeFile
        ZipInputStream(Files.newInputStream(incomeFile.path)).use { zip ->
            generateSequence { zip.nextEntry }.forEach { entry ->
                when (entry.name) {
                    FileConst.PAYLOAD_JSON_FILE_NAME -> {
                        return try {
                            PayloadParseResult(payload = jsonMapper.readTree(zip))
                        } catch (e: Exception) {
                            PayloadParseResult(error = e.message)
                        }
                    }
                }
            }
        }
        return PayloadParseResult(error = "файл не найден")
    }

    private data class PayloadParseResult(
        val payload: JsonNode? = null,
        val error: String? = null,
    )

    companion object {
        private const val UNEXPECTED_TASK_ERROR_DESC =
            "Ошибка в данных архитектуры, проверьте корректность заполнения и попробуйте ещё раз"
        private const val THROWABLE_DESC =
            "Системная ошибка, обратитесь в поддержку указав traceId и taskId"
    }

}