<commit_before>/*
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * Licensed 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 com.facebook.buck.worker;

import com.facebook.buck.core.util.log.Logger;
import com.facebook.buck.util.concurrent.LinkedBlockingStack;
import com.facebook.buck.util.function.ThrowingSupplier;
import com.google.common.base.Preconditions;
import com.google.common.hash.HashCode;
import java.io.Closeable;
import java.io.IOException;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import javax.annotation.Nullable;
import javax.annotation.concurrent.ThreadSafe;

/**
 * A pool of {@link WorkerProcess} instances.
 *
 * <p>This pool supports acquisition and release of worker processes on different threads. Workers
 * are acquired with {@link #borrowWorkerProcess()}, which returns
 */
@ThreadSafe
public class WorkerProcessPool<T extends WorkerProcess> implements Closeable {

  private static final Logger LOG = Logger.get(WorkerProcessPool.class);

  private final int capacity;
  private final BlockingQueue<WorkerLifecycle<T>> availableWorkers;
  private final WorkerLifecycle<T>[] workerLifecycles;
  private final HashCode poolHash;

  public WorkerProcessPool(
      int maxWorkers, HashCode poolHash, ThrowingSupplier<T, IOException> startWorkerProcess) {
    this.capacity = maxWorkers;
    this.availableWorkers = new LinkedBlockingStack<>();
    this.workerLifecycles = getWorkerLifecyclesArray(WorkerLifecycle.class, capacity);
    this.poolHash = poolHash;
    for (int i = 0; i < maxWorkers; i++) {
      WorkerLifecycle<T> workerLifecycle =
          new WorkerLifecycle<>(startWorkerProcess, availableWorkers::add);
      workerLifecycles[i] = workerLifecycle;
      availableWorkers.add(workerLifecycle);
    }
  }

  @SuppressWarnings("unchecked")
  private static <T extends WorkerProcess> WorkerLifecycle<T>[] getWorkerLifecyclesArray(
      Class<?> componentType, int length) {
    Object array = Array.newInstance(componentType, length);
    return (WorkerLifecycle<T>[]) array;
  }

  /**
   * If there are available workers, returns one. Otherwise blocks until one becomes available and
   * returns it. Borrowed worker processes must be released by calling {@link
   * BorrowedWorkerProcess#close()} after using them.
   */
  public BorrowedWorkerProcess<T> borrowWorkerProcess() throws InterruptedException {
    return new BorrowedWorkerProcess<>(availableWorkers.take());
  }

  public Optional<BorrowedWorkerProcess<T>> borrowWorkerProcess(int timeout, TimeUnit unit)
      throws InterruptedException {
    return Optional.ofNullable(availableWorkers.poll(timeout, unit))
        .map(BorrowedWorkerProcess::new);
  }

  @Override
  public synchronized void close() {
    Throwable caughtWhileClosing = null;

    // remove all available workers
    int numAvailableWorkers = availableWorkers.drainTo(new ArrayList<>(capacity));
    for (WorkerLifecycle<T> lifecycle : workerLifecycles) {
      try {
        lifecycle.close();
      } catch (Throwable t) {
        caughtWhileClosing = t;
      }
    }

    Preconditions.checkState(
        numAvailableWorkers == capacity,
        "WorkerProcessPool was still running when shutdown was called.");
    if (caughtWhileClosing != null) {
      throw new RuntimeException(caughtWhileClosing);
    }
  }

  public int getCapacity() {
    return capacity;
  }

  public HashCode getPoolHash() {
    return poolHash;
  }

  /**
   * Represents the lifecycle of one specific worker in a {@link WorkerProcessPool}.
   *
   * <p>Concurrency is controlled by the pool, which supports acquiring and releasing workers with
   * {@link WorkerProcessPool#availableWorkers}.
   *
   * <p>{@link #get()} and {@link #close()} are synchronized to allow closing as part of closing the
   * pool with a consumer trying to acquire a worker in parallel.
   */
  @ThreadSafe
  static class WorkerLifecycle<T extends WorkerProcess>
      implements Closeable, ThrowingSupplier<T, IOException> {

    private final ThrowingSupplier<T, IOException> startWorkerProcess;
    private final Consumer<WorkerLifecycle<T>> onWorkerProcessReturn;
    private boolean isClosed = false;
    @Nullable private T workerProcess;

    WorkerLifecycle(
        ThrowingSupplier<T, IOException> startWorkerProcess,
        Consumer<WorkerLifecycle<T>> onWorkerProcessReturn) {
      this.startWorkerProcess = startWorkerProcess;
      this.onWorkerProcessReturn = onWorkerProcessReturn;
    }

    /** Allows to retrieve the wrapped worker process, starting it up if necessary. */
    @Override
    public synchronized T get() throws IOException {
      Preconditions.checkState(!isClosed, "Worker was already terminated");
      // If the worker is broken, destroy it
      if (workerProcess != null && !workerProcess.isAlive()) {
        closeWorkerProcess();
      }

      // start a worker if necessary, this might throw IOException
      if (workerProcess == null) {
        workerProcess = startWorkerProcess.get();
      }

      return workerProcess;
    }

    private void closeWorkerProcess() {
      try {
        workerProcess.close();
      } catch (Exception ex) {
        LOG.error(ex, "Failed to close dead worker process; ignoring.");
      } finally {
        workerProcess = null;
      }
    }

    public void makeAvailable() {
      onWorkerProcessReturn.accept(this);
    }

    @Override<commit_msg>WorkerLifecycle interface<commit_after>/*
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * Licensed 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 com.facebook.buck.worker;

import com.facebook.buck.core.util.log.Logger;
import com.facebook.buck.util.concurrent.LinkedBlockingStack;
import com.facebook.buck.util.function.ThrowingSupplier;
import com.google.common.base.Preconditions;
import com.google.common.hash.HashCode;
import java.io.Closeable;
import java.io.IOException;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import javax.annotation.Nullable;
import javax.annotation.concurrent.ThreadSafe;

/**
 * A pool of {@link WorkerProcess} instances.
 *
 * <p>This pool supports acquisition and release of worker processes on different threads. Workers
 * are acquired with {@link #borrowWorkerProcess()}, which returns
 */
@ThreadSafe
public class WorkerProcessPool<T extends WorkerProcess> implements Closeable {

  private static final Logger LOG = Logger.get(WorkerProcessPool.class);

  private final int capacity;
  private final BlockingQueue<WorkerLifecycle<T>> availableWorkers;
  private final WorkerLifecycle<T>[] workerLifecycles;
  private final HashCode poolHash;

  public WorkerProcessPool(
      int maxWorkers, HashCode poolHash, ThrowingSupplier<T, IOException> startWorkerProcess) {
    this.capacity = maxWorkers;
    this.availableWorkers = new LinkedBlockingStack<>();
    this.workerLifecycles = getWorkerLifecyclesArray(WorkerLifecycle.class, capacity);
    this.poolHash = poolHash;
    for (int i = 0; i < maxWorkers; i++) {
      WorkerLifecycle<T> workerLifecycle =
          new DefaultWorkerLifecycle<>(startWorkerProcess, availableWorkers::add);
      workerLifecycles[i] = workerLifecycle;
      availableWorkers.add(workerLifecycle);
    }
  }

  @SuppressWarnings("unchecked")
  private static <T extends WorkerProcess> WorkerLifecycle<T>[] getWorkerLifecyclesArray(
      Class<?> componentType, int length) {
    Object array = Array.newInstance(componentType, length);
    return (WorkerLifecycle<T>[]) array;
  }

  /**
   * If there are available workers, returns one. Otherwise blocks until one becomes available and
   * returns it. Borrowed worker processes must be released by calling {@link
   * BorrowedWorkerProcess#close()} after using them.
   */
  public BorrowedWorkerProcess<T> borrowWorkerProcess() throws InterruptedException {
    return new BorrowedWorkerProcess<>(availableWorkers.take());
  }

  public Optional<BorrowedWorkerProcess<T>> borrowWorkerProcess(int timeout, TimeUnit unit)
      throws InterruptedException {
    return Optional.ofNullable(availableWorkers.poll(timeout, unit))
        .map(BorrowedWorkerProcess::new);
  }

  @Override
  public synchronized void close() {
    Throwable caughtWhileClosing = null;

    // remove all available workers
    int numAvailableWorkers = availableWorkers.drainTo(new ArrayList<>(capacity));
    for (WorkerLifecycle<T> lifecycle : workerLifecycles) {
      try {
        lifecycle.close();
      } catch (Throwable t) {
        caughtWhileClosing = t;
      }
    }

    Preconditions.checkState(
        numAvailableWorkers == capacity,
        "WorkerProcessPool was still running when shutdown was called.");
    if (caughtWhileClosing != null) {
      throw new RuntimeException(caughtWhileClosing);
    }
  }

  public int getCapacity() {
    return capacity;
  }

  public HashCode getPoolHash() {
    return poolHash;
  }

  private interface WorkerLifecycle<T extends WorkerProcess>
      extends Closeable, ThrowingSupplier<T, IOException> {

    void makeAvailable();

    @Override
    void close();
  }

  /**
   * Represents the lifecycle of one specific worker in a {@link WorkerProcessPool}.
   *
   * <p>Concurrency is controlled by the pool, which supports acquiring and releasing workers with
   * {@link WorkerProcessPool#availableWorkers}.
   *
   * <p>{@link #get()} and {@link #close()} are synchronized to allow closing as part of closing the
   * pool with a consumer trying to acquire a worker in parallel.
   */
  @ThreadSafe
  private static class DefaultWorkerLifecycle<T extends WorkerProcess>
      implements WorkerLifecycle<T> {

    private final ThrowingSupplier<T, IOException> startWorkerProcess;
    private final Consumer<DefaultWorkerLifecycle<T>> onWorkerProcessReturn;
    private boolean isClosed = false;
    @Nullable private T workerProcess;

    DefaultWorkerLifecycle(
        ThrowingSupplier<T, IOException> startWorkerProcess,
        Consumer<DefaultWorkerLifecycle<T>> onWorkerProcessReturn) {
      this.startWorkerProcess = startWorkerProcess;
      this.onWorkerProcessReturn = onWorkerProcessReturn;
    }

    /** Allows to retrieve the wrapped worker process, starting it up if necessary. */
    @Override
    public synchronized T get() throws IOException {
      Preconditions.checkState(!isClosed, "Worker was already terminated");
      // If the worker is broken, destroy it
      if (workerProcess != null && !workerProcess.isAlive()) {
        closeWorkerProcess();
      }

      // start a worker if necessary, this might throw IOException
      if (workerProcess == null) {
        workerProcess = startWorkerProcess.get();
      }

      return workerProcess;
    }

    private void closeWorkerProcess() {
      try {
        workerProcess.close();
      } catch (Exception ex) {
        LOG.error(ex, "Failed to close dead worker process; ignoring.");
      } finally {
        workerProcess = null;
      }
    }

    @Override
    public void makeAvailable() {
      onWorkerProcessReturn.accept(this);
    }

    @Override
{'fraction_non_alphanumeric': 0.08849129593810445, 'fraction_numerical': 0.0008059316569954867, 'mean_word_length': 3.849159828057835, 'pattern_counts': {'":': 0, '<': 65, '<?xml version=': 0, '>': 63, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4621575', 'n_tokens_mistral': 3334, 'n_tokens_neox': 3284, 'n_words': 1008}