<commit_before>/*
 * Licensed to Elastic Search and <NAME> under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. Elastic Search 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.elasticsearch.action.support.single.custom;

import org.elasticsearch.ElasticSearchException;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.ActionResponse;
import org.elasticsearch.action.NoShardAvailableActionException;
import org.elasticsearch.action.support.TransportAction;
import org.elasticsearch.cluster.ClusterService;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.block.ClusterBlockException;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.cluster.node.DiscoveryNodes;
import org.elasticsearch.cluster.routing.ShardRouting;
import org.elasticsearch.cluster.routing.ShardsIterator;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.io.stream.Streamable;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.transport.*;

import java.io.IOException;

/**
 *
 */
public abstract class TransportSingleCustomOperationAction<Request extends SingleCustomOperationRequest, Response extends ActionResponse> extends TransportAction<Request, Response> {

    protected final ClusterService clusterService;

    protected final TransportService transportService;

    final String transportAction;
    final String transportShardAction;
    final String executor;

    protected TransportSingleCustomOperationAction(Settings settings, ThreadPool threadPool, ClusterService clusterService, TransportService transportService) {
        super(settings, threadPool);
        this.clusterService = clusterService;
        this.transportService = transportService;

        this.transportAction = transportAction();
        this.transportShardAction = transportAction() + "/s";
        this.executor = executor();

        transportService.registerHandler(transportAction, new TransportHandler());
        transportService.registerHandler(transportShardAction, new ShardTransportHandler());
    }

    @Override
    protected void doExecute(Request request, ActionListener<Response> listener) {
        new AsyncSingleAction(request, listener).start();
    }

    protected abstract String transportAction();

    protected abstract String executor();

    /**
     * Can return null to execute on this local node.
     */
    protected abstract ShardsIterator shards(ClusterState state, Request request);

    protected abstract Response shardOperation(Request request, int shardId) throws ElasticSearchException;

    protected abstract Request newRequest();

    protected abstract Response newResponse();

    protected abstract ClusterBlockException checkGlobalBlock(ClusterState state, Request request);

    protected abstract ClusterBlockException checkRequestBlock(ClusterState state, Request request);

    private class AsyncSingleAction {

        private final ActionListener<Response> listener;

        private final ShardsIterator shardsIt;

        private final Request request;

        private final DiscoveryNodes nodes;

        private AsyncSingleAction(Request request, ActionListener<Response> listener) {
            this.request = request;
            this.listener = listener;

            ClusterState clusterState = clusterService.state();
            nodes = clusterState.nodes();
            ClusterBlockException blockException = checkGlobalBlock(clusterState, request);
            if (blockException != null) {
                throw blockException;
            }
            blockException = checkRequestBlock(clusterState, request);
            if (blockException != null) {
                throw blockException;
            }
            this.shardsIt = shards(clusterState, request);
        }

        public void start() {
            performFirst();
        }

        private void onFailure(ShardRouting shardRouting, Exception e) {
            if (logger.isTraceEnabled() && e != null) {
                logger.trace(shardRouting.shortSummary() + ": Failed to execute [" + request + "]", e);
            }
            perform(e);
        }

        /**
         * First get should try and use a shard that exists on a local node for better performance
         */
        private void performFirst() {
            if (shardsIt == null) {
                // just execute it on the local node
                if (request.operationThreaded()) {
                    request.beforeLocalFork();
                    threadPool.executor(executor()).execute(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                Response response = shardOperation(request, -1);
                                listener.onResponse(response);
                            } catch (Exception e) {
                                shardsIt.reset();
                                onFailure(null, e);
                            }
                        }
                    });
                    return;
                } else {
                    try {
                        final Response response = shardOperation(request, -1);
                        listener.onResponse(response);
                        return;
                    } catch (Exception e) {
                        onFailure(null, e);
                    }
                }
                return;
            }

            if (request.preferLocalShard()) {
                boolean foundLocal = false;
                ShardRouting shardX;
                while ((shardX = shardsIt.nextOrNull()) != null) {
                    final ShardRouting shard = shardX;
                    if (shard.currentNodeId().equals(nodes.localNodeId())) {
                        foundLocal = true;
                        if (request.operationThreaded()) {
                            request.beforeLocalFork();<commit_msg>when executing on local node, don't reset the shard iterator, its null...<commit_after>/*
 * Licensed to Elastic Search and <NAME> under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. Elastic Search 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.elasticsearch.action.support.single.custom;

import org.elasticsearch.ElasticSearchException;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.ActionResponse;
import org.elasticsearch.action.NoShardAvailableActionException;
import org.elasticsearch.action.support.TransportAction;
import org.elasticsearch.cluster.ClusterService;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.block.ClusterBlockException;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.cluster.node.DiscoveryNodes;
import org.elasticsearch.cluster.routing.ShardRouting;
import org.elasticsearch.cluster.routing.ShardsIterator;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.io.stream.Streamable;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.transport.*;

import java.io.IOException;

/**
 *
 */
public abstract class TransportSingleCustomOperationAction<Request extends SingleCustomOperationRequest, Response extends ActionResponse> extends TransportAction<Request, Response> {

    protected final ClusterService clusterService;

    protected final TransportService transportService;

    final String transportAction;
    final String transportShardAction;
    final String executor;

    protected TransportSingleCustomOperationAction(Settings settings, ThreadPool threadPool, ClusterService clusterService, TransportService transportService) {
        super(settings, threadPool);
        this.clusterService = clusterService;
        this.transportService = transportService;

        this.transportAction = transportAction();
        this.transportShardAction = transportAction() + "/s";
        this.executor = executor();

        transportService.registerHandler(transportAction, new TransportHandler());
        transportService.registerHandler(transportShardAction, new ShardTransportHandler());
    }

    @Override
    protected void doExecute(Request request, ActionListener<Response> listener) {
        new AsyncSingleAction(request, listener).start();
    }

    protected abstract String transportAction();

    protected abstract String executor();

    /**
     * Can return null to execute on this local node.
     */
    protected abstract ShardsIterator shards(ClusterState state, Request request);

    protected abstract Response shardOperation(Request request, int shardId) throws ElasticSearchException;

    protected abstract Request newRequest();

    protected abstract Response newResponse();

    protected abstract ClusterBlockException checkGlobalBlock(ClusterState state, Request request);

    protected abstract ClusterBlockException checkRequestBlock(ClusterState state, Request request);

    private class AsyncSingleAction {

        private final ActionListener<Response> listener;

        private final ShardsIterator shardsIt;

        private final Request request;

        private final DiscoveryNodes nodes;

        private AsyncSingleAction(Request request, ActionListener<Response> listener) {
            this.request = request;
            this.listener = listener;

            ClusterState clusterState = clusterService.state();
            nodes = clusterState.nodes();
            ClusterBlockException blockException = checkGlobalBlock(clusterState, request);
            if (blockException != null) {
                throw blockException;
            }
            blockException = checkRequestBlock(clusterState, request);
            if (blockException != null) {
                throw blockException;
            }
            this.shardsIt = shards(clusterState, request);
        }

        public void start() {
            performFirst();
        }

        private void onFailure(ShardRouting shardRouting, Exception e) {
            if (logger.isTraceEnabled() && e != null) {
                logger.trace(shardRouting.shortSummary() + ": Failed to execute [" + request + "]", e);
            }
            perform(e);
        }

        /**
         * First get should try and use a shard that exists on a local node for better performance
         */
        private void performFirst() {
            if (shardsIt == null) {
                // just execute it on the local node
                if (request.operationThreaded()) {
                    request.beforeLocalFork();
                    threadPool.executor(executor()).execute(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                Response response = shardOperation(request, -1);
                                listener.onResponse(response);
                            } catch (Exception e) {
                                onFailure(null, e);
                            }
                        }
                    });
                    return;
                } else {
                    try {
                        final Response response = shardOperation(request, -1);
                        listener.onResponse(response);
                        return;
                    } catch (Exception e) {
                        onFailure(null, e);
                    }
                }
                return;
            }

            if (request.preferLocalShard()) {
                boolean foundLocal = false;
                ShardRouting shardX;
                while ((shardX = shardsIt.nextOrNull()) != null) {
                    final ShardRouting shard = shardX;
                    if (shard.currentNodeId().equals(nodes.localNodeId())) {
                        foundLocal = true;
                        if (request.operationThreaded()) {
                            request.beforeLocalFork();
{'fraction_non_alphanumeric': 0.07493007507728544, 'fraction_numerical': 0.0008832621816575887, 'mean_word_length': 2.3756521739130436, 'pattern_counts': {'":': 2, '<': 15, '<?xml version=': 0, '>': 15, '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': '7255426', 'n_tokens_mistral': 3051, 'n_tokens_neox': 2965, 'n_words': 883}