<commit_before>/*
 * (c) Copyright 2018 Palantir Technologies Inc. All rights reserved.
 *
 * 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 com.palantir.atlasdb.sweep;

import com.github.benmanes.caffeine.cache.CacheLoader;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.palantir.atlasdb.AtlasDbConstants;
import com.palantir.atlasdb.keyvalue.api.KeyAlreadyExistsException;
import com.palantir.atlasdb.transaction.impl.TransactionConstants;
import com.palantir.atlasdb.transaction.service.TransactionService;
import com.palantir.logsafe.SafeArg;
import com.palantir.logsafe.logger.SafeLogger;
import com.palantir.logsafe.logger.SafeLoggerFactory;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;

public class AbortingCommitTsLoader implements CacheLoader<Long, Long> {
    private static final SafeLogger log = SafeLoggerFactory.get(AbortingCommitTsLoader.class);
    private final TransactionService transactionService;

    public AbortingCommitTsLoader(TransactionService transactionService) {
        this.transactionService = transactionService;
    }

    @Override
    public Long load(Long startTs) {
        Optional<Long> maybeCommitTs = tryGetFromTransactionService(startTs);

        if (!maybeCommitTs.isPresent()) {
            maybeCommitTs = tryToAbort(startTs);
        }

        if (!maybeCommitTs.isPresent()) {
            maybeCommitTs = tryGetFromTransactionService(startTs);
        }

        return maybeCommitTs.orElse(TransactionConstants.FAILED_COMMIT_TS);
    }

    @Override
    public Map<Long, Long> loadAll(Set<? extends Long> nonCachedKeys) {
        List<Long> missingKeys = ImmutableList.copyOf(nonCachedKeys);
        Map<Long, Long> result = new HashMap<>();

        Lists.partition(missingKeys, AtlasDbConstants.TRANSACTION_TIMESTAMP_LOAD_BATCH_LIMIT)
                .forEach(batch -> result.putAll(transactionService.get(batch)));

        // roll back any uncommitted transactions
        missingKeys.stream()
                .filter(startTs -> !result.containsKey(startTs))
                .forEach(startTs -> result.put(startTs, load(startTs)));

        return result;
    }

    private Optional<Long> tryGetFromTransactionService(Long startTs) {
        return Optional.ofNullable(transactionService.get(startTs));
    }

    private Optional<Long> tryToAbort(Long startTs) {
        try {
            transactionService.putUnlessExists(startTs, TransactionConstants.FAILED_COMMIT_TS);<commit_msg>[TTS] Don't randomly assume aborted in TS (#6275)<commit_after>/*
 * (c) Copyright 2018 Palantir Technologies Inc. All rights reserved.
 *
 * 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 com.palantir.atlasdb.sweep;

import com.github.benmanes.caffeine.cache.CacheLoader;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.palantir.atlasdb.AtlasDbConstants;
import com.palantir.atlasdb.keyvalue.api.KeyAlreadyExistsException;
import com.palantir.atlasdb.transaction.impl.TransactionConstants;
import com.palantir.atlasdb.transaction.service.TransactionService;
import com.palantir.logsafe.SafeArg;
import com.palantir.logsafe.exceptions.SafeIllegalStateException;
import com.palantir.logsafe.logger.SafeLogger;
import com.palantir.logsafe.logger.SafeLoggerFactory;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;

public class AbortingCommitTsLoader implements CacheLoader<Long, Long> {
    private static final SafeLogger log = SafeLoggerFactory.get(AbortingCommitTsLoader.class);
    private final TransactionService transactionService;

    public AbortingCommitTsLoader(TransactionService transactionService) {
        this.transactionService = transactionService;
    }

    @Override
    public Long load(Long startTs) {
        return tryGetFromTransactionService(startTs)
                .or(() -> tryToAbort(startTs))
                .or(() -> tryGetFromTransactionService(startTs))
                .orElseThrow(() -> new SafeIllegalStateException(
                        "failed to abort transaction, but no entry found in the _transactions table",
                        SafeArg.of("start timestamp", startTs)));
    }

    @Override
    public Map<Long, Long> loadAll(Set<? extends Long> nonCachedKeys) {
        List<Long> missingKeys = ImmutableList.copyOf(nonCachedKeys);
        Map<Long, Long> result = new HashMap<>();

        Lists.partition(missingKeys, AtlasDbConstants.TRANSACTION_TIMESTAMP_LOAD_BATCH_LIMIT)
                .forEach(batch -> result.putAll(transactionService.get(batch)));

        // roll back any uncommitted transactions
        missingKeys.stream()
                .filter(startTs -> !result.containsKey(startTs))
                .forEach(startTs -> result.put(startTs, load(startTs)));

        return result;
    }

    private Optional<Long> tryGetFromTransactionService(Long startTs) {
        return Optional.ofNullable(transactionService.get(startTs));
    }

    private Optional<Long> tryToAbort(Long startTs) {
        try {
            transactionService.putUnlessExists(startTs, TransactionConstants.FAILED_COMMIT_TS);
{'fraction_non_alphanumeric': 0.08917803871786735, 'fraction_numerical': 0.0031735956839098697, 'mean_word_length': 3.807780320366133, 'pattern_counts': {'":': 0, '<': 20, '<?xml version=': 0, '>': 29, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4559799', 'n_tokens_mistral': 1788, 'n_tokens_neox': 1698, 'n_words': 429}