/*
 * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
 * or more contributor license agreements. Licensed under the Elastic License;
 * you may not use this file except in compliance with the Elastic License.
 */
package org.elasticsearch.xpack.watcher.transform.search;

import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.message.ParameterizedMessage;
import org.apache.logging.log4j.util.Supplier;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.bytes.BytesArray;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.script.Script;
import org.elasticsearch.xpack.watcher.execution.WatchExecutionContext;
import org.elasticsearch.xpack.watcher.support.search.WatcherSearchTemplateRequest;
import org.elasticsearch.xpack.watcher.support.search.WatcherSearchTemplateService;
import org.elasticsearch.xpack.watcher.transform.ExecutableTransform;
import org.elasticsearch.xpack.watcher.watch.Payload;

import java.util.concurrent.TimeUnit;

import static org.elasticsearch.xpack.watcher.transform.search.SearchTransform.TYPE;

public class ExecutableSearchTransform extends ExecutableTransform<SearchTransform, SearchTransform.Result> {

    public static final SearchType DEFAULT_SEARCH_TYPE = SearchType.QUERY_THEN_FETCH;

    protected final Client client;
    protected final WatcherSearchTemplateService searchTemplateService;
    protected final TimeValue timeout;

    public ExecutableSearchTransform(SearchTransform transform, Logger logger, Client client,
                                     WatcherSearchTemplateService searchTemplateService, TimeValue defaultTimeout) {
        super(transform, logger);
        this.client = client;
        this.searchTemplateService = searchTemplateService;
        this.timeout = transform.getTimeout() != null ? transform.getTimeout() : defaultTimeout;
    }

    @Override
    public SearchTransform.Result execute(WatchExecutionContext ctx, Payload payload) {
        WatcherSearchTemplateRequest request = null;
        try {
            Script template = transform.getRequest().getOrCreateTemplate();
            String renderedTemplate = searchTemplateService.renderTemplate(template, ctx, payload);
            // We need to make a copy, so that we don't modify the original instance that we keep around in a watch:
            request = new WatcherSearchTemplateRequest(transform.getRequest(), new BytesArray(renderedTemplate));
            SearchResponse resp = client.search(searchTemplateService.toSearchRequest(request))
                    .get(timeout.millis(), TimeUnit.MILLISECONDS);
            return new SearchTransform.Result(request, new Payload.XContent(resp));
        } catch (Exception e) {
            logger.error((Supplier<?>) () -> new ParameterizedMessage("failed to execute [{}] transform for [{}]", TYPE, ctx.id()), e);
            return new SearchTransform.Result(request, e);
        }
    }
}

@@ -593,50 +593,8 @@
 nt;%0A
-import org.elasticsearch.common.Nullable;%0A
 impo
@@ -687,16 +687,79 @@
 eValue;%0A
+import org.elasticsearch.common.util.concurrent.ThreadContext;%0A
 import o
@@ -1194,16 +1194,151 @@
 eUnit;%0A%0A
+import static org.elasticsearch.xpack.ClientHelper.WATCHER_ORIGIN;%0Aimport static org.elasticsearch.xpack.ClientHelper.stashWithOrigin;%0A
 import s
@@ -2771,24 +2771,157 @@
 Template));%0A
+            try (ThreadContext.StoredContext ignore = stashWithOrigin(client.threadPool().getThreadContext(), WATCHER_ORIGIN)) %7B%0A    
             
@@ -3075,32 +3075,36 @@
 S);%0A            
+    
 return new Searc
@@ -3155,24 +3155,38 @@
 ent(resp));%0A
+            %7D%0A
         %7D ca

Transform also needs to use stashing client (elastic/x-pack-elasticsearch#3098)