| 
 | 1 | +package com.walmartlabs.concord.runner.engine;  | 
 | 2 | + | 
 | 3 | +/*-  | 
 | 4 | + * *****  | 
 | 5 | + * Concord  | 
 | 6 | + * -----  | 
 | 7 | + * Copyright (C) 2017 - 2024 Walmart Inc.  | 
 | 8 | + * -----  | 
 | 9 | + * Licensed under the Apache License, Version 2.0 (the "License");  | 
 | 10 | + * you may not use this file except in compliance with the License.  | 
 | 11 | + * You may obtain a copy of the License at  | 
 | 12 | + *   | 
 | 13 | + *      http://www.apache.org/licenses/LICENSE-2.0  | 
 | 14 | + *   | 
 | 15 | + * Unless required by applicable law or agreed to in writing, software  | 
 | 16 | + * distributed under the License is distributed on an "AS IS" BASIS,  | 
 | 17 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  | 
 | 18 | + * See the License for the specific language governing permissions and  | 
 | 19 | + * limitations under the License.  | 
 | 20 | + * =====  | 
 | 21 | + */  | 
 | 22 | + | 
 | 23 | +import com.walmartlabs.concord.client2.ApiClientConfiguration;  | 
 | 24 | +import com.walmartlabs.concord.client2.ApiClientFactory;  | 
 | 25 | +import com.walmartlabs.concord.client2.ApiException;  | 
 | 26 | +import com.walmartlabs.concord.client2.ProcessEventRequest;  | 
 | 27 | +import com.walmartlabs.concord.client2.ProcessEventsApi;  | 
 | 28 | +import io.takari.bpm.state.ProcessInstance;  | 
 | 29 | +import org.slf4j.Logger;  | 
 | 30 | +import org.slf4j.LoggerFactory;  | 
 | 31 | + | 
 | 32 | +import java.util.ArrayDeque;  | 
 | 33 | +import java.util.ArrayList;  | 
 | 34 | +import java.util.HashMap;  | 
 | 35 | +import java.util.List;  | 
 | 36 | +import java.util.Map;  | 
 | 37 | +import java.util.Optional;  | 
 | 38 | +import java.util.Queue;  | 
 | 39 | +import java.util.TimerTask;  | 
 | 40 | +import java.util.UUID;  | 
 | 41 | +import java.util.concurrent.Executors;  | 
 | 42 | +import java.util.concurrent.ScheduledExecutorService;  | 
 | 43 | +import java.util.concurrent.TimeUnit;  | 
 | 44 | + | 
 | 45 | +public class DefaultEventReportingService implements EventReportingService {  | 
 | 46 | + | 
 | 47 | +    private static final Logger log = LoggerFactory.getLogger(DefaultEventReportingService.class);  | 
 | 48 | + | 
 | 49 | +    private final ApiClientFactory apiClientFactory;  | 
 | 50 | +    private final int maxBatchSize;  | 
 | 51 | +    private final Object batchLock = new Object();  | 
 | 52 | +    private final ScheduledExecutorService flushScheduler;  | 
 | 53 | +    private final HashMap<ReportingContext, Queue<ProcessEventRequest>> eventQueues;  | 
 | 54 | + | 
 | 55 | +    public DefaultEventReportingService(ApiClientFactory apiClientFactory,  | 
 | 56 | +                                        int batchSize,  | 
 | 57 | +                                        int batchFlushInterval) {  | 
 | 58 | +        this.apiClientFactory = apiClientFactory;  | 
 | 59 | +        this.maxBatchSize = batchSize;  | 
 | 60 | +        this.eventQueues = new HashMap<>(1);  | 
 | 61 | +        this.flushScheduler = Executors.newSingleThreadScheduledExecutor();  | 
 | 62 | + | 
 | 63 | +        flushScheduler.scheduleAtFixedRate(new FlushTimer(this), batchFlushInterval, batchFlushInterval, TimeUnit.SECONDS);  | 
 | 64 | +    }  | 
 | 65 | + | 
 | 66 | +    @Override  | 
 | 67 | +    public ProcessInstance onFinalize(ProcessInstance state) {  | 
 | 68 | +        flushScheduler.shutdown();  | 
 | 69 | +        flush();  | 
 | 70 | +        return state;  | 
 | 71 | +    }  | 
 | 72 | + | 
 | 73 | +    private class ReportingBatch {  | 
 | 74 | +        private final ReportingContext reportingContext;  | 
 | 75 | +        private final List<ProcessEventRequest> events;  | 
 | 76 | + | 
 | 77 | +        public ReportingBatch(ReportingContext reportingContext, List<ProcessEventRequest> events) {  | 
 | 78 | +            this.reportingContext = reportingContext;  | 
 | 79 | +            this.events = events;  | 
 | 80 | +        }  | 
 | 81 | + | 
 | 82 | +        public void send() {  | 
 | 83 | +            try {  | 
 | 84 | +                getProcessEventsApi(reportingContext.sessionToken).batchEvent(reportingContext.instanceId, events);  | 
 | 85 | +            } catch (ApiException e) {  | 
 | 86 | +                log.warn("Error while sending batch of {} event{} to the server: {}",  | 
 | 87 | +                        events.size(), events.isEmpty() ? "" : "s", e.getMessage());  | 
 | 88 | +            }  | 
 | 89 | +        }  | 
 | 90 | +    }  | 
 | 91 | + | 
 | 92 | +    ProcessEventsApi getProcessEventsApi(String sessionToken) {  | 
 | 93 | +        return new ProcessEventsApi(apiClientFactory.create(  | 
 | 94 | +                ApiClientConfiguration.builder()  | 
 | 95 | +                        .sessionToken(sessionToken)  | 
 | 96 | +                        .build()));  | 
 | 97 | +    }  | 
 | 98 | + | 
 | 99 | +    /**  | 
 | 100 | +     * Event source context. Basically a combo of instance ID and session token.  | 
 | 101 | +     * Intended to be used as a key for a map of context -> queue of events  | 
 | 102 | +     */  | 
 | 103 | +    static class ReportingContext {  | 
 | 104 | +        private final UUID instanceId;  | 
 | 105 | +        private final String  sessionToken;  | 
 | 106 | + | 
 | 107 | +        public ReportingContext(UUID instanceId, String sessionToken) {  | 
 | 108 | +            this.instanceId = instanceId;  | 
 | 109 | +            this.sessionToken = sessionToken;  | 
 | 110 | +        }  | 
 | 111 | + | 
 | 112 | +        @Override  | 
 | 113 | +        public boolean equals(Object o) {  | 
 | 114 | +            if (this == o) return true;  | 
 | 115 | +            if (o == null || getClass() != o.getClass()) return false;  | 
 | 116 | + | 
 | 117 | +            ReportingContext that = (ReportingContext) o;  | 
 | 118 | + | 
 | 119 | +            if (!instanceId.equals(that.instanceId)) return false;  | 
 | 120 | +            return sessionToken.equals(that.sessionToken);  | 
 | 121 | +        }  | 
 | 122 | + | 
 | 123 | +        @Override  | 
 | 124 | +        public int hashCode() {  | 
 | 125 | +            int result = instanceId.hashCode();  | 
 | 126 | +            result = 31 * result + sessionToken.hashCode();  | 
 | 127 | +            return result;  | 
 | 128 | +        }  | 
 | 129 | +    }  | 
 | 130 | + | 
 | 131 | +    @Override  | 
 | 132 | +    public void report(ProcessEventRequest req, UUID instanceId, String sessionToken) {  | 
 | 133 | +        if (maxBatchSize > 1) {  | 
 | 134 | +            batch(req, instanceId, sessionToken);  | 
 | 135 | +        } else {  | 
 | 136 | +            sendSingle(req, instanceId, sessionToken);  | 
 | 137 | +        }  | 
 | 138 | +    }  | 
 | 139 | + | 
 | 140 | +    void batch(ProcessEventRequest req, UUID instanceId, String sessionToken) {  | 
 | 141 | +        Queue<ProcessEventRequest> queue;  | 
 | 142 | + | 
 | 143 | +        synchronized (batchLock) {  | 
 | 144 | +            queue = eventQueues.computeIfAbsent(new ReportingContext(instanceId, sessionToken), ctx -> new ArrayDeque<>(maxBatchSize));  | 
 | 145 | +            queue.add(req);  | 
 | 146 | +        }  | 
 | 147 | + | 
 | 148 | +        if (queue.size() >= maxBatchSize) {  | 
 | 149 | +            flush();  | 
 | 150 | +        }  | 
 | 151 | +    }  | 
 | 152 | + | 
 | 153 | +    void sendSingle(ProcessEventRequest req, UUID instanceId, String sessionToken) {  | 
 | 154 | +        try {  | 
 | 155 | +            ProcessEventsApi client = getProcessEventsApi(sessionToken);  | 
 | 156 | +            client.event(instanceId, req);  | 
 | 157 | +        } catch (ApiException e) {  | 
 | 158 | +            log.warn("error while sending an event to the server: {}", e.getMessage());  | 
 | 159 | +        }  | 
 | 160 | +    }  | 
 | 161 | + | 
 | 162 | +    /**  | 
 | 163 | +     * Flushes all queued events across all reporting contexts.  | 
 | 164 | +     */  | 
 | 165 | +    void flush() {  | 
 | 166 | +        ReportingBatch eventBatch = takeBatch();  | 
 | 167 | + | 
 | 168 | +        while (eventBatch != null && !eventBatch.events.isEmpty()) {  | 
 | 169 | +            eventBatch.send();  | 
 | 170 | +            eventBatch = takeBatch();  | 
 | 171 | +        }  | 
 | 172 | +    }  | 
 | 173 | + | 
 | 174 | +    /**  | 
 | 175 | +     * @return batch of up-to {@link #maxBatchSize} queued process events  | 
 | 176 | +     */  | 
 | 177 | +    private ReportingBatch takeBatch() {  | 
 | 178 | +        ReportingContext ctx;  | 
 | 179 | +        List<ProcessEventRequest> batch = new ArrayList<>(maxBatchSize);  | 
 | 180 | + | 
 | 181 | +        synchronized (batchLock) {  | 
 | 182 | +            if (eventQueues.isEmpty()) {  | 
 | 183 | +                return null; // nothing to report  | 
 | 184 | +            }  | 
 | 185 | + | 
 | 186 | +            Optional<ReportingContext> optionalCtx = eventQueues.entrySet().stream()  | 
 | 187 | +                    .findFirst()  | 
 | 188 | +                    .map(Map.Entry::getKey);  | 
 | 189 | + | 
 | 190 | +            if (optionalCtx.isEmpty()) {  | 
 | 191 | +                // that's odd, should've been cleaned up already  | 
 | 192 | +                eventQueues.clear();  | 
 | 193 | +                return null;  | 
 | 194 | +            }  | 
 | 195 | + | 
 | 196 | +            ctx = optionalCtx.get();  | 
 | 197 | + | 
 | 198 | +            Queue<ProcessEventRequest> eventQueue = eventQueues.get(ctx);  | 
 | 199 | + | 
 | 200 | +            for (int i = 0; i < maxBatchSize; i++) {  | 
 | 201 | +                if (eventQueue.isEmpty()) {  | 
 | 202 | +                    eventQueues.remove(ctx);  | 
 | 203 | +                    break;  | 
 | 204 | +                }  | 
 | 205 | + | 
 | 206 | +                batch.add(eventQueue.poll());  | 
 | 207 | +            }  | 
 | 208 | +        }  | 
 | 209 | + | 
 | 210 | +        return new ReportingBatch(ctx, batch);  | 
 | 211 | +    }  | 
 | 212 | + | 
 | 213 | +    private static class FlushTimer extends TimerTask {  | 
 | 214 | +        private final DefaultEventReportingService reportingService;  | 
 | 215 | + | 
 | 216 | +        public FlushTimer(DefaultEventReportingService reportingService) {  | 
 | 217 | +            this.reportingService = reportingService;  | 
 | 218 | +        }  | 
 | 219 | + | 
 | 220 | +        @Override  | 
 | 221 | +        public void run() {  | 
 | 222 | +            reportingService.flush();  | 
 | 223 | +        }  | 
 | 224 | +    }  | 
 | 225 | + | 
 | 226 | +}  | 
0 commit comments