"use strict"
var __createBinding =
  (this && this.__createBinding) ||
  (Object.create
    ? function (o, m, k, k2) {
        if (k2 === undefined) k2 = k
        Object.defineProperty(o, k2, {
          enumerable: true,
          get: function () {
            return m[k]
          }
        })
      }
    : function (o, m, k, k2) {
        if (k2 === undefined) k2 = k
        o[k2] = m[k]
      })
var __setModuleDefault =
  (this && this.__setModuleDefault) ||
  (Object.create
    ? function (o, v) {
        Object.defineProperty(o, "default", { enumerable: true, value: v })
      }
    : function (o, v) {
        o["default"] = v
      })
var __importStar =
  (this && this.__importStar) ||
  function (mod) {
    if (mod && mod.__esModule) return mod
    var result = {}
    if (mod != null)
      for (var k in mod)
        if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k))
          __createBinding(result, mod, k)
    __setModuleDefault(result, mod)
    return result
  }
Object.defineProperty(exports, "__esModule", { value: true })
exports.chainPar = void 0
const Function_1 = require("../../Function")
const P = __importStar(require("../../Promise"))
const Q = __importStar(require("../../Queue"))
const SM = __importStar(require("../../Semaphore"))
const T = __importStar(require("../_internal/effect"))
const F = __importStar(require("../_internal/fiber"))
const M = __importStar(require("../_internal/managed"))
const Pull = __importStar(require("../Pull"))
const chain = __importStar(require("./chain"))
const definitions_1 = require("./definitions")
const forEach = __importStar(require("./forEach"))
const managed_1 = require("./managed")
const tap = __importStar(require("./tap"))
/**
 * Maps each element of this stream to another stream and returns the
 * non-deterministic merge of those streams, executing up to `n` inner streams
 * concurrently. Up to `outputBuffer` elements of the produced streams may be
 * buffered in memory by this operator.
 */
function chainPar(n, outputBuffer = 16) {
  return (f) => (self) => {
    return new definitions_1.Stream(
      M.withChildren((getChildren) =>
        M.map_(
          M.tap_(
            M.bind_(
              M.bind_(
                M.bind_(M.do, "out", () =>
                  T.toManagedRelease_(Q.makeBounded(outputBuffer), Q.shutdown)
                ),
                "permits",
                () => T.toManaged(SM.makeSemaphore(n))
              ),
              "innerFailure",
              () => T.toManaged(P.make())
            ),
            ({ innerFailure, out, permits }) =>
              M.fork(
                M.foldCauseM_(
                  forEach.forEachManaged_(self, (a) =>
                    T.asUnit(
                      T.tap_(
                        T.tap_(
                          T.let_(
                            T.bind_(T.do, "latch", () => P.make()),
                            "innerStream",
                            ({ latch }) =>
                              T.foldCauseM_(
                                forEach.forEachChunk((b) =>
                                  T.asUnit(Q.offer_(out, T.succeed(b)))
                                )(
                                  chain.chain((_) => f(a))(
                                    tap.tap((_) => P.succeed_(latch, undefined))(
                                      (0, managed_1.managed)(
                                        SM.withPermitManaged(permits)
                                      )
                                    )
                                  )
                                ),
                                (cause) =>
                                  T.asUnit(
                                    T.zipRight_(
                                      Q.offer_(out, Pull.halt(cause)),
                                      P.fail_(innerFailure, cause)
                                    )
                                  ),
                                (_) => T.unit
                              )
                          ),
                          ({ innerStream }) => T.fork(innerStream)
                        ),
                        ({ latch }) => P.await(latch)
                      )
                    )
                  ),
                  (cause) =>
                    T.toManaged(
                      T.zipRight_(
                        T.chain_(getChildren, (c) => F.interruptAll(c)),
                        T.asUnit(Q.offer_(out, Pull.halt(cause)))
                      )
                    ),
                  (_) =>
                    T.toManaged(
                      T.raceWith_(
                        T.interruptible(P.await(innerFailure)),
                        SM.withPermits_(T.interruptible(T.unit), permits, n),
                        (_, permitsAcquisition) =>
                          T.zipRight_(
                            T.chain_(getChildren, (c) => F.interruptAll(c)),
                            T.asUnit(F.interrupt(permitsAcquisition))
                          ),
                        (_, failureAwait) =>
                          T.zipRight_(
                            Q.offer_(out, Pull.end),
                            T.asUnit(F.interrupt(failureAwait))
                          )
                      )
                    )
                )
              )
          ),
          ({ out }) => T.flatten(Q.take(out))
        )
      )
    )
  }
}
exports.chainPar = chainPar
//# sourceMappingURL=chainPar.js.map
