<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You 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.apache.jackrabbit.mongomk.impl.command;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.jackrabbit.mongomk.api.instruction.Instruction;
import org.apache.jackrabbit.mongomk.api.model.Commit;
import org.apache.jackrabbit.mongomk.impl.MongoNodeStore;
import org.apache.jackrabbit.mongomk.impl.action.FetchCommitAction;
import org.apache.jackrabbit.mongomk.impl.action.FetchHeadRevisionIdAction;
import org.apache.jackrabbit.mongomk.impl.action.ReadAndIncHeadRevisionAction;
import org.apache.jackrabbit.mongomk.impl.action.SaveAndSetHeadRevisionAction;
import org.apache.jackrabbit.mongomk.impl.action.SaveCommitAction;
import org.apache.jackrabbit.mongomk.impl.action.SaveNodesAction;
import org.apache.jackrabbit.mongomk.impl.command.exception.ConflictingCommitException;
import org.apache.jackrabbit.mongomk.impl.instruction.CommitCommandInstructionVisitor;
import org.apache.jackrabbit.mongomk.impl.model.MongoCommit;
import org.apache.jackrabbit.mongomk.impl.model.MongoNode;
import org.apache.jackrabbit.mongomk.impl.model.MongoSync;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.QueryBuilder;
import com.mongodb.WriteConcern;
import com.mongodb.WriteResult;

/**
 * {@code Command} for {@code MongoMicroKernel#commit(String, String, String, String)}
 */
public class CommitCommand extends BaseCommand<Long> {

    private static final Logger logger = LoggerFactory.getLogger(CommitCommand.class);

    private final MongoCommit commit;

    private Set<String> affectedPaths;
    private Map<String, MongoNode> existingNodes;
    private MongoSync mongoSync;
    private Map<String, MongoNode> nodes;
    private Long revisionId;
    private final Long initialBaseRevisionId;
    private Long baseRevisionId;
    private String branchId;

    /**
     * Constructs a new {@code CommitCommandMongo}.
     *
     * @param nodeStore Node store.
     * @param commit {@link Commit}
     */
    public CommitCommand(MongoNodeStore nodeStore, Commit commit) {
        super(nodeStore);
        this.commit = (MongoCommit)commit;
        this.initialBaseRevisionId = commit.getBaseRevisionId();
    }

    @Override
    public Long execute() throws Exception {
        int retries = 0;
        boolean success;
        do {
            mongoSync = new ReadAndIncHeadRevisionAction(nodeStore).execute();
            revisionId = mongoSync.getNextRevisionId() - 1;
            if (initialBaseRevisionId != null) {
                baseRevisionId = initialBaseRevisionId;
            } else {
                baseRevisionId = mongoSync.getHeadRevisionId();
            }
            logger.debug("Committing @{} with diff: {}", revisionId, commit.getDiff());
            readBranchIdFromBaseCommit();
            createMongoNodes();
            prepareCommit();
            readAndMergeExistingNodes();
            prepareMongoNodes();
            new SaveNodesAction(nodeStore, nodes.values()).execute();
            new SaveCommitAction(nodeStore, commit).execute();
            success = saveAndSetHeadRevision();
            if (success) {
                cacheNodes();
            } else {
                retries++;
            }
        } while (!success);

        String msg = "Commit @{}: success";
        if (retries > 0) {
            msg += " with {} retries.";
        }
        logger.debug(msg, revisionId, retries);
        return revisionId;
    }

    @Override
    public int getNumOfRetries() {
        return 100;
    }

    @Override
    public boolean needsRetry(Exception e) {
        return e instanceof ConflictingCommitException;
    }

    private void readBranchIdFromBaseCommit() throws Exception {
        String commitBranchId = commit.getBranchId();
        if (commitBranchId != null) {
            // This is a newly created branch, so no need to check the base
            // commit's branch id.
            branchId = commitBranchId;
            return;
        }

        Long baseRevisionId = commit.getBaseRevisionId();
        if (baseRevisionId == null) {
            return;
        }

        FetchCommitAction action = new FetchCommitAction(nodeStore, baseRevisionId);
        MongoCommit commit = action.execute();
        branchId = commit.getBranchId();
    }

    private void createMongoNodes() throws Exception {
        CommitCommandInstructionVisitor visitor = new CommitCommandInstructionVisitor(
                nodeStore, baseRevisionId, null);
        visitor.setBranchId(branchId);

        for (Instruction instruction : commit.getInstructions()) {
            instruction.accept(visitor);
        }

        nodes = visitor.getPathNodeMap();
        affectedPaths = nodes.keySet();
    }

    private void prepareCommit() throws Exception {
        commit.setAffectedPaths(affectedPaths);
        commit.setBaseRevisionId(branchId == null?
                mongoSync.getHeadRevisionId() : baseRevisionId);
        commit.setRevisionId(revisionId);
        if (commit.getBranchId() == null && branchId != null) {
            commit.setBranchId(branchId);
        }
        commit.removeField("_id"); // In case this is a retry.
    }

    private void readAndMergeExistingNodes() throws Exception {
        // If base revision is older than the head revision, need to read
        // and merge nodes at the head revision.
        long headRevisionId;
        if (branchId == null) {
            headRevisionId = mongoSync.getHeadRevisionId();
        } else {
            headRevisionId = new FetchHeadRevisionIdAction(nodeStore, branchId).execute();
        }

        if (baseRevisionId < headRevisionId) {
            readExistingNodes();
            mergeNodes();
        }
    }


//    private void readExistingNodes() {
//        FetchNodesAction action = new FetchNodesAction(nodeStore, affectedPaths,
//                mongoSync.getHeadRevisionId());
//        action.setBranchId(branchId);
//        existingNodes = action.execute();
//    }

    // FIXME - Performance, This seems to be faster for commits than the old method.
    private void readExistingNodes() throws Exception {
        if (affectedPaths == null || affectedPaths.isEmpty()) {
            existingNodes = Collections.emptyMap();
        }
<commit_msg>OAK-585 - Reduce cost of commit retry<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You 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.apache.jackrabbit.mongomk.impl.command;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.jackrabbit.mongomk.api.instruction.Instruction;
import org.apache.jackrabbit.mongomk.api.model.Commit;
import org.apache.jackrabbit.mongomk.impl.MongoNodeStore;
import org.apache.jackrabbit.mongomk.impl.action.FetchCommitAction;
import org.apache.jackrabbit.mongomk.impl.action.FetchHeadRevisionIdAction;
import org.apache.jackrabbit.mongomk.impl.action.ReadAndIncHeadRevisionAction;
import org.apache.jackrabbit.mongomk.impl.action.SaveAndSetHeadRevisionAction;
import org.apache.jackrabbit.mongomk.impl.action.SaveCommitAction;
import org.apache.jackrabbit.mongomk.impl.action.SaveNodesAction;
import org.apache.jackrabbit.mongomk.impl.command.exception.ConflictingCommitException;
import org.apache.jackrabbit.mongomk.impl.instruction.CommitCommandInstructionVisitor;
import org.apache.jackrabbit.mongomk.impl.model.MongoCommit;
import org.apache.jackrabbit.mongomk.impl.model.MongoNode;
import org.apache.jackrabbit.mongomk.impl.model.MongoSync;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.QueryBuilder;
import com.mongodb.WriteConcern;
import com.mongodb.WriteResult;

/**
 * {@code Command} for {@code MongoMicroKernel#commit(String, String, String, String)}
 */
public class CommitCommand extends BaseCommand<Long> {

    private static final Logger logger = LoggerFactory.getLogger(CommitCommand.class);

    private final MongoCommit commit;

    private Set<String> affectedPaths;
    private Map<String, MongoNode> existingNodes;
    private MongoSync mongoSync;
    private Map<String, MongoNode> nodes;
    private Long revisionId;
    private final Long initialBaseRevisionId;
    private Long baseRevisionId;
    private String branchId;

    /**
     * Constructs a new {@code CommitCommandMongo}.
     *
     * @param nodeStore Node store.
     * @param commit {@link Commit}
     */
    public CommitCommand(MongoNodeStore nodeStore, Commit commit) {
        super(nodeStore);
        this.commit = (MongoCommit)commit;
        this.initialBaseRevisionId = commit.getBaseRevisionId();
    }

    @Override
    public Long execute() throws Exception {
        int retries = 0;
        boolean success;
        do {
            mongoSync = new ReadAndIncHeadRevisionAction(nodeStore).execute();
            revisionId = mongoSync.getNextRevisionId() - 1;
            if (initialBaseRevisionId != null) {
                baseRevisionId = initialBaseRevisionId;
            } else {
                baseRevisionId = mongoSync.getHeadRevisionId();
            }
            logger.debug("Committing @{} with diff: {}", revisionId, commit.getDiff());
            readBranchIdFromBaseCommit();
            createMongoNodes();
            prepareCommit();
            readAndMergeExistingNodes();
            prepareMongoNodes();
            success = saveNodesAndCommits();
            if (success) {
                success = saveAndSetHeadRevision();
                if (success) {
                    cacheNodes();
                } else {
                    retries++;
                }
            }
        } while (!success);

        String msg = "Commit @{}: success";
        if (retries > 0) {
            msg += " with {} retries.";
        }
        logger.debug(msg, revisionId, retries);
        return revisionId;
    }

    private boolean saveNodesAndCommits() throws Exception {
        long headRevisionId = new FetchHeadRevisionIdAction(nodeStore, branchId).execute();
        if (branchId == null && headRevisionId != mongoSync.getHeadRevisionId()) {
            // Head revision moved on in trunk in the meantime, no need to save
            return false;
        }
        new SaveNodesAction(nodeStore, nodes.values()).execute();
        new SaveCommitAction(nodeStore, commit).execute();
        return true;
    }

    @Override
    public int getNumOfRetries() {
        return 100;
    }

    @Override
    public boolean needsRetry(Exception e) {
        return e instanceof ConflictingCommitException;
    }

    private void readBranchIdFromBaseCommit() throws Exception {
        String commitBranchId = commit.getBranchId();
        if (commitBranchId != null) {
            // This is a newly created branch, so no need to check the base
            // commit's branch id.
            branchId = commitBranchId;
            return;
        }

        Long baseRevisionId = commit.getBaseRevisionId();
        if (baseRevisionId == null) {
            return;
        }

        FetchCommitAction action = new FetchCommitAction(nodeStore, baseRevisionId);
        MongoCommit commit = action.execute();
        branchId = commit.getBranchId();
    }

    private void createMongoNodes() throws Exception {
        CommitCommandInstructionVisitor visitor = new CommitCommandInstructionVisitor(
                nodeStore, baseRevisionId, null);
        visitor.setBranchId(branchId);

        for (Instruction instruction : commit.getInstructions()) {
            instruction.accept(visitor);
        }

        nodes = visitor.getPathNodeMap();
        affectedPaths = nodes.keySet();
    }

    private void prepareCommit() throws Exception {
        commit.setAffectedPaths(affectedPaths);
        commit.setBaseRevisionId(branchId == null?
                mongoSync.getHeadRevisionId() : baseRevisionId);
        commit.setRevisionId(revisionId);
        if (commit.getBranchId() == null && branchId != null) {
            commit.setBranchId(branchId);
        }
        commit.removeField("_id"); // In case this is a retry.
    }

    private void readAndMergeExistingNodes() throws Exception {
        // If base revision is older than the head revision, need to read
        // and merge nodes at the head revision.
        long headRevisionId;
        if (branchId == null) {
            headRevisionId = mongoSync.getHeadRevisionId();
        } else {
            headRevisionId = new FetchHeadRevisionIdAction(nodeStore, branchId).execute();
        }

        if (baseRevisionId < headRevisionId) {
            readExistingNodes();
            mergeNodes();
        }
    }

//    private void readExistingNodes() {
//        FetchNodesAction action = new FetchNodesAction(nodeStore, affectedPaths,
//                mongoSync.getHeadRevisionId());
//        action.setBranchId(branchId);
//        existingNodes = action.execute();
//    }

    // FIXME - Performance, This seems to be faster for commits than the old method.
    private void readExistingNodes() throws Exception {
        if (affectedPaths == null || affectedPaths.isEmpty()) {
            existingNodes = Collections.emptyMap();
        }

{'fraction_non_alphanumeric': 0.0908430712352281, 'fraction_numerical': 0.0017825311942959, 'mean_word_length': 2.810817610062893, 'pattern_counts': {'":': 0, '<': 13, '<?xml version=': 0, '>': 13, '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': '6038814', 'n_tokens_mistral': 4129, 'n_tokens_neox': 3990, 'n_words': 1039}