S3ObjectKeyGenerator.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.fileloader2.service.storage

import java.util.UUID
import org.archtool.fileloader2.configuration.properties.S3Properties
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Component

/**
 * Ключ объекта в хранилище. Ключ не хранится в БД, а вычисляется из идентификатора файла,
 * поэтому все операции с объектом должны получать его здесь.
 */
@Component
class S3ObjectKeyGenerator(
    s3Properties: S3Properties,
) {
    private val log = LoggerFactory.getLogger(javaClass)

    /**
     * Префикс ключей, приведённый к виду «папки» один раз при создании компонента: если в настройке нет
     * завершающего слеша, он добавляется. Пустой префикс остаётся пустым - объекты лежат в корне bucket
     */
    val keyPrefix: String = normalizePrefix(s3Properties.keyPrefix)

    /**
     * @param fileId идентификатор файла
     * @return ключ объекта: префикс ключей + идентификатор
     */
    fun generateObjectKey(fileId: UUID): String = keyPrefix + fileId

    /**
     * @param prefix префикс из настроек
     * @return префикс, заканчивающийся на /, или пустая строка
     */
    private fun normalizePrefix(prefix: String): String {
        if (prefix.isEmpty() || prefix.endsWith(PATH_SEPARATOR)) {
            return prefix
        }
        val normalized = prefix + PATH_SEPARATOR
        log.info("Префикс ключей S3 '{}' не заканчивается на '{}', используется '{}'", prefix, PATH_SEPARATOR, normalized)
        return normalized
    }

    companion object {
        private const val PATH_SEPARATOR = "/"
    }
}