/** Серийный доступ к bandwidth-test по node id (пара узлов не пересекаются). */
const btestNodeLocks = new Map<number, Promise<void>>()

export async function withBtestNodeLocks<T>(nodeIds: number[], fn: () => Promise<T>): Promise<T> {
  const ids = [...new Set(nodeIds.filter((id) => Number.isFinite(id)))].sort((a, b) => a - b)
  const releases: Array<() => void> = []
  try {
    for (const id of ids) {
      const prev = btestNodeLocks.get(id)
      let resolveCurrent!: () => void
      const current = new Promise<void>((resolve) => {
        resolveCurrent = resolve
      })
      btestNodeLocks.set(id, current)
      if (prev) await prev
      releases.push(() => {
        if (btestNodeLocks.get(id) === current) btestNodeLocks.delete(id)
        resolveCurrent()
      })
    }
    return await fn()
  } finally {
    for (let i = releases.length - 1; i >= 0; i -= 1) releases[i]()
  }
}
