<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.asterix.external.dataflow;

import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

import javax.annotation.Nonnull;

import org.apache.asterix.external.api.IFeedMarker;
import org.apache.asterix.external.api.IRawRecord;
import org.apache.asterix.external.api.IRecordDataParser;
import org.apache.asterix.external.api.IRecordReader;
import org.apache.asterix.external.util.ExternalDataConstants;
import org.apache.asterix.external.util.ExternalDataExceptionUtils;
import org.apache.asterix.external.util.FeedLogManager;
import org.apache.hyracks.api.comm.IFrameWriter;
import org.apache.hyracks.api.comm.VSizeFrame;
import org.apache.hyracks.api.context.IHyracksTaskContext;
import org.apache.hyracks.api.exceptions.HyracksDataException;
import org.apache.hyracks.api.util.HyracksConstants;
import org.apache.hyracks.dataflow.common.comm.io.ArrayTupleBuilder;
import org.apache.hyracks.dataflow.common.io.MessagingFrameTupleAppender;
import org.apache.hyracks.dataflow.common.util.TaskUtils;
import org.apache.log4j.Logger;

public class FeedRecordDataFlowController<T> extends AbstractFeedDataFlowController {
    private static final Logger LOGGER = Logger.getLogger(FeedRecordDataFlowController.class.getName());
    protected final IRecordDataParser<T> dataParser;
    protected final IRecordReader<? extends T> recordReader;
    protected final AtomicBoolean closed = new AtomicBoolean(false);
    protected static final long INTERVAL = 1000;
    protected final Object mutex = new Object();
    protected final boolean sendMarker;
    protected boolean failed = false;

    public FeedRecordDataFlowController(IHyracksTaskContext ctx, FeedTupleForwarder tupleForwarder,
            @Nonnull FeedLogManager feedLogManager, int numOfOutputFields, @Nonnull IRecordDataParser<T> dataParser,
            @Nonnull IRecordReader<T> recordReader, boolean sendMarker) throws HyracksDataException {
        super(ctx, tupleForwarder, feedLogManager, numOfOutputFields);
        this.dataParser = dataParser;
        this.recordReader = recordReader;
        this.sendMarker = sendMarker;
        recordReader.setFeedLogManager(feedLogManager);
        recordReader.setController(this);
    }

    @Override
    public void start(IFrameWriter writer) throws HyracksDataException {
        ExecutorService executorService = sendMarker ? Executors.newSingleThreadExecutor() : null;
        Future<?> result = null;
        if (sendMarker) {
            DataflowMarker dataflowMarker = new DataflowMarker(recordReader.getProgressReporter(),
                    TaskUtils.<VSizeFrame> get(HyracksConstants.KEY_MESSAGE, ctx));
            result = executorService.submit(dataflowMarker);
        }
        HyracksDataException hde = null;
        try {
            failed = false;
            tupleForwarder.initialize(ctx, writer);
            while (recordReader.hasNext()) {
                // synchronized on mutex before we call next() so we don't a marker before its record
                synchronized (mutex) {
                    IRawRecord<? extends T> record = recordReader.next();
                    if (record == null) {
                        flush();
                        wait(INTERVAL);
                        continue;
                    }
                    tb.reset();
                    parseAndForward(record);
                }
            }
        } catch (InterruptedException e) {
            //TODO: Find out what could cause an interrupted exception beside termination of a job/feed
            LOGGER.warn("Feed has been interrupted. Closing the feed", e);
            Thread.currentThread().interrupt();
        } catch (Exception e) {
            failed = true;
            tupleForwarder.flush();
            LOGGER.warn("Failure while operating a feed source", e);
            throw new HyracksDataException(e);
        }
        try {
            tupleForwarder.close();
        } catch (Throwable th) {
            hde = ExternalDataExceptionUtils.suppressIntoHyracksDataException(hde, th);
        }
        try {
            recordReader.close();
        } catch (Throwable th) {
            LOGGER.warn("Failure during while operating a feed sourcec", th);
            hde = ExternalDataExceptionUtils.suppressIntoHyracksDataException(hde, th);
        } finally {
            closeSignal();
            if (sendMarker && result != null) {
                result.cancel(true);
            }
        }
        if (hde != null) {
            throw hde;
        }
    }

    private void parseAndForward(IRawRecord<? extends T> record) throws IOException {
        synchronized (dataParser) {
            try {
                dataParser.parse(record, tb.getDataOutput());
            } catch (Exception e) {
                LOGGER.warn(ExternalDataConstants.ERROR_PARSE_RECORD, e);
                feedLogManager.logRecord(record.toString(), ExternalDataConstants.ERROR_PARSE_RECORD);
                // continue the outer loop
                return;
            }
            tb.addFieldEndOffset();
            addMetaPart(tb, record);
            addPrimaryKeys(tb, record);
            tupleForwarder.addTuple(tb);
        }
    }

    protected void addMetaPart(ArrayTupleBuilder tb, IRawRecord<? extends T> record) throws IOException {
    }

    protected void addPrimaryKeys(ArrayTupleBuilder tb, IRawRecord<? extends T> record) throws IOException {
    }

    private void closeSignal() {
        synchronized (closed) {
            closed.set(true);
            closed.notifyAll();
        }
    }

    private void waitForSignal() throws InterruptedException {
        synchronized (closed) {
            while (!closed.get()) {
                closed.wait();
            }
        }
    }

    @Override
    public boolean stop() throws HyracksDataException {
        HyracksDataException hde = null;
        if (recordReader.stop()) {
            if (failed) {
                // failed, close here
                try {
                    tupleForwarder.close();
                } catch (Throwable th) {
                    hde = ExternalDataExceptionUtils.suppressIntoHyracksDataException(hde, th);
                }
                try {
                    recordReader.close();
                } catch (Throwable th) {
                    hde = ExternalDataExceptionUtils.suppressIntoHyracksDataException(hde, th);
                }
                if (hde != null) {<commit_msg>Fix Synchronization Issue in FeedRecordDataflowController<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.asterix.external.dataflow;

import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

import javax.annotation.Nonnull;

import org.apache.asterix.external.api.IFeedMarker;
import org.apache.asterix.external.api.IRawRecord;
import org.apache.asterix.external.api.IRecordDataParser;
import org.apache.asterix.external.api.IRecordReader;
import org.apache.asterix.external.util.ExternalDataConstants;
import org.apache.asterix.external.util.ExternalDataExceptionUtils;
import org.apache.asterix.external.util.FeedLogManager;
import org.apache.hyracks.api.comm.IFrameWriter;
import org.apache.hyracks.api.comm.VSizeFrame;
import org.apache.hyracks.api.context.IHyracksTaskContext;
import org.apache.hyracks.api.exceptions.HyracksDataException;
import org.apache.hyracks.api.util.HyracksConstants;
import org.apache.hyracks.dataflow.common.comm.io.ArrayTupleBuilder;
import org.apache.hyracks.dataflow.common.io.MessagingFrameTupleAppender;
import org.apache.hyracks.dataflow.common.util.TaskUtils;
import org.apache.log4j.Logger;

public class FeedRecordDataFlowController<T> extends AbstractFeedDataFlowController {
    private static final Logger LOGGER = Logger.getLogger(FeedRecordDataFlowController.class.getName());
    protected final IRecordDataParser<T> dataParser;
    protected final IRecordReader<? extends T> recordReader;
    protected final AtomicBoolean closed = new AtomicBoolean(false);
    protected static final long INTERVAL = 1000;
    protected final Object mutex = new Object();
    protected final boolean sendMarker;
    protected boolean failed = false;
    private FeedRecordDataFlowController<T>.DataflowMarker dataflowMarker;
    private Future<?> result;

    public FeedRecordDataFlowController(IHyracksTaskContext ctx, FeedTupleForwarder tupleForwarder,
            @Nonnull FeedLogManager feedLogManager, int numOfOutputFields, @Nonnull IRecordDataParser<T> dataParser,
            @Nonnull IRecordReader<T> recordReader, boolean sendMarker) throws HyracksDataException {
        super(ctx, tupleForwarder, feedLogManager, numOfOutputFields);
        this.dataParser = dataParser;
        this.recordReader = recordReader;
        this.sendMarker = sendMarker;
        recordReader.setFeedLogManager(feedLogManager);
        recordReader.setController(this);
    }

    @Override
    public void start(IFrameWriter writer) throws HyracksDataException {
        ExecutorService executorService = sendMarker ? Executors.newSingleThreadExecutor() : null;
        if (sendMarker && dataflowMarker == null) {
            dataflowMarker = new DataflowMarker(recordReader.getProgressReporter(),
                    TaskUtils.<VSizeFrame> get(HyracksConstants.KEY_MESSAGE, ctx));
            result = executorService.submit(dataflowMarker);
        }
        HyracksDataException hde = null;
        try {
            failed = false;
            tupleForwarder.initialize(ctx, writer);
            while (recordReader.hasNext()) {
                // synchronized on mutex before we call next() so we don't a marker before its record
                synchronized (mutex) {
                    IRawRecord<? extends T> record = recordReader.next();
                    if (record == null) {
                        flush();
                        mutex.wait(INTERVAL);
                        continue;
                    }
                    tb.reset();
                    parseAndForward(record);
                }
            }
        } catch (InterruptedException e) {
            //TODO: Find out what could cause an interrupted exception beside termination of a job/feed
            LOGGER.warn("Feed has been interrupted. Closing the feed", e);
            Thread.currentThread().interrupt();
        } catch (Exception e) {
            failed = true;
            tupleForwarder.flush();
            LOGGER.warn("Failure while operating a feed source", e);
            throw new HyracksDataException(e);
        }
        if(dataflowMarker != null){
            dataflowMarker.stop();
        }
        try {
            tupleForwarder.close();
        } catch (Throwable th) {
            hde = ExternalDataExceptionUtils.suppressIntoHyracksDataException(hde, th);
        }
        try {
            recordReader.close();
        } catch (Throwable th) {
            LOGGER.warn("Failure during while operating a feed sourcec", th);
            hde = ExternalDataExceptionUtils.suppressIntoHyracksDataException(hde, th);
        } finally {
            closeSignal();
            if (sendMarker && result != null) {
                result.cancel(true);
            }
        }
        if (hde != null) {
            throw hde;
        }
    }

    private void parseAndForward(IRawRecord<? extends T> record) throws IOException {
        synchronized (dataParser) {
            try {
                dataParser.parse(record, tb.getDataOutput());
            } catch (Exception e) {
                LOGGER.warn(ExternalDataConstants.ERROR_PARSE_RECORD, e);
                feedLogManager.logRecord(record.toString(), ExternalDataConstants.ERROR_PARSE_RECORD);
                // continue the outer loop
                return;
            }
            tb.addFieldEndOffset();
            addMetaPart(tb, record);
            addPrimaryKeys(tb, record);
            tupleForwarder.addTuple(tb);
        }
    }

    protected void addMetaPart(ArrayTupleBuilder tb, IRawRecord<? extends T> record) throws IOException {
    }

    protected void addPrimaryKeys(ArrayTupleBuilder tb, IRawRecord<? extends T> record) throws IOException {
    }

    private void closeSignal() {
        synchronized (closed) {
            closed.set(true);
            closed.notifyAll();
        }
    }

    private void waitForSignal() throws InterruptedException {
        synchronized (closed) {
            while (!closed.get()) {
                closed.wait();
            }
        }
    }

    @Override
    public boolean stop() throws HyracksDataException {
        if (dataflowMarker != null) {
            dataflowMarker.stop();
        }
        HyracksDataException hde = null;
        if (recordReader.stop()) {
            if (failed) {
                // failed, close here
                try {
                    tupleForwarder.close();
                } catch (Throwable th) {
                    hde = ExternalDataExceptionUtils.suppressIntoHyracksDataException(hde, th);
                }
                try {
                    recordReader.close();
                } catch (Throwable th) {
                    hde = ExternalDataExceptionUtils.suppressIntoHyracksDataException(hde, th);
                }
                if (hde != null) {
{'fraction_non_alphanumeric': 0.08349220958516863, 'fraction_numerical': 0.0011833541516008152, 'mean_word_length': 2.4525646845211075, 'pattern_counts': {'":': 0, '<': 26, '<?xml version=': 0, '>': 26, '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': '4160290', 'n_tokens_mistral': 3919, 'n_tokens_neox': 3827, 'n_words': 989}