import { joinIterables, wrapIterable } from "../../../../shared/src/iterables.js";
class Forwarder {
  #active = /* @__PURE__ */ new Set();
  #queued = /* @__PURE__ */ new Set();
  #inTransaction = false;
  /**
   * `add()` is called in lock step with `Storer.catchup()` so that the
   * two components have an equivalent interpretation of whether a Transaction is
   * currently being streamed.
   */
  add(sub) {
    if (this.#inTransaction) {
      this.#queued.add(sub);
    } else {
      this.#active.add(sub);
    }
  }
  remove(sub) {
    this.#active.delete(sub);
    this.#queued.delete(sub);
    sub.close();
  }
  /**
   * `forward()` is called in lockstep with `Storer.store()` so that the
   * two components have an equivalent interpretation of whether a Transaction is
   * currently being streamed.
   */
  async forward(entry) {
    const [type] = entry[1];
    const results = Array.from(this.#active.values(), (sub) => sub.send(entry));
    switch (type) {
      case "begin":
        this.#inTransaction = true;
        break;
      case "commit":
      case "rollback":
        this.#inTransaction = false;
        for (const sub of this.#queued.values()) {
          this.#active.add(sub);
        }
        this.#queued.clear();
        break;
    }
    await Promise.all(results);
  }
  getAcks() {
    return new Set(
      joinIterables(
        wrapIterable(this.#active).map((s) => s.acked),
        wrapIterable(this.#queued).map((s) => s.acked)
      )
    );
  }
}
export {
  Forwarder
};
//# sourceMappingURL=forwarder.js.map
