LockHelper.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.helper

import org.archtool.service.SettingsService
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Component
import java.time.Instant
import java.util.UUID

@Component
class LockHelper(
    private val settingsService: SettingsService
) {
    private val log: Logger = LoggerFactory.getLogger(javaClass)

    suspend operator fun invoke(lockKey: String, expirationTime: Instant? = null, block: suspend () -> Unit) {
        val lockId = UUID.randomUUID()
        log.trace("Attempting to acquire lock for key: {} with id: {}", lockKey, lockId)
        val acquired = settingsService.tryLock(lockKey, lockId, expirationTime)
        log.trace("Lock acquisition result for key {}: {}", lockKey, acquired)
        if (acquired) {
            try {
                log.trace("Lock acquired for key {}, executing block", lockKey)
                block()
            } catch (e: Exception) {
                log.error("Exception occurred in block() for lock key {}: {}", lockKey, e.message, e)
                throw e
            } finally {
                log.trace("Releasing lock for key: {}", lockKey)
                settingsService.unlock(lockKey, lockId)
            }
        } else {
            log.trace("Failed to acquire lock for key: {}", lockKey)
        }
    }
}