ManifestReloadTaskControllerImpl.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 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:
      Alexander Romashin <romashin.a.va@sberbank.ru>, Sber - 2026

  Contributors:
      Alexander Romashin <romashin.a.va@sberbank.ru>, Sber - 2026

*/

package org.archtool.controller

import com.github.kagkarlsson.scheduler.SchedulerClient
import com.github.kagkarlsson.scheduler.task.Task
import org.archtool.configuration.tasks.ReloadTaskConfig
import org.archtool.data.dto.TaskStatusDto
import org.archtool.data.dto.TaskStatusResponseDto
import org.archtool.data.model.ManifestReloadTaskModel
import org.archtool.helper.BackendServiceClient
import org.archtool.service.HistoryService
import org.slf4j.LoggerFactory
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.RestController
import java.time.Instant

@RestController
class ManifestReloadTaskControllerImpl(
    private val schedulerClient: SchedulerClient,
    private val reloadTask: Task<ManifestReloadTaskModel>,
    private val historyService: HistoryService,
    private val backendServiceClient: BackendServiceClient
) : ManifestReloadTaskController {

    private val log = LoggerFactory.getLogger(javaClass)

    override fun reload(
        backend: String,
        secret: String?,
        reloadRoot: Boolean?,
        mode: String?,
        aliases: List<String>?
    ): ResponseEntity<TaskStatusResponseDto> {
        val initialData = ManifestReloadTaskModel(
            backend = backend,
            secret = secret,
            reloadRoot = reloadRoot,
            mode = mode,
            aliases = aliases
        )
        val taskInstance = reloadTask.instance(
            ReloadTaskConfig.instanceId(backend),
            initialData
        )
        val isScheduled = schedulerClient.scheduleIfNotExists(taskInstance, Instant.now())
        return if (isScheduled) {
            log.info("Процесс оркестрации reload успешно запущен для бэкенда '{}'.", backend)
            ResponseEntity.ok(fetchStatus(backend).copy(message = "Оркестрация запущена асинхронно"))
        } else {
            log.warn("Попытка дублирующего запуска для бэкенда '{}'. Процесс уже выполняется. Возвращаем текущий статус.", backend)
            ResponseEntity.ok(fetchStatus(backend).copy(message = "Попытка дублирующего запуска"))
        }
    }

    override fun status(): ResponseEntity<Map<String, TaskStatusResponseDto>> {
        val statuses = backendServiceClient.backends().keys.associateWith { backend -> fetchStatus(backend) }
        return ResponseEntity.ok(statuses)
    }

    private fun fetchStatus(backend: String): TaskStatusResponseDto {
        val instanceId = ReloadTaskConfig.instanceId(backend)
        val execution = schedulerClient.getScheduledExecutionsForTask(
            ReloadTaskConfig.TASK_NAME,
            ManifestReloadTaskModel::class.java
        ).find {
            it.taskInstance.taskName == ReloadTaskConfig.TASK_NAME && it.taskInstance.id == instanceId
        }
        return TaskStatusResponseDto(
            orchestrator = execution?.data?.let {
                TaskStatusDto(
                    currentStep = it.currentStep.name
                )
            } ?: TaskStatusDto.idle(),
            history = historyService.getTaskHistory(ReloadTaskConfig.TASK_NAME, instanceId)
        )
    }
}