VcsReposInfoScheduler.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
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.
*/
package org.archtool.scheduler
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.withContext
import org.archtool.configuration.ServiceProperties
import org.archtool.data.model.UpdateStatus
import org.archtool.helper.GasOrgInfoLoader
import org.archtool.helper.LockHelper
import org.archtool.vcs.provider.SyncedRepositories
import org.archtool.vcs.provider.VcsAccessProvider
import org.archtool.service.OrganizationService
import org.archtool.service.RepoService
import org.archtool.service.SettingsService
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.scheduling.annotation.Scheduled
import org.springframework.stereotype.Component
import java.time.Instant
import kotlin.time.measureTime
@Component
class VcsReposInfoScheduler(
private val vcsAccessProvider: VcsAccessProvider,
private val gasOrgInfoLoader: GasOrgInfoLoader,
private val serviceProperties: ServiceProperties,
private val lock: LockHelper,
private val settingsService: SettingsService,
private val repoService: RepoService,
private val organizationService: OrganizationService,
) {
@Scheduled(fixedRateString = "\${seaf.update-scheduler-rate}")
suspend fun scheduleUpdateAccessInfo() {
val expirationTime = Instant.now()
.plus(serviceProperties.vcsScanInterval.multipliedBy(2))
lock(UPDATE_ROLE_INFO_LOCK_KEY, expirationTime) {
val currentStatus = settingsService.getUpdateStatus()
if (currentStatus != UpdateStatus.SCHEDULED) {
log.trace("Статус обновления '{}', пропускаем проход", currentStatus)
return@lock
}
try {
settingsService.setUpdateStatus(UpdateStatus.IN_PROGRESS, expirationTime)
settingsService.deleteUpdateErrorMessage()
val sequence = settingsService.incrementUpdateSequence()
log.trace("Получен sequence number {}", sequence)
log.info("Загружаем информацию из VCS")
val t = measureTime {
val repositories = vcsAccessProvider.syncRepositories(sequence, expirationTime)
vcsAccessProvider.syncUsers(repositories, sequence, expirationTime)
if (!serviceProperties.orgAccessFile.isNullOrBlank()) {
fetchOrganizationsFromVcs(sequence, expirationTime)
}
}
log.info("Загрузка репозиториев из VCS завершена за {}", t)
settingsService.setActiveSequence(sequence, expirationTime)
settingsService.setUpdateStatus(UpdateStatus.SUCCESS)
settingsService.setUpdateCompletionTime(Instant.now())
} catch (e: CancellationException) {
log.warn("Обновление информации из VCS прервано остановкой сервиса")
withContext(NonCancellable) {
settingsService.setUpdateStatus(UpdateStatus.ERROR)
settingsService.setUpdateErrorMessage("Обновление прервано остановкой сервиса")
settingsService.setUpdateCompletionTime(Instant.now())
}
throw e
} catch (e: Exception) {
log.error("Ошибка при обновлении информации из VCS", e)
settingsService.setUpdateStatus(UpdateStatus.ERROR)
settingsService.setUpdateErrorMessage(e.message ?: e.toString())
settingsService.setUpdateCompletionTime(Instant.now())
} catch (e: Throwable) {
// Error оставил бы статус в IN_PROGRESS навсегда (следующие запуски молча
// пропускались бы, пока статус не SCHEDULED) — фиксируем ERROR и пробрасываем дальше.
log.error("Критическая ошибка JVM при обновлении информации из VCS", e)
settingsService.setUpdateStatus(UpdateStatus.ERROR)
settingsService.setUpdateErrorMessage(e.message ?: e.toString())
settingsService.setUpdateCompletionTime(Instant.now())
throw e
}
}
}
private suspend fun fetchOrganizationsFromVcs(sequence: Long, expirationTime: Instant) {
log.debug("=== Загружаем информацию о дочерних организациях ===")
val organizations = gasOrgInfoLoader.load(serviceProperties.orgAccessFile!!)
var validOrgCounter = 0
for ((orgId, org) in organizations) {
val validRepo = repoService.checkRepositoriesExistence(sequence, org.repos)
if (validRepo) {
organizationService.insertOrganizationIfNotExistsAndSaveRepoRelations(
orgId.toString(),
org.name,
org.repos,
sequence,
expirationTime,
)
validOrgCounter++
}
}
log.debug("Загружено {} организаций", validOrgCounter)
}
companion object {
const val KEY_PREFIX = "access-management-service"
const val UPDATE_ROLE_INFO_LOCK_KEY = "${KEY_PREFIX}:update-access-info-lock"
val log: Logger = LoggerFactory.getLogger(VcsReposInfoScheduler::class.java)
}
}